diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..d6547ce30 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# change black settings +108955b601e768fd56696be903fc8b471c73ebf7 diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..4a08579c2 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,12 @@ +# Salesforce Open Source project configuration +# Learn more: https://github.com/salesforce/oss-template +#ECCN:Open Source +#GUSINFO:Open Source,Open Source Workflow + +# @slackapi/slack-platform-python +# are code reviewers for all changes in this repo. +* @slackapi/slack-platform-python + +# @slackapi/developer-education +# are code reviewers for changes in the `/docs` directory. +/docs/ @slackapi/developer-education diff --git a/.github/ISSUE_TEMPLATE/01_question.md b/.github/ISSUE_TEMPLATE/01_question.md index 628fb4160..66971561d 100644 --- a/.github/ISSUE_TEMPLATE/01_question.md +++ b/.github/ISSUE_TEMPLATE/01_question.md @@ -1,5 +1,5 @@ --- -name: Question +name: SDK Question about: Submit a question about this SDK title: (Set a clear title describing your question) labels: "untriaged" @@ -30,7 +30,7 @@ sw_vers && uname -v # or `ver` #### Steps to reproduce: -(Share the commands to run, source code, and project settings (e.g., setup.py)) +(Share the commands to run, source code, and project settings (e.g., pyproject.toml)) 1. 2. diff --git a/.github/ISSUE_TEMPLATE/02_enhancement.md b/.github/ISSUE_TEMPLATE/02_enhancement.md index 1c6e56778..33c349f68 100644 --- a/.github/ISSUE_TEMPLATE/02_enhancement.md +++ b/.github/ISSUE_TEMPLATE/02_enhancement.md @@ -1,5 +1,5 @@ --- -name: Enhancement / Feature Request +name: SDK Enhancement / Feature Request about: Submit an enhancement/feature request title: (Set a clear title describing your idea) labels: "untriaged" @@ -10,11 +10,14 @@ assignees: "" ### Category (place an `x` in each of the `[ ]`) -- [ ] **slack_sdk.web.WebClient** (Web API client) -- [ ] **slack_sdk.webhook.WebhookClient** (Incoming Webhook, response_url sender) +- [ ] **slack_sdk.web.WebClient (sync/async)** (Web API client) +- [ ] **slack_sdk.webhook.WebhookClient (sync/async)** (Incoming Webhook, response_url sender) - [ ] **slack_sdk.models** (UI component builders) - [ ] **slack_sdk.oauth** (OAuth Flow Utilities) -- [ ] **slack_sdk.rtm.RTMClient** (RTM client) +- [ ] **slack_sdk.socket_mode** (Socket Mode client) +- [ ] **slack_sdk.audit_logs** (Audit Logs API client) +- [ ] **slack_sdk.scim** (SCIM API client) +- [ ] **slack_sdk.rtm** (RTM client) - [ ] **slack_sdk.signature** (Request Signature Verifier) ### Requirements diff --git a/.github/ISSUE_TEMPLATE/03_document.md b/.github/ISSUE_TEMPLATE/03_document.md index a07f7a441..822bc2ee4 100644 --- a/.github/ISSUE_TEMPLATE/03_document.md +++ b/.github/ISSUE_TEMPLATE/03_document.md @@ -1,5 +1,5 @@ --- -name: Document +name: SDK Document about: Submit an issue on documents title: (Set a clear title describing your idea) labels: "untriaged" @@ -10,7 +10,7 @@ assignees: "" ### The page URLs -- https://slack.dev/python-slack-sdk/ +- https://docs.slack.dev/tools/python-slack-sdk/ ### Requirements diff --git a/.github/ISSUE_TEMPLATE/04_bug.md b/.github/ISSUE_TEMPLATE/04_bug.md index 89fa4bcbe..fd1fc5718 100644 --- a/.github/ISSUE_TEMPLATE/04_bug.md +++ b/.github/ISSUE_TEMPLATE/04_bug.md @@ -1,5 +1,5 @@ --- -name: Bug +name: SDK Bug about: Report the SDK bug title: (Set a clear title describing the issue) labels: "untriaged" @@ -30,7 +30,7 @@ sw_vers && uname -v # or `ver` #### Steps to reproduce: -(Share the commands to run, source code, and project settings (e.g., setup.py)) +(Share the commands to run, source code, and project settings (e.g., pyproject.toml)) 1. 2. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..1925abae7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +blank_issues_enabled: false +contact_links: + - name: Slack Platform Customer Support + url: https://my.slack.com/help/requests/new + about: | + This issue tracker is a place to track bugs, feature requests, and questions on this SDK side. + If you have a general question on how to use the Slack platform, please get in touch with our customer support agents first via either /feedback in your Slack workspace or the help page link here. diff --git a/.github/contributing.md b/.github/contributing.md index 686241b75..f15e0c46a 100644 --- a/.github/contributing.md +++ b/.github/contributing.md @@ -38,8 +38,8 @@ Issues labelled `good first contribution`. For your contribution to be accepted: -- [x] You must have signed the [Contributor License Agreement (CLA)](https://cla-assistant.io/slackapi/python-slack-sdk). -- [x] The test suite must be complete and pass. +- [x] You must have signed the [Contributor License Agreement (CLA)](https://cla.salesforce.com/sign-cla). +- [x] The test suite must be complete and pass (see the [Maintainer's Guide](./maintainers_guide.md) for details on how to run the tests). - [x] The changes must be approved by code review. - [x] Commits should be atomic and messages must be descriptive. Related issues should be mentioned by Issue number. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..ac86badc1 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +# Please see the documentation for all configuration options: +# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file + +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 5 + ignore: + - dependency-name: "black" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" diff --git a/.github/issue_template.md b/.github/issue_template.md index 4c61970db..33b393830 100644 --- a/.github/issue_template.md +++ b/.github/issue_template.md @@ -22,7 +22,7 @@ sw_vers && uname -v # or `ver` #### Steps to reproduce: -(Share the commands to run, source code, and project settings (e.g., setup.py)) +(Share the commands to run, source code, and project settings (e.g., pyproject.toml)) 1. 2. diff --git a/.github/maintainers_guide.md b/.github/maintainers_guide.md index 6bdbc1b02..ccda1607f 100644 --- a/.github/maintainers_guide.md +++ b/.github/maintainers_guide.md @@ -10,123 +10,242 @@ this project. If you use this package within your own software as is but don't p We recommend using [pyenv](https://github.com/pyenv/pyenv) for Python runtime management. If you use macOS, follow the following steps: -```bash -$ brew update -$ brew install pyenv +```sh +brew update +brew install pyenv ``` -Install necessary Python runtimes for development/testing. You can rely on Travis CI builds for testing with various major versions. https://github.com/slackapi/python-slack-sdk/blob/main/.travis.yml +You can hook `pyenv` into your shell automatically by running `pyenv init` and following the instructions. -```bash +Install necessary Python runtimes for development/testing. It is not necessary +to install all the various Python versions we test in [continuous integration on +GitHub Actions](https://github.com/slackapi/python-slack-sdk/blob/main/.github/workflows/tests.yml), +but make sure you are running at least one version that we execute our tests in +locally so that you can run the tests yourself. + +```sh $ pyenv install -l | grep -v "-e[conda|stackless|pypy]" -$ pyenv install 3.8.5 # select the latest patch version -$ pyenv local 3.8.5 +$ pyenv install 3.9.6 # select the latest patch version +$ pyenv local 3.9.6 $ pyenv versions system 3.6.10 3.7.7 -* 3.8.5 (set by /path-to-python-slack-sdk/.python-version) +* 3.9.6 (set by /path-to-python-slack-sdk/.python-version) $ pyenv rehash ``` -Then, you can create a new Virtual Environment this way: +Then, you can create a new [Virtual Environment](https://docs.python.org/3/tutorial/venv.html) specific to the Python version you just installed by running: +```sh +python -m venv env_3.9.6 +source env_3.9.6/bin/activate ``` -$ python -m venv env_3.8.5 -$ source env_3.8.5/bin/activate + +At this point you have a clean, Python-version-specific environment "activated" for +use just for this project. All `python` and `pip` commands run in your shell +from this point on run in the context of this virtual environment. You can +deactivate the virtual environment by running `deactivate`; it is recommended to +do so after you are done working in this project. To come back to development +work for this project again in the future, `cd` into this project directory and +run `source env_3.9.6/bin/activate` again. + +The last step is to install this project's dependencies and run all unit tests; to do so, you can run + +```sh +./scripts/run_validation.sh ``` -## Tasks +Also check out [how +we configure GitHub Actions to install dependencies for this project for use in +our continuous integration](https://github.com/slackapi/python-slack-sdk/blob/v3.17.0/.github/workflows/ci-build.yml#L28-L32). -### Testing (Unit Tests) +## Tasks -When you make changes to this SDK, please write unit tests verifying if the changes work as you expected. You can easily run all the tests by running the command. The `validate` command runs Flake8 (static code analyzer), Black (code formatter), and unit tests in the `tests` directory for you. +### Formatting -```bash -python setup.py validate # run all +This project uses code formatting tools to maintain consistent style. You can format the codebase by running: -# run a single test -python setup.py validate \ - --test-target tests/web/test_web_client.py +```sh +./scripts/format.sh ``` -You can rely on Travis CI builds for running the tests on a variety of Python runtimes. +### Testing -### Testing (Integration Tests with Real Slack APIs) +#### Unit Tests -This project also has integration tests that verify the SDK works with the Slack API platform. As a preparation, you need to set [the required env variables](https://github.com/slackapi/python-slack-sdk/blob/main/integration_tests/env_variable_names.py) properly. You don't need to setup all of them if you just want to run some of the tests. Commonly, `SLACK_SDK_TEST_BOT_TOKEN` and `SLACK_SDK_TEST_USER_TOKEN` are used for running `WebClient` tests. +When you make changes to this SDK, please write unit tests verifying if the changes work as you expected. You can easily run all the tests and formatting/linter with the below scripts. -```bash -python setup.py run_integration_tests # run all +Run all the unit tests, code linter, and code analyzer: -# run a single test -python setup.py run_integration_tests \ - --test-target integration_tests/web/test_web_client.py +```sh +./scripts/run_validation.sh ``` -### Generating Documentation +Run all the unit tests (no linter nor code analyzer): -The documentation is generated from the source and templates in the `docs-src` directory. The generated documentation -gets committed to the repo in `docs` and also published to a GitHub Pages website. +```sh +./scripts/run_unit_tests.sh +``` -You can generate the documentation by running `./docs.sh`. +Run a specific unit test: -### Releasing +```sh +./scripts/run_unit_tests.sh tests/web/test_web_client.py +``` -1. Create the commit for the release: +You can rely on GitHub Actions builds for running the tests on a variety of Python runtimes. -- Bump the version number in adherence to [Semantic Versioning](http://semver.org/) in `slackclient/version.py`. -- Add a description of changes to the Changelog in `docs-src/changelog.rst` -- Build the docs with `./docs.sh`. -- Cut off a branch for the release with `git branch -b v2.5.0-release` -- Set the version in `slack/version.py` (e.g., `2.5.0`) -- Commit with a message including the new version number: `git commit -m'version 2.5.0'`. -- Push the commit to a branch and create a PR to sanity check. -- Merge in release PR after receiving at least one approval from other maintainers. -- Create a git tag for the release. For example `git tag 2.5.0`. -- Push the tag up to github with `git push origin --tags` +#### Integration Tests with Real Slack APIs -2. Distribute the release +This project also has integration tests that verify the SDK works with the Slack API platform. As a preparation, you need to set [the required env variables](https://github.com/slackapi/python-slack-sdk/blob/main/integration_tests/env_variable_names.py) properly. You don't need to setup all of them if you just want to run some of the tests. Commonly, `SLACK_SDK_TEST_BOT_TOKEN` and `SLACK_SDK_TEST_USER_TOKEN` are used for running `WebClient` tests. -- Use the latest stable Python runtime - - `python -m venv env` - - `python setup.py upload` -- Create a GitHub Release. You will select the commit with updated version number (e.g. `version 2.5.0`) to associate with the tag, and name the tag after this version (e.g. `v2.5.0`). This will also serve as a Changelog for the project. Add a description of changes to the Release. Mention Issue and PR #'s and @-mention contributors. +Run all integration tests: -```markdown -Refer to [v{version} milestone](https://github.com/slackapi/python-slack-sdk/milestone/{TODO}?closed=1) to know the complete list of the issues resolved by this release. +```sh +./scripts/run_integration_tests.sh +``` -**Updates** +Run a specific integration test: -1. [WebClient] #111 Make an awesome change - Thanks @SlackHQ -1. [RTMClient] #222 Make an awesome change - Thanks @SlackAPI +```sh +./scripts/run_integration_tests.sh integration_tests/web/test_async_web_client.py +``` + +#### Develop Locally + +If you want to test the package locally you can. + +1. Build the package locally + - Run + ```sh + scripts/build_pypi_package.sh + ``` + - This will create a `.whl` file in the `./dist` folder +2. Use the built package + - Example `/dist/slack_sdk-1.2.3-py2.py3-none-any.whl` was created + - From anywhere on your machine you can install this package to a project with + ```sh + pip install /dist/slack_sdk-1.2.3-py2.py3-none-any.whl + ``` + - It is also possible to include `slack_sdk @ file:////dist/slack_sdk-1.2.3-py2.py3-none-any.whl` in a [requirements.txt](https://pip.pypa.io/en/stable/user_guide/#requirements-files) file + +### Generating Documentation -**All Changes** +See [`/docs/README`](https://github.com/slackapi/python-slack-sdk/blob/main/docs/README.md) for information on editing documentation pages. -https://github.com/slackapi/python-slack-sdk/compare/{the previous release version tag}...{the release version tag} +The API reference is generated from a script. You can generate and preview the **API _reference_ documents for `slack_sdk` package modules** by running: + +```sh +./scripts/generate_api_docs.sh ``` -3. (Slack Internal) Communicate the release internally +### Releasing + +#### test.pypi.org deployment -- Include a link to the GitHub release +[TestPyPI](https://test.pypi.org/) is a separate instance of the Python Package +Index that allows you to try distribution tools and processes without affecting +the real index. This is particularly useful when making changes related to the +package configuration itself, for example, modifications to the `pyproject.toml` file. -4. Make announcements +You can deploy this project to TestPyPI using GitHub Actions. -- #slack-api in dev4slack.slack.com -- #lang-python in community.slack.com +To deploy using GitHub Actions: -5. (Slack Internal) Tweet by @SlackAPI +1. Push your changes to a branch or tag +2. Navigate to +3. Click on "Run workflow" +4. Select your branch or tag from the dropdown +5. Click "Run workflow" to build and deploy your branch to TestPyPI + +Alternatively, you can deploy from your local machine with: + +```sh +./scripts/deploy_to_test_pypi.sh +``` -- Not necessary for patch updates, might be needed for minor updates, definitely needed for major updates. Include a link to the GitHub release +#### Development Deployment + +Deploying a new version of this library to PyPI is triggered by publishing a GitHub Release. +Before creating a new release, ensure that everything on a stable branch has +landed, then [run the tests](#unit-tests). + +1. Create the commit for the release + 1. Use the latest supported Python version. Using a [virtual environment](#python-and-friends) is recommended. + 2. In `slack_sdk/version.py` bump the version number in adherence to [Semantic Versioning](http://semver.org/) and [Developmental Release](https://peps.python.org/pep-0440/#developmental-releases). + - Example: if the current version is `1.2.3`, a proper development bump would be `1.2.4.dev0` + - `.dev` will indicate to pip that this is a [Development Release](https://peps.python.org/pep-0440/#developmental-releases) + - Note that the `dev` version can be bumped in development releases: `1.2.4.dev0` -> `1.2.4.dev1` + 3. Build the docs with `./scripts/generate_api_docs.sh`. + 4. Commit with a message including the new version number. For example `1.2.4.dev0` & push the commit to a branch where the development release will live (create it if it does not exist) + 1. `git checkout -b future-release` + 2. `git add --all` (review files with `git status` before committing) + 3. `git commit -m 'chore(release): version 1.2.4.dev0'` + 4. `git push -u origin future-release` +2. Create a new GitHub Release + 1. Navigate to the [Releases page](https://github.com/slackapi/python-slack-sdk/releases). + 2. Click the "Draft a new release" button. + 3. Set the "Target" to the feature branch with the development changes. + 4. Click "Tag: Select tag" + 5. Input a new tag name manually. The tag name must match the version in `slack_sdk/version.py` prefixed with "v" (e.g., if version is `1.2.4.dev0`, enter `v1.2.4.dev0`) + 6. Click the "Create a new tag" button. This won't create your tag immediately. + 7. Click the "Generate release notes" button. + 8. The release name should match the tag name! + 9. Edit the resulting notes to ensure they have decent messaging that is understandable by non-contributors, but each commit should still have its own line. + 10. Set this release as a pre-release. + 11. Publish the release by clicking the "Publish release" button! +3. Navigate to the [release workflow run](https://github.com/slackapi/python-slack-sdk/actions/workflows/pypi-release.yml). You will need to approve the deployment! +4. After a few minutes, the corresponding version will be available on . +5. (Slack Internal) Communicate the release internally + +#### Production Deployment + +Deploying a new version of this library to PyPI is triggered by publishing a GitHub Release. +Before creating a new release, ensure that everything on the `main` branch since +the last tag is in a releasable state! At a minimum, [run the tests](#unit-tests). + +1. Create the commit for the release + 1. Use the latest supported Python version. Using a [virtual environment](#python-and-friends) is recommended. + 2. In `slack_sdk/version.py` bump the version number in adherence to [Semantic Versioning](http://semver.org/) and the [Versioning](#versioning-and-tags) section. + 3. Build the docs with `./scripts/generate_api_docs.sh`. + 4. Commit with a message including the new version number. For example `1.2.3` & push the commit to a branch and create a PR to sanity check. + 1. `git checkout -b 1.2.3-release` + 2. `git add --all` (review files with `git status` before committing) + 3. `git commit -m 'chore(release): version 1.2.3'` + 4. `git push -u origin 1.2.3-release` + 5. Add relevant labels to the PR and add the PR to a GitHub Milestone. + 6. Merge in release PR after getting an approval from at least one maintainer. +2. Create a new GitHub Release + 1. Navigate to the [Releases page](https://github.com/slackapi/python-slack-sdk/releases). + 2. Click the "Draft a new release" button. + 3. Set the "Target" to the `main` branch. + 4. Click "Tag: Select tag" + 5. Input a new tag name manually. The tag name must match the version in `slack_sdk/version.py` prefixed with "v" (e.g., if version is `1.2.3`, enter `v1.2.3`) + 6. Click the "Create a new tag" button. This won't create your tag immediately. + 7. Click the "Generate release notes" button. + 8. The release name should match the tag name! + 9. Edit the resulting notes to ensure they have decent messaging that is understandable by non-contributors, but each commit should still have its own line. + 10. Include a link to the current GitHub Milestone. + 11. Ensure the "latest release" checkbox is checked to mark this as the latest stable release. + 12. Publish the release by clicking the "Publish release" button! +3. Navigate to the [release workflow run](https://github.com/slackapi/python-slack-sdk/actions/workflows/pypi-release.yml). You will need to approve the deployment! +4. After a few minutes, the corresponding version will be available on . +5. Close the current GitHub Milestone and create one for the next patch version. +6. (Slack Internal) Communicate the release internally + - Include a link to the GitHub release +7. (Slack Internal) Tweet by @SlackAPI + - Not necessary for patch updates, might be needed for minor updates, + definitely needed for major updates. Include a link to the GitHub release ## Workflow ### Versioning and Tags -This project uses semantic versioning, expressed through the numbering scheme of +This project uses [Semantic Versioning](http://semver.org/), expressed through the numbering scheme of [PEP-0440](https://www.python.org/dev/peps/pep-0440/). ### Branches diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index db43ca9d6..ae9cb65ab 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,20 +1,28 @@ ## Summary -(Describe the goal of this PR. Mention any related Issue numbers) + -### Category (place an `x` in each of the `[ ]`) +### Testing -- [ ] **slack_sdk.web.WebClient** (Web API client) -- [ ] **slack_sdk.webhook.WebhookClient** (Incoming Webhook, response_url sender) -- [ ] **slack_sdk.models** (UI component builders) -- [ ] **slack_sdk.oauth** (OAuth Flow Utilities) -- [ ] **slack_sdk.rtm.RTMClient** (RTM client) + + +### Category + +- [ ] **slack_sdk.web.WebClient (sync/async)** (Web API client) +- [ ] **slack_sdk.webhook.WebhookClient (sync/async)** (Incoming Webhook, response_url sender) +- [ ] **slack_sdk.socket_mode** (Socket Mode client) - [ ] **slack_sdk.signature** (Request Signature Verifier) -- [ ] `/docs-src` (Documents, have you run `./docs.sh`?) -- [ ] `/docs-src-v2` (Documents, have you run `./docs-v2.sh`?) +- [ ] **slack_sdk.oauth** (OAuth Flow Utilities) +- [ ] **slack_sdk.models** (UI component builders) +- [ ] **slack_sdk.scim** (SCIM API client) +- [ ] **slack_sdk.audit_logs** (Audit Logs API client) +- [ ] **slack_sdk.rtm_v2** (RTM client) +- [ ] `/docs` (Documents) +- [ ] `/tutorial` (PythOnBoardingBot tutorial) +- [ ] `tests`/`integration_tests` (Automated tests for this library) -## Requirements (place an `x` in each `[ ]`) +## Requirements - [ ] I've read and understood the [Contributing Guidelines](https://github.com/slackapi/python-slack-sdk/blob/main/.github/contributing.md) and have done my best effort to follow them. - [ ] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). -- [ ] I've run `python setup.py validate` after making the changes. +- [ ] I've run `python3 -m venv .venv && source .venv/bin/activate && ./scripts/run_validation.sh` after making the changes. diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 000000000..b2574b7cc --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,24 @@ +# https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes#configuring-automatically-generated-release-notes +changelog: + categories: + - title: πŸš€ Enhancements + labels: + - enhancement + - title: πŸ› Bug Fixes + labels: + - bug + - title: πŸ“š Documentation + labels: + - docs + - title: πŸ€– Build + labels: + - build + - title: πŸ§ͺ Testing/Code Health + labels: + - code health + - title: πŸ”’ Security + labels: + - security + - title: πŸ“¦ Other changes + labels: + - "*" diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 68f732657..c0fd021f0 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -1,36 +1,134 @@ -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions -name: CI Build +name: Python CI on: push: - branches: [ main ] + branches: + - main pull_request: - branches: [ main ] + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +env: + LATEST_SUPPORTED_PY: "3.14" jobs: - build: + lint: + name: Lint + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} + uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 + with: + python-version: ${{ env.LATEST_SUPPORTED_PY }} + - name: Run lint verification + run: ./scripts/lint.sh + + typecheck: + name: Typecheck runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} + uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 + with: + python-version: ${{ env.LATEST_SUPPORTED_PY }} + - name: Run mypy verification + run: ./scripts/run_mypy.sh + + unittest: + name: Unit tests + runs-on: ubuntu-22.04 + timeout-minutes: 15 strategy: + fail-fast: false matrix: - python-version: ['3.6', '3.7', '3.8', '3.9'] + python-version: + - "3.14" + - "3.13" + - "3.12" + - "3.11" + - "3.10" + - "3.9" + - "3.8" + - "3.7" + - "pypy3.10" + - "pypy3.11" + permissions: + contents: read + env: + CI_LARGE_SOCKET_MODE_PAYLOAD_TESTING_DISABLED: "1" + FORCE_COLOR: "1" + steps: + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - name: Install dependencies + run: | + pip install -U pip + pip install -r requirements/testing.txt + pip install -r requirements/optional.txt + - name: Run tests + run: | + PYTHONPATH=$PWD:$PYTHONPATH pytest --cov-report=xml --cov=slack_sdk/ --junitxml=reports/test_report.xml tests/ + - name: Run tests for SQLAlchemy v1.4 (backward-compatibility) + run: | + # Install v1.4 for testing + pip install "SQLAlchemy>=1.4,<2" + PYTHONPATH=$PWD:$PYTHONPATH pytest tests/slack_sdk/oauth/installation_store/test_sqlalchemy.py + PYTHONPATH=$PWD:$PYTHONPATH pytest tests/slack_sdk/oauth/state_store/test_sqlalchemy.py + - name: Upload test results to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + with: + directory: ./reports/ + fail_ci_if_error: true + flags: ${{ matrix.python-version }} + report_type: test_results + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true + - name: Upload test coverage to Codecov (only with latest supported version) + if: startsWith(matrix.python-version, env.LATEST_SUPPORTED_PY) + uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + with: + fail_ci_if_error: true + # Run validation generates the coverage file + files: ./coverage.xml + report_type: coverage + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true + notifications: + name: Regression notifications + runs-on: ubuntu-latest + needs: + - lint + - typecheck + - unittest + if: ${{ !success() && github.ref == 'refs/heads/main' && github.event_name != 'workflow_dispatch' }} steps: - - uses: actions/checkout@v2 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - pip install -U pip wheel - pip install -e ".[testing]" - pip install "aiohttp>=3,<4" - - name: Run validation - run: | - python setup.py validate - - name: Run codecov - run: | - python_version=`python -V` - if [ ${python_version:7:3} == "3.8" ]; then - codecov -e ${python_version:7} - fi + - name: Send notifications of failing tests + uses: slackapi/slack-github-action@91efab103c0de0a537f72a35f6b8cda0ee76bf0a # v2.1.1 + with: + errors: true + webhook: ${{ secrets.SLACK_REGRESSION_FAILURES_WEBHOOK_URL }} + webhook-type: webhook-trigger + payload: | + action_url: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" + repository: "${{ github.repository }}" diff --git a/.github/workflows/pypi-release.yml b/.github/workflows/pypi-release.yml new file mode 100644 index 000000000..89a18c827 --- /dev/null +++ b/.github/workflows/pypi-release.yml @@ -0,0 +1,87 @@ +name: Upload A Release to pypi.org or test.pypi.org + +on: + release: + types: + - published + workflow_dispatch: + inputs: + dry_run: + description: "Dry run (build only, do not publish)" + required: false + type: boolean + +jobs: + release-build: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + with: + ref: ${{ github.event.release.tag_name || github.ref }} + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0 + with: + python-version: "3.x" + + - name: Build release distributions + run: | + scripts/build_pypi_package.sh + + - name: Persist dist folder + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 + with: + name: release-dist + path: dist/ + + test-pypi-publish: + runs-on: ubuntu-latest + needs: + - release-build + # Run this job for workflow_dispatch events when dry_run input is not 'true' + # Note: The comparison is against a string value 'true' since GitHub Actions inputs are strings + if: github.event_name == 'workflow_dispatch' && github.event.inputs.dry_run != 'true' + environment: + name: testpypi + permissions: + id-token: write + + steps: + - name: Retrieve dist folder + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: release-dist + path: dist/ + + - name: Publish release distributions to test.pypi.org + # Using OIDC for PyPI publishing (no API tokens needed) + # See: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-pypi + uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0 + with: + repository-url: https://test.pypi.org/legacy/ + + pypi-publish: + runs-on: ubuntu-latest + needs: + - release-build + if: github.event_name == 'release' + environment: + name: pypi + permissions: + id-token: write + + steps: + - name: Retrieve dist folder + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: release-dist + path: dist/ + + - name: Publish release distributions to pypi.org + # Using OIDC for PyPI publishing (no API tokens needed) + # See: https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-pypi + uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e # v1.13.0 diff --git a/.github/workflows/triage-issues.yml b/.github/workflows/triage-issues.yml new file mode 100644 index 000000000..cf13d3afc --- /dev/null +++ b/.github/workflows/triage-issues.yml @@ -0,0 +1,32 @@ +# This workflow uses the following github action to automate +# management of stale issues and prs in this repo: +# https://github.com/marketplace/actions/close-stale-issues + +name: Close stale issues and PRs + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * 1" + +jobs: + stale: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10.1.1 + with: + days-before-issue-stale: 30 + days-before-issue-close: 10 + days-before-pr-stale: -1 + days-before-pr-close: -1 + stale-issue-label: auto-triage-stale + stale-issue-message: πŸ‘‹ It looks like this issue has been open for 30 days with no activity. We'll mark this as stale for now, and wait 10 days for an update or for further comment before closing this issue out. If you think this issue needs to be prioritized, please comment to get the thread going again! Maintainers also review issues marked as stale on a regular basis and comment or adjust status if the issue needs to be reprioritized. + close-issue-message: As this issue has been inactive for more than one month, we will be closing it. Thank you to all the participants! If you would like to raise a related issue, please create a new issue which includes your specific details and references this issue number. + exempt-issue-labels: auto-triage-skip + exempt-all-milestones: true + remove-stale-when-updated: true + enable-statistics: true + operations-per-run: 60 diff --git a/.gitignore b/.gitignore index 092f6afd4..5f316a341 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,6 @@ # general things to ignore build/ dist/ -docs/_sources/ -docs/.doctrees -docs-v2/_sources/ -docs-v2/.doctrees .eggs/ *.egg-info/ *.egg @@ -15,12 +11,15 @@ __pycache__/ # virtualenv env*/ -venv/ +venv*/ +.venv*/ +.env*/ # codecov / coverage .coverage* cov_* coverage.xml +reports/ # due to using tox and pytest .tox @@ -38,3 +37,5 @@ tmp.txt logs/ .pytype/ +*.db +.env* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3b434f2e7..000000000 --- a/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -dist: xenial -language: python -python: - - "3.6" - - "3.7" - - "3.8" - - "3.9" -install: - - python setup.py install - - pip install -e ".[testing]" -script: - - pip install "aiohttp>=3,<4" - - travis_retry python setup.py validate - # TODO: Enable this - # - if git status --porcelain | grep .; then git --no-pager diff; exit 1; fi -after_success: - - codecov -e $TRAVIS_PYTHON_VERSION diff --git a/LICENSE b/LICENSE index 73da6e975..a63845785 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015-2016 Slack Technologies, Inc +Copyright (c) 2015- Slack Technologies, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md old mode 100755 new mode 100644 index ff523b21c..2d0638e7d --- a/README.md +++ b/README.md @@ -1,31 +1,46 @@ -# Python Slack SDK +

Python Slack SDK

+ +

+ + Tests + + Codecov + + Pepy Total Downloads +
+ + PyPI - Version + + Python Versions + + Documentation +

The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slack’s APIs. They are small and powerful when used independently, and work seamlessly when used together, too. -**Comprehensive documentation on using the Slack Python can be found at [https://slack.dev/python-slack-sdk/](https://slack.dev/python-slack-sdk/)** +**Comprehensive documentation on using the Slack Python can be found at [https://docs.slack.dev/tools/python-slack-sdk/](https://docs.slack.dev/tools/python-slack-sdk/)** -[![pypi package][pypi-image]][pypi-url] -[![Build Status][build-image]][build-url] -[![Python Version][python-version]][pypi-url] -[![codecov][codecov-image]][codecov-url] -[![contact][contact-image]][contact-url] +--- Whether you're building a custom app for your team, or integrating a third party service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility of Python to get your project up and running as quickly as possible. The **Python Slack SDK** allows interaction with: -- `slack_sdk.web`: for calling the Slack Web API methods ([API Docs site][api-methods]) -- `slack_sdk.webhook`: for utilizing the Incoming Webhooks and `response_url`s in payloads -- `slack_sdk.signature`: for verifying incoming requests from the Slack API server -- `slack_sdk.oauth`: for implementing the Slack OAuth flow -- `slack_sdk.models`: for constructing UI components using easy-to-use builders +- `slack_sdk.web`: for calling the [Web API methods][api-methods] +- `slack_sdk.webhook`: for utilizing the [Incoming Webhooks](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/) and [`response_url`s in payloads](https://docs.slack.dev/interactivity/handling-user-interaction/#message_responses) +- `slack_sdk.signature`: for [verifying incoming requests from the Slack API server](https://docs.slack.dev/authentication/verifying-requests-from-slack/) +- `slack_sdk.socket_mode`: for receiving and sending messages over [Socket Mode](https://docs.slack.dev/apis/events-api/using-socket-mode/) connections +- `slack_sdk.audit_logs`: for utilizing [Audit Logs APIs](https://docs.slack.dev/admins/audit-logs-api/) +- `slack_sdk.scim`: for utilizing [SCIM APIs](https://docs.slack.dev/admins/scim-api/) +- `slack_sdk.oauth`: for implementing the [Slack OAuth flow](https://docs.slack.dev/authentication/installing-with-oauth/) +- `slack_sdk.models`: for constructing [Block Kit](https://docs.slack.dev/block-kit/) UI components using easy-to-use builders - `slack_sdk.rtm`: for utilizing the [RTM API][rtm-docs] -If you want to use our [Events API][events-docs] and Interactivity features, please check the [Bolt for Python][bolt-python] library. Details on the Tokens and Authentication can be found in our [Auth Guide](https://slack.dev/python-slack-sdk/auth.html). +If you want to use our [Events API][events-docs] and Interactivity features, please check the [Bolt for Python][bolt-python] library. Details on the Tokens and Authentication can be found in our [Auth Guide](https://docs.slack.dev/tools/python-slack-sdk/installation/). ## slackclient is in maintenance mode -Are you looking for [slackclient](https://pypi.org/project/slackclient/)? The website is live [here](https://slack.dev/python-slackclient/) just like before. However, the slackclient project is in maintenance mode now and this [`slack_sdk`](https://pypi.org/project/slack-sdk/) is the successor. If you have time to make a migration to slack_sdk v3, please follow [our migration guide](https://slack.dev/python-slack-sdk/v3-migration/) to ensure your app continues working after updating. +Are you looking for [slackclient](https://pypi.org/project/slackclient/)? The slackclient project is in maintenance mode now and this [`slack_sdk`](https://pypi.org/project/slack-sdk/) is the successor. If you have time to make a migration to slack_sdk v3, please follow [our migration guide](https://docs.slack.dev/tools/python-slack-sdk/v3-migration/) to ensure your app continues working after updating. ## Table of contents @@ -35,7 +50,6 @@ Are you looking for [slackclient](https://pypi.org/project/slackclient/)? The we * [Basic Usage of the Web Client](#basic-usage-of-the-web-client) * [Sending a message to Slack](#sending-a-message-to-slack) * [Uploading files to Slack](#uploading-files-to-slack) -* [Basic Usage of the RTM Client](#basic-usage-of-the-rtm-client) * [Async usage](#async-usage) * [WebClient as a script](#asyncwebclient-in-a-script) * [WebClient in a framework](#asyncwebclient-in-a-framework) @@ -46,12 +60,13 @@ Are you looking for [slackclient](https://pypi.org/project/slackclient/)? The we * [Example](#example) * [Migrating from v1](#migrating-from-v1) * [Support](#support) +* [Development](#development) ### Requirements --- -This library requires Python 3.6 and above. If you require Python 2, please use our [SlackClient - v1.x][slackclientv1]. If you're unsure how to check what version of Python you're on, you can check it using the following: +This library requires Python 3.7 and above. If you're unsure how to check what version of Python you're on, you can check it using the following: > **Note:** You may need to use `python3` before your commands to ensure you use the correct Python path. e.g. `python3 --version` @@ -75,15 +90,15 @@ $ pip install slack_sdk --- -We've created this [tutorial](/tutorial) to build a basic Slack app in less than 10 minutes. It requires some general programming knowledge, and Python basics. It focuses on the interacting with Slack's Web and RTM API. Use it to give you an idea of how to use this SDK. +We've created this [tutorial](https://github.com/slackapi/python-slack-sdk/tree/main/tutorial) to build a basic Slack app in less than 10 minutes. It requires some general programming knowledge, and Python basics. It focuses on the interacting with the Slack Web API and RTM API. Use it to give you an idea of how to use this SDK. -**[Read the tutorial to get started!](/tutorial)** +**[Read the tutorial to get started!](https://github.com/slackapi/python-slack-sdk/tree/main/tutorial)** ### Basic Usage of the Web Client --- -Slack provide a Web API that gives you the ability to build applications that interact with Slack in a variety of ways. This Development Kit is a module based wrapper that makes interaction with that API easier. We have a basic example here with some of the more common uses but a full list of the available methods are available [here][api-methods]. More detailed examples can be found in [our guide](https://slack.dev/python-slack-sdk/web/). +Slack provide a Web API that gives you the ability to build applications that interact with Slack in a variety of ways. This Development Kit is a module based wrapper that makes interaction with that API easier. We have a basic example here with some of the more common uses but a full list of the available methods are available [here][api-methods]. More detailed examples can be found in [our guide](https://docs.slack.dev/tools/python-slack-sdk/web/). #### Sending a message to Slack @@ -104,13 +119,16 @@ except SlackApiError as e: assert e.response["ok"] is False assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' print(f"Got an error: {e.response['error']}") + # Also receive a corresponding status_code + assert isinstance(e.response.status_code, int) + print(f"Received a response status_code: {e.response.status_code}") ``` Here we also ensure that the response back from Slack is a successful one and that the message is the one we sent by using the `assert` statement. #### Uploading files to Slack -We've changed the process for uploading files to Slack to be much easier and straight forward. You can now just include a path to the file directly in the API call and upload it that way. You can find the details on this api call [here][files.upload] +We've changed the process for uploading files to Slack to be much easier and straight forward. You can now just include a path to the file directly in the API call and upload it that way. ```python import os @@ -121,7 +139,7 @@ client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) try: filepath="./tmp.txt" - response = client.files_upload(channels='#random', file=filepath) + response = client.files_upload_v2(channel='C0123456789', file=filepath) assert response["file"] # the uploaded file except SlackApiError as e: # You will get a SlackApiError if "ok" is False @@ -130,13 +148,15 @@ except SlackApiError as e: print(f"Got an error: {e.response['error']}") ``` +More details on the `files_upload_v2` method can be found [here][files_upload_v2]. + ### Async usage `AsyncWebClient` in this SDK requires [AIOHttp][aiohttp] under the hood for asynchronous requests. #### AsyncWebClient in a script -```python +```python import asyncio import os from slack_sdk.web.async_client import AsyncWebClient @@ -247,7 +267,7 @@ print(response) If you're migrating from slackclient v2.x of slack_sdk to v3.x, Please follow our migration guide to ensure your app continues working after updating. -**[Check out the Migration Guide here!](https://slack.dev/python-slack-sdk/v3-migration/)** +**[Check out the Migration Guide here!](https://docs.slack.dev/tools/python-slack-sdk/v3-migration/)** ### Migrating from v1 @@ -264,25 +284,22 @@ If you get stuck, we’re here to help. The following are the best ways to get a Use our [Github Issue Tracker][gh-issues] for reporting bugs or requesting features. Visit the [Slack Community][slack-community] for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers. +### Contributing + +We welcome contributions from everyone! Please check out our +[Contributor's Guide](.github/contributing.md) for how to contribute in a +helpful and collaborative way. + -[pypi-image]: https://badge.fury.io/py/slack-sdk.svg -[pypi-url]: https://pypi.org/project/slack-sdk/ -[python-version]: https://img.shields.io/pypi/pyversions/slack-sdk.svg -[build-image]: https://github.com/slackapi/python-slack-sdk/workflows/CI%20Build/badge.svg -[build-url]: https://github.com/slackapi/python-slack-sdk/actions?query=workflow%3A%22CI+Build%22 -[codecov-image]: https://codecov.io/gh/slackapi/python-slack-sdk/branch/main/graph/badge.svg -[codecov-url]: https://codecov.io/gh/slackapi/python-slack-sdk -[contact-image]: https://img.shields.io/badge/contact-support-green.svg -[contact-url]: https://slack.com/support [slackclientv1]: https://github.com/slackapi/python-slackclient/tree/v1 -[api-methods]: https://api.slack.com/methods -[rtm-docs]: https://api.slack.com/rtm -[events-docs]: https://api.slack.com/events-api +[api-methods]: https://docs.slack.dev/reference/methods +[rtm-docs]: https://docs.slack.dev/legacy/legacy-rtm-api/ +[events-docs]: https://docs.slack.dev/apis/events-api/ [bolt-python]: https://github.com/slackapi/bolt-python [pypi]: https://pypi.org/ [gh-issues]: https://github.com/slackapi/python-slack-sdk/issues -[slack-community]: http://slackcommunity.com/ -[files.upload]: https://api.slack.com/methods/files.upload +[slack-community]: https://slackcommunity.com/ +[files_upload_v2]: https://github.com/slackapi/python-slack-sdk/releases/tag/v3.19.0 [aiohttp]: https://aiohttp.readthedocs.io/ -[urllib]: https://docs.python.org/3/library/urllib.request.html + diff --git a/codecov.yml b/codecov.yml index b24c2afb1..5568e5e6b 100644 --- a/codecov.yml +++ b/codecov.yml @@ -2,7 +2,7 @@ coverage: status: project: default: - threshold: 0.3% + threshold: 2.0% patch: default: target: 50% diff --git a/docs-src-v2/.gitignore b/docs-src-v2/.gitignore deleted file mode 100644 index e35d8850c..000000000 --- a/docs-src-v2/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build diff --git a/docs-src-v2/Makefile b/docs-src-v2/Makefile deleted file mode 100644 index ecbc9e80a..000000000 --- a/docs-src-v2/Makefile +++ /dev/null @@ -1,225 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = ../docs/ - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . -# the i18n builder cannot share the environment and doctrees with the others -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " applehelp to make an Apple Help Book" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " epub3 to make an epub3" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " texinfo to make Texinfo files" - @echo " info to make Texinfo files and run them through makeinfo" - @echo " gettext to make PO message catalogs" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " xml to make Docutils-native XML files" - @echo " pseudoxml to make pseudoxml-XML files for display purposes" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - @echo " coverage to run coverage check of the documentation (if enabled)" - @echo " dummy to check syntax errors of document sources" - -.PHONY: clean -clean: - rm -rf $(BUILDDIR)/* - -.PHONY: html -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -.PHONY: dirhtml -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -.PHONY: singlehtml -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -.PHONY: pickle -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -.PHONY: json -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -.PHONY: htmlhelp -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -.PHONY: qthelp -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-slackclient.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-slackclient.qhc" - -.PHONY: applehelp -applehelp: - $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp - @echo - @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." - @echo "N.B. You won't be able to view it unless you put it in" \ - "~/Library/Documentation/Help or install it in your application" \ - "bundle." - -.PHONY: devhelp -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/python-slackclient" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-slackclient" - @echo "# devhelp" - -.PHONY: epub -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -.PHONY: epub3 -epub3: - $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 - @echo - @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." - -.PHONY: latex -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -.PHONY: latexpdf -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: latexpdfja -latexpdfja: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through platex and dvipdfmx..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -.PHONY: text -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -.PHONY: man -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -.PHONY: texinfo -texinfo: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo - @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." - @echo "Run \`make' in that directory to run these through makeinfo" \ - "(use \`make info' here to do that automatically)." - -.PHONY: info -info: - $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo - @echo "Running Texinfo files through makeinfo..." - make -C $(BUILDDIR)/texinfo info - @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." - -.PHONY: gettext -gettext: - $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale - @echo - @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." - -.PHONY: changes -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -.PHONY: linkcheck -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -.PHONY: doctest -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." - -.PHONY: coverage -coverage: - $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage - @echo "Testing of coverage in the sources finished, look at the " \ - "results in $(BUILDDIR)/coverage/python.txt." - -.PHONY: xml -xml: - $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml - @echo - @echo "Build finished. The XML files are in $(BUILDDIR)/xml." - -.PHONY: pseudoxml -pseudoxml: - $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml - @echo - @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." - -.PHONY: dummy -dummy: - $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy - @echo - @echo "Build finished. Dummy builder generates no files." diff --git a/docs-src-v2/_themes/slack/conf.py b/docs-src-v2/_themes/slack/conf.py deleted file mode 100644 index 61eee861c..000000000 --- a/docs-src-v2/_themes/slack/conf.py +++ /dev/null @@ -1,342 +0,0 @@ -# -*- coding: utf-8 -*- -# -# python-slackclient documentation build configuration file, created by -# sphinx-quickstart on Mon Jun 27 17:36:09 2016. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os -import sys -sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.coverage', -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['../../_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.rst' - -# The encoding of source files. -# -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'slackclient (Legacy Python Slack SDK)' -copyright = u'2015–2016 Slack Technologies, Inc. and contributors' -author = u'Slack Technologies, Inc. and contributors' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = u'1.0' -# The full version, including alpha/beta/rc tags. -release = u'1.0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# -# today = '' -# -# Else, today_fmt is used as the format for a strftime call. -# -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'emacs' - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "slack" -html_theme_path = ["../../_themes", ] - -highlight_language = "python" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. -# " v documentation" by default. -# -# html_title = u'python-slackclient v1.0.1' - -# A shorter title for the navigation bar. Default is the same as html_title. -# -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# -# html_logo = None - -# The name of an image file (relative to this directory) to use as a favicon of -# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['static'] - -html_context = { - 'css_files': ['static/pygments.css'], -} - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# -# html_extra_path = [] - -# If not None, a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -# The empty string is equivalent to '%b %d, %Y'. -# -# html_last_updated_fmt = None - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# -# html_additional_pages = {} - -# If false, no module index is generated. -# -# html_domain_indices = True - -# If false, no index is generated. -# -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' -# -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# 'ja' uses this config value. -# 'zh' user can custom change `jieba` dictionary path. -# -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'python-slackclientdoc' - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'python-slackclient.tex', u'python-slackclient Documentation', - u'Ryan Huber, Jeff Ammons', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# -# latex_use_parts = False - -# If true, show page references after internal links. -# -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# -# latex_appendices = [] - -# If false, no module index is generated. -# -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'python-slackclient', u'python-slackclient Documentation', - [author], 1) -] - -# If true, show URL addresses after external links. -# -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'python-slackclient', u'python-slackclient Documentation', - author, 'python-slackclient', 'A basic client for Slack.com, which can optionally connect to the Slack Real Time Messaging (RTM) API.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -# -# texinfo_appendices = [] - -# If false, no module index is generated. -# -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# -# texinfo_no_detailmenu = False diff --git a/docs-src-v2/_themes/slack/layout.html b/docs-src-v2/_themes/slack/layout.html deleted file mode 100644 index 6c336bc06..000000000 --- a/docs-src-v2/_themes/slack/layout.html +++ /dev/null @@ -1,169 +0,0 @@ - - - - - {{ - metatags - }} - - {%- block htmltitle %} - {{ title|striptags|e + " — "|safe + project|e }} - {%- endblock %} {%- macro css() %} - - - - - - {%- endmacro %} - - - - - {{ - css() - }} - {%- block linktags %} - - - {%- endblock %} - - - - - - - - {%- block header %} -
- - - - - - - {{ project }} - - -
- {% endblock %} - -
-
- - - - - -
- -
- {%- block body %} - {{ body }} - {% endblock %} -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-src-v2/_themes/slack/localtoc.html b/docs-src-v2/_themes/slack/localtoc.html deleted file mode 100644 index e0ffc3f4f..000000000 --- a/docs-src-v2/_themes/slack/localtoc.html +++ /dev/null @@ -1,4 +0,0 @@ -
Table of Contents?
-
    - {{ toc }} -
\ No newline at end of file diff --git a/docs-src-v2/_themes/slack/relations.html b/docs-src-v2/_themes/slack/relations.html deleted file mode 100644 index e3faec04a..000000000 --- a/docs-src-v2/_themes/slack/relations.html +++ /dev/null @@ -1,19 +0,0 @@ -{# - basic/relations.html - ~~~~~~~~~~~~~~~~~~~~ - - Sphinx sidebar template: relation links. - - :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- if prev %} -

{{ _('Previous topic') }}

-

{{ prev.title }}

-{%- endif %} -{%- if next %} -

{{ _('Next topic') }}

-

{{ next.title }}

-{%- endif %} diff --git a/docs-src-v2/_themes/slack/sidebar.html b/docs-src-v2/_themes/slack/sidebar.html deleted file mode 100644 index 2ca9f37d1..000000000 --- a/docs-src-v2/_themes/slack/sidebar.html +++ /dev/null @@ -1,15 +0,0 @@ -{{ toctree(maxdepth=-1, collapse=False,includehidden=True) }} - - diff --git a/docs-src-v2/_themes/slack/static/default.css_t b/docs-src-v2/_themes/slack/static/default.css_t deleted file mode 100644 index b7221ce92..000000000 --- a/docs-src-v2/_themes/slack/static/default.css_t +++ /dev/null @@ -1,79 +0,0 @@ -a.headerlink { - display: none !important; -} - -h2 { - margin-top: -120px; - padding-top: 120px; -} - -.section-title { - font-size: 2rem; - line-height: 2.5rem; - letter-spacing: -1px; - font-weight: 700; - margin: 0 0 1rem; -} - -nav#api_nav .toctree-l1 { - margin-bottom: 1.5rem; -} - -nav#api_nav #api_sections ul { - list-style: none; - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l1>a { - color: #1264a3; - letter-spacing: 0; - font-size: .8rem; - font-weight: 800; - text-transform: uppercase; - border: none; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 { - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 a { - color: #1d1c1d; - text-transform: none; - font-weight: inherit; - padding: 0; - display: block; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - font-size: 15px!important; - line-height:15px; - padding: 4px 8px; - border: 1px solid transparent; - border-radius: 4px; -} - -nav#api_nav #api_sections ul li.toctree-l2 a:hover { - cursor: pointer; - text-decoration: none; - background-color:#e8f5fa; - border-color:#dcf0fb; -} - -nav#api_nav #footer #footer_nav { - font-size: .9375rem; -} - -nav#api_nav #footer #footer_nav a { - border: none; - padding: 0; - color: #616061; -} - -nav#api_nav #footer #footer_nav a:hover { - text-decoration: none; - color: #1c1c1c; -} diff --git a/docs-src-v2/_themes/slack/static/docs.css_t b/docs-src-v2/_themes/slack/static/docs.css_t deleted file mode 100644 index 7f360ac66..000000000 --- a/docs-src-v2/_themes/slack/static/docs.css_t +++ /dev/null @@ -1,34 +0,0 @@ -/* Updates body font */ -body { - font-family: Slack-Lato,appleLogo,sans-serif; -} - -/* Replaces old sidebar styled links */ -.sidebar_menu h5 { - font-size: 0.8rem; - font-weight: 800; - margin-bottom: 3px; -} - -/* Aligns footer navigation to the left of the sidebar */ -.footer_nav { - margin: 0 !important; -} - -/* Styles the signature all nice and pretty <3 */ -#footer_signature { - color:#e01e5a; - font-size:.9rem; - margin-top: 10px; -} - -/* Fixes link hover state */ -a:hover { - text-decoration: underline; -} - -/* Makes footer consistent */ -footer { - background-color: transparent; - border: 0; -} \ No newline at end of file diff --git a/docs-src-v2/_themes/slack/static/pygments.css_t b/docs-src-v2/_themes/slack/static/pygments.css_t deleted file mode 100644 index a94b170ff..000000000 --- a/docs-src-v2/_themes/slack/static/pygments.css_t +++ /dev/null @@ -1,60 +0,0 @@ -.highlight .hll { background-color: #ffffcc } -.highlight { background: #ffffff; } -.highlight .c { color: #999988; font-style: italic } /* Comment */ -.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ -.highlight .k { font-weight: bold } /* Keyword */ -.highlight .o { font-weight: bold } /* Operator */ -.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ -.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ -.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ -.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ -.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ -.highlight .ge { font-style: italic } /* Generic.Emph */ -.highlight .gr { color: #aa0000 } /* Generic.Error */ -.highlight .gh { color: #999999 } /* Generic.Heading */ -.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ -.highlight .go { color: #888888 } /* Generic.Output */ -.highlight .gp { color: #555555 } /* Generic.Prompt */ -.highlight .gs { font-weight: bold } /* Generic.Strong */ -.highlight .gu { color: #aaaaaa } /* Generic.Subheading */ -.highlight .gt { color: #aa0000 } /* Generic.Traceback */ -.highlight .kc { font-weight: bold } /* Keyword.Constant */ -.highlight .kd { font-weight: bold } /* Keyword.Declaration */ -.highlight .kn { font-weight: bold } /* Keyword.Namespace */ -.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ -.highlight .kr { font-weight: bold } /* Keyword.Reserved */ -.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ -.highlight .m { color: #009999 } /* Literal.Number */ -.highlight .s { color: #bb8844 } /* Literal.String */ -.highlight .na { color: #008080 } /* Name.Attribute */ -.highlight .nb { color: #999999 } /* Name.Builtin */ -.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ -.highlight .no { color: #008080 } /* Name.Constant */ -.highlight .ni { color: #800080 } /* Name.Entity */ -.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ -.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ -.highlight .nn { color: #555555 } /* Name.Namespace */ -.highlight .nt { color: #000080 } /* Name.Tag */ -.highlight .nv { color: #008080 } /* Name.Variable */ -.highlight .ow { font-weight: bold } /* Operator.Word */ -.highlight .w { color: #bbbbbb } /* Text.Whitespace */ -.highlight .mf { color: #009999 } /* Literal.Number.Float */ -.highlight .mh { color: #009999 } /* Literal.Number.Hex */ -.highlight .mi { color: #009999 } /* Literal.Number.Integer */ -.highlight .mo { color: #009999 } /* Literal.Number.Oct */ -.highlight .sb { color: #bb8844 } /* Literal.String.Backtick */ -.highlight .sc { color: #bb8844 } /* Literal.String.Char */ -.highlight .sd { color: #bb8844 } /* Literal.String.Doc */ -.highlight .s2 { color: #bb8844 } /* Literal.String.Double */ -.highlight .se { color: #bb8844 } /* Literal.String.Escape */ -.highlight .sh { color: #bb8844 } /* Literal.String.Heredoc */ -.highlight .si { color: #bb8844 } /* Literal.String.Interpol */ -.highlight .sx { color: #bb8844 } /* Literal.String.Other */ -.highlight .sr { color: #808000 } /* Literal.String.Regex */ -.highlight .s1 { color: #bb8844 } /* Literal.String.Single */ -.highlight .ss { color: #bb8844 } /* Literal.String.Symbol */ -.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ -.highlight .vc { color: #008080 } /* Name.Variable.Class */ -.highlight .vg { color: #008080 } /* Name.Variable.Global */ -.highlight .vi { color: #008080 } /* Name.Variable.Instance */ -.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ diff --git a/docs-src-v2/_themes/slack/theme.conf b/docs-src-v2/_themes/slack/theme.conf deleted file mode 100644 index b13de3cbb..000000000 --- a/docs-src-v2/_themes/slack/theme.conf +++ /dev/null @@ -1,6 +0,0 @@ -[theme] -inherit = default -stylesheet = default.css -show_sphinx = False - -[options] diff --git a/docs-src-v2/about.rst b/docs-src-v2/about.rst deleted file mode 100644 index 17fad157f..000000000 --- a/docs-src-v2/about.rst +++ /dev/null @@ -1,18 +0,0 @@ -============================================== -About -============================================== - -|product_name| -************** - - -Access the Slack Platform from your Python app. |product_name| lets you build on the Slack Web APIs pythonically. - -|product_name| is proudly maintained with πŸ’– by the Slack Developer Tools team - -- `License`_ -- `Code of Conduct`_ -- `Contributing`_ -- `Contributor License Agreement`_ - -.. include:: metadata.rst \ No newline at end of file diff --git a/docs-src-v2/auth.rst b/docs-src-v2/auth.rst deleted file mode 100644 index 6448bac29..000000000 --- a/docs-src-v2/auth.rst +++ /dev/null @@ -1,136 +0,0 @@ -============================================== -Tokens & Installation -============================================== -.. _handling-tokens: - -Keeping tokens safe -------------------- - -The OAuth token you use to call the Slack API has access to the data on the workspace where it is installed. Depending on the scopes granted to the token, it potentially has the ability to read and write data. Treat these tokens just as you would a password -- don't publish them, don't check them into source code, don't share them with others. - -🚫Avoid this: - -.. code-block:: python - - token = 'xoxb-111-222-xxxxx' - -We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as: - -.. code-block:: python - - SLACK_BOT_TOKEN="xoxb-111-222-xxxxx" python myapp.py - -Then retrieve the key with: - -.. code-block:: python - - import os - SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"] - -For additional information, please see our `Safely Storing Credentials `_ page. - -Single Workspace Install ---------------------------------------- -If you're building an application for a single Slack workspace, there's no need to build out the entire OAuth flow. - -Once you've setup your features, click on the **Install App to Team** button found on the **Install App** page. -If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to -your workspace for changes to take effect. - -For additional information, see the `Installing Apps `_ of our `Building Slack apps `_ page. - -Multiple Workspace Install -------------------------------------------------------- -If you intend for an app to be installed on multiple Slack workspaces, you will need to handle this installation via the industry-standard OAuth protocol. You can read more about `how Slack handles Oauth `_. - -(The OAuth exchange is facilitated via HTTP and requires a webserver; in this example, we'll use `Flask `_.) - -To configure your app for OAuth, you'll need a client ID, a client secret, and a set of one or more scopes that will be applied to the token once it is granted. The client ID and client secret are available from your `app's configuration page `_. The scopes are determined by the functionality of the app -- every method you wish to access has a corresponding scope and your app will need to request that scope in order to be able to access the method. Review Slack's `full list of OAuth scopes `_. - -.. code-block:: python - - import os - from slack import WebClient - from flask import Flask, request - - client_id = os.environ["SLACK_CLIENT_ID"] - client_secret = os.environ["SLACK_CLIENT_SECRET"] - oauth_scope = os.environ["SLACK_SCOPES"] - - app = Flask(__name__) - -**The OAuth initiation link** - -To begin the OAuth flow that will install your app on a workspace, you'll need to provide the user with a link to Slack's OAuth page. This can be a simple link to ``https://slack.com/oauth/v2/authorize`` with ``scope`` and ``client_id`` query parameters, or you can use our pre-built `Add to Slack button `_ to do all the work for you. - -This link directs the user to Slack's OAuth acceptance page, where the user will review and accept or refuse the permissions your app is requesting as defined by the scope(s). - -.. code-block:: python - - @app.route("/slack/install", methods=["GET"]) - def pre_install(): - state = "randomly-generated-one-time-value" - return '' \ - 'Add to Slack' - -**The OAuth completion page** - -Once the user has agreed to the permissions you've requested, Slack will redirect the user to your auth completion page, which includes a ``code`` query string param. You'll use the ``code`` param to call the ``oauth.v2.access`` `endpoint `_ that will finally grant you the token. - -.. code-block:: python - - @app.route("/slack/oauth_redirect", methods=["GET"]) - def post_install(): - # Verify the "state" parameter - - # Retrieve the auth code from the request params - code_param = request.args['code'] - - # An empty string is a valid token for this request - client = WebClient() - - # Request the auth tokens from Slack - response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code_param - ) - -A successful request to ``oauth.v2.access`` will yield a JSON payload with at least one token, a bot token that begins with ``xoxb``. - -.. code-block:: python - - @app.route("/slack/oauth_redirect", methods=["GET"]) - def post_install(): - # Verify the "state" parameter - - # Retrieve the auth code from the request params - code_param = request.args['code'] - - # An empty string is a valid token for this request - client = WebClient() - - # Request the auth tokens from Slack - response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code_param - ) - print(response) - - # Save the bot token to an environmental variable or to your data store - # for later use - os.environ["SLACK_BOT_TOKEN"] = response['access_token'] - - # Don't forget to let the user know that OAuth has succeeded! - return "Installation is completed!" - - if __name__ == "__main__": - app.run("localhost", 3000) - -Once your user has completed the OAuth flow, you'll be able to use the provided tokens to call any of Slack's API methods that require an access token. - -See the `Basic Usage <./basic_usage.html>`_ section of this documentation for usage examples. - -.. include:: metadata.rst diff --git a/docs-src-v2/basic_usage.rst b/docs-src-v2/basic_usage.rst deleted file mode 100644 index 7075e2265..000000000 --- a/docs-src-v2/basic_usage.rst +++ /dev/null @@ -1,494 +0,0 @@ -.. _web-api-examples: - -============================================== -Basic Usage -============================================== - -The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations we provide out of the box. - -Access Slack's API methods requires an OAuth token -- see the `Tokens & Authentication `_ section for more on how Slack uses OAuth tokens as well as best practices. - -`Each of these API methods `_ is fully documented on our developer site at api.slack.com - -Sending a message ------------------------ -One of the primary uses of Slack is posting messages to a channel using the channel ID or as a DM to another person using their user ID. This method will handle either a channel ID or a user ID passed to the ``channel`` parameter. - -.. code-block:: python - - import logging - logging.basicConfig(level=logging.DEBUG) - - import os - from slack import WebClient - from slack.errors import SlackApiError - - slack_token = os.environ["SLACK_API_TOKEN"] - client = WebClient(token=slack_token) - - try: - response = client.chat_postMessage( - channel="C0XXXXXX", - text="Hello from your app! :tada:" - ) - except SlackApiError as e: - # You will get a SlackApiError if "ok" is False - assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' - -Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same -as sending a regular message, but with an additional ``user`` parameter. - -.. code-block:: python - - import os - from slack import WebClient - - slack_token = os.environ["SLACK_API_TOKEN"] - client = WebClient(token=slack_token) - - response = client.chat_postEphemeral( - channel="C0XXXXXX", - text="Hello silently from your app! :tada:", - user="U0XXXXXXX" - ) - -See `chat.postEphemeral `_ for more info. - --------- - -Formatting with Block Kit ------------------------------- -Messages posted from apps can contain more than just text, though. They can include full user interfaces composed of `blocks `_. - -The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. Blocks specified in a single object literal, so just add additional keys for any optional argument. - -To send a message to a channel, use the channel's ID. For IMs, use the user's ID. - -.. code-block:: python - - client.chat_postMessage( - channel="C0XXXXXX", - blocks=[ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": "Danny Torrence left the following review for your property:" - } - }, - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": " \n :star: \n Doors had too many axe holes, guest in room " + - "237 was far too rowdy, whole place felt stuck in the 1920s." - }, - "accessory": { - "type": "image", - "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg", - "alt_text": "Haunted hotel image" - } - }, - { - "type": "section", - "fields": [ - { - "type": "mrkdwn", - "text": "*Average Rating*\n1.0" - } - ] - } - ] - ) - -**Note:** You can use the `Block Kit Builder `_ to prototype your message's look and feel. - --------- - -Threading Messages ------------------- -Threaded messages are a way of grouping messages together to provide greater context. You can reply to a thread or start a new threaded conversation by simply passing the original message's ``ts`` ID in the ``thread_ts`` attribute when posting a message. If you're replying to a threaded message, you'll pass the `thread_ts` ID of the message you're replying to. - -A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message. - -.. code-block:: python - - response = client.chat_postMessage( - channel="C0XXXXXX", - thread_ts="1476746830.000003", - text="Hello from your app! :tada:" - ) - -By default, ``reply_broadcast`` is set to ``False``. To indicate your reply is germane to all members of a channel, and therefore a notification of the reply should be posted in-channel, set the ``reply_broadcast`` to ``True``. - -.. code-block:: python - - response = client.chat_postMessage( - channel="C0XXXXXX", - thread_ts="1476746830.000003", - text="Hello from your app! :tada:", - reply_broadcast=True - ) - -**Note:** While threaded messages may contain attachments and message buttons, when your reply is broadcast to the -channel, it'll actually be a reference to your reply, not the reply itself. -So, when appearing in the channel, it won't contain any attachments or message buttons. Also note that updates and -deletion of threaded replies works the same as regular messages. - -See the `Threading messages together `_ -article for more information. - --------- - -Updating a message ----------------------------------- -Let's say you have a bot which posts the status of a request. When that request changes, you'll want to update the message to reflect it's state. - -.. code-block:: python - - response = client.chat_update( - channel="C0XXXXXX", - ts="1476746830.000003", - text="updates from your app! :tada:" - ) - -See `chat.update `_ for formatting options and some special considerations when calling this with a bot user. - --------- - -Deleting a message -------------------- -Sometimes you need to delete things. - -.. code-block:: python - - response = client.chat_delete( - channel="C0XXXXXX", - ts="1476745373.000002" - ) - -See `chat.delete `_ for more info. - --------- - -Opening a modal ----------------------------------- -Modals allow you to collect data from users and display dynamic information in a focused surface. - -Modals use the same blocks that compose messages with the addition of an `input` block. - -.. code-block:: python - - # This module is available since v2.6 - from slack.signature import SignatureVerifier - signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) - - from flask import Flask, request, make_response - app = Flask(__name__) - - @app.route("/slack/events", methods=["POST"]) - def slack_app(): - if not signature_verifier.is_valid_request(request.get_data(), request.headers): - return make_response("invalid request", 403) - - if "payload" in request.form: - payload = json.loads(request.form["payload"]) - - if payload["type"] == "shortcut" \ - and payload["callback_id"] == "open-modal-shortcut": - # Open a new modal by a global shortcut - try: - api_response = client.views_open( - trigger_id=payload["trigger_id"], - view={ - "type": "modal", - "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - return make_response("", 200) - except SlackApiError as e: - code = e.response["error"] - return make_response(f"Failed to open a modal due to {code}", 200) - - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": - # Handle a data submission request from the modal - submitted_data = payload["view"]["state"]["values"] - print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - return make_response("", 200) - - return make_response("", 404) - - if __name__ == "__main__": - # export SLACK_SIGNING_SECRET=*** - # export SLACK_API_TOKEN=xoxb-*** - # export FLASK_ENV=development - # python3 app.py - app.run("localhost", 3000) - -See `views.open `_ more details and additional parameters. - -Also, to run the above example, the following `Slack app configurations `_ are required. - -* Enable **Interactivity** with a valid Request URL: ``https://{your-public-domain}/slack/events`` -* Add a global shortcut with the Callback ID: ``open-modal-shortcut`` - --------- - -Updating and pushing modals ------------------------------- -You can dynamically update a view inside of a modal by calling `views.update` and passing the view ID returned in the previous `views.open` call. - -.. code-block:: python - - private_metadata = "any str data you want to store" - response = client.views_update( - view_id=payload["view"]["id"], - hash=payload["view"]["hash"], - view={ - "type": "modal", - "callback_id": "modal-id", - "private_metadata": private_metadata, - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - -See `views.update `_ for more info. - -If you want to push a new view onto the modal instead of updating an existing view, reference the `views.push `_ documentation. - --------- - -Emoji reactions ---------------------------------------- -You can quickly respond to any message on Slack with an emoji reaction. Reactions can be used for any purpose: voting, checking off to-do items, showing excitement -β€” or just for fun. - -This method adds a reaction (emoji) to an item (``file``, ``file comment``, ``channel message``, ``group message``, or ``direct message``). One of file, file_comment, or the combination of channel and timestamp must be specified. - -.. code-block:: python - - response = client.reactions_add( - channel="C0XXXXXXX", - name="thumbsup", - timestamp="1234567890.123456" - ) - -Removing an emoji reaction is basically the same format, but you'll use ``reactions.remove`` instead of ``reactions.add`` - -.. code-block:: python - - response = client.reactions_remove( - channel="C0XXXXXXX", - name="thumbsup", - timestamp="1234567890.123456" - ) - - -See `reactions.add `_ and `reactions.remove `_ for more info. - --------- - -Listing public channels ---------------------------- -At some point, you'll want to find out what channels are available to your app. This is how you get that list. - -.. code-block:: python - - response = client.conversations_list(types="public_channel") - -Archived channels are included by default. You can exclude them by passing ``exclude_archived=1`` to your request. - -.. code-block:: python - - response = client.conversations_list(exclude_archived=1) - -See `conversations.list `_ for more info. - --------- - -Getting a channel's info -------------------------- -Once you have the ID for a specific channel, you can fetch information about that channel. - -.. code-block:: python - - response = client.conversations_info(channel="C0XXXXXXX") - -See `conversations.info `_ for more info. - --------- - -Joining a channel ------------------- -Channels are the social hub of most Slack teams. Here's how you hop into one: - -.. code-block:: python - - response = client.conversations_join(channel="C0XXXXXXY") - -If you are already in the channel, the response is slightly different. -``already_in_channel`` will be true, and a limited ``channel`` object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user. - -See `conversations.join `_ for more info. - --------- - -Leaving a channel ------------------- -Maybe you've finished up all the business you had in a channel, or maybe you -joined one by accident. This is how you leave a channel. - -.. code-block:: python - - response = client.conversations_leave(channel="C0XXXXXXX") - -See `conversations.leave `_ for more info. - --------- - -Listing team members --------------------- - -.. code-block:: python - - response = client.users_list() - users = response["members"] - user_ids = list(map(lambda u: u["id"], users)) - -See `users.list `_ for more info. - - --------- - -Uploading files ---------------- - -.. code-block:: python - - response = client.files_upload( - channels="C3UKJTQAC", - file="files.pdf", - title="Test upload" - ) - -See `files.upload `_ for more info. - --------- - -Calling any API methods --------------------------- - -This library covers all the public endpoints as the methods in ``WebClient``. That said, you may see a bit delay of the library release. When you're in a hurry, you can directly use ``api_call`` method as below. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ['SLACK_API_TOKEN']) - response = client.api_call( - api_method='chat.postMessage', - json={'channel': '#random','text': "Hello world!"} - ) - assert response["message"]["text"] == "Hello world!" - - --------- - -Web API Rate Limits --------------------- -When posting messages to a channel, Slack allows applications to send no more than one message per channel per second. We allow bursts over that limit for short periods. However, if your app continues to exceed the limit over a longer period of time it will be rate limited. Different API methods have other rate limits -- be sure to `check the limits `_ and test that your application has a graceful fallback if it should hit those limits. - -If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, a JSON object containing the number of calls you have been making, and a Retry-After header containing the number of seconds until you can retry. - -Here's a very basic example of how one might deal with rate limited requests. - -.. code-block:: python - - import os - import time - from slack import WebClient - from slack.errors import SlackApiError - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - - # Simple wrapper for sending a Slack message - def send_slack_message(channel, message): - return client.chat_postMessage( - channel=channel, - text=message - ) - - # Make the API call and save results to `response` - channel = "#random" - message = "Hello, from Python!" - # Do until being rate limited - while True: - try: - response = send_slack_message(channel, message) - except SlackApiError as e: - if e.response["error"] == "ratelimited": - # The `Retry-After` header will tell you how long to wait before retrying - delay = int(e.response.headers['Retry-After']) - print(f"Rate limited. Retrying in {delay} seconds") - time.sleep(delay) - response = send_slack_message(channel, message) - else: - # other errors - raise e - -See the documentation on `Rate Limiting `_ for more info. - -.. include:: metadata.rst - diff --git a/docs-src-v2/changelog.rst b/docs-src-v2/changelog.rst deleted file mode 100644 index 19c504c53..000000000 --- a/docs-src-v2/changelog.rst +++ /dev/null @@ -1,451 +0,0 @@ -============================================== -Changelog -============================================== - -v3.0.0 (2020-11-09) -------------------- - -This is the first stable version of `slack_sdk `_ v3. The remarkable updates in this major version are: - -* Newly added OAuth flow support -* Better Async/sync separation for ``WebClient`` and ``WebhookClient`` -* Renamed packages (from ``slack`` to ``slack_sdk``) with deprecation warnings - -Refer to `v3.0.0 milestone `_ and `the website `_ for details. If you're a slackclient user, the migration guide for `slackclient` v2.x users is available at https://slack.dev/python-slack-sdk/v3-migration/ - -v2.9.3 (2020-10-20) -------------------- - -Refer to `v2.9.3 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [Block Kit] #851 #852 Set default_type for HeaderBlock text - Thanks @fwump38 -2. [Block Kit] #853 #854 Enable to use input blocks in Home tab views - Thanks @fwump38 -3. [RTMClient] #857 #846 RTMClient does not pass timeout value to WebClient - Thanks @Luden @seratch - -v2.9.2 (2020-10-09) -------------------- - -Refer to `v2.9.2 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [Block Kit] #841 Dispatch Action in Input blocks - Thanks @seratch -2. [WebClient] #838 Add apps.event.authorizations.list and other APIs - Thanks @seratch -3. [WebClient][WebhookClient] #829 Improve error body parser to handle no charset responses - Thanks @adamchainz @seratch -4. [Block Kit] #824 Correct text field validation in Header blocks - Thanks @seratch - -v2.9.1 (2020-09-23) -------------------- - -Refer to `v2.9.1 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient][WebhookClient] #820 #821 #822 The proxy option in WebClient/WebhookClient no longer works - Thanks @seratch - -v2.9.0 (2020-09-17) -------------------- - -Refer to `v2.9.0 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] #811 Add workflows.* API support - Thanks @misscoded -2. [WebClient] #810 #809 Only set default filename in files_upload if file is an instance of str - Thanks @csaska - -v2.8.2 (2020-09-04) -------------------- - -Refer to `v2.8.2 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] #795 #794 Add admin.conversations.* API methods in WebClient/AsyncWebClient - Thanks @ruberVulpes -2. [WebClient] #796 Fix a link to the Static options documentation - Thanks @Jamim - -v2.8.1 (2020-08-28) -------------------- - -Refer to `v2.8.1 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] #778 #779 Adding support for View objects for views.push/update/publish - Thanks @ruberVulpes -2. [WebClient] #786 Fix admin.conversations.restrictAccess.* methods to match documentation - Thanks @ruberVulpes - -v2.8.0 (2020-08-06) -------------------- - -Refer to `v2.8.0 milestone `_ to know the complete list of the issues resolved by this release. - -**New Features** - -1. [WebClient] #765 #766 Introduce AsyncWebClient/AsyncWebhookClient providing coroutines - Thanks @seratch -2. [Block Kit] #767 #768 Add "header" block support - Thanks @mwbrooks - -**Updates** - -1. [WebClient] #738 Add HTTP_PROXY, HTTPS_PROXY env variable support in async WebClient - Thanks @iamtofr @seratch -2. [WebClient] #769 #773 Enable User-Agent to have additional info part - Thanks @seratch -3. [WebClient] #770 #771 Fix a bug where ``files.upload``'s file param doesn't accept bytes data - Thanks @seratch - -v2.7.3 (2020-07-20) -------------------- - -Refer to `v2.7.3 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] #754 Fix #729 Add admin.conversations.restrictAccess.*, conversations.mark API - Thanks @ruberVulpes @kian2attari -2. [WebClient] #758 Fix #757 Add admin.usergroups.addTeams, calls.participants.remove API - Thanks @seratch -3. [WebClient] #727 Fix #645 Unclosed client session - Thanks @NoAnyLove @jourdanrodrigues -4. [WebClient] #745 Fix #744 a validation logic bug in DatePickerElement - Thanks @dzudi941 -5. [WebClient] #752 Fix #733 Better error handling when getting TimeoutError in RTMClient#start() - Thanks @liorblob @seratch -6. [WebClient] #751 Fix #718 by handling unexpected response body format - Thanks @jeffbuswell @seratch - -v2.7.2 (2020-06-23) -------------------- - -Refer to `v2.7.2 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] Fix #728 by adding bytearray support in files_upload (sync mode) - Thanks @sofya-salmanova @seratch -2. [WebClient] #726 Fix InputBlock.hint validation failure - Thanks @jourdanrodrigues -3. [WebClient] #723 Correct the default value of InputBlock.label, hint - Thanks @jourdanrodrigues - -v2.7.1 (2020-06-04) -------------------- - -This release includes the fixes for regression bugs in `WebClient` since v2.6.0. Refer to `v2.7.1 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [WebClient] #716 #712 Support timeout in sync sync web clients - Thanks @DanialErfanian @seratch -2. [WebClient] #713 Support custom SSL context in sync sync web clients - Thanks @austinbutler -3. [WebClient] #715 #714 Support proxy in sync sync web clients - Thanks @austinbutler @seratch - -v2.7.0 (2020-06-02) -------------------- - -Refer to `v2.7.0 milestone `_ to know the complete list of the issues resolved by this release. - -**New Features** - -1. [WebhookClient] #707 #270 #531 Add `WebhookClient` for Incoming Webhooks & response_url - Thanks @seratch @chubz @Ambro17 - -**Updates** - -1. [WebClient] #704 #695 Add `calls_*` methods to `WebClient` and `CallBlock` in Block Kit classes - Thanks @seratch -2. [WebClient] #710 #536 Allow Tokens to be specified per request - Thanks @seratch -3. [WebClient] #709 #708 Add default_to_current_conversation in conversations_select elements - Thanks @seratch - -v2.6.2 (2020-05-28) -------------------- - -Refer to `v2.6.2 milestone `_ to know the complete details of this release. - -**Updates** - -1. [WebClient] #705 WebClient's paginated API calls may fail with no params - Thanks @seratch - -v2.6.1 (2020-05-24) -------------------- - -This patch release is a quick fix for #701, a major issue that affected RTMClient users in v2.6.0. The malfunction was introduced by #667 trying to address #558 #619. Those issues were reopened and will be resolved by another approach. Refer to `v2.6.1 milestone `_ to know the complete list of the issues resolved by this release. - -**Updates** - -1. [RTMClient] #701 RTMClient drops some messages when they come in rapid succession - Thanks @pbrackin @seratch - -v2.6.0 (2020-05-21) -------------------- - -Refer to `v2.6.0 milestone `_ to know the complete list of the issues resolved by this release. - -**New Features** - -1. [Block Kit] #659 Add complete supports for Block Kit components and fixed a few existing bugs as well (#500 #519 #623 #632 #635 #639 #676 #699) - Thanks @seratch @diurnalist @ruberVulpes @jeremyschulman @e271828- @RodneyU215 -2. [Signature] #686 Add slack.signature.SignatureVerifier for request verification - Thanks @seratch -3. [WebClient] #682 Add missing Grid admin APIs (`admin.usergroups.*`, `admin.users.*`, `admin.apps.*`) - Thanks @stevengill @seratch - -**Updates** - -1. [WebClient][RTMClient] Fixed a bunch of the currency issues this SDK had (#429 #463 #492 #497 #530 #569 #605 #613 #626 #630 #631 #633 #669) - Thanks @seratch @aaguilartablada @aoberoi @stevengill @marshallino16 -2. [WebClient] #681 #560 Enable using bool values for request parameters - Thanks @roman-kachanovsky @seratch -3. [WebClient] #661 #678 Improve handling of required "ids" parameters (e.g., channel_ids, users) - Thanks @seratch -4. [WebClient] #680 Add non-conversation API deprecation warnings - Thanks @seratch -5. [WebClient] #671 #670 Enable passing None values for request parameters (they used to result in errors) - Thanks @yuji38kwmt @seratch -6. [WebClient] #673 Fix #672 files.upload fails with a filepath containing multi byte chars - Thanks @yuji38kwmt @seratch -7. [WebClient] #656 Fix #594 preview_image for files.remote.add API method is not properly supported - Thanks @Eothred @seratch -8. [Maintenance] #618 Add py.typed file to package distribution - Thanks @JKillian -9. [WebClient] #599 Strip token string parameters of whitespace - Thanks @TheFrozenFire -10. [WebClient] #692 Fix superfluous_charset warnings since v2.4.0 - Thanks @seratch -11. [WebClient] #652 Update oauth_v2_access to include redirect_uri (as optional) - Thanks @tomasreimers - -v2.5.0 (2019-12-09) -------------------- -**New Features** - -1. [WebClient] Adding new oauth.v2.access Web API method. #577 - -v2.4.0 (2019-11-27) -------------------- -**New Features** - -1. [WebClient] Adding new admin.* Web API methods. #571 - -**Updates** -1. [WebClient] We're no longer validating token types for Web API methods. Improves compatibility with granular bot permissions. #568 (Thanks @Smotko) -2. [WebClient] Correcting typos in descriptions #554 (Thanks @phamk) -3. [WebClient] Fixed 'iteracting' typo in library file headers #564 (Thanks @acabey) -4. [Message Builders] Remove value from LinkButtonElement #563 (Thanks @pedroma) - -v2.3.1 (2019-10-29) -------------------- -**Updates** - -1. [WebClient] Fixing a regression that causes the client to close sessions prematurely. #544 (Thanks @fatih-acar!) -2. [WebClient] Adding required missing `view` param to views.update Web API method. #542 - -v2.3.0 (2019-10-22) -------------------- -**New Features** - -1. [WebClient] Adding new views.publish Web API method. #540 - -**Updates** - -1. [WebClient] Some server responses don't return json. Correcting initial assumption. #540 -2. [Maintenance] Add `py.typed` to mark the library to support type hinting #524s - -v2.2.1 (2019-10-08) -------------------- -**Updates** - -1. [Docs] Fix Indentation of Code Snippets in README.md #525 (Thanks @abhishekjiitr) -2. [WebClient] Fix Web Client custom iterator #521 (Thanks @smaeda-ks) -3. [WebClient] Oauth previously failed to pass along credentials properly. This is fixed now. #527 -4. [WebClient] When a SlackApiError occurs we're now passing the entire SlackResponse into the exception. #527 - -v2.2.0 (2019-09-25) -------------------- -**New Features** - -1. [WebClient] Adding new admin and remote files API methods. #501 -2. [WebClient] Adding new view API methods. #517 - -**Updates** - -1. [Message Builders] Update BlockAttachment to not send invalid JSON due to fields attribute #473 (Thanks @paul-griffith) -2. [Docs] Add RTM section for docs v2 #477 (Thanks @shanedewael) -3. [Docs] Fix typo; recieved -> received #478 (Thanks @joakimnordling) -4. [Docs] Fix block kit link & update docs #484 (Thanks @clavin) -5. [RTMClient] Return callback from `RTMClient.run_on` #490 (Thanks @clavin) -6. [Docs] Fix link to Auth Guide in readme #498 (Thanks @asherf) -7. [Docs] Fix missing word and typo #512 (Thanks @marks) -8. [Message Builders] bugfix for value length in button elements #514 (Thanks @avanderm) -9. [Docs] Fixes formatting #515 (Thanks @vpetersson) -10. [Docs] Improve a code snippet on README #516 (Thanks @seratch) -11. [WebClient] Fixed an OAuth Headers bug and made the `token` param optional. #517 - -v2.1.0 (2019-07-01) -------------------- -**New Features** - -1. Type-hinted helper classes for building messages in v2 #400 (Thanks @paul-griffith) - -**Breaking Changes** - -1. [RTMClient] Converted the `RTMClient#typing()` function to async #446 - -**Updates** - -1. [RTMClient] Handle case in which aiohttp closes the websocket due to lack of ping responses. #453 (Thanks @flyte) -2. Modify package identifier in user agent to match v1.x identifier #418 (Thanks @aoberoi) -3. [WebClient] Fixed typo in Scheduled message #428 & #435 (Thanks @splinterific) -4. Transform install_requires of 'aiodns' into extras_require. #440 (Thanks @staticdev) - -**Thank you!!** -To everyone who's opened, commented or reacted to an issue; this project is better because of you! -Thank you for helping the Slack community! - -v2.0.0 (2019-04-29) -------------------- -`Original RFC `_ - -`v2 PR `_ - -**New Features** - -1. Client Decomposition: We’ve split the client into two. - - a. WebClient: A HTTP client focused on Slack's Web API. - b. RTMClient: A websocket client focused on Slack's RTM API. - -2. RTMClient: Completely redesigned, this client allows you to link your application's callbacks to corresponding Slack events. -3. WebClient: The WebClient now provides built-in methods for Slack's Web API. These methods act as helpers enabling you to focus less on how the request is constructed. Here are a few things that this provides: - - a. Basic information about each method through the docstring. - b. Easy File Uploads: You can now pass in the location of a file and the library will handle opening and retrieving the file object to be transmitted. - c. Token type validation: This gives you better error messaging when you're attempting to consume an api method that your token doesn't have access to. - d. Constructs requests using Slack's preferred HTTP methods and content-types. - -**Breaking Changes:** -If you're migrating from v1.x of slackclient to v2.x, Please follow our migration guide to ensure your app continues working after updating. - -`Check out the Migration Guide here! `_ - -**Thank you!** -This release would not have been possible without the support of our community. Thank you to everyone who’s contributed to this release. - - -v1.3.1 (2019-02-28) -------------------- - -- Lock websocket-client version to < 0.55.0: temp fix for #385 - - -v1.3.0 (2018-09-11) -------------------- - -## New Features -- Adds support for short lived tokens and automatic token refresh #347 (Thanks @roach!) - -## Other -- update RTM rate limiting comment and error message #308 (Thanks @benoitlavigne!) -- Use logging instead of traceback #309 (Thanks @harlowja!) -- Remove Python 3.3 from test environments #346 (Thanks @roach!) -- Enforced linting when using VSCode. #347 (Thanks @roach!) - - -v1.2.1 (2018-03-26) -------------------- - -- Added rate limit handling for rtm connections (thanks @jayalane!) - - -v1.2.0 (2018-03-20) -------------------- - -- You can now tell the RTM client to automatically reconnect by passing `auto_reconnect=True` - -v1.1.3 (2018-03-01) -------------------- - -- Fixed another API param encoding bug. It encodes things properly now. - -v1.1.2 (2018-01-31) -------------------- - -- Fixed an encoding issue which was encoding some Web API params incorrectly (sorry) - -v1.1.1 (2018-01-30) -------------------- - - - Adds HTTP response headers to `api_call` responses to expose things like rate limit info - - Moves `token` into auth header rather than request params - -v1.1.0 (2017-11-21) -------------------- - - - Aadds new SlackClientError and ResponseParseError types to describe errors - thanks @aoberoi! - - Fix Build Error (#245) - thanks @stasfilin! - - include email as user property (#173) - thanks @acaire! - - Add http reply into slack login and slack connection error (#216) - thanks @harlowja! - - Removed unused exception class (#233) - - Fix rtm_send_message bug (#225) - thanks @kt5356! - - Allow use of custom parameters on rtm_connect() (#210) - thanks @kamushadenes! - - Fix link to rtm.connect docs (#223) - @sampart! - -v1.0.9 (2017-08-31) -------------------- - - - Fixed rtm_send_message ID bug introduced in 1.0.8 - -v1.0.8 (2017-08-31) -------------------- - - - Added rtm.connect support - -v1.0.7 (2017-08-02) -------------------- - - - Fixes an issue where connecting over RTM to large teams may result in β€œWebsocket URL expired” errors - - A load of packaging improvements - -v1.0.6 (2017-06-12) -------------------- - - - Added proxy support (thanks @timfeirg!) - - Tidied up docs (thanks @schlueter!) - - Added tox settings for Python 3 testing (thanks @cclauss!) - -v1.0.5 (2017-01-23) -------------------- - - - Allow RTM Channel.send_message to reply to a thread - - Index users by ID instead of Name (non-breaking change) - - Added timeout to api calls. - - Fixed a typo about token access in auth.rst, thanks @kelvintaywl! - - Added Message Threads to the docs - -v1.0.4 (2016-12-15) -------------------- - - - fixed the ability to search for a user by ID - -v1.0.3 (2016-12-13) -------------------- - - - fixed an issue causing RTM connections to fail for large teams - -v1.0.2 (2016-09-22) -------------------- - - - removed unused ping counter - - fixed contributor guidelines links - - updated documentation - - Fix bug preventing API calls requiring a file ID - - Removes files from api_calls before JSON encoding, so the request is properly formatted - -v1.0.1 (2016-03-25) -------------------- - - - fix for __eq__ comparison in channels using '#' in channel name - - added copyright info to the LICENSE file - -v1.0.0 (2016-02-28) -------------------- - - - the ``api_call`` function now returns a decoded JSON object, rather than a JSON encoded string - - some ``api_call`` calls now call actions on the parent server object: - - ``im.open`` - - ``mpim.open``, ``groups.create``, ``groups.createChild`` - - ``channels.create``, `channels.join`` - -v0.18.0 (2016-02-21) --------------------- - - - Moves to use semver for versioning - - Adds support for private groups and MPDMs - - Switches to use requests instead of urllib - - Gets Travis CI integration working - - Fixes some formatting issues so the code will work for python 2.6 - - Cleans up some unused imports, some PEP-8 fixes and a couple bad default args fixes - -v0.17.0 (2016-02-15) --------------------- - - - Fixes the server so that it doesn't add duplicate users or channels to its internal lists, https://github.com/slackapi/python-slackclient/commit/0cb4bcd6e887b428e27e8059b6278b86ee661aaa - - README updates: - - Updates the URLs pointing to Slack docs for configuring authentication, https://github.com/slackapi/python-slackclient/commit/7d01515cebc80918a29100b0e4793790eb83e7b9 - - s/channnels/channels, https://github.com/slackapi/python-slackclient/commit/d45285d2f1025899dcd65e259624ee73771f94bb - - Adds users to the local cache when they join the team, https://github.com/slackapi/python-slackclient/commit/f7bb8889580cc34471ba1ddc05afc34d1a5efa23 - - Fixes urllib py 2/3 compatibility, https://github.com/slackapi/python-slackclient/commit/1046cc2375a85a22e94573e2aad954ba7287c886 - - - -.. include:: metadata.rst \ No newline at end of file diff --git a/docs-src-v2/conf.py b/docs-src-v2/conf.py deleted file mode 100644 index 241164b38..000000000 --- a/docs-src-v2/conf.py +++ /dev/null @@ -1,337 +0,0 @@ -# -*- coding: utf-8 -*- -# -# python-slackclient documentation build configuration file, created by -# sphinx-quickstart on Mon Jun 27 17:36:09 2016. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os -import sys -sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.coverage', -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.rst' - -# The encoding of source files. -# -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'python-slackclient' -copyright = u'2016, Ryan Huber, Jeff Ammons' -author = u'Ryan Huber, Jeff Ammons' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = u'1.0' -# The full version, including alpha/beta/rc tags. -release = u'1.0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# -# today = '' -# -# Else, today_fmt is used as the format for a strftime call. -# -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -# Use the slack theme -html_theme_path = ["_themes"] -html_theme = "slack" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. -# " v documentation" by default. -# -# html_title = u'python-slackclient v1.0.1' - -# A shorter title for the navigation bar. Default is the same as html_title. -# -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# -# html_logo = None - -# The name of an image file (relative to this directory) to use as a favicon of -# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -# html_static_path = ['_static'] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# -# html_extra_path = [] - -# If not None, a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -# The empty string is equivalent to '%b %d, %Y'. -# -# html_last_updated_fmt = None - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# -# html_additional_pages = {} - -# If false, no module index is generated. -# -# html_domain_indices = True - -# If false, no index is generated. -# -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' -# -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# 'ja' uses this config value. -# 'zh' user can custom change `jieba` dictionary path. -# -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'python-slackclientdoc' - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'python-slackclient.tex', u'python-slackclient Documentation', - u'Ryan Huber, Jeff Ammons', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# -# latex_use_parts = False - -# If true, show page references after internal links. -# -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# -# latex_appendices = [] - -# If false, no module index is generated. -# -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'python-slackclient', u'python-slackclient Documentation', - [author], 1) -] - -# If true, show URL addresses after external links. -# -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'python-slackclient', u'python-slackclient Documentation', - author, 'python-slackclient', 'A basic client for Slack.com, which can optionally connect to the Slack Real Time Messaging (RTM) API.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -# -# texinfo_appendices = [] - -# If false, no module index is generated. -# -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# -# texinfo_no_detailmenu = False diff --git a/docs-src-v2/conversations.rst b/docs-src-v2/conversations.rst deleted file mode 100644 index ca1fe2589..000000000 --- a/docs-src-v2/conversations.rst +++ /dev/null @@ -1,140 +0,0 @@ -.. _conversations_api: - -============================================== -Conversations API -============================================== -The Slack Conversations API provides your app with a unified interface to work with all the channel-like things encountered in Slack; public channels, private channels, direct messages, group direct messages, and our newest channel type, Shared Channels. - - -See `Conversations API `_ docs for more info. - --------- - -Direct messages ---------------------------------------------------------- -The ``conversations_open`` method opens either a 1:1 direct message with a single user or a a multi-person direct message, depending on the number of users supplied to the ``users`` parameter. - -*For public or private channels, use the ``conversations_create`` method.* - -Provide a ``users`` parameter as an array with 1 to 8 user IDs to open or resume a conversation. Providing only 1 ID will create a direct message. Providing more will create a new multi-party DM or resume an existing conversation. - -Subsequent calls to ``conversations_open`` with the same set of users will return the already existing conversation. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_open(users=["W123456789", "U987654321"]) - -See `conversations.open `_ additional info. - --------- - -Creating channels -------------------------------------- -Creates a new channel, either public or private. The ``name`` parameter is required, may contain numbers, letters, hyphens, and underscores, and must contain fewer than 21 characters. To make the channel private, set the option ``is_private`` parameter to ``True``. - -.. code-block:: python - - import os - from slack import WebClient - from time import time - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - channel_name = f"my-private-channel-{round(time())}" - response = client.conversations_create( - name=channel_name, - is_private=True - ) - channel_id = response["channel"]["id"] - response = client.conversations_archive(channel=channel_id) - -See `conversations.create `_ additional info. - --------- - -Getting more information ------------------------------------------ -To retrieve a set of metadata about a channel (public, private, DM, or multi-party DM), use ``conversations_info``. The ``channel`` parameter is required and must be a valid channel ID. The optional ``include_locale`` boolean parameter will return locale data, which may be useful if you wish to return localized responses. The ``include_num_members`` boolean parameter will return the number of people in a channel. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_info( - channel="C031415926", - include_num_members=1 - ) - -See `conversations.info `_ for more info. - - --------- - -Listing conversations --------------------------------- -To get a list of all the conversations in a workspace, use ``conversations_list``. By default, only public conversations are returned; use the ``types`` parameter specify which types of conversations you're interested in (Note: ``types`` is a string of comma-separated values) - - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_list() - conversations = response["channels"] - -Use the ``types`` parameter to request additional channels, including ``public_channel``, ``private_channel``, ``mpim``, and ``im``. This parameter is a string of comma-separated values. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_list( - types="public_channel, private_channel" - ) - -See `conversations.list `_ for more info. - - --------- - -Leaving a conversation ------------------------ -To leave a conversation, use ``conversations_leave`` with the required ``channel`` param containing the ID of the channel to leave. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_leave(channel="C27182818") - -See `conversations.leave `_ for more info. - --------- - -Getting members ------------------------------- -To get a list of the members of a conversation, use ``conversations_members`` with the required ``channel`` parameter. - -.. code-block:: python - - import os - from slack import WebClient - - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - response = client.conversations_members(channel="C16180339") - user_ids = response["members"] - -See `conversations.members `_ for more info. - -.. include:: metadata.rst diff --git a/docs-src-v2/faq.rst b/docs-src-v2/faq.rst deleted file mode 100644 index 5bcf05273..000000000 --- a/docs-src-v2/faq.rst +++ /dev/null @@ -1,88 +0,0 @@ -============================================== -Frequently Asked Questions -============================================== - -I cannot install slackclient... -********************************* - -We recommend using `virtualenv (venv) `_ to set up your Python runtime. - -.. code-block:: bash - - # Create a dedicated virtual env for running your Python scripts - python -m venv env - - # Run env\Scripts\activate on Windows OS - source env/bin/activate - - # Install slackclient PyPI package - pip install "slackclient>=2.0" - - # Set your token as an env variable (`set` command for Windows OS) - export SLACK_API_TOKEN=xoxb-*** - -Then, verify the following code works on the Python REPL (you can start it by just ``python``). - -.. code-block:: python - - import os - import logging - from slack import WebClient - logging.basicConfig(level=logging.DEBUG) - client = WebClient(token=os.environ["SLACK_API_TOKEN"]) - res = client.api_test() - - -If you encounter an error saying ``AttributeError: module 'slack' has no attribute 'WebClient'``, run ``pip list``. If you find both ``slackclient`` and ``slack`` in the output, try removing ``slack`` by ``pip uninstall slack`` and reinstalling ``slackclient``. - -Should I go with run_async? -**************************** - -For most cases, we recommend going with ``run_async=False`` mode. So, the default is ``False``. - -If your application turns ``run_async`` on, the app should follow right and efficient ways to use `asyncio `_'s non-blocking event loops and `aiohttp `_. Also, consider using async frameworks and their appropriate runtime. Running event loops along with Flask or similar may not be a good fit. - -If you have to simultaneously run ``WebClient`` with ``run_async=True`` outside an event loop for some reason, sharing a single ``WebClient`` instance doesn't work for you. Create an instance every time you run the code. The ``run_async=False`` mode doesn't have such issues. - -I found a bug! -****************** - -That's great! Thank you. Let us know on the `Issue Tracker`_. If you're feeling particularly ambitious, why not submit a `pull request`_ with a bug fix? - -There's a feature missing! -******************************* - -There's always something more that could be added! You can let us know in the `Issue Tracker`_ to start a discussion around the proposed feature, that's a good start. If you're feeling particularly ambitious, why not write the feature yourself, and submit a `pull request`_! We love feedback and we love help and we don't bite. Much. - -How do I contribute? -********************************* - -What an excellent question. First of all, please have a look at our general `contributing guidelines`_. - -All done? Great! While we're super excited to incorporate your new feature, there are a couple of things we want to make sure you've given thought to. - -- Please write unit tests for your new code. But don't **just** aim to increase the test coverage, rather, we expect you - to have written **thoughtful** tests that ensure your new feature will continue to work as expected, and to help future - contributors to ensure they don't break it! - -- Please document your new feature. Think about **concrete use cases** for your feature, and add a section to the - appropriate document, including a **complete** sample program that demonstrates your feature. Don't forget to update - the changelog in ``changelog.rst``! - -Including these two items with your pull request will totally make our dayβ€”and, more importantly, your future users' days! - -On that note... - -How do I compile the documentation? -************************************* - -This project's documentation is generated with `Sphinx `_. If you are editing one of the many reStructuredText files in the ``docs-src`` folder, you'll need to rebuild the documentation. It is recommended to run the following steps inside a ``virtualenv`` environment. - -.. code-block:: bash - - tox -e docs - -Do be sure to add the ``docs`` folder and its contents to your pull request! - - -.. include:: metadata.rst diff --git a/docs-src-v2/index.rst b/docs-src-v2/index.rst deleted file mode 100644 index 7aa9ab195..000000000 --- a/docs-src-v2/index.rst +++ /dev/null @@ -1,84 +0,0 @@ -.. toctree:: - :hidden: - - self - auth - basic_usage - conversations - real_time_messaging - faq - changelog - about - -============================================== -|product_name| -============================================== -Slack's APIs allow anyone to build full featured integrations that extend -and expand the capabilities of your Slack workspace. These APIs allow you -to build applications that interact with Slack just like the people on your -team -- they can post messages, respond to events that happen -- as well -as build complex UIs for getting work done. - -To make it easier for Python programmers to build Slack applications, we've -provided this open source SDK. |product_name| will let you get started building -Python apps as quickly as possible. The current version, |current_version|, is -built for Python 3.6 and higher -- if you need to target Python 2.x, you might -consider using v1 of the SDK. - -Slack Platform Basics -********************* -If you're new to the Slack platform, we have a general purpose `guide for building apps `_ that isn't specific to any language or framework. It's a great place to learn all about the concepts that go into building a great Slack app. - -Before you get started building on the Slack platform, you need to `set up your app's configuration `_. This is where you define things like your app's permissions and the endpoints that Slack should use for interacting with the backend you will build with Python. - -The app configuration page is also where you will acquire the OAuth token you will use to call Slack's APIs. Treat this token with care, just like you would a password, because it has access to workspace and can potentially read and write data to and from it. - - -Installation -************ - -We recommend using `PyPI `_ to install |product_name| - -.. code-block:: bash - - pip install slackclient - -Of course, you can always pull the source code directly into your project: - -.. code-block:: bash - - git clone https://github.com/slackapi/python-slackclient.git - -And then, save a few lines of code as ``./test.py``. - -.. code-block:: python - - # test.py - import sys - # Load the local source directly - sys.path.insert(1, "./python-slackclient") - # Enable debug logging - import logging - logging.basicConfig(level=logging.DEBUG) - # Verify it works - from slack import WebClient - client = WebClient() - api_response = client.api_test() - -You can run the code this way. - -.. code-block:: bash - - python test.py - -It's also good to try on the Python REPL. - -Getting Help -************ - -If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue: - -- Use our `Github Issue Tracker `_ for reporting bugs or requesting features. -- Visit the `Slack Developer Community `_ for getting help using |product_name| or just generally bond with your fellow Slack developers. - -.. include:: metadata.rst diff --git a/docs-src-v2/make.bat b/docs-src-v2/make.bat deleted file mode 100644 index e66ba12ac..000000000 --- a/docs-src-v2/make.bat +++ /dev/null @@ -1,281 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -set I18NSPHINXOPTS=%SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% - set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. epub3 to make an epub3 - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. texinfo to make Texinfo files - echo. gettext to make PO message catalogs - echo. changes to make an overview over all changed/added/deprecated items - echo. xml to make Docutils-native XML files - echo. pseudoxml to make pseudoxml-XML files for display purposes - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - echo. coverage to run coverage check of the documentation if enabled - echo. dummy to check syntax errors of document sources - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - - -REM Check if sphinx-build is available and fallback to Python version if any -%SPHINXBUILD% 1>NUL 2>NUL -if errorlevel 9009 goto sphinx_python -goto sphinx_ok - -:sphinx_python - -set SPHINXBUILD=python -m sphinx.__init__ -%SPHINXBUILD% 2> nul -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -:sphinx_ok - - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-slackclient.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-slackclient.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "epub3" ( - %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdf" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf - cd %~dp0 - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "latexpdfja" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - cd %BUILDDIR%/latex - make all-pdf-ja - cd %~dp0 - echo. - echo.Build finished; the PDF files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "texinfo" ( - %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. - goto end -) - -if "%1" == "gettext" ( - %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The message catalogs are in %BUILDDIR%/locale. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -if "%1" == "coverage" ( - %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage - if errorlevel 1 exit /b 1 - echo. - echo.Testing of coverage in the sources finished, look at the ^ -results in %BUILDDIR%/coverage/python.txt. - goto end -) - -if "%1" == "xml" ( - %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The XML files are in %BUILDDIR%/xml. - goto end -) - -if "%1" == "pseudoxml" ( - %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. - goto end -) - -if "%1" == "dummy" ( - %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. Dummy builder generates no files. - goto end -) - -:end diff --git a/docs-src-v2/metadata.rst b/docs-src-v2/metadata.rst deleted file mode 100644 index 204e46f02..000000000 --- a/docs-src-v2/metadata.rst +++ /dev/null @@ -1,20 +0,0 @@ -.. Site settings -.. |product_name| replace:: slackclient (Legacy Python Slack SDK) -.. |current_version| replace:: 2.0 -.. |latest_release_date| replace:: April 29, 2019 -.. |email| replace:: opensource@slack.com -.. |repo_name| replace:: python-slackclient -.. |github_username| replace:: SlackAPI -.. |twitter_username| replace:: SlackAPI - -.. _Bot Developer Hangout: https://dev4slack.slack.com/archives/sdk-python-slackclient -.. _Issue Tracker: http://github.com/SlackAPI/python-slackclient/issues -.. _pull request: http://github.com/SlackAPI/python-slackclient/pulls -.. _Python RTMBot: https://slackapi.github.io/python-rtmbot -.. _License: https://github.com/SlackAPI/python-slackclient/blob/main/LICENSE -.. _Code of Conduct: https://slackhq.github.io/code-of-conduct -.. _Contributing: https://github.com/slackapi/python-slackclient/blob/main/.github/contributing.md -.. _contributing guidelines: https://github.com/slackapi/python-slackclient/blob/main/.github/contributing.md -.. _Contributor License Agreement: https://docs.google.com/a/slack-corp.com/forms/d/e/1FAIpQLSfzjVoCM7ohBnjWf7eDYQxzti1EPpinsIJQA5RAUBwJKRUQHg/viewform -.. _Real Time Messaging (RTM) API: https://api.slack.com/rtm -.. _Web API: https://api.slack.com/web diff --git a/docs-src-v2/real_time_messaging.rst b/docs-src-v2/real_time_messaging.rst deleted file mode 100644 index bc48b123d..000000000 --- a/docs-src-v2/real_time_messaging.rst +++ /dev/null @@ -1,105 +0,0 @@ -.. _real-time-messaging: - -============================================== -Real Time Messaging (RTM) -============================================== -The `Real Time Messaging (RTM) API`_ is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users. - -If you prefer events to be pushed to your app, we recommend using the HTTP-based `Events API `_ instead. -The Events API contains some events that aren't supported in the RTM API (like `app_home_opened event `_), -and it supports most of the event types in the RTM API. If you'd like to use the Events API, you can use the `Python Slack Events Adaptor `_. - -The RTMClient allows apps to communicate with the Slack Platform's RTM API. - -The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks. - -In our example below, we watch for a `message event `_ that contains "Hello" and if its received, we call the ``say_hello()`` function. We then issue a call to the web client to post back to the channel saying "Hi" to the user. - -Configuring the RTM API ------------------------------------------- - -Events using the RTM API **must** use a classic Slack app (with a plain ``bot`` scope). - -If you already have a classic Slack app, you can use those credentials. If you don't and need to use the RTM API, you can `create a classic Slack app `_. You can learn more in the `API documentation `_. - -Also, even if the Slack app configuration pages encourage you to upgrade to the newer permission model, don't upgrade it and keep using the "classic" bot permission. - -Connecting to the RTM API ------------------------------------------- - -.. code-block:: python - - import os - from slack import RTMClient - - @RTMClient.run_on(event="message") - def say_hello(**payload): - data = payload['data'] - web_client = payload['web_client'] - - if 'Hello' in data['text']: - channel_id = data['channel'] - thread_ts = data['ts'] - user = data['user'] # This is not username but user ID (the format is either U*** or W***) - - web_client.chat_postMessage( - channel=channel_id, - text=f"Hi <@{user}>!", - thread_ts=thread_ts - ) - - slack_token = os.environ["SLACK_API_TOKEN"] - rtm_client = RTMClient(token=slack_token) - rtm_client.start() - -rtm.start vs rtm.connect ---------------------------- - -By default, the RTM client uses ``rtm.connect`` to establish a WebSocket connection with Slack. The response contains basic information about the team and WebSocket url. - -If you'd rather use ``rtm.start`` to establish the connection, which provides more information about the conversations and users on the team, you can set the ``connect_method`` option to ``rtm.start`` when instantiating the RTM Client. Note that on larger teams, use of ``rtm.start`` can be slow and unreliable. - -.. code-block:: python - - import os - from slack import RTMClient - - @RTMClient.run_on(event="message") - def say_hello(**payload): - data = payload['data'] - web_client = payload['web_client'] - if 'text' in data and 'Hello' in data['text']: - channel_id = data['channel'] - thread_ts = data['ts'] - user = data['user'] # This is not username but user ID (the format is either U*** or W***) - - web_client.chat_postMessage( - channel=channel_id, - text=f"Hi <@{user}>!", - thread_ts=thread_ts - ) - - slack_token = os.environ["SLACK_API_TOKEN"] - rtm_client = RTMClient( - token=slack_token, - connect_method='rtm.start' - ) - rtm_client.start() - -Read the `rtm.connect docs `_ and the `rtm.start docs `_ for more details. - - -RTM Events -------------- -.. code-block:: javascript - - { - 'type': 'message', - 'ts': '1358878749.000002', - 'user': 'U023BECGF', - 'text': 'Hello' - } - -See `RTM Events `_ for a complete list of events. - -.. include:: metadata.rst diff --git a/docs-src/.gitignore b/docs-src/.gitignore deleted file mode 100644 index e35d8850c..000000000 --- a/docs-src/.gitignore +++ /dev/null @@ -1 +0,0 @@ -_build diff --git a/docs-src/_themes/slack/conf.py b/docs-src/_themes/slack/conf.py deleted file mode 100644 index c00b2e3c4..000000000 --- a/docs-src/_themes/slack/conf.py +++ /dev/null @@ -1,349 +0,0 @@ -# -*- coding: utf-8 -*- -# -# python-slack-sdk documentation build configuration file, created by -# sphinx-quickstart on Mon Jun 27 17:36:09 2016. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os -import sys -sys.path.insert(0, os.path.abspath('../')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.coverage', -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['../../_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] -source_suffix = '.rst' - -# The encoding of source files. -# -# source_encoding = 'utf-8-sig' - -# The master toctree document. -master_doc = 'index' - -# General information about the project. -project = u'Python Slack SDK' -copyright = u'2015– Slack Technologies, Inc. and contributors' -author = u'Slack Technologies, Inc. and contributors' - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = u'1.0' -# The full version, including alpha/beta/rc tags. -release = u'1.0.1' - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# -# today = '' -# -# Else, today_fmt is used as the format for a strftime call. -# -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -exclude_patterns = [ - '_build', - 'Thumbs.db', - '.DS_Store', - 'auth.rst', - 'basic_usage.rst', - 'conversations.rst', -] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'emacs' - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "slack" -html_theme_path = ["../../_themes", ] - -highlight_language = "python" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. -# " v documentation" by default. -# -# html_title = u'python-slack-sdk v1.0.1' - -# A shorter title for the navigation bar. Default is the same as html_title. -# -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# -# html_logo = None - -# The name of an image file (relative to this directory) to use as a favicon of -# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['static'] - -html_context = { - 'css_files': ['static/pygments.css'], -} - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# -# html_extra_path = [] - -# If not None, a 'Last updated on:' timestamp is inserted at every page -# bottom, using the given strftime format. -# The empty string is equivalent to '%b %d, %Y'. -# -# html_last_updated_fmt = None - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# -# html_additional_pages = {} - -# If false, no module index is generated. -# -# html_domain_indices = True - -# If false, no index is generated. -# -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' -# -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# 'ja' uses this config value. -# 'zh' user can custom change `jieba` dictionary path. -# -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = 'python-slack-sdkdoc' - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - (master_doc, 'python-slack-sdk.tex', u'python-slack-sdk Documentation', - u'Ryan Huber, Jeff Ammons', 'manual'), -] - -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# -# latex_use_parts = False - -# If true, show page references after internal links. -# -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# -# latex_appendices = [] - -# If false, no module index is generated. -# -# latex_domain_indices = True - - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'python-slack-sdk', u'python-slack-sdk Documentation', - [author], 1) -] - -# If true, show URL addresses after external links. -# -# man_show_urls = False - - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'python-slack-sdk', u'python-slack-sdk Documentation', - author, 'python-slack-sdk', 'A basic client for Slack.com, which can optionally connect to the Slack Real Time Messaging (RTM) API.', - 'Miscellaneous'), -] - -# Documents to append as an appendix to all manuals. -# -# texinfo_appendices = [] - -# If false, no module index is generated. -# -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# -# texinfo_no_detailmenu = False diff --git a/docs-src/_themes/slack/layout.html b/docs-src/_themes/slack/layout.html deleted file mode 100644 index ff68e217d..000000000 --- a/docs-src/_themes/slack/layout.html +++ /dev/null @@ -1,165 +0,0 @@ - - - - - {{ - metatags - }} - - {%- block htmltitle %} - {{ title|striptags|e + " — "|safe + project|e }} - {%- endblock %} {%- macro css() %} - - - - - - {%- endmacro %} - - - - - {{ - css() - }} - {%- block linktags %} - - - {%- endblock %} - - - - - - - - {%- block header %} -
- - - - - - - {{ project }} - - -
- {% endblock %} - -
-
- - - - - -
- -
- {%- block body %} - {{ body }} - {% endblock %} -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-src/_themes/slack/localtoc.html b/docs-src/_themes/slack/localtoc.html deleted file mode 100644 index 9ee3dab97..000000000 --- a/docs-src/_themes/slack/localtoc.html +++ /dev/null @@ -1,4 +0,0 @@ -
Table of Contents?
-
    - {{ toc }} -
\ No newline at end of file diff --git a/docs-src/_themes/slack/relations.html b/docs-src/_themes/slack/relations.html deleted file mode 100644 index f90a7b212..000000000 --- a/docs-src/_themes/slack/relations.html +++ /dev/null @@ -1,19 +0,0 @@ -{# - basic/relations.html - ~~~~~~~~~~~~~~~~~~~~ - - Sphinx sidebar template: relation links. - - :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. - :license: BSD, see LICENSE for details. -#} -{%- if prev %} -

{{ _('Previous topic') }}

-

{{ prev.title }}

-{%- endif %} -{%- if next %} -

{{ _('Next topic') }}

-

{{ next.title }}

-{%- endif %} diff --git a/docs-src/_themes/slack/sidebar.html b/docs-src/_themes/slack/sidebar.html deleted file mode 100644 index 6f461834f..000000000 --- a/docs-src/_themes/slack/sidebar.html +++ /dev/null @@ -1,15 +0,0 @@ -{{ toctree(maxdepth=-1, collapse=False,includehidden=True) }} - - diff --git a/docs-src/_themes/slack/static/default.css_t b/docs-src/_themes/slack/static/default.css_t deleted file mode 100644 index d4c603379..000000000 --- a/docs-src/_themes/slack/static/default.css_t +++ /dev/null @@ -1,79 +0,0 @@ -a.headerlink { - display: none !important; -} - -h2 { - margin-top: -120px; - padding-top: 120px; -} - -.section-title { - font-size: 2rem; - line-height: 2.5rem; - letter-spacing: -1px; - font-weight: 700; - margin: 0 0 1rem; -} - -nav#api_nav .toctree-l1 { - margin-bottom: 1.5rem; -} - -nav#api_nav #api_sections ul { - list-style: none; - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l1>a { - color: #1264a3; - letter-spacing: 0; - font-size: .8rem; - font-weight: 800; - text-transform: uppercase; - border: none; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 { - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 a { - color: #1d1c1d; - text-transform: none; - font-weight: inherit; - padding: 0; - display: block; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - font-size: 15px!important; - line-height:15px; - padding: 4px 8px; - border: 1px solid transparent; - border-radius: 4px; -} - -nav#api_nav #api_sections ul li.toctree-l2 a:hover { - cursor: pointer; - text-decoration: none; - background-color:#e8f5fa; - border-color:#dcf0fb; -} - -nav#api_nav #footer #footer_nav { - font-size: .9375rem; -} - -nav#api_nav #footer #footer_nav a { - border: none; - padding: 0; - color: #616061; -} - -nav#api_nav #footer #footer_nav a:hover { - text-decoration: none; - color: #1c1c1c; -} diff --git a/docs-src/_themes/slack/static/docs.css_t b/docs-src/_themes/slack/static/docs.css_t deleted file mode 100644 index 12c715d28..000000000 --- a/docs-src/_themes/slack/static/docs.css_t +++ /dev/null @@ -1,34 +0,0 @@ -/* Updates body font */ -body { - font-family: Slack-Lato,appleLogo,sans-serif; -} - -/* Replaces old sidebar styled links */ -.sidebar_menu h5 { - font-size: 0.8rem; - font-weight: 800; - margin-bottom: 3px; -} - -/* Aligns footer navigation to the left of the sidebar */ -.footer_nav { - margin: 0 !important; -} - -/* Styles the signature all nice and pretty <3 */ -#footer_signature { - color:#e01e5a; - font-size:.9rem; - margin-top: 10px; -} - -/* Fixes link hover state */ -a:hover { - text-decoration: underline; -} - -/* Makes footer consistent */ -footer { - background-color: transparent; - border: 0; -} \ No newline at end of file diff --git a/docs-src/_themes/slack/static/pygments.css_t b/docs-src/_themes/slack/static/pygments.css_t deleted file mode 100644 index ae05f6c90..000000000 --- a/docs-src/_themes/slack/static/pygments.css_t +++ /dev/null @@ -1,60 +0,0 @@ -.highlight .hll { background-color: #ffffcc } -.highlight { background: #ffffff; } -.highlight .c { color: #999988; font-style: italic } /* Comment */ -.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ -.highlight .k { font-weight: bold } /* Keyword */ -.highlight .o { font-weight: bold } /* Operator */ -.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ -.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ -.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ -.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ -.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ -.highlight .ge { font-style: italic } /* Generic.Emph */ -.highlight .gr { color: #aa0000 } /* Generic.Error */ -.highlight .gh { color: #999999 } /* Generic.Heading */ -.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ -.highlight .go { color: #888888 } /* Generic.Output */ -.highlight .gp { color: #555555 } /* Generic.Prompt */ -.highlight .gs { font-weight: bold } /* Generic.Strong */ -.highlight .gu { color: #aaaaaa } /* Generic.Subheading */ -.highlight .gt { color: #aa0000 } /* Generic.Traceback */ -.highlight .kc { font-weight: bold } /* Keyword.Constant */ -.highlight .kd { font-weight: bold } /* Keyword.Declaration */ -.highlight .kn { font-weight: bold } /* Keyword.Namespace */ -.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ -.highlight .kr { font-weight: bold } /* Keyword.Reserved */ -.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ -.highlight .m { color: #009999 } /* Literal.Number */ -.highlight .s { color: #bb8844 } /* Literal.String */ -.highlight .na { color: #008080 } /* Name.Attribute */ -.highlight .nb { color: #999999 } /* Name.Builtin */ -.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ -.highlight .no { color: #008080 } /* Name.Constant */ -.highlight .ni { color: #800080 } /* Name.Entity */ -.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ -.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ -.highlight .nn { color: #555555 } /* Name.Namespace */ -.highlight .nt { color: #000080 } /* Name.Tag */ -.highlight .nv { color: #008080 } /* Name.Variable */ -.highlight .ow { font-weight: bold } /* Operator.Word */ -.highlight .w { color: #bbbbbb } /* Text.Whitespace */ -.highlight .mf { color: #009999 } /* Literal.Number.Float */ -.highlight .mh { color: #009999 } /* Literal.Number.Hex */ -.highlight .mi { color: #009999 } /* Literal.Number.Integer */ -.highlight .mo { color: #009999 } /* Literal.Number.Oct */ -.highlight .sb { color: #bb8844 } /* Literal.String.Backtick */ -.highlight .sc { color: #bb8844 } /* Literal.String.Char */ -.highlight .sd { color: #bb8844 } /* Literal.String.Doc */ -.highlight .s2 { color: #bb8844 } /* Literal.String.Double */ -.highlight .se { color: #bb8844 } /* Literal.String.Escape */ -.highlight .sh { color: #bb8844 } /* Literal.String.Heredoc */ -.highlight .si { color: #bb8844 } /* Literal.String.Interpol */ -.highlight .sx { color: #bb8844 } /* Literal.String.Other */ -.highlight .sr { color: #808000 } /* Literal.String.Regex */ -.highlight .s1 { color: #bb8844 } /* Literal.String.Single */ -.highlight .ss { color: #bb8844 } /* Literal.String.Symbol */ -.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ -.highlight .vc { color: #008080 } /* Name.Variable.Class */ -.highlight .vg { color: #008080 } /* Name.Variable.Global */ -.highlight .vi { color: #008080 } /* Name.Variable.Instance */ -.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ diff --git a/docs-src/_themes/slack/theme.conf b/docs-src/_themes/slack/theme.conf deleted file mode 100644 index b13de3cbb..000000000 --- a/docs-src/_themes/slack/theme.conf +++ /dev/null @@ -1,6 +0,0 @@ -[theme] -inherit = default -stylesheet = default.css -show_sphinx = False - -[options] diff --git a/docs-src/about.rst b/docs-src/about.rst deleted file mode 100644 index 17fad157f..000000000 --- a/docs-src/about.rst +++ /dev/null @@ -1,18 +0,0 @@ -============================================== -About -============================================== - -|product_name| -************** - - -Access the Slack Platform from your Python app. |product_name| lets you build on the Slack Web APIs pythonically. - -|product_name| is proudly maintained with πŸ’– by the Slack Developer Tools team - -- `License`_ -- `Code of Conduct`_ -- `Contributing`_ -- `Contributor License Agreement`_ - -.. include:: metadata.rst \ No newline at end of file diff --git a/docs-src/auth.rst b/docs-src/auth.rst deleted file mode 100644 index e8f6c125f..000000000 --- a/docs-src/auth.rst +++ /dev/null @@ -1,8 +0,0 @@ -============================================== -Tokens & Installation -============================================== -.. _handling-tokens: - -See `Installation <./installation/index.html>`_ page. - -.. include:: metadata.rst diff --git a/docs-src/basic_usage.rst b/docs-src/basic_usage.rst deleted file mode 100644 index c021499e5..000000000 --- a/docs-src/basic_usage.rst +++ /dev/null @@ -1,8 +0,0 @@ -============================================== -Basic Usage -============================================== - -See `Installation <./web/index.html>`_ page. - -.. include:: metadata.rst - diff --git a/docs-src/conversations.rst b/docs-src/conversations.rst deleted file mode 100644 index 64074ff40..000000000 --- a/docs-src/conversations.rst +++ /dev/null @@ -1,8 +0,0 @@ -============================================== -Conversations API -============================================== - -See `WebClient Basics <./web/index.html>`_ page. - -.. include:: metadata.rst - diff --git a/docs-src/faq.rst b/docs-src/faq.rst deleted file mode 100644 index b2ab21c22..000000000 --- a/docs-src/faq.rst +++ /dev/null @@ -1,75 +0,0 @@ -============================================== -FAQ -============================================== - -Installation Issues -********************************* - -We recommend using `virtualenv (venv) `_ to set up your Python runtime. - -.. code-block:: bash - - # Create a dedicated virtual env for running your Python scripts - python -m venv .venv - - # Run .venv\Scripts\activate on Windows OS - source .venv/bin/activate - - # Install slack_sdk PyPI package - pip install "slack_sdk>=3.0" - - # Set your token as an env variable (`set` command for Windows OS) - export SLACK_BOT_TOKEN=xoxb-*** - -Then, verify the following code works on the Python REPL (you can start it by just ``python``). - -.. code-block:: python - - import os - import logging - from slack_sdk import WebClient - logging.basicConfig(level=logging.DEBUG) - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - res = client.api_test() - - -As ``slack`` package is deprecated, we recommend switching to ``slack_sdk`` package. That being said, the code you're working on may be still using the old package. If you encounter an error saying ``AttributeError: module 'slack' has no attribute 'WebClient'``, run ``pip list``. If you find both ``slack_sdk`` and ``slack`` in the output, try removing ``slack`` by ``pip uninstall slack`` and reinstalling ``slack_sdk``. - - -Bug Report -****************** - -That's great! Thank you. Let us know on the `Issue Tracker`_. If you're feeling particularly ambitious, why not submit a `pull request`_ with a bug fix? - -Feature Requests -******************************* - -There's always something more that could be added! You can let us know in the `Issue Tracker`_ to start a discussion around the proposed feature, that's a good start. If you're feeling particularly ambitious, why not write the feature yourself, and submit a `pull request`_! We love feedback and we love help and we don't bite. Much. - -Contributions -********************************* - -What an excellent question. First of all, please have a look at our general `contributing guidelines`_. - -All done? Great! While we're super excited to incorporate your new feature, there are a couple of things we want to make sure you've given thought to. - -- Please write unit tests for your new code. But don't **just** aim to increase the test coverage, rather, we expect you to have written **thoughtful** tests that ensure your new feature will continue to work as expected, and to help future contributors to ensure they don't break it! - -- Please document your new feature. Think about **concrete use cases** for your feature, and add a section to the appropriate document, including a **complete** sample program that demonstrates your feature. Don't forget to update the changelog in ``changelog.rst``! - -Including these two items with your pull request will totally make our dayβ€”and, more importantly, your future users' days! - -On that note... - -Documentation -************************************* - -This project's documentation is generated with `Sphinx `_. If you are editing one of the many reStructuredText files in the ``docs-src`` folder, you'll need to rebuild the documentation. It is recommended to run the following steps inside a ``virtualenv`` environment. - -.. code-block:: bash - - ./docs-v3.sh - -Do be sure to add the ``docs-v3`` folder and its contents to your pull request! - -.. include:: metadata.rst diff --git a/docs-src/index.rst b/docs-src/index.rst deleted file mode 100644 index ff53028bc..000000000 --- a/docs-src/index.rst +++ /dev/null @@ -1,85 +0,0 @@ -.. toctree:: - :hidden: - - self - v3-migration/index - installation/index - web/index - webhook/index - oauth/index - real_time_messaging - faq - about - -============================================== -|product_name| -============================================== - -The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slack’s APIs. They are small and powerful when used independently, and work seamlessly when used together, too. - -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| Feature | What its for | Package | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| Web API | Send data to or query data from Slack using any of over 200 methods. | ``slack_sdk.web`` | -| | | ``slack_sdk.web.async_client`` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| Webhooks / response_url | Send a message using Incoming Webhooks or response_url | ``slack_sdk.webhook`` | -| | | ``slack_sdk.webhook.async_client`` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| OAuth | Setup the authentication flow using V2 OAuth for Slack apps. | ``slack_sdk.oauth`` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| RTM API | Listen for incoming messages and a limited set of events happening in Slack, using WebSocket. | ``slack_sdk.rtm``` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| Request Signature Verification | Verify incoming requests from the Slack API servers. | ``slack_sdk.signature`` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ -| UI Builders | Construct UI components using easy-to-use builders. | ``slack_sdk.models`` | -+--------------------------------+-----------------------------------------------------------------------------------------------+------------------------------------+ - -Installation -************ - -This package supports Python 3.6 and higher. We recommend using `PyPI `_ to install |product_name| - -.. code-block:: bash - - pip install slack_sdk - -Of course, you can always pull the source code directly into your project: - -.. code-block:: bash - - git clone https://github.com/slackapi/python-slack-sdk.git - -And then, save a few lines of code as ``./test.py``. - -.. code-block:: python - - # test.py - import sys - # Load the local source directly - sys.path.insert(1, "./python-slack-sdk") - # Enable debug logging - import logging - logging.basicConfig(level=logging.DEBUG) - # Verify it works - from slack_sdk import WebClient - client = WebClient() - api_response = client.api_test() - -You can run the code this way. - -.. code-block:: bash - - python test.py - -It's also good to try on the Python REPL. - -Getting Help -************ - -If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue: - -- `GitHub Issue Tracker `_ for questions, feature requests, bug reports and general discussion related to this package. -- Visit the `Slack Developer Community `_ for getting help using |product_name| or just generally bond with your fellow Slack developers. - -.. include:: metadata.rst diff --git a/docs-src/installation/index.rst b/docs-src/installation/index.rst deleted file mode 100644 index e35413887..000000000 --- a/docs-src/installation/index.rst +++ /dev/null @@ -1,143 +0,0 @@ -============================================== -Installation -============================================== -.. _handling-tokens: - -Access Tokens -------------------- - -**Keeping access tokens safe** - -The OAuth token you use to call the Slack API has access to the data on the workspace where it is installed. - -Depending on the scopes granted to the token, it potentially has the ability to read and write data. Treat these tokens just as you would a password -- don't publish them, don't check them into source code, don't share them with others. - -🚫Avoid this: - -.. code-block:: python - - token = 'xoxb-111-222-xxxxx' - -We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as: - -.. code-block:: python - - SLACK_BOT_TOKEN="xoxb-111-222-xxxxx" python myapp.py - -Then retrieve the key with: - -.. code-block:: python - - import os - SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"] - -For additional information, please see our `Safely Storing Credentials `_ page. - -Workspace Installations ---------------------------------------- - -**Single Workspace Install** - -If you're building an application for a single Slack workspace, there's no need to build out the entire OAuth flow. - -Once you've setup your features, click on the **Install App to Team** button found on the **Install App** page. -If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to -your workspace for changes to take effect. - -For additional information, see the `Installing Apps `_ of our `Building Slack apps `_ page. - -**Multiple Workspace Install** - -If you intend for an app to be installed on multiple Slack workspaces, you will need to handle this installation via the industry-standard OAuth protocol. You can read more about `how Slack handles Oauth `_. - -(The OAuth exchange is facilitated via HTTP and requires a webserver; in this example, we'll use `Flask `_.) - -To configure your app for OAuth, you'll need a client ID, a client secret, and a set of one or more scopes that will be applied to the token once it is granted. The client ID and client secret are available from your `app's configuration page `_. The scopes are determined by the functionality of the app -- every method you wish to access has a corresponding scope and your app will need to request that scope in order to be able to access the method. Review Slack's `full list of OAuth scopes `_. - -.. code-block:: python - - import os - from slack_sdk import WebClient - from flask import Flask, request - - client_id = os.environ["SLACK_CLIENT_ID"] - client_secret = os.environ["SLACK_CLIENT_SECRET"] - oauth_scope = os.environ["SLACK_SCOPES"] - - app = Flask(__name__) - -**The OAuth initiation link** - -To begin the OAuth flow that will install your app on a workspace, you'll need to provide the user with a link to Slack's OAuth page. This can be a simple link to ``https://slack.com/oauth/v2/authorize`` with ``scope`` and ``client_id`` query parameters, or you can use our pre-built `Add to Slack button `_ to do all the work for you. - -This link directs the user to Slack's OAuth acceptance page, where the user will review and accept or refuse the permissions your app is requesting as defined by the scope(s). - -.. code-block:: python - - @app.route("/slack/install", methods=["GET"]) - def pre_install(): - state = "randomly-generated-one-time-value" - return '' \ - 'Add to Slack' - -**The OAuth completion page** - -Once the user has agreed to the permissions you've requested, Slack will redirect the user to your auth completion page, which includes a ``code`` query string param. You'll use the ``code`` param to call the ``oauth.v2.access`` `endpoint `_ that will finally grant you the token. - -.. code-block:: python - - @app.route("/slack/oauth_redirect", methods=["GET"]) - def post_install(): - # Verify the "state" parameter - - # Retrieve the auth code from the request params - code_param = request.args['code'] - - # An empty string is a valid token for this request - client = WebClient() - - # Request the auth tokens from Slack - response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code_param - ) - -A successful request to ``oauth.v2.access`` will yield a JSON payload with at least one token, a bot token that begins with ``xoxb``. - -.. code-block:: python - - @app.route("/slack/oauth_redirect", methods=["GET"]) - def post_install(): - # Verify the "state" parameter - - # Retrieve the auth code from the request params - code_param = request.args['code'] - - # An empty string is a valid token for this request - client = WebClient() - - # Request the auth tokens from Slack - response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code_param - ) - print(response) - - # Save the bot token to an environmental variable or to your data store - # for later use - os.environ["SLACK_BOT_TOKEN"] = response['access_token'] - - # Don't forget to let the user know that OAuth has succeeded! - return "Installation is completed!" - - if __name__ == "__main__": - app.run("localhost", 3000) - -Once your user has completed the OAuth flow, you'll be able to use the provided tokens to call any of Slack's API methods that require an access token. - -See the `Basic Usage <../basic_usage.html>`_ section of this documentation for usage examples. - -.. include:: ../metadata.rst diff --git a/docs-src/metadata.rst b/docs-src/metadata.rst deleted file mode 100644 index d7f207c07..000000000 --- a/docs-src/metadata.rst +++ /dev/null @@ -1,17 +0,0 @@ -.. Site settings -.. |product_name| replace:: Python Slack SDK -.. |email| replace:: opensource@slack.com -.. |repo_name| replace:: python-slack-sdk -.. |github_username| replace:: SlackAPI -.. |twitter_username| replace:: SlackAPI - -.. _Bot Developer Hangout: https://dev4slack.slack.com/archives/sdk-python-slack-sdk -.. _Issue Tracker: http://github.com/SlackAPI/python-slack-sdk/issues -.. _pull request: http://github.com/SlackAPI/python-slack-sdk/pulls -.. _License: https://github.com/SlackAPI/python-slack-sdk/blob/main/LICENSE -.. _Code of Conduct: https://slackhq.github.io/code-of-conduct -.. _Contributing: https://github.com/slackapi/python-slack-sdk/blob/main/.github/contributing.md -.. _contributing guidelines: https://github.com/slackapi/python-slack-sdk/blob/main/.github/contributing.md -.. _Contributor License Agreement: https://docs.google.com/a/slack-corp.com/forms/d/e/1FAIpQLSfzjVoCM7ohBnjWf7eDYQxzti1EPpinsIJQA5RAUBwJKRUQHg/viewform -.. _Real Time Messaging (RTM) API: https://api.slack.com/rtm -.. _Web API: https://api.slack.com/web diff --git a/docs-src/oauth/index.rst b/docs-src/oauth/index.rst deleted file mode 100644 index cc71b31d1..000000000 --- a/docs-src/oauth/index.rst +++ /dev/null @@ -1,238 +0,0 @@ -============================================== -OAuth Modules -============================================== - -This section explains the details about how to handle Slack's OAuth flow. - -If you're looking for a much easier way to do the same, check `Bolt for Python `_, which is a full-stack Slack App framework. With Bolt, you don't need to implement most of the following code on your own. - -App Installation Flow -************************************************* - -OAuth lets a user in any Slack workspace install your app. At the end of OAuth, your app gains an access token. Refer to `Installing with OAuth `_ for details. - -Python Slack SDK provides the necessary modules for building the OAuth flow. - -**Starting an OAuth flow** - -The first step of Slack OAuth flow is to redirect a Slack user to https://slack.com/oauth/v2/authorize with a valida ``state`` parameter. To implement this process, you can use the following modules. - -+---------------------------+-----------------------------------------------------------------------------+---------------------------+ -| Module | What its for | Default Implementation | -+---------------------------+-----------------------------------------------------------------------------+---------------------------+ -| ``InstallationStore`` | Persist installation data and lookup it by IDs. | ``FileInstallationStore`` | -+---------------------------+-----------------------------------------------------------------------------+---------------------------+ -| ``OAuthStateStore`` | Issue and consume ``state`` parameter value on the server-side. | ``FileOAuthStateStore`` | -+---------------------------+-----------------------------------------------------------------------------+---------------------------+ -| ``AuthorizeUrlGenerator`` | Build https://slack.com/oauth/v2/authorize with sufficient query parameters | (same) | -+---------------------------+-----------------------------------------------------------------------------+---------------------------+ - -The code snippet below demonstrates how to build it using `Flask `_. - -.. code-block:: python - - import os - from slack_sdk.oauth import AuthorizeUrlGenerator - from slack_sdk.oauth.installation_store import FileInstallationStore, Installation - from slack_sdk.oauth.state_store import FileOAuthStateStore - - # Issue and consume state parameter value on the server-side. - state_store = FileOAuthStateStore(expiration_seconds=300, base_dir="./data") - # Persist installation data and lookup it by IDs. - installation_store = FileInstallationStore(base_dir="./data") - - # Build https://slack.com/oauth/v2/authorize with sufficient query parameters - authorize_url_generator = AuthorizeUrlGenerator( - client_id=os.environ["SLACK_CLIENT_ID"], - scopes=["app_mentions:read", "chat:write"], - user_scopes=["search:read"], - ) - - from flask import Flask, request, make_response - app = Flask(__name__) - - @app.route("/slack/install", methods=["GET"]) - def oauth_start(): - # Generate a random value and store it on the server-side - state = state_store.issue() - # https://slack.com/oauth/v2/authorize?state=(generated value)&client_id={client_id}&scope=app_mentions:read,chat:write&user_scope=search:read - url = authorize_url_generator.generate(state) - return f'' \ - f'' - -When accessing ``https://(your domain)/slack/install``, you will see "Add to Slack" button in the webpage. You can start the app's installation flow by clicking the button. - -**Handling a callback request from Slack** - -If all's well, a user goes through the Slack app installation UI and okays your app with all the scopes that it requests. After that happens, Slack redirects the user back to your specified Redirect URL. - -The redirection gives you a ``code`` parameter. You can exchange the value for an access token by calling `oauth.v2.access `_ API method. - -.. code-block:: python - - from slack_sdk.web import WebClient - client_secret = os.environ["SLACK_CLIENT_SECRET"] - - # Redirect URL - @app.route("/slack/oauth/callback", methods=["GET"]) - def oauth_callback(): - # Retrieve the auth code and state from the request params - if "code" in request.args: - # Verify the state parameter - if state_store.consume(request.args["state"]): - client = WebClient() # no prepared token needed for this - # Complete the installation by calling oauth.v2.access API method - oauth_response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - redirect_uri=redirect_uri, - code=request.args["code"] - ) - - installed_enterprise = oauth_response.get("enterprise") or {} - is_enterprise_install = oauth_response.get("is_enterprise_install") or False - installed_team = oauth_response.get("team") or {} - installer = oauth_response.get("authed_user") or {} - incoming_webhook = oauth_response.get("incoming_webhook") or {} - bot_token = oauth_response.get("access_token") - # NOTE: As oauth.v2.access doesn't include bot_id in response, - # we call bots.info for storing the installation data along with bot_id. - bot_id = None - enterprise_url = None - if bot_token is not None: - auth_test = client.auth_test(token=bot_token) - bot_id = auth_test["bot_id"] - if is_enterprise_install is True: - enterprise_url = auth_test.get("url") - - # Build an installation data - installation = 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"), # comma-separated string - user_id=installer.get("id"), - user_token=installer.get("access_token"), - user_scopes=installer.get("scope"), # comma-separated string - 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"), - ) - # Store the installation - installation_store.save(installation) - - return "Thanks for installing this app!" - else: - return make_response(f"Try the installation again (the state value is already expired)", 400) - - error = request.args["error"] if "error" in request.args else "" - return make_response(f"Something is wrong with the installation (error: {error})", 400) - -Token Lookup -************************************************* - -Now that your Flask app can choose the right access token for incoming event requests, let's add the Slack event handler endpoint. - -You can use the same ``InstallationStore`` in the Slack event handler. - -.. code-block:: python - - import json - from slack_sdk.errors import SlackApiError - - from slack_sdk.signature import SignatureVerifier - signing_secret = os.environ["SLACK_SIGNING_SECRET"] - signature_verifier = SignatureVerifier(signing_secret=signing_secret) - - @app.route("/slack/events", methods=["POST"]) - def slack_app(): - # Verify incoming requests from Slack - # https://api.slack.com/authentication/verifying-requests-from-slack - if not signature_verifier.is_valid( - body=request.get_data(), - timestamp=request.headers.get("X-Slack-Request-Timestamp"), - signature=request.headers.get("X-Slack-Signature")): - return make_response("invalid request", 403) - - # Handle a slash command invocation - if "command" in request.form \ - and request.form["command"] == "/open-modal": - try: - # in the case where this app gets a request from an Enterprise Grid workspace - enterprise_id = request.form.get("enterprise_id") - # The workspace's ID - team_id = request.form["team_id"] - # Lookup the stored bot token for this workspace - bot = installation_store.find_bot( - enterprise_id=enterprise_id, - team_id=team_id, - ) - bot_token = bot.bot_token if bot else None - if not bot_token: - # The app may be uninstalled or be used in a shared channel - return make_response("Please install this app first!", 200) - - # Open a modal using the valid bot token - client = WebClient(token=bot_token) - trigger_id = request.form["trigger_id"] - response = client.views_open( - trigger_id=trigger_id, - view={ - "type": "modal", - "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - return make_response("", 200) - except SlackApiError as e: - code = e.response["error"] - return make_response(f"Failed to open a modal due to {code}", 200) - - elif "payload" in request.form: - # Data submission from the modal - payload = json.loads(request.form["payload"]) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": - submitted_data = payload["view"]["state"]["values"] - print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - # You can use WebClient with a valid token here too - return make_response("", 200) - - # Indicate unsupported request patterns - return make_response("", 404) - - -Again, if you're looking for an easier solution, take a look at `Bolt for Python `_. With Bolt, you don't need to implement most of the above code on your own. - - -.. include:: ../metadata.rst \ No newline at end of file diff --git a/docs-src/real_time_messaging.rst b/docs-src/real_time_messaging.rst deleted file mode 100644 index 32a502529..000000000 --- a/docs-src/real_time_messaging.rst +++ /dev/null @@ -1,108 +0,0 @@ -.. _real-time-messaging: - -============================================== -RTM Client -============================================== - -Real Time Messaging (RTM) ---------------------------------------- - - -The `Real Time Messaging (RTM) API`_ is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users. - -If you prefer events to be pushed to your app, we recommend using the HTTP-based `Events API `_ instead. -The Events API contains some events that aren't supported in the RTM API (like `app_home_opened event `_), -and it supports most of the event types in the RTM API. If you'd like to use the Events API, you can use the `Python Slack Events Adaptor `_. - -The RTMClient allows apps to communicate with the Slack Platform's RTM API. - -The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks. - -In our example below, we watch for a `message event `_ that contains "Hello" and if its received, we call the ``say_hello()`` function. We then issue a call to the web client to post back to the channel saying "Hi" to the user. - -**Configuring the RTM API** - -Events using the RTM API **must** use a classic Slack app (with a plain ``bot`` scope). - -If you already have a classic Slack app, you can use those credentials. If you don't and need to use the RTM API, you can `create a classic Slack app `_. You can learn more in the `API documentation `_. - -Also, even if the Slack app configuration pages encourage you to upgrade to the newer permission model, don't upgrade it and keep using the "classic" bot permission. - -**Connecting to the RTM API** - -.. code-block:: python - - import os - from slack_sdk.rtm import RTMClient - - @RTMClient.run_on(event="message") - def say_hello(**payload): - data = payload['data'] - web_client = payload['web_client'] - - if 'Hello' in data['text']: - channel_id = data['channel'] - thread_ts = data['ts'] - user = data['user'] # This is not username but user ID (the format is either U*** or W***) - - web_client.chat_postMessage( - channel=channel_id, - text=f"Hi <@{user}>!", - thread_ts=thread_ts - ) - - slack_token = os.environ["SLACK_BOT_TOKEN"] - rtm_client = RTMClient(token=slack_token) - rtm_client.start() - -**rtm.start vs rtm.connect** - -By default, the RTM client uses ``rtm.connect`` to establish a WebSocket connection with Slack. The response contains basic information about the team and WebSocket url. - -If you'd rather use ``rtm.start`` to establish the connection, which provides more information about the conversations and users on the team, you can set the ``connect_method`` option to ``rtm.start`` when instantiating the RTM Client. Note that on larger teams, use of ``rtm.start`` can be slow and unreliable. - -.. code-block:: python - - import os - from slack_sdk import RTMClient - - @RTMClient.run_on(event="message") - def say_hello(**payload): - data = payload['data'] - web_client = payload['web_client'] - if 'text' in data and 'Hello' in data['text']: - channel_id = data['channel'] - thread_ts = data['ts'] - user = data['user'] # This is not username but user ID (the format is either U*** or W***) - - web_client.chat_postMessage( - channel=channel_id, - text=f"Hi <@{user}>!", - thread_ts=thread_ts - ) - - slack_token = os.environ["SLACK_BOT_TOKEN"] - rtm_client = RTMClient( - token=slack_token, - connect_method='rtm.start' - ) - rtm_client.start() - -Read the `rtm.connect docs `_ and the `rtm.start docs `_ for more details. - - -RTM Events -------------- - -.. code-block:: javascript - - { - 'type': 'message', - 'ts': '1358878749.000002', - 'user': 'U023BECGF', - 'text': 'Hello' - } - -See `RTM Events `_ for a complete list of events. - -.. include:: metadata.rst diff --git a/docs-src/v3-migration/index.rst b/docs-src/v3-migration/index.rst deleted file mode 100644 index 6a24a5995..000000000 --- a/docs-src/v3-migration/index.rst +++ /dev/null @@ -1,64 +0,0 @@ -============================================== -Migration Guide -============================================== - -The v2 website is live `here `_ just like before. However, the **slackclient** project is in maintenance mode now and this **slack_sdk** project is the successor. - -From slackclient 2.x -************************************************* - -There are a few changes introduced in v3.0: - -* The PyPI project is renamed from ``slackclient`` to ``slack_sdk`` -* Importing ``slack_sdk.*`` is recommended. You can still use ``slack.*`` with deprecation warnings for a while. -* ``slack_sdk`` has no required dependencies. This means ``aiohttp`` is no longer automatically resolved. -* ``WebClient`` no longer has ``run_async`` and ``aiohttp`` specific options. If you still need the option or other ``aiohttp`` specific options, use ``LegacyWebClient`` (``slackclient`` v2 compatible) or ``AsyncWebClient``. - -We're sorry for the inconvenience. - ------ - -**Change:** The PyPI project is renamed from ``slackclient`` to ``slack_sdk`` - -**Action**: Remove ``slackclient``, add ``slack_sdk`` in ``requirements.txt`` - -Since v3, the PyPI project name is `slack_sdk `_ (technically ``slack-sdk`` also works). - -The biggest reason for the renaming is the feature coverage in v3 and newer. The SDK v3 provides not only API clients but also other modules. As the first step, it starts supporting OAuth flow out-of-the-box. The secondary reason is to make the names more consistent. The renaming addresses the long-lived confusion between the PyPI project and package names. - ------ - -**Change:** Importing ``slack_sdk.*`` is recommended. You can still use ``slack.*`` with deprecation warnings for a while. - -**Action**: Replace ``from slack import``, ``import slack``, and so on in your source code. - - -Most imports can be simply replaced by ``find your_app -name '*.py' | xargs sed -i '' 's/from slack /from slack_sdk /g'`` or something similar. If you use ``slack.web.classes.*``, the conversion is not so simple that we recommend manually replacing imports for those. - -That said, all existing code can be migrated to v3 without any code changes. If you don't have time for it, you can use ``slack`` package with deprecation warnings saying ``UserWarning: slack package is deprecated. Please use slack_sdk.web/webhook/rtm package instead. For more info, go to https://slack.dev/python-slack-sdk/v3-migration/`` for a while. We won't remove the compatibility in the short term. - ------ - -**Change:** ``slack_sdk`` has no required dependencies. This means ``aiohttp`` is no longer automatically resolved. - -**Action**: Add ``aiohttp`` to ``requirements.txt`` if you use any of ``AsyncWebClient``, ``AsyncWebhookClient``, and ``LegacyWebClient`` - -If you use some modules that require ``aiohttp``, your ``requirements.txt`` needs to explicitly have ``aiohttp``. The ``slack_sdk`` dependency doesn't resolve it for you, unlike ``slackclient`` v2. - - ------ - -**Change:** ``WebClient`` no longer has ``run_async`` and ``aiohttp`` specific options. - -**Action:** If you still need the option or other ``aiohttp`` specific options, use ``LegacyWebClient`` (``slackclient`` v2 compatible) or ``AsyncWebClient``. - -The new ``slack_sdk.web.WebClient`` doesn't rely on ``aiohttp`` internally at all. The class provides only the synchronous way to call Web APIs. If you need a v2 compatible one, you can use ``LegacyWebClient``. Apart from the name, there is no breaking change in the class. - -If you're using ``run_async=True`` option, we highly recommend switching to ``AsyncWebClient``. ``AsyncWebClient`` is a straight-forward async HTTP client. You can expect the class properly works in the nature of ``async/await`` provided by the standard ``asyncio`` library. - -From slackclient 1.x -************************************************* - -Refer to `the migration guide `_. - -.. include:: ../metadata.rst diff --git a/docs-src/web/index.rst b/docs-src/web/index.rst deleted file mode 100644 index 1275024db..000000000 --- a/docs-src/web/index.rst +++ /dev/null @@ -1,611 +0,0 @@ -============================================== -Web Client -============================================== - -The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations we provide out of the box. - -Access Slack's API methods requires an OAuth token -- see the `Tokens & Authentication <../installation/index.html>`_ section for more on how Slack uses OAuth tokens as well as best practices. - -`Each of these API methods `_ is fully documented on our developer site at https://api.slack.com/ - - -Messaging -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Sending a message** - -One of the primary uses of Slack is posting messages to a channel using the channel ID or as a DM to another person using their user ID. This method will handle either a channel ID or a user ID passed to the ``channel`` parameter. - -.. code-block:: python - - import logging - logging.basicConfig(level=logging.DEBUG) - - import os - from slack_sdk import WebClient - from slack_sdk.errors import SlackApiError - - slack_token = os.environ["SLACK_BOT_TOKEN"] - client = WebClient(token=slack_token) - - try: - response = client.chat_postMessage( - channel="C0XXXXXX", - text="Hello from your app! :tada:" - ) - except SlackApiError as e: - # You will get a SlackApiError if "ok" is False - assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' - -Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same -as sending a regular message, but with an additional ``user`` parameter. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - slack_token = os.environ["SLACK_BOT_TOKEN"] - client = WebClient(token=slack_token) - - response = client.chat_postEphemeral( - channel="C0XXXXXX", - text="Hello silently from your app! :tada:", - user="U0XXXXXXX" - ) - -See `chat.postEphemeral `_ for more info. - -**Formatting with Block Kit** - -Messages posted from apps can contain more than just text, though. They can include full user interfaces composed of `blocks `_. - -The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. Blocks specified in a single object literal, so just add additional keys for any optional argument. - -To send a message to a channel, use the channel's ID. For IMs, use the user's ID. - -.. code-block:: python - - client.chat_postMessage( - channel="C0XXXXXX", - blocks=[ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": "Danny Torrence left the following review for your property:" - } - }, - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": " \n :star: \n Doors had too many axe holes, guest in room " + - "237 was far too rowdy, whole place felt stuck in the 1920s." - }, - "accessory": { - "type": "image", - "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg", - "alt_text": "Haunted hotel image" - } - }, - { - "type": "section", - "fields": [ - { - "type": "mrkdwn", - "text": "*Average Rating*\n1.0" - } - ] - } - ] - ) - -**Note:** You can use the `Block Kit Builder `_ to prototype your message's look and feel. - -**Threading Messages** - -Threaded messages are a way of grouping messages together to provide greater context. You can reply to a thread or start a new threaded conversation by simply passing the original message's ``ts`` ID in the ``thread_ts`` attribute when posting a message. If you're replying to a threaded message, you'll pass the `thread_ts` ID of the message you're replying to. - -A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message. - -.. code-block:: python - - response = client.chat_postMessage( - channel="C0XXXXXX", - thread_ts="1476746830.000003", - text="Hello from your app! :tada:" - ) - -By default, ``reply_broadcast`` is set to ``False``. To indicate your reply is germane to all members of a channel, and therefore a notification of the reply should be posted in-channel, set the ``reply_broadcast`` to ``True``. - -.. code-block:: python - - response = client.chat_postMessage( - channel="C0XXXXXX", - thread_ts="1476746830.000003", - text="Hello from your app! :tada:", - reply_broadcast=True - ) - -**Note:** While threaded messages may contain attachments and message buttons, when your reply is broadcast to the -channel, it'll actually be a reference to your reply, not the reply itself. -So, when appearing in the channel, it won't contain any attachments or message buttons. Also note that updates and -deletion of threaded replies works the same as regular messages. - -See the `Threading messages together `_ article for more information. - -**Updating a message** - -Let's say you have a bot which posts the status of a request. When that request changes, you'll want to update the message to reflect it's state. - -.. code-block:: python - - response = client.chat_update( - channel="C0XXXXXX", - ts="1476746830.000003", - text="updates from your app! :tada:" - ) - -See `chat.update `_ for formatting options and some special considerations when calling this with a bot user. - -**Deleting a message** - -Sometimes you need to delete things. - -.. code-block:: python - - response = client.chat_delete( - channel="C0XXXXXX", - ts="1476745373.000002" - ) - -See `chat.delete `_ for more info. - - -**Emoji reactions** - -You can quickly respond to any message on Slack with an emoji reaction. Reactions can be used for any purpose: voting, checking off to-do items, showing excitement -β€” or just for fun. - -This method adds a reaction (emoji) to an item (``file``, ``file comment``, ``channel message``, ``group message``, or ``direct message``). One of file, file_comment, or the combination of channel and timestamp must be specified. - -.. code-block:: python - - response = client.reactions_add( - channel="C0XXXXXXX", - name="thumbsup", - timestamp="1234567890.123456" - ) - -Removing an emoji reaction is basically the same format, but you'll use ``reactions.remove`` instead of ``reactions.add`` - -.. code-block:: python - - response = client.reactions_remove( - channel="C0XXXXXXX", - name="thumbsup", - timestamp="1234567890.123456" - ) - - -See `reactions.add `_ and `reactions.remove `_ for more info. - --------- - -Files -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Uploading files** - -You can upload files onto Slack and share the file with people in channels. - -.. code-block:: python - - response = client.files_upload( - channels="C3UKJTQAC", - file="files.pdf", - title="Test upload" - ) - -See `files.upload `_ for more info. - -**Adding a remote file** - -You can add a file information that is stored in an external storage, not in Slack. - -.. code-block:: python - - response = client.files_remote_add( - external_id="the-all-hands-deck-12345", - external_url="https://{your domain}/files/the-all-hands-deck-12345", - title="The All-hands Deck", - preview_image="./preview.png" # will be displayed in channels - ) - -See `files.remote.add `_ for more info. - - --------- - -Conversations -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The Slack Conversations API provides your app with a unified interface to work with all the channel-like things encountered in Slack; public channels, private channels, direct messages, group direct messages, and our newest channel type, Shared Channels. - -See `Conversations API `_ docs for more info. - -**Start a direct message** - -The ``conversations_open`` method opens either a 1:1 direct message with a single user or a a multi-person direct message, depending on the number of users supplied to the ``users`` parameter. - -*For public or private channels, use the conversations_create method.* - -Provide a ``users`` parameter as an array with 1 to 8 user IDs to open or resume a conversation. Providing only 1 ID will create a direct message. Providing more will create a new multi-party DM or resume an existing conversation. - -Subsequent calls to ``conversations_open`` with the same set of users will return the already existing conversation. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_open(users=["W123456789", "U987654321"]) - -See `conversations.open `_ additional info. - -**Creating channels** - -Creates a new channel, either public or private. The ``name`` parameter is required, may contain numbers, letters, hyphens, and underscores, and must contain fewer than 21 characters. To make the channel private, set the option ``is_private`` parameter to ``True``. - -.. code-block:: python - - import os - from slack_sdk import WebClient - from time import time - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - channel_name = f"my-private-channel-{round(time())}" - response = client.conversations_create( - name=channel_name, - is_private=True - ) - channel_id = response["channel"]["id"] - response = client.conversations_archive(channel=channel_id) - -See `conversations.create `_ additional info. - -**Listing conversations** - -To get a list of all the conversations in a workspace, use ``conversations_list``. By default, only public conversations are returned; use the ``types`` parameter specify which types of conversations you're interested in (Note: ``types`` is a string of comma-separated values) - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_list() - conversations = response["channels"] - -Use the ``types`` parameter to request additional channels, including ``public_channel``, ``private_channel``, ``mpim``, and ``im``. This parameter is a string of comma-separated values. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_list( - types="public_channel, private_channel" - ) - -See `conversations.list `_ for more info. - -Archived channels are included by default. You can exclude them by passing ``exclude_archived=True`` to your request. - -.. code-block:: python - - response = client.conversations_list(exclude_archived=True) - -See `conversations.list `_ for more info. - -**Getting a conversation information** - -To retrieve a set of metadata about a channel (public, private, DM, or multi-party DM), use ``conversations_info``. The ``channel`` parameter is required and must be a valid channel ID. The optional ``include_locale`` boolean parameter will return locale data, which may be useful if you wish to return localized responses. The ``include_num_members`` boolean parameter will return the number of people in a channel. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_info( - channel="C031415926", - include_num_members=1 - ) - -See `conversations.info `_ for more info. - -**Getting members of a conversation** - -To get a list of the members of a conversation, use ``conversations_members`` with the required ``channel`` parameter. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_members(channel="C16180339") - user_ids = response["members"] - -See `conversations.members `_ for more info. - -**Joining a conversation** - -Channels are the social hub of most Slack teams. Here's how you hop into one: - -.. code-block:: python - - response = client.conversations_join(channel="C0XXXXXXY") - -If you are already in the channel, the response is slightly different. -``already_in_channel`` will be true, and a limited ``channel`` object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user. - -See `conversations.join `_ for more info. - -**Leaving a conversation** - -To leave a conversation, use ``conversations_leave`` with the required ``channel`` param containing the ID of the channel to leave. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - response = client.conversations_leave(channel="C27182818") - -See `conversations.leave `_ for more info. - --------- - -Modals -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -**Opening a modal** - -Modals allow you to collect data from users and display dynamic information in a focused surface. - -Modals use the same blocks that compose messages with the addition of an `input` block. - -.. code-block:: python - - from slack_sdk.signature import SignatureVerifier - signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) - - from flask import Flask, request, make_response - app = Flask(__name__) - - @app.route("/slack/events", methods=["POST"]) - def slack_app(): - if not signature_verifier.is_valid_request(request.get_data(), request.headers): - return make_response("invalid request", 403) - - if "payload" in request.form: - payload = json.loads(request.form["payload"]) - - if payload["type"] == "shortcut" \ - and payload["callback_id"] == "open-modal-shortcut": - # Open a new modal by a global shortcut - try: - api_response = client.views_open( - trigger_id=payload["trigger_id"], - view={ - "type": "modal", - "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - return make_response("", 200) - except SlackApiError as e: - code = e.response["error"] - return make_response(f"Failed to open a modal due to {code}", 200) - - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": - # Handle a data submission request from the modal - submitted_data = payload["view"]["state"]["values"] - print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - return make_response("", 200) - - return make_response("", 404) - - if __name__ == "__main__": - # export SLACK_SIGNING_SECRET=*** - # export SLACK_BOT_TOKEN=xoxb-*** - # export FLASK_ENV=development - # python3 app.py - app.run("localhost", 3000) - -See `views.open `_ more details and additional parameters. - -Also, to run the above example, the following `Slack app configurations `_ are required. - -* Enable **Interactivity** with a valid Request URL: ``https://{your-public-domain}/slack/events`` -* Add a global shortcut with the Callback ID: ``open-modal-shortcut`` - -**Updating and pushing modals** - -You can dynamically update a view inside of a modal by calling `views.update` and passing the view ID returned in the previous `views.open` call. - -.. code-block:: python - - private_metadata = "any str data you want to store" - response = client.views_update( - view_id=payload["view"]["id"], - hash=payload["view"]["hash"], - view={ - "type": "modal", - "callback_id": "modal-id", - "private_metadata": private_metadata, - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - -See `views.update `_ for more info. - -If you want to push a new view onto the modal instead of updating an existing view, reference the `views.push `_ documentation. - - --------- - -Rate Limits -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -When posting messages to a channel, Slack allows applications to send no more than one message per channel per second. We allow bursts over that limit for short periods. However, if your app continues to exceed the limit over a longer period of time it will be rate limited. Different API methods have other rate limits -- be sure to `check the limits `_ and test that your application has a graceful fallback if it should hit those limits. - -If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, a JSON object containing the number of calls you have been making, and a Retry-After header containing the number of seconds until you can retry. - -Here's a very basic example of how one might deal with rate limited requests. - -.. code-block:: python - - import os - import time - from slack_sdk import WebClient - from slack_sdk.errors import SlackApiError - - client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) - - # Simple wrapper for sending a Slack message - def send_slack_message(channel, message): - return client.chat_postMessage( - channel=channel, - text=message - ) - - # Make the API call and save results to `response` - channel = "#random" - message = "Hello, from Python!" - # Do until being rate limited - while True: - try: - response = send_slack_message(channel, message) - except SlackApiError as e: - if e.response["error"] == "ratelimited": - # The `Retry-After` header will tell you how long to wait before retrying - delay = int(e.response.headers['Retry-After']) - print(f"Rate limited. Retrying in {delay} seconds") - time.sleep(delay) - response = send_slack_message(channel, message) - else: - # other errors - raise e - -See the documentation on `Rate Limiting `_ for more info. - --------- - -Calling any API methods --------------------------- - -This library covers all the public endpoints as the methods in ``WebClient``. That said, you may see a bit delay of the library release. When you're in a hurry, you can directly use ``api_call`` method as below. - -.. code-block:: python - - import os - from slack_sdk import WebClient - - client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) - response = client.api_call( - api_method='chat.postMessage', - json={'channel': '#random','text': "Hello world!"} - ) - assert response["message"]["text"] == "Hello world!" - - --------- - -AsyncWebClient -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -All the API methods are available in asynchronous programming using the standard `asyncio `_ library. You use ``AsyncWebClient`` instead for it. - -``AsyncWebClient`` internally relies on `AIOHTTP `_ library but it is an optional dependency. So, to use this class, run ``pip install aiohttp`` beforehand. - -.. code-block:: python - - import asyncio - import os - # requires: pip install aiohttp - from slack_sdk.web.async_client import AsyncWebClient - from slack_sdk.errors import SlackApiError - - client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN']) - - # This must be an async method - async def post_message(): - try: - # Don't forget `await` keyword here - response = await client.chat_postMessage( - channel='#random', - text="Hello world!" - ) - assert response["message"]["text"] == "Hello world!" - except SlackApiError as e: - assert e.response["ok"] is False - assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' - print(f"Got an error: {e.response['error']}") - - # This is the simplest way to run the async method - # but you can go with any ways to run it - asyncio.run(post_message()) - -.. include:: ../metadata.rst diff --git a/docs-src/webhook/index.rst b/docs-src/webhook/index.rst deleted file mode 100644 index 383072d0d..000000000 --- a/docs-src/webhook/index.rst +++ /dev/null @@ -1,108 +0,0 @@ -============================================== -Webhook Client -============================================== - -You can use ``slack_sdk.webhook.WebhookClient`` for `Incoming Webhooks `_ and message responses using `response_url in payloads `_. - -Incoming Webhooks -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -To use `Incoming Webhooks `_, just calling ``WebhookClient(url)#send(payload)`` method works for you. The call posts a message in a channel associated with the webhook URL. - -.. code-block:: python - - from slack_sdk.webhook import WebhookClient - url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" - webhook = WebhookClient(url) - - response = webhook.send(text="Hello!") - assert response.status_code == 200 - assert response.body == "ok" - -It's also possible to use ``blocks``, richer message using `Block Kit `_. - -.. code-block:: python - - from slack_sdk.webhook import WebhookClient - url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" - webhook = WebhookClient(url) - response = webhook.send( - text="fallback", - blocks=[ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": "You have a new request:\n**" - } - } - ] - ) - - -response_url -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -User actions in channels generates a `response_url `_ and includes the URL in its payload. You can use ``WebhookClient`` to send a message via the ``response_url``. - -.. code-block:: python - - import os - from slack_sdk.signature import SignatureVerifier - signature_verifier = SignatureVerifier( - signing_secret=os.environ["SLACK_SIGNING_SECRET"] - ) - - from slack_sdk.webhook import WebhookClient - - from flask import Flask, request, make_response - app = Flask(__name__) - - @app.route("/slack/events", methods=["POST"]) - def slack_app(): - # Verify incoming requests from Slack - # https://api.slack.com/authentication/verifying-requests-from-slack - if not signature_verifier.is_valid( - body=request.get_data(), - timestamp=request.headers.get("X-Slack-Request-Timestamp"), - signature=request.headers.get("X-Slack-Signature")): - return make_response("invalid request", 403) - - # Handle a slash command invocation - if "command" in request.form \ - and request.form["command"] == "/reply-this": - response_url = request.form["response_url"] - text = request.form["text"] - webhook = WebhookClient(response_url) - # Send a reply in the channel - response = webhook.send(text=f"You said '{text}'") - # Acknowledge this request - return make_response("", 200) - - return make_response("", 404) - -AsyncWebhookClient -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -The webhook client is available in asynchronous programming using the standard `asyncio `_ library, too. You use ``AsyncWebhookClient`` instead for it. - -``AsyncWebhookClient`` internally relies on `AIOHTTP `_ library but it is an optional dependency. So, to use this class, run ``pip install aiohttp`` beforehand. - -.. code-block:: python - - import asyncio - # requires: pip install aiohttp - from slack_sdk.webhook.async_client import AsyncWebhookClient - url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" - - async def send_message_via_webhook(url: str): - webhook = AsyncWebhookClient(url) - response = await webhook.send(text="Hello!") - assert response.status_code == 200 - assert response.body == "ok" - - # This is the simplest way to run the async method - # but you can go with any ways to run it - asyncio.run(send_message_via_webhook(url)) - -.. include:: ../metadata.rst diff --git a/docs-v2.sh b/docs-v2.sh deleted file mode 100755 index 148224720..000000000 --- a/docs-v2.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -sphinx-build -E -c ./docs-src-v2/_themes/slack/ -b html docs-src-v2 docs-v2 \ - && touch ./docs-v2/.nojekyll \ - && cd docs-v2/ \ - && mv _static/* assets/ \ - && find . -name '*.html' | xargs sed -i '' 's/_static/assets/'g \ - && cd - diff --git a/docs-v2/.buildinfo b/docs-v2/.buildinfo deleted file mode 100644 index d7923b624..000000000 --- a/docs-v2/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 2cfca20515a7ec4c5dfdf57393105f87 -tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs-v2/about.html b/docs-v2/about.html deleted file mode 100644 index d21f22173..000000000 --- a/docs-v2/about.html +++ /dev/null @@ -1,287 +0,0 @@ - - - - - - About — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

AboutΒΆ

-
-

slackclient (Legacy Python Slack SDK)ΒΆ

-

Access the Slack Platform from your Python app. slackclient (Legacy Python Slack SDK) lets you build on the Slack Web APIs pythonically.

-

slackclient (Legacy Python Slack SDK) is proudly maintained with πŸ’– by the Slack Developer Tools team

- -
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/assets/basic.css b/docs-v2/assets/basic.css deleted file mode 100644 index 24bc73e7f..000000000 --- a/docs-v2/assets/basic.css +++ /dev/null @@ -1,855 +0,0 @@ -/* - * basic.css - * ~~~~~~~~~ - * - * Sphinx stylesheet -- basic theme. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -/* -- main layout ----------------------------------------------------------- */ - -div.clearer { - clear: both; -} - -div.section::after { - display: block; - content: ''; - clear: left; -} - -/* -- relbar ---------------------------------------------------------------- */ - -div.related { - width: 100%; - font-size: 90%; -} - -div.related h3 { - display: none; -} - -div.related ul { - margin: 0; - padding: 0 0 0 10px; - list-style: none; -} - -div.related li { - display: inline; -} - -div.related li.right { - float: right; - margin-right: 5px; -} - -/* -- sidebar --------------------------------------------------------------- */ - -div.sphinxsidebarwrapper { - padding: 10px 5px 0 10px; -} - -div.sphinxsidebar { - float: left; - width: 230px; - margin-left: -100%; - font-size: 90%; - word-wrap: break-word; - overflow-wrap : break-word; -} - -div.sphinxsidebar ul { - list-style: none; -} - -div.sphinxsidebar ul ul, -div.sphinxsidebar ul.want-points { - margin-left: 20px; - list-style: square; -} - -div.sphinxsidebar ul ul { - margin-top: 0; - margin-bottom: 0; -} - -div.sphinxsidebar form { - margin-top: 10px; -} - -div.sphinxsidebar input { - border: 1px solid #98dbcc; - font-family: sans-serif; - font-size: 1em; -} - -div.sphinxsidebar #searchbox form.search { - overflow: hidden; -} - -div.sphinxsidebar #searchbox input[type="text"] { - float: left; - width: 80%; - padding: 0.25em; - box-sizing: border-box; -} - -div.sphinxsidebar #searchbox input[type="submit"] { - float: left; - width: 20%; - border-left: none; - padding: 0.25em; - box-sizing: border-box; -} - - -img { - border: 0; - max-width: 100%; -} - -/* -- search page ----------------------------------------------------------- */ - -ul.search { - margin: 10px 0 0 20px; - padding: 0; -} - -ul.search li { - padding: 5px 0 5px 20px; - background-image: url(file.png); - background-repeat: no-repeat; - background-position: 0 7px; -} - -ul.search li a { - font-weight: bold; -} - -ul.search li div.context { - color: #888; - margin: 2px 0 0 30px; - text-align: left; -} - -ul.keywordmatches li.goodmatch a { - font-weight: bold; -} - -/* -- index page ------------------------------------------------------------ */ - -table.contentstable { - width: 90%; - margin-left: auto; - margin-right: auto; -} - -table.contentstable p.biglink { - line-height: 150%; -} - -a.biglink { - font-size: 1.3em; -} - -span.linkdescr { - font-style: italic; - padding-top: 5px; - font-size: 90%; -} - -/* -- general index --------------------------------------------------------- */ - -table.indextable { - width: 100%; -} - -table.indextable td { - text-align: left; - vertical-align: top; -} - -table.indextable ul { - margin-top: 0; - margin-bottom: 0; - list-style-type: none; -} - -table.indextable > tbody > tr > td > ul { - padding-left: 0em; -} - -table.indextable tr.pcap { - height: 10px; -} - -table.indextable tr.cap { - margin-top: 10px; - background-color: #f2f2f2; -} - -img.toggler { - margin-right: 3px; - margin-top: 3px; - cursor: pointer; -} - -div.modindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -div.genindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -/* -- domain module index --------------------------------------------------- */ - -table.modindextable td { - padding: 2px; - border-collapse: collapse; -} - -/* -- general body styles --------------------------------------------------- */ - -div.body { - min-width: 450px; - max-width: 800px; -} - -div.body p, div.body dd, div.body li, div.body blockquote { - -moz-hyphens: auto; - -ms-hyphens: auto; - -webkit-hyphens: auto; - hyphens: auto; -} - -a.headerlink { - visibility: hidden; -} - -a.brackets:before, -span.brackets > a:before{ - content: "["; -} - -a.brackets:after, -span.brackets > a:after { - content: "]"; -} - -h1:hover > a.headerlink, -h2:hover > a.headerlink, -h3:hover > a.headerlink, -h4:hover > a.headerlink, -h5:hover > a.headerlink, -h6:hover > a.headerlink, -dt:hover > a.headerlink, -caption:hover > a.headerlink, -p.caption:hover > a.headerlink, -div.code-block-caption:hover > a.headerlink { - visibility: visible; -} - -div.body p.caption { - text-align: inherit; -} - -div.body td { - text-align: left; -} - -.first { - margin-top: 0 !important; -} - -p.rubric { - margin-top: 30px; - font-weight: bold; -} - -img.align-left, .figure.align-left, object.align-left { - clear: left; - float: left; - margin-right: 1em; -} - -img.align-right, .figure.align-right, object.align-right { - clear: right; - float: right; - margin-left: 1em; -} - -img.align-center, .figure.align-center, object.align-center { - display: block; - margin-left: auto; - margin-right: auto; -} - -img.align-default, .figure.align-default { - display: block; - margin-left: auto; - margin-right: auto; -} - -.align-left { - text-align: left; -} - -.align-center { - text-align: center; -} - -.align-default { - text-align: center; -} - -.align-right { - text-align: right; -} - -/* -- sidebars -------------------------------------------------------------- */ - -div.sidebar { - margin: 0 0 0.5em 1em; - border: 1px solid #ddb; - padding: 7px; - background-color: #ffe; - width: 40%; - float: right; - clear: right; - overflow-x: auto; -} - -p.sidebar-title { - font-weight: bold; -} - -div.admonition, div.topic, blockquote { - clear: left; -} - -/* -- topics ---------------------------------------------------------------- */ - -div.topic { - border: 1px solid #ccc; - padding: 7px; - margin: 10px 0 10px 0; -} - -p.topic-title { - font-size: 1.1em; - font-weight: bold; - margin-top: 10px; -} - -/* -- admonitions ----------------------------------------------------------- */ - -div.admonition { - margin-top: 10px; - margin-bottom: 10px; - padding: 7px; -} - -div.admonition dt { - font-weight: bold; -} - -p.admonition-title { - margin: 0px 10px 5px 0px; - font-weight: bold; -} - -div.body p.centered { - text-align: center; - margin-top: 25px; -} - -/* -- content of sidebars/topics/admonitions -------------------------------- */ - -div.sidebar > :last-child, -div.topic > :last-child, -div.admonition > :last-child { - margin-bottom: 0; -} - -div.sidebar::after, -div.topic::after, -div.admonition::after, -blockquote::after { - display: block; - content: ''; - clear: both; -} - -/* -- tables ---------------------------------------------------------------- */ - -table.docutils { - margin-top: 10px; - margin-bottom: 10px; - border: 0; - border-collapse: collapse; -} - -table.align-center { - margin-left: auto; - margin-right: auto; -} - -table.align-default { - margin-left: auto; - margin-right: auto; -} - -table caption span.caption-number { - font-style: italic; -} - -table caption span.caption-text { -} - -table.docutils td, table.docutils th { - padding: 1px 8px 1px 5px; - border-top: 0; - border-left: 0; - border-right: 0; - border-bottom: 1px solid #aaa; -} - -table.footnote td, table.footnote th { - border: 0 !important; -} - -th { - text-align: left; - padding-right: 5px; -} - -table.citation { - border-left: solid 1px gray; - margin-left: 1px; -} - -table.citation td { - border-bottom: none; -} - -th > :first-child, -td > :first-child { - margin-top: 0px; -} - -th > :last-child, -td > :last-child { - margin-bottom: 0px; -} - -/* -- figures --------------------------------------------------------------- */ - -div.figure { - margin: 0.5em; - padding: 0.5em; -} - -div.figure p.caption { - padding: 0.3em; -} - -div.figure p.caption span.caption-number { - font-style: italic; -} - -div.figure p.caption span.caption-text { -} - -/* -- field list styles ----------------------------------------------------- */ - -table.field-list td, table.field-list th { - border: 0 !important; -} - -.field-list ul { - margin: 0; - padding-left: 1em; -} - -.field-list p { - margin: 0; -} - -.field-name { - -moz-hyphens: manual; - -ms-hyphens: manual; - -webkit-hyphens: manual; - hyphens: manual; -} - -/* -- hlist styles ---------------------------------------------------------- */ - -table.hlist { - margin: 1em 0; -} - -table.hlist td { - vertical-align: top; -} - - -/* -- other body styles ----------------------------------------------------- */ - -ol.arabic { - list-style: decimal; -} - -ol.loweralpha { - list-style: lower-alpha; -} - -ol.upperalpha { - list-style: upper-alpha; -} - -ol.lowerroman { - list-style: lower-roman; -} - -ol.upperroman { - list-style: upper-roman; -} - -:not(li) > ol > li:first-child > :first-child, -:not(li) > ul > li:first-child > :first-child { - margin-top: 0px; -} - -:not(li) > ol > li:last-child > :last-child, -:not(li) > ul > li:last-child > :last-child { - margin-bottom: 0px; -} - -ol.simple ol p, -ol.simple ul p, -ul.simple ol p, -ul.simple ul p { - margin-top: 0; -} - -ol.simple > li:not(:first-child) > p, -ul.simple > li:not(:first-child) > p { - margin-top: 0; -} - -ol.simple p, -ul.simple p { - margin-bottom: 0; -} - -dl.footnote > dt, -dl.citation > dt { - float: left; - margin-right: 0.5em; -} - -dl.footnote > dd, -dl.citation > dd { - margin-bottom: 0em; -} - -dl.footnote > dd:after, -dl.citation > dd:after { - content: ""; - clear: both; -} - -dl.field-list { - display: grid; - grid-template-columns: fit-content(30%) auto; -} - -dl.field-list > dt { - font-weight: bold; - word-break: break-word; - padding-left: 0.5em; - padding-right: 5px; -} - -dl.field-list > dt:after { - content: ":"; -} - -dl.field-list > dd { - padding-left: 0.5em; - margin-top: 0em; - margin-left: 0em; - margin-bottom: 0em; -} - -dl { - margin-bottom: 15px; -} - -dd > :first-child { - margin-top: 0px; -} - -dd ul, dd table { - margin-bottom: 10px; -} - -dd { - margin-top: 3px; - margin-bottom: 10px; - margin-left: 30px; -} - -dl > dd:last-child, -dl > dd:last-child > :last-child { - margin-bottom: 0; -} - -dt:target, span.highlighted { - background-color: #fbe54e; -} - -rect.highlighted { - fill: #fbe54e; -} - -dl.glossary dt { - font-weight: bold; - font-size: 1.1em; -} - -.optional { - font-size: 1.3em; -} - -.sig-paren { - font-size: larger; -} - -.versionmodified { - font-style: italic; -} - -.system-message { - background-color: #fda; - padding: 5px; - border: 3px solid red; -} - -.footnote:target { - background-color: #ffa; -} - -.line-block { - display: block; - margin-top: 1em; - margin-bottom: 1em; -} - -.line-block .line-block { - margin-top: 0; - margin-bottom: 0; - margin-left: 1.5em; -} - -.guilabel, .menuselection { - font-family: sans-serif; -} - -.accelerator { - text-decoration: underline; -} - -.classifier { - font-style: oblique; -} - -.classifier:before { - font-style: normal; - margin: 0.5em; - content: ":"; -} - -abbr, acronym { - border-bottom: dotted 1px; - cursor: help; -} - -/* -- code displays --------------------------------------------------------- */ - -pre { - overflow: auto; - overflow-y: hidden; /* fixes display issues on Chrome browsers */ -} - -pre, div[class*="highlight-"] { - clear: both; -} - -span.pre { - -moz-hyphens: none; - -ms-hyphens: none; - -webkit-hyphens: none; - hyphens: none; -} - -div[class*="highlight-"] { - margin: 1em 0; -} - -td.linenos pre { - border: 0; - background-color: transparent; - color: #aaa; -} - -table.highlighttable { - display: block; -} - -table.highlighttable tbody { - display: block; -} - -table.highlighttable tr { - display: flex; -} - -table.highlighttable td { - margin: 0; - padding: 0; -} - -table.highlighttable td.linenos { - padding-right: 0.5em; -} - -table.highlighttable td.code { - flex: 1; - overflow: hidden; -} - -.highlight .hll { - display: block; -} - -div.highlight pre, -table.highlighttable pre { - margin: 0; -} - -div.code-block-caption + div { - margin-top: 0; -} - -div.code-block-caption { - margin-top: 1em; - padding: 2px 5px; - font-size: small; -} - -div.code-block-caption code { - background-color: transparent; -} - -table.highlighttable td.linenos, -div.doctest > div.highlight span.gp { /* gp: Generic.Prompt */ - user-select: none; -} - -div.code-block-caption span.caption-number { - padding: 0.1em 0.3em; - font-style: italic; -} - -div.code-block-caption span.caption-text { -} - -div.literal-block-wrapper { - margin: 1em 0; -} - -code.descname { - background-color: transparent; - font-weight: bold; - font-size: 1.2em; -} - -code.descclassname { - background-color: transparent; -} - -code.xref, a code { - background-color: transparent; - font-weight: bold; -} - -h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { - background-color: transparent; -} - -.viewcode-link { - float: right; -} - -.viewcode-back { - float: right; - font-family: sans-serif; -} - -div.viewcode-block:target { - margin: -1px -10px; - padding: 0 10px; -} - -/* -- math display ---------------------------------------------------------- */ - -img.math { - vertical-align: middle; -} - -div.body div.math p { - text-align: center; -} - -span.eqno { - float: right; -} - -span.eqno a.headerlink { - position: absolute; - z-index: 1; -} - -div.math:hover a.headerlink { - visibility: visible; -} - -/* -- printout stylesheet --------------------------------------------------- */ - -@media print { - div.document, - div.documentwrapper, - div.bodywrapper { - margin: 0 !important; - width: 100%; - } - - div.sphinxsidebar, - div.related, - div.footer, - #top-link { - display: none; - } -} \ No newline at end of file diff --git a/docs-v2/assets/classic.css b/docs-v2/assets/classic.css deleted file mode 100644 index cceb67ac4..000000000 --- a/docs-v2/assets/classic.css +++ /dev/null @@ -1,266 +0,0 @@ -/* - * classic.css_t - * ~~~~~~~~~~~~~ - * - * Sphinx stylesheet -- classic theme. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -html { - /* CSS hack for macOS's scrollbar (see #1125) */ - background-color: #FFFFFF; -} - -body { - font-family: sans-serif; - font-size: 100%; - background-color: #11303d; - color: #000; - margin: 0; - padding: 0; -} - -div.document { - background-color: #1c4e63; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 0 0 0 230px; -} - -div.body { - background-color: #ffffff; - color: #000000; - padding: 0 20px 30px 20px; -} - -div.footer { - color: #ffffff; - width: 100%; - padding: 9px 0 9px 0; - text-align: center; - font-size: 75%; -} - -div.footer a { - color: #ffffff; - text-decoration: underline; -} - -div.related { - background-color: #133f52; - line-height: 30px; - color: #ffffff; -} - -div.related a { - color: #ffffff; -} - -div.sphinxsidebar { -} - -div.sphinxsidebar h3 { - font-family: 'Trebuchet MS', sans-serif; - color: #ffffff; - font-size: 1.4em; - font-weight: normal; - margin: 0; - padding: 0; -} - -div.sphinxsidebar h3 a { - color: #ffffff; -} - -div.sphinxsidebar h4 { - font-family: 'Trebuchet MS', sans-serif; - color: #ffffff; - font-size: 1.3em; - font-weight: normal; - margin: 5px 0 0 0; - padding: 0; -} - -div.sphinxsidebar p { - color: #ffffff; -} - -div.sphinxsidebar p.topless { - margin: 5px 10px 10px 10px; -} - -div.sphinxsidebar ul { - margin: 10px; - padding: 0; - color: #ffffff; -} - -div.sphinxsidebar a { - color: #98dbcc; -} - -div.sphinxsidebar input { - border: 1px solid #98dbcc; - font-family: sans-serif; - font-size: 1em; -} - - - -/* -- hyperlink styles ------------------------------------------------------ */ - -a { - color: #355f7c; - text-decoration: none; -} - -a:visited { - color: #355f7c; - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - - - -/* -- body styles ----------------------------------------------------------- */ - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: 'Trebuchet MS', sans-serif; - background-color: #f2f2f2; - font-weight: normal; - color: #20435c; - border-bottom: 1px solid #ccc; - margin: 20px -20px 10px -20px; - padding: 3px 0 3px 10px; -} - -div.body h1 { margin-top: 0; font-size: 200%; } -div.body h2 { font-size: 160%; } -div.body h3 { font-size: 140%; } -div.body h4 { font-size: 120%; } -div.body h5 { font-size: 110%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: #c60f0f; - font-size: 0.8em; - padding: 0 4px 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - background-color: #c60f0f; - color: white; -} - -div.body p, div.body dd, div.body li, div.body blockquote { - text-align: justify; - line-height: 130%; -} - -div.admonition p.admonition-title + p { - display: inline; -} - -div.admonition p { - margin-bottom: 5px; -} - -div.admonition pre { - margin-bottom: 5px; -} - -div.admonition ul, div.admonition ol { - margin-bottom: 5px; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -div.warning { - background-color: #ffe4e4; - border: 1px solid #f66; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre { - padding: 5px; - background-color: unset; - color: unset; - line-height: 120%; - border: 1px solid #ac9; - border-left: none; - border-right: none; -} - -code { - background-color: #ecf0f3; - padding: 0 1px 0 1px; - font-size: 0.95em; -} - -th, dl.field-list > dt { - background-color: #ede; -} - -.warning code { - background: #efc2c2; -} - -.note code { - background: #d6d6d6; -} - -.viewcode-back { - font-family: sans-serif; -} - -div.viewcode-block:target { - background-color: #f4debf; - border-top: 1px solid #ac9; - border-bottom: 1px solid #ac9; -} - -div.code-block-caption { - color: #efefef; - background-color: #1c4e63; -} \ No newline at end of file diff --git a/docs-v2/assets/default.css b/docs-v2/assets/default.css deleted file mode 100644 index 80043f544..000000000 --- a/docs-v2/assets/default.css +++ /dev/null @@ -1,79 +0,0 @@ -a.headerlink { - display: none !important; -} - -h2 { - margin-top: -120px; - padding-top: 120px; -} - -.section-title { - font-size: 2rem; - line-height: 2.5rem; - letter-spacing: -1px; - font-weight: 700; - margin: 0 0 1rem; -} - -nav#api_nav .toctree-l1 { - margin-bottom: 1.5rem; -} - -nav#api_nav #api_sections ul { - list-style: none; - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l1>a { - color: #1264a3; - letter-spacing: 0; - font-size: .8rem; - font-weight: 800; - text-transform: uppercase; - border: none; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 { - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 a { - color: #1d1c1d; - text-transform: none; - font-weight: inherit; - padding: 0; - display: block; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - font-size: 15px!important; - line-height:15px; - padding: 4px 8px; - border: 1px solid transparent; - border-radius: 4px; -} - -nav#api_nav #api_sections ul li.toctree-l2 a:hover { - cursor: pointer; - text-decoration: none; - background-color:#e8f5fa; - border-color:#dcf0fb; -} - -nav#api_nav #footer #footer_nav { - font-size: .9375rem; -} - -nav#api_nav #footer #footer_nav a { - border: none; - padding: 0; - color: #616061; -} - -nav#api_nav #footer #footer_nav a:hover { - text-decoration: none; - color: #1c1c1c; -} \ No newline at end of file diff --git a/docs-v2/assets/docs.css b/docs-v2/assets/docs.css deleted file mode 100644 index 7f360ac66..000000000 --- a/docs-v2/assets/docs.css +++ /dev/null @@ -1,34 +0,0 @@ -/* Updates body font */ -body { - font-family: Slack-Lato,appleLogo,sans-serif; -} - -/* Replaces old sidebar styled links */ -.sidebar_menu h5 { - font-size: 0.8rem; - font-weight: 800; - margin-bottom: 3px; -} - -/* Aligns footer navigation to the left of the sidebar */ -.footer_nav { - margin: 0 !important; -} - -/* Styles the signature all nice and pretty <3 */ -#footer_signature { - color:#e01e5a; - font-size:.9rem; - margin-top: 10px; -} - -/* Fixes link hover state */ -a:hover { - text-decoration: underline; -} - -/* Makes footer consistent */ -footer { - background-color: transparent; - border: 0; -} \ No newline at end of file diff --git a/docs-v2/assets/doctools.js b/docs-v2/assets/doctools.js deleted file mode 100644 index daccd209d..000000000 --- a/docs-v2/assets/doctools.js +++ /dev/null @@ -1,315 +0,0 @@ -/* - * doctools.js - * ~~~~~~~~~~~ - * - * Sphinx JavaScript utilities for all documentation. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -/** - * select a different prefix for underscore - */ -$u = _.noConflict(); - -/** - * make the code below compatible with browsers without - * an installed firebug like debugger -if (!window.console || !console.firebug) { - var names = ["log", "debug", "info", "warn", "error", "assert", "dir", - "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", - "profile", "profileEnd"]; - window.console = {}; - for (var i = 0; i < names.length; ++i) - window.console[names[i]] = function() {}; -} - */ - -/** - * small helper function to urldecode strings - */ -jQuery.urldecode = function(x) { - return decodeURIComponent(x).replace(/\+/g, ' '); -}; - -/** - * small helper function to urlencode strings - */ -jQuery.urlencode = encodeURIComponent; - -/** - * This function returns the parsed url parameters of the - * current request. Multiple values per key are supported, - * it will always return arrays of strings for the value parts. - */ -jQuery.getQueryParameters = function(s) { - if (typeof s === 'undefined') - s = document.location.search; - var parts = s.substr(s.indexOf('?') + 1).split('&'); - var result = {}; - for (var i = 0; i < parts.length; i++) { - var tmp = parts[i].split('=', 2); - var key = jQuery.urldecode(tmp[0]); - var value = jQuery.urldecode(tmp[1]); - if (key in result) - result[key].push(value); - else - result[key] = [value]; - } - return result; -}; - -/** - * highlight a given string on a jquery object by wrapping it in - * span elements with the given class name. - */ -jQuery.fn.highlightText = function(text, className) { - function highlight(node, addItems) { - if (node.nodeType === 3) { - var val = node.nodeValue; - var pos = val.toLowerCase().indexOf(text); - if (pos >= 0 && - !jQuery(node.parentNode).hasClass(className) && - !jQuery(node.parentNode).hasClass("nohighlight")) { - var span; - var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); - if (isInSVG) { - span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); - } else { - span = document.createElement("span"); - span.className = className; - } - span.appendChild(document.createTextNode(val.substr(pos, text.length))); - node.parentNode.insertBefore(span, node.parentNode.insertBefore( - document.createTextNode(val.substr(pos + text.length)), - node.nextSibling)); - node.nodeValue = val.substr(0, pos); - if (isInSVG) { - var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); - var bbox = node.parentElement.getBBox(); - rect.x.baseVal.value = bbox.x; - rect.y.baseVal.value = bbox.y; - rect.width.baseVal.value = bbox.width; - rect.height.baseVal.value = bbox.height; - rect.setAttribute('class', className); - addItems.push({ - "parent": node.parentNode, - "target": rect}); - } - } - } - else if (!jQuery(node).is("button, select, textarea")) { - jQuery.each(node.childNodes, function() { - highlight(this, addItems); - }); - } - } - var addItems = []; - var result = this.each(function() { - highlight(this, addItems); - }); - for (var i = 0; i < addItems.length; ++i) { - jQuery(addItems[i].parent).before(addItems[i].target); - } - return result; -}; - -/* - * backward compatibility for jQuery.browser - * This will be supported until firefox bug is fixed. - */ -if (!jQuery.browser) { - jQuery.uaMatch = function(ua) { - ua = ua.toLowerCase(); - - var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || - /(webkit)[ \/]([\w.]+)/.exec(ua) || - /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || - /(msie) ([\w.]+)/.exec(ua) || - ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || - []; - - return { - browser: match[ 1 ] || "", - version: match[ 2 ] || "0" - }; - }; - jQuery.browser = {}; - jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; -} - -/** - * Small JavaScript module for the documentation. - */ -var Documentation = { - - init : function() { - this.fixFirefoxAnchorBug(); - this.highlightSearchWords(); - this.initIndexTable(); - if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { - this.initOnKeyListeners(); - } - }, - - /** - * i18n support - */ - TRANSLATIONS : {}, - PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, - LOCALE : 'unknown', - - // gettext and ngettext don't access this so that the functions - // can safely bound to a different name (_ = Documentation.gettext) - gettext : function(string) { - var translated = Documentation.TRANSLATIONS[string]; - if (typeof translated === 'undefined') - return string; - return (typeof translated === 'string') ? translated : translated[0]; - }, - - ngettext : function(singular, plural, n) { - var translated = Documentation.TRANSLATIONS[singular]; - if (typeof translated === 'undefined') - return (n == 1) ? singular : plural; - return translated[Documentation.PLURALEXPR(n)]; - }, - - addTranslations : function(catalog) { - for (var key in catalog.messages) - this.TRANSLATIONS[key] = catalog.messages[key]; - this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); - this.LOCALE = catalog.locale; - }, - - /** - * add context elements like header anchor links - */ - addContextElements : function() { - $('div[id] > :header:first').each(function() { - $('\u00B6'). - attr('href', '#' + this.id). - attr('title', _('Permalink to this headline')). - appendTo(this); - }); - $('dt[id]').each(function() { - $('\u00B6'). - attr('href', '#' + this.id). - attr('title', _('Permalink to this definition')). - appendTo(this); - }); - }, - - /** - * workaround a firefox stupidity - * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 - */ - fixFirefoxAnchorBug : function() { - if (document.location.hash && $.browser.mozilla) - window.setTimeout(function() { - document.location.href += ''; - }, 10); - }, - - /** - * highlight the search words provided in the url in the text - */ - highlightSearchWords : function() { - var params = $.getQueryParameters(); - var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; - if (terms.length) { - var body = $('div.body'); - if (!body.length) { - body = $('body'); - } - window.setTimeout(function() { - $.each(terms, function() { - body.highlightText(this.toLowerCase(), 'highlighted'); - }); - }, 10); - $('') - .appendTo($('#searchbox')); - } - }, - - /** - * init the domain index toggle buttons - */ - initIndexTable : function() { - var togglers = $('img.toggler').click(function() { - var src = $(this).attr('src'); - var idnum = $(this).attr('id').substr(7); - $('tr.cg-' + idnum).toggle(); - if (src.substr(-9) === 'minus.png') - $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); - else - $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); - }).css('display', ''); - if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { - togglers.click(); - } - }, - - /** - * helper function to hide the search marks again - */ - hideSearchWords : function() { - $('#searchbox .highlight-link').fadeOut(300); - $('span.highlighted').removeClass('highlighted'); - }, - - /** - * make the url absolute - */ - makeURL : function(relativeURL) { - return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; - }, - - /** - * get the current relative url - */ - getCurrentURL : function() { - var path = document.location.pathname; - var parts = path.split(/\//); - $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { - if (this === '..') - parts.pop(); - }); - var url = parts.join('/'); - return path.substring(url.lastIndexOf('/') + 1, path.length - 1); - }, - - initOnKeyListeners: function() { - $(document).keydown(function(event) { - var activeElementType = document.activeElement.tagName; - // don't navigate when in search box or textarea - if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' - && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { - switch (event.keyCode) { - case 37: // left - var prevHref = $('link[rel="prev"]').prop('href'); - if (prevHref) { - window.location.href = prevHref; - return false; - } - case 39: // right - var nextHref = $('link[rel="next"]').prop('href'); - if (nextHref) { - window.location.href = nextHref; - return false; - } - } - } - }); - } -}; - -// quick alias for translations -_ = Documentation.gettext; - -$(document).ready(function() { - Documentation.init(); -}); diff --git a/docs-v2/assets/documentation_options.js b/docs-v2/assets/documentation_options.js deleted file mode 100644 index 9fd31e439..000000000 --- a/docs-v2/assets/documentation_options.js +++ /dev/null @@ -1,12 +0,0 @@ -var DOCUMENTATION_OPTIONS = { - URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), - VERSION: '1.0.1', - LANGUAGE: 'None', - COLLAPSE_INDEX: false, - BUILDER: 'html', - FILE_SUFFIX: '.html', - LINK_SUFFIX: '.html', - HAS_SOURCE: true, - SOURCELINK_SUFFIX: '.txt', - NAVIGATION_WITH_KEYS: false -}; \ No newline at end of file diff --git a/docs-v2/assets/file.png b/docs-v2/assets/file.png deleted file mode 100644 index a858a410e..000000000 Binary files a/docs-v2/assets/file.png and /dev/null differ diff --git a/docs-v2/assets/jquery-3.2.1.js b/docs-v2/assets/jquery-3.2.1.js deleted file mode 100644 index d2d8ca479..000000000 --- a/docs-v2/assets/jquery-3.2.1.js +++ /dev/null @@ -1,10253 +0,0 @@ -/*! - * jQuery JavaScript Library v3.2.1 - * https://jquery.com/ - * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://jquery.org/license - * - * Date: 2017-03-20T18:59Z - */ -( function( global, factory ) { - - "use strict"; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 -// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode -// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common -// enough that all such attempts are guarded in a try block. -"use strict"; - -var arr = []; - -var document = window.document; - -var getProto = Object.getPrototypeOf; - -var slice = arr.slice; - -var concat = arr.concat; - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var fnToString = hasOwn.toString; - -var ObjectFunctionString = fnToString.call( Object ); - -var support = {}; - - - - function DOMEval( code, doc ) { - doc = doc || document; - - var script = doc.createElement( "script" ); - - script.text = code; - doc.head.appendChild( script ).parentNode.removeChild( script ); - } -/* global Symbol */ -// Defining this global in .eslintrc.json would create a danger of using the global -// unguarded in another place, it seems safer to define global only for this module - - - -var - version = "3.2.1", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }, - - // Support: Android <=4.0 only - // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }; - -jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - - // Return all the elements in a clean array - if ( num == null ) { - return slice.call( this ); - } - - // Return just the one element from the set - return num < 0 ? this[ num + this.length ] : this[ num ]; - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - - if ( copyIsArray ) { - copyIsArray = false; - clone = src && Array.isArray( src ) ? src : []; - - } else { - clone = src && jQuery.isPlainObject( src ) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isFunction: function( obj ) { - return jQuery.type( obj ) === "function"; - }, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - - // As of jQuery 3.0, isNumeric is limited to - // strings and numbers (primitives or objects) - // that can be coerced to finite numbers (gh-2662) - var type = jQuery.type( obj ); - return ( type === "number" || type === "string" ) && - - // parseFloat NaNs numeric-cast false positives ("") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - !isNaN( obj - parseFloat( obj ) ); - }, - - isPlainObject: function( obj ) { - var proto, Ctor; - - // Detect obvious negatives - // Use toString instead of jQuery.type to catch host objects - if ( !obj || toString.call( obj ) !== "[object Object]" ) { - return false; - } - - proto = getProto( obj ); - - // Objects with no prototype (e.g., `Object.create( null )`) are plain - if ( !proto ) { - return true; - } - - // Objects with prototype are plain iff they were constructed by a global Object function - Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; - return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; - }, - - isEmptyObject: function( obj ) { - - /* eslint-disable no-unused-vars */ - // See https://github.com/eslint/eslint/issues/6125 - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - type: function( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android <=2.3 only (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; - }, - - // Evaluates a script in a global context - globalEval: function( code ) { - DOMEval( code ); - }, - - // Convert dashed to camelCase; used by the css and data modules - // Support: IE <=9 - 11, Edge 12 - 13 - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // Support: Android <=4.0 only - trim: function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var tmp, args, proxy; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - now: Date.now, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -} ); - -if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; -} - -// Populate the class2type map -jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), -function( i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -} ); - -function isArrayLike( obj ) { - - // Support: real iOS 8.2 only (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = jQuery.type( obj ); - - if ( type === "function" || jQuery.isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.3.3 - * https://sizzlejs.com/ - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2016-08-08 - */ -(function( window ) { - -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + - "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - - // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; - } - - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }, - - disabledAncestor = addCombinator( - function( elem ) { - return elem.disabled === true && ("form" in elem || "label" in elem); - }, - { dir: "parentNode", next: "legend" } - ); - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { - - // ID selector - if ( (m = match[1]) ) { - - // Document context - if ( nodeType === 9 ) { - if ( (elem = context.getElementById( m )) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && (elem = newContext.getElementById( m )) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( (m = match[3]) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !compilerCache[ selector + " " ] && - (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - - if ( nodeType !== 1 ) { - newContext = context; - newSelector = selector; - - // qSA looks outside Element context, which is not what we want - // Thanks to Andrew Dupont for this workaround technique - // Support: IE <=8 - // Exclude object elements - } else if ( context.nodeName.toLowerCase() !== "object" ) { - - // Capture the context ID, setting it first if necessary - if ( (nid = context.getAttribute( "id" )) ) { - nid = nid.replace( rcssescape, fcssescape ); - } else { - context.setAttribute( "id", (nid = expando) ); - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - while ( i-- ) { - groups[i] = "#" + nid + " " + toSelector( groups[i] ); - } - newSelector = groups.join( "," ); - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - } - - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key + " " ] = value); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created element and returns a boolean result - */ -function assert( fn ) { - var el = document.createElement("fieldset"); - - try { - return !!fn( el ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( el.parentNode ) { - el.parentNode.removeChild( el ); - } - // release memory in IE - el = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split("|"), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[i] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for :enabled/:disabled - * @param {Boolean} disabled true for :disabled; false for :enabled - */ -function createDisabledPseudo( disabled ) { - - // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable - return function( elem ) { - - // Only certain elements can match :enabled or :disabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled - if ( "form" in elem ) { - - // Check for inherited disabledness on relevant non-disabled elements: - // * listed form-associated elements in a disabled fieldset - // https://html.spec.whatwg.org/multipage/forms.html#category-listed - // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled - // * option elements in a disabled optgroup - // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled - // All such elements have a "form" property. - if ( elem.parentNode && elem.disabled === false ) { - - // Option elements defer to a parent optgroup if present - if ( "label" in elem ) { - if ( "label" in elem.parentNode ) { - return elem.parentNode.disabled === disabled; - } else { - return elem.disabled === disabled; - } - } - - // Support: IE 6 - 11 - // Use the isDisabled shortcut property to check for disabled fieldset ancestors - return elem.isDisabled === disabled || - - // Where there is no isDisabled, check manually - /* jshint -W018 */ - elem.isDisabled !== !disabled && - disabledAncestor( elem ) === disabled; - } - - return elem.disabled === disabled; - - // Try to winnow out elements that can't be disabled before trusting the disabled property. - // Some victims get caught in our net (label, legend, menu, track), but it shouldn't - // even exist on them, let alone have a boolean value. - } else if ( "label" in elem ) { - return elem.disabled === disabled; - } - - // Remaining elements are neither :enabled nor :disabled - return false; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9-11, Edge - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - if ( preferredDoc !== document && - (subWindow = document.defaultView) && subWindow.top !== subWindow ) { - - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } - } - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert(function( el ) { - el.className = "i"; - return !el.getAttribute("className"); - }); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( el ) { - el.appendChild( document.createComment("") ); - return !el.getElementsByTagName("*").length; - }); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - }); - - // ID filter and find - if ( support.getById ) { - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var elem = context.getElementById( id ); - return elem ? [ elem ] : []; - } - }; - } else { - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - - // Support: IE 6 - 7 only - // getElementById is not reliable as a find shortcut - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var node, i, elems, - elem = context.getElementById( id ); - - if ( elem ) { - - // Verify the id attribute - node = elem.getAttributeNode("id"); - if ( node && node.value === id ) { - return [ elem ]; - } - - // Fall back on getElementsByName - elems = context.getElementsByName( id ); - i = 0; - while ( (elem = elems[i++]) ) { - node = elem.getAttributeNode("id"); - if ( node && node.value === id ) { - return [ elem ]; - } - } - } - - return []; - } - }; - } - - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( el ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll("[msallowcapture^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push("~="); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push(".#.+[+~]"); - } - }); - - assert(function( el ) { - el.innerHTML = "" + - ""; - - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement("input"); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll("[name=d]").length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll(":enabled").length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll(":disabled").length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( el ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - - // Choose the first element that is related to our preferred document - if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { - return -1; - } - if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - return a === document ? -1 : - b === document ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - if ( support.matchesSelector && documentIsHTML && - !compilerCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch (e) {} - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null; -}; - -Sizzle.escape = function( sel ) { - return (sel + "").replace( rcssescape, fcssescape ); -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - while ( (node = elem[i++]) ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[6] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[3] ) { - match[2] = match[4] || match[5] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - // Use previously-cached element index if available - if ( useCache ) { - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - // Don't keep the element (issue #299) - input[0] = null; - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } -}; - -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( (tokens = []) ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - skip = combinator.next, - key = skip || dir, - checkNonElements = base && key === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - return false; - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { - elem = elem[ dir ] || elem; - } else if ( (oldCache = uniqueCache[ key ]) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return (newCache[ 2 ] = oldCache[ 2 ]); - } else { - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { - return true; - } - } - } - } - } - return false; - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), - len = elems.length; - - if ( outermost ) { - outermostContext = context === document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - if ( !context && elem.ownerDocument !== document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context || document, xml) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( (selector = compiled.selector || selector) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { - - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert(function( el ) { - // Should return 1, but returns 4 (following) - return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; -}); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert(function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute("href") === "#" ; -}) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; -}) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( el ) { - return el.getAttribute("disabled") == null; -}) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); -} - -return Sizzle; - -})( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; - -// Deprecated -jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; -jQuery.escapeSelector = Sizzle.escape; - - - - -var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; -}; - - -var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; -}; - - -var rneedsContext = jQuery.expr.match.needsContext; - - - -function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - -}; -var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); - - - -var risSimple = /^.[^:#\[\.,]*$/; - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) !== not; - } ); - } - - // Single element - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - } - - // Arraylike of elements (jQuery, arguments, Array) - if ( typeof qualifier !== "string" ) { - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); - } - - // Simple selector that can be filtered directly, removing non-Elements - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - // Complex selector, compare the two sets, removing non-Elements - qualifier = jQuery.filter( qualifier, elements ); - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; - } ); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - if ( elems.length === 1 && elem.nodeType === 1 ) { - return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; - } - - return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); -}; - -jQuery.fn.extend( { - find: function( selector ) { - var i, ret, - len = this.length, - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - ret = this.pushStack( [] ); - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - return len > 1 ? jQuery.uniqueSort( ret ) : ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -} ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - // Shortcut simple #id case for speed - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - if ( elem ) { - - // Inject the element directly into the jQuery object - this[ 0 ] = elem; - this.length = 1; - } - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - targets = typeof selectors !== "string" && jQuery( selectors ); - - // Positional selectors never match, since there's no _selection_ context - if ( !rneedsContext.test( selectors ) ) { - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( targets ? - targets.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } -} ); - -function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - if ( nodeName( elem, "iframe" ) ) { - return elem.contentDocument; - } - - // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only - // Treat the template element as a regular one in browsers that - // don't support it. - if ( nodeName( elem, "template" ) ) { - elem = elem.content || elem; - } - - return jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -} ); -var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); - - - -// Convert String-formatted options into Object-formatted ones -function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = locked || options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( jQuery.isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory && !firing ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -function Identity( v ) { - return v; -} -function Thrower( ex ) { - throw ex; -} - -function adoptValue( value, resolve, reject, noValue ) { - var method; - - try { - - // Check for promise aspect first to privilege synchronous behavior - if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { - method.call( value ).done( resolve ).fail( reject ); - - // Other thenables - } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { - method.call( value, resolve, reject ); - - // Other non-thenables - } else { - - // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: - // * false: [ value ].slice( 0 ) => resolve( value ) - // * true: [ value ].slice( 1 ) => resolve() - resolve.apply( undefined, [ value ].slice( noValue ) ); - } - - // For Promises/A+, convert exceptions into rejections - // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in - // Deferred#then to conditionally suppress rejection. - } catch ( value ) { - - // Support: Android 4.0 only - // Strict mode functions invoked without .call/.apply get global-object context - reject.apply( undefined, [ value ] ); - } -} - -jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, callbacks, - // ... .then handlers, argument index, [final state] - [ "notify", "progress", jQuery.Callbacks( "memory" ), - jQuery.Callbacks( "memory" ), 2 ], - [ "resolve", "done", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 0, "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 1, "rejected" ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - "catch": function( fn ) { - return promise.then( null, fn ); - }, - - // Keep pipe for back-compat - pipe: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - - // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; - - // deferred.progress(function() { bind to newDefer or newDefer.notify }) - // deferred.done(function() { bind to newDefer or newDefer.resolve }) - // deferred.fail(function() { bind to newDefer or newDefer.reject }) - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - then: function( onFulfilled, onRejected, onProgress ) { - var maxDepth = 0; - function resolve( depth, deferred, handler, special ) { - return function() { - var that = this, - args = arguments, - mightThrow = function() { - var returned, then; - - // Support: Promises/A+ section 2.3.3.3.3 - // https://promisesaplus.com/#point-59 - // Ignore double-resolution attempts - if ( depth < maxDepth ) { - return; - } - - returned = handler.apply( that, args ); - - // Support: Promises/A+ section 2.3.1 - // https://promisesaplus.com/#point-48 - if ( returned === deferred.promise() ) { - throw new TypeError( "Thenable self-resolution" ); - } - - // Support: Promises/A+ sections 2.3.3.1, 3.5 - // https://promisesaplus.com/#point-54 - // https://promisesaplus.com/#point-75 - // Retrieve `then` only once - then = returned && - - // Support: Promises/A+ section 2.3.4 - // https://promisesaplus.com/#point-64 - // Only check objects and functions for thenability - ( typeof returned === "object" || - typeof returned === "function" ) && - returned.then; - - // Handle a returned thenable - if ( jQuery.isFunction( then ) ) { - - // Special processors (notify) just wait for resolution - if ( special ) { - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ) - ); - - // Normal processors (resolve) also hook into progress - } else { - - // ...and disregard older resolution values - maxDepth++; - - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ), - resolve( maxDepth, deferred, Identity, - deferred.notifyWith ) - ); - } - - // Handle all other returned values - } else { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Identity ) { - that = undefined; - args = [ returned ]; - } - - // Process the value(s) - // Default process is resolve - ( special || deferred.resolveWith )( that, args ); - } - }, - - // Only normal processors (resolve) catch and reject exceptions - process = special ? - mightThrow : - function() { - try { - mightThrow(); - } catch ( e ) { - - if ( jQuery.Deferred.exceptionHook ) { - jQuery.Deferred.exceptionHook( e, - process.stackTrace ); - } - - // Support: Promises/A+ section 2.3.3.3.4.1 - // https://promisesaplus.com/#point-61 - // Ignore post-resolution exceptions - if ( depth + 1 >= maxDepth ) { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Thrower ) { - that = undefined; - args = [ e ]; - } - - deferred.rejectWith( that, args ); - } - } - }; - - // Support: Promises/A+ section 2.3.3.3.1 - // https://promisesaplus.com/#point-57 - // Re-resolve promises immediately to dodge false rejection from - // subsequent errors - if ( depth ) { - process(); - } else { - - // Call an optional hook to record the stack, in case of exception - // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); - } - window.setTimeout( process ); - } - }; - } - - return jQuery.Deferred( function( newDefer ) { - - // progress_handlers.add( ... ) - tuples[ 0 ][ 3 ].add( - resolve( - 0, - newDefer, - jQuery.isFunction( onProgress ) ? - onProgress : - Identity, - newDefer.notifyWith - ) - ); - - // fulfilled_handlers.add( ... ) - tuples[ 1 ][ 3 ].add( - resolve( - 0, - newDefer, - jQuery.isFunction( onFulfilled ) ? - onFulfilled : - Identity - ) - ); - - // rejected_handlers.add( ... ) - tuples[ 2 ][ 3 ].add( - resolve( - 0, - newDefer, - jQuery.isFunction( onRejected ) ? - onRejected : - Thrower - ) - ); - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 5 ]; - - // promise.progress = list.add - // promise.done = list.add - // promise.fail = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( - function() { - - // state = "resolved" (i.e., fulfilled) - // state = "rejected" - state = stateString; - }, - - // rejected_callbacks.disable - // fulfilled_callbacks.disable - tuples[ 3 - i ][ 2 ].disable, - - // progress_callbacks.lock - tuples[ 0 ][ 2 ].lock - ); - } - - // progress_handlers.fire - // fulfilled_handlers.fire - // rejected_handlers.fire - list.add( tuple[ 3 ].fire ); - - // deferred.notify = function() { deferred.notifyWith(...) } - // deferred.resolve = function() { deferred.resolveWith(...) } - // deferred.reject = function() { deferred.rejectWith(...) } - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); - return this; - }; - - // deferred.notifyWith = list.fireWith - // deferred.resolveWith = list.fireWith - // deferred.rejectWith = list.fireWith - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( singleValue ) { - var - - // count of uncompleted subordinates - remaining = arguments.length, - - // count of unprocessed arguments - i = remaining, - - // subordinate fulfillment data - resolveContexts = Array( i ), - resolveValues = slice.call( arguments ), - - // the master Deferred - master = jQuery.Deferred(), - - // subordinate callback factory - updateFunc = function( i ) { - return function( value ) { - resolveContexts[ i ] = this; - resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( !( --remaining ) ) { - master.resolveWith( resolveContexts, resolveValues ); - } - }; - }; - - // Single- and empty arguments are adopted like Promise.resolve - if ( remaining <= 1 ) { - adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, - !remaining ); - - // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( master.state() === "pending" || - jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - - return master.then(); - } - } - - // Multiple arguments are aggregated like Promise.all array elements - while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); - } - - return master.promise(); - } -} ); - - -// These usually indicate a programmer mistake during development, -// warn about them ASAP rather than swallowing them by default. -var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; - -jQuery.Deferred.exceptionHook = function( error, stack ) { - - // Support: IE 8 - 9 only - // Console exists when dev tools are open, which can happen at any time - if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); - } -}; - - - - -jQuery.readyException = function( error ) { - window.setTimeout( function() { - throw error; - } ); -}; - - - - -// The deferred used on DOM ready -var readyList = jQuery.Deferred(); - -jQuery.fn.ready = function( fn ) { - - readyList - .then( fn ) - - // Wrap jQuery.readyException in a function so that the lookup - // happens at the time of error handling instead of callback - // registration. - .catch( function( error ) { - jQuery.readyException( error ); - } ); - - return this; -}; - -jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - } -} ); - -jQuery.ready.then = readyList.then; - -// The ready event handler and self cleanup method -function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); -} - -// Catch cases where $(document).ready() is called -// after the browser event has already occurred. -// Support: IE <=9 - 10 only -// Older IE sometimes signals "interactive" too soon -if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - -} else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); -} - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - if ( chainable ) { - return elems; - } - - // Gets - if ( bulk ) { - return fn.call( elems ); - } - - return len ? fn( elems[ 0 ], key ) : emptyGet; -}; -var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - - - -function Data() { - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; - -Data.prototype = { - - cache: function( owner ) { - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - // Always use camelCase key (gh-2257) - if ( typeof data === "string" ) { - cache[ jQuery.camelCase( data ) ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ jQuery.camelCase( prop ) ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - - // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; - }, - access: function( owner, key, value ) { - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - return this.get( owner, key ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key !== undefined ) { - - // Support array or space separated string of keys - if ( Array.isArray( key ) ) { - - // If key is an array of keys... - // We always set camelCase keys, so remove that. - key = key.map( jQuery.camelCase ); - } else { - key = jQuery.camelCase( key ); - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - key = key in cache ? - [ key ] : - ( key.match( rnothtmlwhite ) || [] ); - } - - i = key.length; - - while ( i-- ) { - delete cache[ key[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <=35 - 45 - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } -}; -var dataPriv = new Data(); - -var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - -function getData( data ) { - if ( data === "true" ) { - return true; - } - - if ( data === "false" ) { - return false; - } - - if ( data === "null" ) { - return null; - } - - // Only convert to a number if it doesn't change the string - if ( data === +data + "" ) { - return +data; - } - - if ( rbrace.test( data ) ) { - return JSON.parse( data ); - } - - return data; -} - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = getData( data ); - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } -} ); - -jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE 11 only - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // The key will always be camelCased in Data - data = dataUser.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, key ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each( function() { - - // We always store the camelCased key - dataUser.set( this, key, value ); - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } -} ); - - -jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || Array.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } -} ); - -jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -} ); -var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - -var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var isHiddenWithinTree = function( elem, el ) { - - // isHiddenWithinTree might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - - // Inline style trumps all - return elem.style.display === "none" || - elem.style.display === "" && - - // Otherwise, check computed style - // Support: Firefox <=43 - 45 - // Disconnected elements can have computed display: none, so first confirm that elem is - // in the document. - jQuery.contains( elem.ownerDocument, elem ) && - - jQuery.css( elem, "display" ) === "none"; - }; - -var swap = function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; -}; - - - - -function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, - scale = 1, - maxIterations = 20, - currentValue = tween ? - function() { - return tween.cur(); - } : - function() { - return jQuery.css( elem, prop, "" ); - }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - do { - - // If previous iteration zeroed out, double until we get *something*. - // Use string for doubling so we don't accidentally see scale as unchanged below - scale = scale || ".5"; - - // Adjust and apply - initialInUnit = initialInUnit / scale; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Update scale, tolerating zero or NaN from tween.cur() - // Break the loop if scale is unchanged or perfect, or if we've just had enough. - } while ( - scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations - ); - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; -} - - -var defaultDisplayMap = {}; - -function getDefaultDisplay( elem ) { - var temp, - doc = elem.ownerDocument, - nodeName = elem.nodeName, - display = defaultDisplayMap[ nodeName ]; - - if ( display ) { - return display; - } - - temp = doc.body.appendChild( doc.createElement( nodeName ) ); - display = jQuery.css( temp, "display" ); - - temp.parentNode.removeChild( temp ); - - if ( display === "none" ) { - display = "block"; - } - defaultDisplayMap[ nodeName ] = display; - - return display; -} - -function showHide( elements, show ) { - var display, elem, - values = [], - index = 0, - length = elements.length; - - // Determine new display value for elements that need to change - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - display = elem.style.display; - if ( show ) { - - // Since we force visibility upon cascade-hidden elements, an immediate (and slow) - // check is required in this first loop unless we have a nonempty display value (either - // inline or about-to-be-restored) - if ( display === "none" ) { - values[ index ] = dataPriv.get( elem, "display" ) || null; - if ( !values[ index ] ) { - elem.style.display = ""; - } - } - if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { - values[ index ] = getDefaultDisplay( elem ); - } - } else { - if ( display !== "none" ) { - values[ index ] = "none"; - - // Remember what we're overwriting - dataPriv.set( elem, "display", display ); - } - } - } - - // Set the display of the elements in a second loop to avoid constant reflow - for ( index = 0; index < length; index++ ) { - if ( values[ index ] != null ) { - elements[ index ].style.display = values[ index ]; - } - } - - return elements; -} - -jQuery.fn.extend( { - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - if ( typeof state === "boolean" ) { - return state ? this.show() : this.hide(); - } - - return this.each( function() { - if ( isHiddenWithinTree( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - } ); - } -} ); -var rcheckableType = ( /^(?:checkbox|radio)$/i ); - -var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); - -var rscriptType = ( /^$|\/(?:java|ecma)script/i ); - - - -// We have to close these tags to support XHTML (#13200) -var wrapMap = { - - // Support: IE <=9 only - option: [ 1, "" ], - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] -}; - -// Support: IE <=9 only -wrapMap.optgroup = wrapMap.option; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - - -function getAll( context, tag ) { - - // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret; - - if ( typeof context.getElementsByTagName !== "undefined" ) { - ret = context.getElementsByTagName( tag || "*" ); - - } else if ( typeof context.querySelectorAll !== "undefined" ) { - ret = context.querySelectorAll( tag || "*" ); - - } else { - ret = []; - } - - if ( tag === undefined || tag && nodeName( context, tag ) ) { - return jQuery.merge( [ context ], ret ); - } - - return ret; -} - - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } -} - - -var rhtml = /<|&#?\w+;/; - -function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, contains, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; -} - - -( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Android <=4.1 only - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE <=11 only - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; -} )(); -var documentElement = document.documentElement; - - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 only -// See #13393 for more info -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = {}; - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - // Make a writable jQuery.Event from the native event object - var event = jQuery.event.fix( nativeEvent ); - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: jQuery.isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Includes all common event props including KeyEvent and MouseEvent specific props -jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - - which: function( event ) { - var button = event.button; - - // Add which for key events - if ( event.which == null && rkeyEvent.test( event.type ) ) { - return event.charCode != null ? event.charCode : event.keyCode; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { - if ( button & 1 ) { - return 1; - } - - if ( button & 2 ) { - return 3; - } - - if ( button & 4 ) { - return 2; - } - - return 0; - } - - return event.which; - } -}, jQuery.event.addProp ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - - /* eslint-disable max-len */ - - // See https://github.com/eslint/eslint/issues/3229 - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, - - /* eslint-enable */ - - // Support: IE <=10 - 11, Edge 12 - 13 - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows -function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( ">tbody", elem )[ 0 ] || elem; - } - - return elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; - } else { - elem.removeAttribute( "type" ); - } - - return elem; -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.access( src ); - pdataCur = dataPriv.set( dest, pdataOld ); - events = pdataOld.events; - - if ( events ) { - delete pdataCur.handle; - pdataCur.events = {}; - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = concat.apply( [], args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( isFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl ) { - jQuery._evalUrl( node.src ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); - } - } - } - } - } - } - - return collection; -} - -function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; -} - -jQuery.extend( { - htmlPrefilter: function( html ) { - return html.replace( rxhtmlTag, "<$1>" ); - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = jQuery.contains( elem.ownerDocument, elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } -} ); - -jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } -} ); - -jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -} ); -var rmargin = ( /^margin/ ); - -var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - -var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - - - -( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - div.style.cssText = - "box-sizing:border-box;" + - "position:relative;display:block;" + - "margin:auto;border:1px;padding:1px;" + - "top:1%;width:50%"; - div.innerHTML = ""; - documentElement.appendChild( container ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = divStyle.marginLeft === "2px"; - boxSizingReliableVal = divStyle.width === "4px"; - - // Support: Android 4.0 - 4.3 only - // Some styles come back with percentage values, even though they shouldn't - div.style.marginRight = "50%"; - pixelMarginRightVal = divStyle.marginRight === "4px"; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + - "padding:0;margin-top:1px;position:absolute"; - container.appendChild( div ); - - jQuery.extend( support, { - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelMarginRight: function() { - computeStyleTests(); - return pixelMarginRightVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - } - } ); -} )(); - - -function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; -} - - -function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; -} - - -var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }, - - cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style; - -// Return a css property mapped to a potentially vendor prefixed property -function vendorPropName( name ) { - - // Shortcut for names that are not vendor prefixed - if ( name in emptyStyle ) { - return name; - } - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } -} - -// Return a property mapped along what jQuery.cssProps suggests or to -// a vendor prefixed property. -function finalPropName( name ) { - var ret = jQuery.cssProps[ name ]; - if ( !ret ) { - ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; - } - return ret; -} - -function setPositiveNumber( elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; -} - -function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { - var i, - val = 0; - - // If we already have the right measurement, avoid augmentation - if ( extra === ( isBorderBox ? "border" : "content" ) ) { - i = 4; - - // Otherwise initialize for horizontal or vertical properties - } else { - i = name === "width" ? 1 : 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin, so add it if we want it - if ( extra === "margin" ) { - val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); - } - - if ( isBorderBox ) { - - // border-box includes padding, so remove it if we want content - if ( extra === "content" ) { - val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // At this point, extra isn't border nor margin, so remove border - if ( extra !== "margin" ) { - val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } else { - - // At this point, extra isn't content, so add padding - val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // At this point, extra isn't content nor padding, so add border - if ( extra !== "padding" ) { - val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - return val; -} - -function getWidthOrHeight( elem, name, extra ) { - - // Start with computed style - var valueIsBorderBox, - styles = getStyles( elem ), - val = curCSS( elem, name, styles ), - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // Computed unit is not pixels. Stop here and return. - if ( rnumnonpx.test( val ) ) { - return val; - } - - // Check for style in case a browser which returns unreliable values - // for getComputedStyle silently falls back to the reliable elem.style - valueIsBorderBox = isBorderBox && - ( support.boxSizingReliable() || val === elem.style[ name ] ); - - // Fall back to offsetWidth/Height when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - if ( val === "auto" ) { - val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; - } - - // Normalize "", auto, and prepare for extra - val = parseFloat( val ) || 0; - - // Use the active box-sizing model to add/subtract irrelevant styles - return ( val + - augmentWidthOrHeight( - elem, - name, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles - ) - ) + "px"; -} - -jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: { - "float": "cssFloat" - }, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = jQuery.camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - if ( type === "number" ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = jQuery.camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } -} ); - -jQuery.each( [ "height", "width" ], function( i, name ) { - jQuery.cssHooks[ name ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, name, extra ); - } ) : - getWidthOrHeight( elem, name, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = extra && getStyles( elem ), - subtract = extra && augmentWidthOrHeight( - elem, - name, - extra, - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - styles - ); - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ name ] = value; - value = jQuery.css( elem, name ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; -} ); - -jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } -); - -// These hooks are used by animate to expand properties -jQuery.each( { - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( !rmargin.test( prefix ) ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -} ); - -jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } -} ); - - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && - ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || - jQuery.cssHooks[ tween.prop ] ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" -}; - -jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point -jQuery.fx.step = {}; - - - - -var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - -function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } -} - -// Animations created synchronously will run synchronously -function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = jQuery.now() ); -} - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } -} - -function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 13 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } -} - -function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = jQuery.camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( jQuery.isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - jQuery.proxy( result.stop, result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( jQuery.isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( jQuery.isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } -} ); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - jQuery.isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( jQuery.isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue && type !== false ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } -} ); - -jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -} ); - -// Generate shortcuts for custom animations -jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -} ); - -jQuery.timers = []; -jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = jQuery.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); -}; - -jQuery.fx.interval = 13; -jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); -}; - -jQuery.fx.stop = function() { - inProgress = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 -}; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ -jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); -}; - - -( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; -} )(); - - -var boolHook, - attrHandle = jQuery.expr.attrHandle; - -jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } -} ); - -jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } -} ); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; - -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; -} ); - - - - -var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - -jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } -} ); - -jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } -} ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop -if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; -} - -jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -} ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - -function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; -} - -jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( jQuery.isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; - - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( jQuery.isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; - - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value; - - if ( typeof stateVal === "boolean" && type === "string" ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( jQuery.isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( type === "string" ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = value.match( rnothtmlwhite ) || []; - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } -} ); - - - - -var rreturn = /\r/g; - -jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, isFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } -} ); - -jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } -} ); - -// Radios and checkboxes getter/setter -jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } -} ); - - - - -// Return jQuery for attributes-only inclusion - - -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; - -jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - -} ); - -jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -} ); - - -jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup contextmenu" ).split( " " ), - function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; -} ); - -jQuery.fn.extend( { - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -} ); - - - - -support.focusin = "onfocusin" in window; - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = jQuery.now(); - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; -}; - - -var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && jQuery.type( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } -} - -// Serialize an array of form elements or a set of -// key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = jQuery.isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); -}; - -jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ) - .filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ) - .map( function( i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } -} ); - - -var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( jQuery.isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -/* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -/* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ -function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; -} - -jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; - } - } - match = responseHeaders[ key.toLowerCase() ]; - } - return match == null ? null : match; - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 13 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available, append data to url - if ( s.data ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } -} ); - -jQuery.each( [ "get", "post" ], function( i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( jQuery.isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; -} ); - - -jQuery._evalUrl = function( url ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - "throws": true - } ); -}; - - -jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( jQuery.isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( jQuery.isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var isFunction = jQuery.isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } -} ); - - -jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); -}; -jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); -}; - - - - -jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} -}; - -var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - -support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -support.ajax = xhrSupported = !!xhrSupported; - -jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } -} ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) -jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } -} ); - -// Install script dataType -jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -} ); - -// Handle cache's special case and crossDomain -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } -} ); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain requests - if ( s.crossDomain ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

Tokens & InstallationΒΆ

-
-

Keeping tokens safeΒΆ

-

The OAuth token you use to call the Slack API has access to the data on the workspace where it is installed. Depending on the scopes granted to the token, it potentially has the ability to read and write data. Treat these tokens just as you would a password – don’t publish them, don’t check them into source code, don’t share them with others.

-

🚫Avoid this:

-
token = 'xoxb-111-222-xxxxx'
-
-
-

We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as:

-
SLACK_BOT_TOKEN="xoxb-111-222-xxxxx" python myapp.py
-
-
-

Then retrieve the key with:

-
import os
-SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
-
-
-

For additional information, please see our Safely Storing Credentials page.

-
-
-

Single Workspace InstallΒΆ

-

If you’re building an application for a single Slack workspace, there’s no need to build out the entire OAuth flow.

-

Once you’ve setup your features, click on the Install App to Team button found on the Install App page. -If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to -your workspace for changes to take effect.

-

For additional information, see the Installing Apps of our Building Slack apps page.

-
-
-

Multiple Workspace InstallΒΆ

-

If you intend for an app to be installed on multiple Slack workspaces, you will need to handle this installation via the industry-standard OAuth protocol. You can read more about how Slack handles Oauth.

-

(The OAuth exchange is facilitated via HTTP and requires a webserver; in this example, we’ll use Flask.)

-

To configure your app for OAuth, you’ll need a client ID, a client secret, and a set of one or more scopes that will be applied to the token once it is granted. The client ID and client secret are available from your app’s configuration page. The scopes are determined by the functionality of the app – every method you wish to access has a corresponding scope and your app will need to request that scope in order to be able to access the method. Review Slack’s full list of OAuth scopes.

-
import os
-from slack import WebClient
-from flask import Flask, request
-
-client_id = os.environ["SLACK_CLIENT_ID"]
-client_secret = os.environ["SLACK_CLIENT_SECRET"]
-oauth_scope = os.environ["SLACK_SCOPES"]
-
-app = Flask(__name__)
-
-
-

The OAuth initiation link

-

To begin the OAuth flow that will install your app on a workspace, you’ll need to provide the user with a link to Slack’s OAuth page. This can be a simple link to https://slack.com/oauth/v2/authorize with scope and client_id query parameters, or you can use our pre-built Add to Slack button to do all the work for you.

-

This link directs the user to Slack’s OAuth acceptance page, where the user will review and accept or refuse the permissions your app is requesting as defined by the scope(s).

-
@app.route("/slack/install", methods=["GET"])
-def pre_install():
-  state = "randomly-generated-one-time-value"
-  return '<a href="https://slack.com/oauth/v2/authorize?' \
-    f'scope={oauth_scope}&client_id={client_id}&state={state}">' \
-    'Add to Slack</a>'
-
-
-

The OAuth completion page

-

Once the user has agreed to the permissions you’ve requested, Slack will redirect the user to your auth completion page, which includes a code query string param. You’ll use the code param to call the oauth.v2.access endpoint that will finally grant you the token.

-
@app.route("/slack/oauth_redirect", methods=["GET"])
-def post_install():
-  # Verify the "state" parameter
-
-  # Retrieve the auth code from the request params
-  code_param = request.args['code']
-
-  # An empty string is a valid token for this request
-  client = WebClient()
-
-  # Request the auth tokens from Slack
-  response = client.oauth_v2_access(
-    client_id=client_id,
-    client_secret=client_secret,
-    code=code_param
-  )
-
-
-

A successful request to oauth.v2.access will yield a JSON payload with at least one token, a bot token that begins with xoxb.

-
@app.route("/slack/oauth_redirect", methods=["GET"])
-def post_install():
-  # Verify the "state" parameter
-
-  # Retrieve the auth code from the request params
-  code_param = request.args['code']
-
-  # An empty string is a valid token for this request
-  client = WebClient()
-
-  # Request the auth tokens from Slack
-  response = client.oauth_v2_access(
-    client_id=client_id,
-    client_secret=client_secret,
-    code=code_param
-  )
-  print(response)
-
-  # Save the bot token to an environmental variable or to your data store
-  # for later use
-  os.environ["SLACK_BOT_TOKEN"] = response['access_token']
-
-  # Don't forget to let the user know that OAuth has succeeded!
-  return "Installation is completed!"
-
-if __name__ == "__main__":
-  app.run("localhost", 3000)
-
-
-

Once your user has completed the OAuth flow, you’ll be able to use the provided tokens to call any of Slack’s API methods that require an access token.

-

See the Basic Usage section of this documentation for usage examples.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/basic_usage.html b/docs-v2/basic_usage.html deleted file mode 100644 index 68d9df027..000000000 --- a/docs-v2/basic_usage.html +++ /dev/null @@ -1,691 +0,0 @@ - - - - - - Basic Usage — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

Basic UsageΒΆ

-

The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations we provide out of the box.

-

Access Slack’s API methods requires an OAuth token – see the Tokens & Authentication section for more on how Slack uses OAuth tokens as well as best practices.

-

Each of these API methods is fully documented on our developer site at api.slack.com

-
-

Sending a messageΒΆ

-

One of the primary uses of Slack is posting messages to a channel using the channel ID or as a DM to another person using their user ID. This method will handle either a channel ID or a user ID passed to the channel parameter.

-
import logging
-logging.basicConfig(level=logging.DEBUG)
-
-import os
-from slack import WebClient
-from slack.errors import SlackApiError
-
-slack_token = os.environ["SLACK_API_TOKEN"]
-client = WebClient(token=slack_token)
-
-try:
-  response = client.chat_postMessage(
-    channel="C0XXXXXX",
-    text="Hello from your app! :tada:"
-  )
-except SlackApiError as e:
-  # You will get a SlackApiError if "ok" is False
-  assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
-
-
-

Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same -as sending a regular message, but with an additional user parameter.

-
import os
-from slack import WebClient
-
-slack_token = os.environ["SLACK_API_TOKEN"]
-client = WebClient(token=slack_token)
-
-response = client.chat_postEphemeral(
-  channel="C0XXXXXX",
-  text="Hello silently from your app! :tada:",
-  user="U0XXXXXXX"
-)
-
-
-

See chat.postEphemeral for more info.

-
-
-
-

Formatting with Block KitΒΆ

-

Messages posted from apps can contain more than just text, though. They can include full user interfaces composed of blocks.

-

The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. Blocks specified in a single object literal, so just add additional keys for any optional argument.

-

To send a message to a channel, use the channel’s ID. For IMs, use the user’s ID.

-
client.chat_postMessage(
-  channel="C0XXXXXX",
-  blocks=[
-    {
-      "type": "section",
-      "text": {
-        "type": "mrkdwn",
-        "text": "Danny Torrence left the following review for your property:"
-      }
-    },
-    {
-      "type": "section",
-      "text": {
-        "type": "mrkdwn",
-        "text": "<https://example.com|Overlook Hotel> \n :star: \n Doors had too many axe holes, guest in room " +
-          "237 was far too rowdy, whole place felt stuck in the 1920s."
-      },
-      "accessory": {
-        "type": "image",
-        "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg",
-        "alt_text": "Haunted hotel image"
-      }
-    },
-    {
-      "type": "section",
-      "fields": [
-        {
-          "type": "mrkdwn",
-          "text": "*Average Rating*\n1.0"
-        }
-      ]
-    }
-  ]
-)
-
-
-

Note: You can use the Block Kit Builder to prototype your message’s look and feel.

-
-
-
-

Threading MessagesΒΆ

-

Threaded messages are a way of grouping messages together to provide greater context. You can reply to a thread or start a new threaded conversation by simply passing the original message’s ts ID in the thread_ts attribute when posting a message. If you’re replying to a threaded message, you’ll pass the thread_ts ID of the message you’re replying to.

-

A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message.

-
response = client.chat_postMessage(
-  channel="C0XXXXXX",
-  thread_ts="1476746830.000003",
-  text="Hello from your app! :tada:"
-)
-
-
-

By default, reply_broadcast is set to False. To indicate your reply is germane to all members of a channel, and therefore a notification of the reply should be posted in-channel, set the reply_broadcast to True.

-
response = client.chat_postMessage(
-  channel="C0XXXXXX",
-  thread_ts="1476746830.000003",
-  text="Hello from your app! :tada:",
-  reply_broadcast=True
-)
-
-
-

Note: While threaded messages may contain attachments and message buttons, when your reply is broadcast to the -channel, it’ll actually be a reference to your reply, not the reply itself. -So, when appearing in the channel, it won’t contain any attachments or message buttons. Also note that updates and -deletion of threaded replies works the same as regular messages.

-

See the Threading messages together -article for more information.

-
-
-
-

Updating a messageΒΆ

-

Let’s say you have a bot which posts the status of a request. When that request changes, you’ll want to update the message to reflect it’s state.

-
response = client.chat_update(
-  channel="C0XXXXXX",
-  ts="1476746830.000003",
-  text="updates from your app! :tada:"
-)
-
-
-

See chat.update for formatting options and some special considerations when calling this with a bot user.

-
-
-
-

Deleting a messageΒΆ

-

Sometimes you need to delete things.

-
response = client.chat_delete(
-  channel="C0XXXXXX",
-  ts="1476745373.000002"
-)
-
-
-

See chat.delete for more info.

-
-
-
-

Opening a modalΒΆ

-

Modals allow you to collect data from users and display dynamic information in a focused surface.

-

Modals use the same blocks that compose messages with the addition of an input block.

-
# This module is available since v2.6
-from slack.signature import SignatureVerifier
-signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"])
-
-from flask import Flask, request, make_response
-app = Flask(__name__)
-
-@app.route("/slack/events", methods=["POST"])
-def slack_app():
-  if not signature_verifier.is_valid_request(request.get_data(), request.headers):
-    return make_response("invalid request", 403)
-
-  if "payload" in request.form:
-    payload = json.loads(request.form["payload"])
-
-    if payload["type"] == "shortcut" \
-      and payload["callback_id"] == "open-modal-shortcut":
-      # Open a new modal by a global shortcut
-      try:
-        api_response = client.views_open(
-          trigger_id=payload["trigger_id"],
-          view={
-            "type": "modal",
-            "callback_id": "modal-id",
-            "title": {
-              "type": "plain_text",
-              "text": "Awesome Modal"
-            },
-            "submit": {
-              "type": "plain_text",
-              "text": "Submit"
-            },
-            "close": {
-              "type": "plain_text",
-              "text": "Cancel"
-            },
-            "blocks": [
-              {
-                "type": "input",
-                "block_id": "b-id",
-                "label": {
-                  "type": "plain_text",
-                  "text": "Input label",
-                },
-                "element": {
-                  "action_id": "a-id",
-                  "type": "plain_text_input",
-                }
-              }
-            ]
-          }
-        )
-        return make_response("", 200)
-      except SlackApiError as e:
-        code = e.response["error"]
-        return make_response(f"Failed to open a modal due to {code}", 200)
-
-    if payload["type"] == "view_submission" \
-      and payload["view"]["callback_id"] == "modal-id":
-      # Handle a data submission request from the modal
-      submitted_data = payload["view"]["state"]["values"]
-      print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
-      return make_response("", 200)
-
-  return make_response("", 404)
-
-if __name__ == "__main__":
-  # export SLACK_SIGNING_SECRET=***
-  # export SLACK_API_TOKEN=xoxb-***
-  # export FLASK_ENV=development
-  # python3 app.py
-  app.run("localhost", 3000)
-
-
-

See views.open more details and additional parameters.

-

Also, to run the above example, the following Slack app configurations are required.

-
    -
  • Enable Interactivity with a valid Request URL: https://{your-public-domain}/slack/events

  • -
  • Add a global shortcut with the Callback ID: open-modal-shortcut

  • -
-
-
-
-

Updating and pushing modalsΒΆ

-

You can dynamically update a view inside of a modal by calling views.update and passing the view ID returned in the previous views.open call.

-
private_metadata = "any str data you want to store"
-response = client.views_update(
-  view_id=payload["view"]["id"],
-  hash=payload["view"]["hash"],
-  view={
-    "type": "modal",
-    "callback_id": "modal-id",
-    "private_metadata": private_metadata,
-    "title": {
-      "type": "plain_text",
-      "text": "Awesome Modal"
-    },
-    "submit": {
-      "type": "plain_text",
-      "text": "Submit"
-    },
-    "close": {
-      "type": "plain_text",
-      "text": "Cancel"
-    },
-    "blocks": [
-      {
-        "type": "input",
-        "block_id": "b-id",
-        "label": {
-          "type": "plain_text",
-          "text": "Input label",
-        },
-        "element": {
-          "action_id": "a-id",
-          "type": "plain_text_input",
-        }
-      }
-    ]
-  }
-)
-
-
-

See views.update for more info.

-

If you want to push a new view onto the modal instead of updating an existing view, reference the views.push documentation.

-
-
-
-

Emoji reactionsΒΆ

-

You can quickly respond to any message on Slack with an emoji reaction. Reactions can be used for any purpose: voting, checking off to-do items, showing excitement -β€” or just for fun.

-

This method adds a reaction (emoji) to an item (file, file comment, channel message, group message, or direct message). One of file, file_comment, or the combination of channel and timestamp must be specified.

-
response = client.reactions_add(
-  channel="C0XXXXXXX",
-  name="thumbsup",
-  timestamp="1234567890.123456"
-)
-
-
-

Removing an emoji reaction is basically the same format, but you’ll use reactions.remove instead of reactions.add

-
response = client.reactions_remove(
-  channel="C0XXXXXXX",
-  name="thumbsup",
-  timestamp="1234567890.123456"
-)
-
-
-

See reactions.add and reactions.remove for more info.

-
-
-
-

Listing public channelsΒΆ

-

At some point, you’ll want to find out what channels are available to your app. This is how you get that list.

-
response = client.conversations_list(types="public_channel")
-
-
-

Archived channels are included by default. You can exclude them by passing exclude_archived=1 to your request.

-
response = client.conversations_list(exclude_archived=1)
-
-
-

See conversations.list for more info.

-
-
-
-

Getting a channel’s infoΒΆ

-

Once you have the ID for a specific channel, you can fetch information about that channel.

-
response = client.conversations_info(channel="C0XXXXXXX")
-
-
-

See conversations.info for more info.

-
-
-
-

Joining a channelΒΆ

-

Channels are the social hub of most Slack teams. Here’s how you hop into one:

-
response = client.conversations_join(channel="C0XXXXXXY")
-
-
-

If you are already in the channel, the response is slightly different. -already_in_channel will be true, and a limited channel object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user.

-

See conversations.join for more info.

-
-
-
-

Leaving a channelΒΆ

-

Maybe you’ve finished up all the business you had in a channel, or maybe you -joined one by accident. This is how you leave a channel.

-
response = client.conversations_leave(channel="C0XXXXXXX")
-
-
-

See conversations.leave for more info.

-
-
-
-

Listing team membersΒΆ

-
response = client.users_list()
-users = response["members"]
-user_ids = list(map(lambda u: u["id"], users))
-
-
-

See users.list for more info.

-
-
-
-

Uploading filesΒΆ

-
response = client.files_upload(
-  channels="C3UKJTQAC",
-  file="files.pdf",
-  title="Test upload"
-)
-
-
-

See files.upload for more info.

-
-
-
-

Calling any API methodsΒΆ

-

This library covers all the public endpoints as the methods in WebClient. That said, you may see a bit delay of the library release. When you’re in a hurry, you can directly use api_call method as below.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ['SLACK_API_TOKEN'])
-response = client.api_call(
-  api_method='chat.postMessage',
-  json={'channel': '#random','text': "Hello world!"}
-)
-assert response["message"]["text"] == "Hello world!"
-
-
-
-
-
-

Web API Rate LimitsΒΆ

-

When posting messages to a channel, Slack allows applications to send no more than one message per channel per second. We allow bursts over that limit for short periods. However, if your app continues to exceed the limit over a longer period of time it will be rate limited. Different API methods have other rate limits – be sure to check the limits and test that your application has a graceful fallback if it should hit those limits.

-

If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, a JSON object containing the number of calls you have been making, and a Retry-After header containing the number of seconds until you can retry.

-

Here’s a very basic example of how one might deal with rate limited requests.

-
import os
-import time
-from slack import WebClient
-from slack.errors import SlackApiError
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-
-# Simple wrapper for sending a Slack message
-def send_slack_message(channel, message):
-  return client.chat_postMessage(
-    channel=channel,
-    text=message
-  )
-
-# Make the API call and save results to `response`
-channel = "#random"
-message = "Hello, from Python!"
-# Do until being rate limited
-while True:
-  try:
-    response = send_slack_message(channel, message)
-  except SlackApiError as e:
-    if e.response["error"] == "ratelimited":
-      # The `Retry-After` header will tell you how long to wait before retrying
-      delay = int(e.response.headers['Retry-After'])
-      print(f"Rate limited. Retrying in {delay} seconds")
-      time.sleep(delay)
-      response = send_slack_message(channel, message)
-    else:
-      # other errors
-      raise e
-
-
-

See the documentation on Rate Limiting for more info.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/changelog.html b/docs-v2/changelog.html deleted file mode 100644 index 394351b64..000000000 --- a/docs-v2/changelog.html +++ /dev/null @@ -1,754 +0,0 @@ - - - - - - Changelog — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

ChangelogΒΆ

-
-

v3.0.0 (2020-11-09)ΒΆ

-

This is the first stable version of slack_sdk v3. The remarkable updates in this major version are:

-
    -
  • Newly added OAuth flow support

  • -
  • Better Async/sync separation for WebClient and WebhookClient

  • -
  • Renamed packages (from slack to slack_sdk) with deprecation warnings

  • -
-

Refer to v3.0.0 milestone and the website for details. If you’re a slackclient user, the migration guide for slackclient v2.x users is available at https://slack.dev/python-slack-sdk/v3-migration/

-
-
-

v2.9.3 (2020-10-20)ΒΆ

-

Refer to v2.9.3 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [Block Kit] #851 #852 Set default_type for HeaderBlock text - Thanks @fwump38

  2. -
  3. [Block Kit] #853 #854 Enable to use input blocks in Home tab views - Thanks @fwump38

  4. -
  5. [RTMClient] #857 #846 RTMClient does not pass timeout value to WebClient - Thanks @Luden @seratch

  6. -
-
-
-

v2.9.2 (2020-10-09)ΒΆ

-

Refer to v2.9.2 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [Block Kit] #841 Dispatch Action in Input blocks - Thanks @seratch

  2. -
  3. [WebClient] #838 Add apps.event.authorizations.list and other APIs - Thanks @seratch

  4. -
  5. [WebClient][WebhookClient] #829 Improve error body parser to handle no charset responses - Thanks @adamchainz @seratch

  6. -
  7. [Block Kit] #824 Correct text field validation in Header blocks - Thanks @seratch

  8. -
-
-
-

v2.9.1 (2020-09-23)ΒΆ

-

Refer to v2.9.1 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient][WebhookClient] #820 #821 #822 The proxy option in WebClient/WebhookClient no longer works - Thanks @seratch

  2. -
-
-
-

v2.9.0 (2020-09-17)ΒΆ

-

Refer to v2.9.0 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] #811 Add workflows.* API support - Thanks @misscoded

  2. -
  3. [WebClient] #810 #809 Only set default filename in files_upload if file is an instance of str - Thanks @csaska

  4. -
-
-
-

v2.8.2 (2020-09-04)ΒΆ

-

Refer to v2.8.2 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] #795 #794 Add admin.conversations.* API methods in WebClient/AsyncWebClient - Thanks @ruberVulpes

  2. -
  3. [WebClient] #796 Fix a link to the Static options documentation - Thanks @Jamim

  4. -
-
-
-

v2.8.1 (2020-08-28)ΒΆ

-

Refer to v2.8.1 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] #778 #779 Adding support for View objects for views.push/update/publish - Thanks @ruberVulpes

  2. -
  3. [WebClient] #786 Fix admin.conversations.restrictAccess.* methods to match documentation - Thanks @ruberVulpes

  4. -
-
-
-

v2.8.0 (2020-08-06)ΒΆ

-

Refer to v2.8.0 milestone to know the complete list of the issues resolved by this release.

-

New Features

-
    -
  1. [WebClient] #765 #766 Introduce AsyncWebClient/AsyncWebhookClient providing coroutines - Thanks @seratch

  2. -
  3. [Block Kit] #767 #768 Add β€œheader” block support - Thanks @mwbrooks

  4. -
-

Updates

-
    -
  1. [WebClient] #738 Add HTTP_PROXY, HTTPS_PROXY env variable support in async WebClient - Thanks @iamtofr @seratch

  2. -
  3. [WebClient] #769 #773 Enable User-Agent to have additional info part - Thanks @seratch

  4. -
  5. [WebClient] #770 #771 Fix a bug where files.upload’s file param doesn’t accept bytes data - Thanks @seratch

  6. -
-
-
-

v2.7.3 (2020-07-20)ΒΆ

-

Refer to v2.7.3 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] #754 Fix #729 Add admin.conversations.restrictAccess.*, conversations.mark API - Thanks @ruberVulpes @kian2attari

  2. -
  3. [WebClient] #758 Fix #757 Add admin.usergroups.addTeams, calls.participants.remove API - Thanks @seratch

  4. -
  5. [WebClient] #727 Fix #645 Unclosed client session - Thanks @NoAnyLove @jourdanrodrigues

  6. -
  7. [WebClient] #745 Fix #744 a validation logic bug in DatePickerElement - Thanks @dzudi941

  8. -
  9. [WebClient] #752 Fix #733 Better error handling when getting TimeoutError in RTMClient#start() - Thanks @liorblob @seratch

  10. -
  11. [WebClient] #751 Fix #718 by handling unexpected response body format - Thanks @jeffbuswell @seratch

  12. -
-
-
-

v2.7.2 (2020-06-23)ΒΆ

-

Refer to v2.7.2 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] Fix #728 by adding bytearray support in files_upload (sync mode) - Thanks @sofya-salmanova @seratch

  2. -
  3. [WebClient] #726 Fix InputBlock.hint validation failure - Thanks @jourdanrodrigues

  4. -
  5. [WebClient] #723 Correct the default value of InputBlock.label, hint - Thanks @jourdanrodrigues

  6. -
-
-
-

v2.7.1 (2020-06-04)ΒΆ

-

This release includes the fixes for regression bugs in WebClient since v2.6.0. Refer to v2.7.1 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [WebClient] #716 #712 Support timeout in sync sync web clients - Thanks @DanialErfanian @seratch

  2. -
  3. [WebClient] #713 Support custom SSL context in sync sync web clients - Thanks @austinbutler

  4. -
  5. [WebClient] #715 #714 Support proxy in sync sync web clients - Thanks @austinbutler @seratch

  6. -
-
-
-

v2.7.0 (2020-06-02)ΒΆ

-

Refer to v2.7.0 milestone to know the complete list of the issues resolved by this release.

-

New Features

-
    -
  1. [WebhookClient] #707 #270 #531 Add WebhookClient for Incoming Webhooks & response_url - Thanks @seratch @chubz @Ambro17

  2. -
-

Updates

-
    -
  1. [WebClient] #704 #695 Add calls_* methods to WebClient and CallBlock in Block Kit classes - Thanks @seratch

  2. -
  3. [WebClient] #710 #536 Allow Tokens to be specified per request - Thanks @seratch

  4. -
  5. [WebClient] #709 #708 Add default_to_current_conversation in conversations_select elements - Thanks @seratch

  6. -
-
-
-

v2.6.2 (2020-05-28)ΒΆ

-

Refer to v2.6.2 milestone to know the complete details of this release.

-

Updates

-
    -
  1. [WebClient] #705 WebClient’s paginated API calls may fail with no params - Thanks @seratch

  2. -
-
-
-

v2.6.1 (2020-05-24)ΒΆ

-

This patch release is a quick fix for #701, a major issue that affected RTMClient users in v2.6.0. The malfunction was introduced by #667 trying to address #558 #619. Those issues were reopened and will be resolved by another approach. Refer to v2.6.1 milestone to know the complete list of the issues resolved by this release.

-

Updates

-
    -
  1. [RTMClient] #701 RTMClient drops some messages when they come in rapid succession - Thanks @pbrackin @seratch

  2. -
-
-
-

v2.6.0 (2020-05-21)ΒΆ

-

Refer to v2.6.0 milestone to know the complete list of the issues resolved by this release.

-

New Features

-
    -
  1. [Block Kit] #659 Add complete supports for Block Kit components and fixed a few existing bugs as well (#500 #519 #623 #632 #635 #639 #676 #699) - Thanks @seratch @diurnalist @ruberVulpes @jeremyschulman @e271828- @RodneyU215

  2. -
  3. [Signature] #686 Add slack.signature.SignatureVerifier for request verification - Thanks @seratch

  4. -
  5. [WebClient] #682 Add missing Grid admin APIs (admin.usergroups.*, admin.users.*, admin.apps.*) - Thanks @stevengill @seratch

  6. -
-

Updates

-
    -
  1. [WebClient][RTMClient] Fixed a bunch of the currency issues this SDK had (#429 #463 #492 #497 #530 #569 #605 #613 #626 #630 #631 #633 #669) - Thanks @seratch @aaguilartablada @aoberoi @stevengill @marshallino16

  2. -
  3. [WebClient] #681 #560 Enable using bool values for request parameters - Thanks @roman-kachanovsky @seratch

  4. -
  5. [WebClient] #661 #678 Improve handling of required β€œids” parameters (e.g., channel_ids, users) - Thanks @seratch

  6. -
  7. [WebClient] #680 Add non-conversation API deprecation warnings - Thanks @seratch

  8. -
  9. [WebClient] #671 #670 Enable passing None values for request parameters (they used to result in errors) - Thanks @yuji38kwmt @seratch

  10. -
  11. [WebClient] #673 Fix #672 files.upload fails with a filepath containing multi byte chars - Thanks @yuji38kwmt @seratch

  12. -
  13. [WebClient] #656 Fix #594 preview_image for files.remote.add API method is not properly supported - Thanks @Eothred @seratch

  14. -
  15. [Maintenance] #618 Add py.typed file to package distribution - Thanks @JKillian

  16. -
  17. [WebClient] #599 Strip token string parameters of whitespace - Thanks @TheFrozenFire

  18. -
  19. [WebClient] #692 Fix superfluous_charset warnings since v2.4.0 - Thanks @seratch

  20. -
  21. [WebClient] #652 Update oauth_v2_access to include redirect_uri (as optional) - Thanks @tomasreimers

  22. -
-
-
-

v2.5.0 (2019-12-09)ΒΆ

-

New Features

-
    -
  1. [WebClient] Adding new oauth.v2.access Web API method. #577

  2. -
-
-
-

v2.4.0 (2019-11-27)ΒΆ

-

New Features

-
    -
  1. [WebClient] Adding new admin.* Web API methods. #571

  2. -
-

Updates -1. [WebClient] We’re no longer validating token types for Web API methods. Improves compatibility with granular bot permissions. #568 (Thanks @Smotko) -2. [WebClient] Correcting typos in descriptions #554 (Thanks @phamk) -3. [WebClient] Fixed β€˜iteracting’ typo in library file headers #564 (Thanks @acabey) -4. [Message Builders] Remove value from LinkButtonElement #563 (Thanks @pedroma)

-
-
-

v2.3.1 (2019-10-29)ΒΆ

-

Updates

-
    -
  1. [WebClient] Fixing a regression that causes the client to close sessions prematurely. #544 (Thanks @fatih-acar!)

  2. -
  3. [WebClient] Adding required missing view param to views.update Web API method. #542

  4. -
-
-
-

v2.3.0 (2019-10-22)ΒΆ

-

New Features

-
    -
  1. [WebClient] Adding new views.publish Web API method. #540

  2. -
-

Updates

-
    -
  1. [WebClient] Some server responses don’t return json. Correcting initial assumption. #540

  2. -
  3. [Maintenance] Add py.typed to mark the library to support type hinting #524s

  4. -
-
-
-

v2.2.1 (2019-10-08)ΒΆ

-

Updates

-
    -
  1. [Docs] Fix Indentation of Code Snippets in README.md #525 (Thanks @abhishekjiitr)

  2. -
  3. [WebClient] Fix Web Client custom iterator #521 (Thanks @smaeda-ks)

  4. -
  5. [WebClient] Oauth previously failed to pass along credentials properly. This is fixed now. #527

  6. -
  7. [WebClient] When a SlackApiError occurs we’re now passing the entire SlackResponse into the exception. #527

  8. -
-
-
-

v2.2.0 (2019-09-25)ΒΆ

-

New Features

-
    -
  1. [WebClient] Adding new admin and remote files API methods. #501

  2. -
  3. [WebClient] Adding new view API methods. #517

  4. -
-

Updates

-
    -
  1. [Message Builders] Update BlockAttachment to not send invalid JSON due to fields attribute #473 (Thanks @paul-griffith)

  2. -
  3. [Docs] Add RTM section for docs v2 #477 (Thanks @shanedewael)

  4. -
  5. [Docs] Fix typo; recieved -> received #478 (Thanks @joakimnordling)

  6. -
  7. [Docs] Fix block kit link & update docs #484 (Thanks @clavin)

  8. -
  9. [RTMClient] Return callback from RTMClient.run_on #490 (Thanks @clavin)

  10. -
  11. [Docs] Fix link to Auth Guide in readme #498 (Thanks @asherf)

  12. -
  13. [Docs] Fix missing word and typo #512 (Thanks @marks)

  14. -
  15. [Message Builders] bugfix for value length in button elements #514 (Thanks @avanderm)

  16. -
  17. [Docs] Fixes formatting #515 (Thanks @vpetersson)

  18. -
  19. [Docs] Improve a code snippet on README #516 (Thanks @seratch)

  20. -
  21. [WebClient] Fixed an OAuth Headers bug and made the token param optional. #517

  22. -
-
-
-

v2.1.0 (2019-07-01)ΒΆ

-

New Features

-
    -
  1. Type-hinted helper classes for building messages in v2 #400 (Thanks @paul-griffith)

  2. -
-

Breaking Changes

-
    -
  1. [RTMClient] Converted the RTMClient#typing() function to async #446

  2. -
-

Updates

-
    -
  1. [RTMClient] Handle case in which aiohttp closes the websocket due to lack of ping responses. #453 (Thanks @flyte)

  2. -
  3. Modify package identifier in user agent to match v1.x identifier #418 (Thanks @aoberoi)

  4. -
  5. [WebClient] Fixed typo in Scheduled message #428 & #435 (Thanks @splinterific)

  6. -
  7. Transform install_requires of β€˜aiodns’ into extras_require. #440 (Thanks @staticdev)

  8. -
-

Thank you!! -To everyone who’s opened, commented or reacted to an issue; this project is better because of you! -Thank you for helping the Slack community!

-
-
-

v2.0.0 (2019-04-29)ΒΆ

-

Original RFC

-

v2 PR

-

New Features

-
    -
  1. Client Decomposition: We’ve split the client into two.

  2. -
-
-
    -
  1. WebClient: A HTTP client focused on Slack’s Web API.

  2. -
  3. RTMClient: A websocket client focused on Slack’s RTM API.

  4. -
-
-
    -
  1. RTMClient: Completely redesigned, this client allows you to link your application’s callbacks to corresponding Slack events.

  2. -
  3. WebClient: The WebClient now provides built-in methods for Slack’s Web API. These methods act as helpers enabling you to focus less on how the request is constructed. Here are a few things that this provides:

  4. -
-
-
    -
  1. Basic information about each method through the docstring.

  2. -
  3. Easy File Uploads: You can now pass in the location of a file and the library will handle opening and retrieving the file object to be transmitted.

  4. -
  5. Token type validation: This gives you better error messaging when you’re attempting to consume an api method that your token doesn’t have access to.

  6. -
  7. Constructs requests using Slack’s preferred HTTP methods and content-types.

  8. -
-
-

Breaking Changes: -If you’re migrating from v1.x of slackclient to v2.x, Please follow our migration guide to ensure your app continues working after updating.

-

Check out the Migration Guide here!

-

Thank you! -This release would not have been possible without the support of our community. Thank you to everyone who’s contributed to this release.

-
-
-

v1.3.1 (2019-02-28)ΒΆ

-
    -
  • Lock websocket-client version to < 0.55.0: temp fix for #385

  • -
-
-
-

v1.3.0 (2018-09-11)ΒΆ

-

## New Features -- Adds support for short lived tokens and automatic token refresh #347 (Thanks @roach!)

-

## Other -- update RTM rate limiting comment and error message #308 (Thanks @benoitlavigne!) -- Use logging instead of traceback #309 (Thanks @harlowja!) -- Remove Python 3.3 from test environments #346 (Thanks @roach!) -- Enforced linting when using VSCode. #347 (Thanks @roach!)

-
-
-

v1.2.1 (2018-03-26)ΒΆ

-
    -
  • Added rate limit handling for rtm connections (thanks @jayalane!)

  • -
-
-
-

v1.2.0 (2018-03-20)ΒΆ

-
    -
  • You can now tell the RTM client to automatically reconnect by passing auto_reconnect=True

  • -
-
-
-

v1.1.3 (2018-03-01)ΒΆ

-
    -
  • Fixed another API param encoding bug. It encodes things properly now.

  • -
-
-
-

v1.1.2 (2018-01-31)ΒΆ

-
    -
  • Fixed an encoding issue which was encoding some Web API params incorrectly (sorry)

  • -
-
-
-

v1.1.1 (2018-01-30)ΒΆ

-
-
    -
  • Adds HTTP response headers to api_call responses to expose things like rate limit info

  • -
  • Moves token into auth header rather than request params

  • -
-
-
-
-

v1.1.0 (2017-11-21)ΒΆ

-
-
    -
  • Aadds new SlackClientError and ResponseParseError types to describe errors - thanks @aoberoi!

  • -
  • Fix Build Error (#245) - thanks @stasfilin!

  • -
  • include email as user property (#173) - thanks @acaire!

  • -
  • Add http reply into slack login and slack connection error (#216) - thanks @harlowja!

  • -
  • Removed unused exception class (#233)

  • -
  • Fix rtm_send_message bug (#225) - thanks @kt5356!

  • -
  • Allow use of custom parameters on rtm_connect() (#210) - thanks @kamushadenes!

  • -
  • Fix link to rtm.connect docs (#223) - @sampart!

  • -
-
-
-
-

v1.0.9 (2017-08-31)ΒΆ

-
-
    -
  • Fixed rtm_send_message ID bug introduced in 1.0.8

  • -
-
-
-
-

v1.0.8 (2017-08-31)ΒΆ

-
-
    -
  • Added rtm.connect support

  • -
-
-
-
-

v1.0.7 (2017-08-02)ΒΆ

-
-
    -
  • Fixes an issue where connecting over RTM to large teams may result in β€œWebsocket URL expired” errors

  • -
  • A load of packaging improvements

  • -
-
-
-
-

v1.0.6 (2017-06-12)ΒΆ

-
-
    -
  • Added proxy support (thanks @timfeirg!)

  • -
  • Tidied up docs (thanks @schlueter!)

  • -
  • Added tox settings for Python 3 testing (thanks @cclauss!)

  • -
-
-
-
-

v1.0.5 (2017-01-23)ΒΆ

-
-
    -
  • Allow RTM Channel.send_message to reply to a thread

  • -
  • Index users by ID instead of Name (non-breaking change)

  • -
  • Added timeout to api calls.

  • -
  • Fixed a typo about token access in auth.rst, thanks @kelvintaywl!

  • -
  • Added Message Threads to the docs

  • -
-
-
-
-

v1.0.4 (2016-12-15)ΒΆ

-
-
    -
  • fixed the ability to search for a user by ID

  • -
-
-
-
-

v1.0.3 (2016-12-13)ΒΆ

-
-
    -
  • fixed an issue causing RTM connections to fail for large teams

  • -
-
-
-
-

v1.0.2 (2016-09-22)ΒΆ

-
-
    -
  • removed unused ping counter

  • -
  • fixed contributor guidelines links

  • -
  • updated documentation

  • -
  • Fix bug preventing API calls requiring a file ID

  • -
  • Removes files from api_calls before JSON encoding, so the request is properly formatted

  • -
-
-
-
-

v1.0.1 (2016-03-25)ΒΆ

-
-
    -
  • fix for __eq__ comparison in channels using β€˜#’ in channel name

  • -
  • added copyright info to the LICENSE file

  • -
-
-
-
-

v1.0.0 (2016-02-28)ΒΆ

-
-
    -
  • the api_call function now returns a decoded JSON object, rather than a JSON encoded string

  • -
  • some api_call calls now call actions on the parent server object: -- im.open -- mpim.open, groups.create, groups.createChild -- channels.create, channels.join`

  • -
-
-
-
-

v0.18.0 (2016-02-21)ΒΆ

-
-
    -
  • Moves to use semver for versioning

  • -
  • Adds support for private groups and MPDMs

  • -
  • Switches to use requests instead of urllib

  • -
  • Gets Travis CI integration working

  • -
  • Fixes some formatting issues so the code will work for python 2.6

  • -
  • Cleans up some unused imports, some PEP-8 fixes and a couple bad default args fixes

  • -
-
-
-
-

v0.17.0 (2016-02-15)ΒΆ

-
-
-
-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/conversations.html b/docs-v2/conversations.html deleted file mode 100644 index e29466fdb..000000000 --- a/docs-v2/conversations.html +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - Conversations API — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

Conversations APIΒΆ

-

The Slack Conversations API provides your app with a unified interface to work with all the channel-like things encountered in Slack; public channels, private channels, direct messages, group direct messages, and our newest channel type, Shared Channels.

-

See Conversations API docs for more info.

-
-
-

Direct messagesΒΆ

-

The conversations_open method opens either a 1:1 direct message with a single user or a a multi-person direct message, depending on the number of users supplied to the users parameter.

-

For public or private channels, use the ``conversations_create`` method.

-

Provide a users parameter as an array with 1 to 8 user IDs to open or resume a conversation. Providing only 1 ID will create a direct message. Providing more will create a new multi-party DM or resume an existing conversation.

-

Subsequent calls to conversations_open with the same set of users will return the already existing conversation.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_open(users=["W123456789", "U987654321"])
-
-
-

See conversations.open additional info.

-
-
-
-

Creating channelsΒΆ

-

Creates a new channel, either public or private. The name parameter is required, may contain numbers, letters, hyphens, and underscores, and must contain fewer than 21 characters. To make the channel private, set the option is_private parameter to True.

-
import os
-from slack import WebClient
-from time import time
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-channel_name = f"my-private-channel-{round(time())}"
-response = client.conversations_create(
-  name=channel_name,
-  is_private=True
-)
-channel_id = response["channel"]["id"]
-response = client.conversations_archive(channel=channel_id)
-
-
-

See conversations.create additional info.

-
-
-
-

Getting more informationΒΆ

-

To retrieve a set of metadata about a channel (public, private, DM, or multi-party DM), use conversations_info. The channel parameter is required and must be a valid channel ID. The optional include_locale boolean parameter will return locale data, which may be useful if you wish to return localized responses. The include_num_members boolean parameter will return the number of people in a channel.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_info(
-  channel="C031415926",
-  include_num_members=1
-)
-
-
-

See conversations.info for more info.

-
-
-
-

Listing conversationsΒΆ

-

To get a list of all the conversations in a workspace, use conversations_list. By default, only public conversations are returned; use the types parameter specify which types of conversations you’re interested in (Note: types is a string of comma-separated values)

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_list()
-conversations = response["channels"]
-
-
-

Use the types parameter to request additional channels, including public_channel, private_channel, mpim, and im. This parameter is a string of comma-separated values.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_list(
-  types="public_channel, private_channel"
-)
-
-
-

See conversations.list for more info.

-
-
-
-

Leaving a conversationΒΆ

-

To leave a conversation, use conversations_leave with the required channel param containing the ID of the channel to leave.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_leave(channel="C27182818")
-
-
-

See conversations.leave for more info.

-
-
-
-

Getting membersΒΆ

-

To get a list of the members of a conversation, use conversations_members with the required channel parameter.

-
import os
-from slack import WebClient
-
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-response = client.conversations_members(channel="C16180339")
-user_ids = response["members"]
-
-
-

See conversations.members for more info.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/faq.html b/docs-v2/faq.html deleted file mode 100644 index 2d53ba3ce..000000000 --- a/docs-v2/faq.html +++ /dev/null @@ -1,340 +0,0 @@ - - - - - - Frequently Asked Questions — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

Frequently Asked QuestionsΒΆ

-
-

I cannot install slackclient…¢

-

We recommend using virtualenv (venv) to set up your Python runtime.

-
# Create a dedicated virtual env for running your Python scripts
-python -m venv env
-
-# Run env\Scripts\activate on Windows OS
-source env/bin/activate
-
-# Install slackclient PyPI package
-pip install "slackclient>=2.0"
-
-# Set your token as an env variable (`set` command for Windows OS)
-export SLACK_API_TOKEN=xoxb-***
-
-
-

Then, verify the following code works on the Python REPL (you can start it by just python).

-
import os
-import logging
-from slack import WebClient
-logging.basicConfig(level=logging.DEBUG)
-client = WebClient(token=os.environ["SLACK_API_TOKEN"])
-res = client.api_test()
-
-
-

If you encounter an error saying AttributeError: module 'slack' has no attribute 'WebClient', run pip list. If you find both slackclient and slack in the output, try removing slack by pip uninstall slack and reinstalling slackclient.

-
-
-

Should I go with run_async?ΒΆ

-

For most cases, we recommend going with run_async=False mode. So, the default is False.

-

If your application turns run_async on, the app should follow right and efficient ways to use asyncio’s non-blocking event loops and aiohttp. Also, consider using async frameworks and their appropriate runtime. Running event loops along with Flask or similar may not be a good fit.

-

If you have to simultaneously run WebClient with run_async=True outside an event loop for some reason, sharing a single WebClient instance doesn’t work for you. Create an instance every time you run the code. The run_async=False mode doesn’t have such issues.

-
-
-

I found a bug!ΒΆ

-

That’s great! Thank you. Let us know on the Issue Tracker. If you’re feeling particularly ambitious, why not submit a pull request with a bug fix?

-
-
-

There’s a feature missing!ΒΆ

-

There’s always something more that could be added! You can let us know in the Issue Tracker to start a discussion around the proposed feature, that’s a good start. If you’re feeling particularly ambitious, why not write the feature yourself, and submit a pull request! We love feedback and we love help and we don’t bite. Much.

-
-
-

How do I contribute?ΒΆ

-

What an excellent question. First of all, please have a look at our general contributing guidelines.

-

All done? Great! While we’re super excited to incorporate your new feature, there are a couple of things we want to make sure you’ve given thought to.

-
    -
  • Please write unit tests for your new code. But don’t just aim to increase the test coverage, rather, we expect you -to have written thoughtful tests that ensure your new feature will continue to work as expected, and to help future -contributors to ensure they don’t break it!

  • -
  • Please document your new feature. Think about concrete use cases for your feature, and add a section to the -appropriate document, including a complete sample program that demonstrates your feature. Don’t forget to update -the changelog in changelog.rst!

  • -
-

Including these two items with your pull request will totally make our dayβ€”and, more importantly, your future users’ days!

-

On that note…

-
-
-

How do I compile the documentation?ΒΆ

-

This project’s documentation is generated with Sphinx. If you are editing one of the many reStructuredText files in the docs-src folder, you’ll need to rebuild the documentation. It is recommended to run the following steps inside a virtualenv environment.

-
tox -e docs
-
-
-

Do be sure to add the docs folder and its contents to your pull request!

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/genindex.html b/docs-v2/genindex.html deleted file mode 100644 index 34394ac3c..000000000 --- a/docs-v2/genindex.html +++ /dev/null @@ -1,279 +0,0 @@ - - - - - - Index — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
- -

Index

- -
- -
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/index.html b/docs-v2/index.html deleted file mode 100644 index afd07e1e6..000000000 --- a/docs-v2/index.html +++ /dev/null @@ -1,332 +0,0 @@ - - - - - - slackclient (Legacy Python Slack SDK) — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-
-
-

slackclient (Legacy Python Slack SDK)ΒΆ

-

Slack’s APIs allow anyone to build full featured integrations that extend -and expand the capabilities of your Slack workspace. These APIs allow you -to build applications that interact with Slack just like the people on your -team – they can post messages, respond to events that happen – as well -as build complex UIs for getting work done.

-

To make it easier for Python programmers to build Slack applications, we’ve -provided this open source SDK. slackclient (Legacy Python Slack SDK) will let you get started building -Python apps as quickly as possible. The current version, 2.0, is -built for Python 3.6 and higher – if you need to target Python 2.x, you might -consider using v1 of the SDK.

-
-

Slack Platform BasicsΒΆ

-

If you’re new to the Slack platform, we have a general purpose guide for building apps that isn’t specific to any language or framework. It’s a great place to learn all about the concepts that go into building a great Slack app.

-

Before you get started building on the Slack platform, you need to set up your app’s configuration. This is where you define things like your app’s permissions and the endpoints that Slack should use for interacting with the backend you will build with Python.

-

The app configuration page is also where you will acquire the OAuth token you will use to call Slack’s APIs. Treat this token with care, just like you would a password, because it has access to workspace and can potentially read and write data to and from it.

-
-
-

InstallationΒΆ

-

We recommend using PyPI to install slackclient (Legacy Python Slack SDK)

-
pip install slackclient
-
-
-

Of course, you can always pull the source code directly into your project:

-
git clone https://github.com/slackapi/python-slackclient.git
-
-
-

And then, save a few lines of code as ./test.py.

-
# test.py
-import sys
-# Load the local source directly
-sys.path.insert(1, "./python-slackclient")
-# Enable debug logging
-import logging
-logging.basicConfig(level=logging.DEBUG)
-# Verify it works
-from slack import WebClient
-client = WebClient()
-api_response = client.api_test()
-
-
-

You can run the code this way.

-
python test.py
-
-
-

It’s also good to try on the Python REPL.

-
-
-

Getting HelpΒΆ

-

If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:

-
    -
  • Use our Github Issue Tracker for reporting bugs or requesting features.

  • -
  • Visit the Slack Developer Community for getting help using slackclient (Legacy Python Slack SDK) or just generally bond with your fellow Slack developers.

  • -
-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/metadata.html b/docs-v2/metadata.html deleted file mode 100644 index f3ff24fd2..000000000 --- a/docs-v2/metadata.html +++ /dev/null @@ -1,273 +0,0 @@ - - - - - - <no title> — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/objects.inv b/docs-v2/objects.inv deleted file mode 100644 index 9eb345a54..000000000 Binary files a/docs-v2/objects.inv and /dev/null differ diff --git a/docs-v2/real_time_messaging.html b/docs-v2/real_time_messaging.html deleted file mode 100644 index 3bb83bf13..000000000 --- a/docs-v2/real_time_messaging.html +++ /dev/null @@ -1,360 +0,0 @@ - - - - - - Real Time Messaging (RTM) — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-
-

Real Time Messaging (RTM)ΒΆ

-

The Real Time Messaging (RTM) API is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users.

-

If you prefer events to be pushed to your app, we recommend using the HTTP-based Events API instead. -The Events API contains some events that aren’t supported in the RTM API (like app_home_opened event), -and it supports most of the event types in the RTM API. If you’d like to use the Events API, you can use the Python Slack Events Adaptor.

-

The RTMClient allows apps to communicate with the Slack Platform’s RTM API.

-

The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks.

-

In our example below, we watch for a message event that contains β€œHello” and if its received, we call the say_hello() function. We then issue a call to the web client to post back to the channel saying β€œHi” to the user.

-
-

Configuring the RTM APIΒΆ

-

Events using the RTM API must use a classic Slack app (with a plain bot scope).

-

If you already have a classic Slack app, you can use those credentials. If you don’t and need to use the RTM API, you can create a classic Slack app. You can learn more in the API documentation.

-

Also, even if the Slack app configuration pages encourage you to upgrade to the newer permission model, don’t upgrade it and keep using the β€œclassic” bot permission.

-
-
-

Connecting to the RTM APIΒΆ

-
import os
-from slack import RTMClient
-
-@RTMClient.run_on(event="message")
-def say_hello(**payload):
-  data = payload['data']
-  web_client = payload['web_client']
-
-  if 'Hello' in data['text']:
-    channel_id = data['channel']
-    thread_ts = data['ts']
-    user = data['user'] # This is not username but user ID (the format is either U*** or W***)
-
-    web_client.chat_postMessage(
-      channel=channel_id,
-      text=f"Hi <@{user}>!",
-      thread_ts=thread_ts
-    )
-
-slack_token = os.environ["SLACK_API_TOKEN"]
-rtm_client = RTMClient(token=slack_token)
-rtm_client.start()
-
-
-
-
-

rtm.start vs rtm.connectΒΆ

-

By default, the RTM client uses rtm.connect to establish a WebSocket connection with Slack. The response contains basic information about the team and WebSocket url.

-

If you’d rather use rtm.start to establish the connection, which provides more information about the conversations and users on the team, you can set the connect_method option to rtm.start when instantiating the RTM Client. Note that on larger teams, use of rtm.start can be slow and unreliable.

-
import os
-from slack import RTMClient
-
-@RTMClient.run_on(event="message")
-def say_hello(**payload):
-  data = payload['data']
-  web_client = payload['web_client']
-  if 'text' in data and 'Hello' in data['text']:
-    channel_id = data['channel']
-    thread_ts = data['ts']
-    user = data['user'] # This is not username but user ID (the format is either U*** or W***)
-
-    web_client.chat_postMessage(
-      channel=channel_id,
-      text=f"Hi <@{user}>!",
-      thread_ts=thread_ts
-    )
-
-slack_token = os.environ["SLACK_API_TOKEN"]
-rtm_client = RTMClient(
-  token=slack_token,
-  connect_method='rtm.start'
-)
-rtm_client.start()
-
-
-

Read the rtm.connect docs and the rtm.start docs for more details.

-
-
-

RTM EventsΒΆ

-
{
-  'type': 'message',
-  'ts': '1358878749.000002',
-  'user': 'U023BECGF',
-  'text': 'Hello'
-}
-
-
-

See RTM Events for a complete list of events.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/search.html b/docs-v2/search.html deleted file mode 100644 index c4fb3c330..000000000 --- a/docs-v2/search.html +++ /dev/null @@ -1,293 +0,0 @@ - - - - - - Search — slackclient (Legacy Python Slack SDK) - - - - - - - - - - - - - - - - - - -
- - - - - - - slackclient (Legacy Python Slack SDK) - - -
- - -
-
- - - - - -
- -
-

Search

-
- -

- Please activate JavaScript to enable the search - functionality. -

-
-

- Searching for multiple words only shows matches that contain - all words. -

-
- - - -
- -
- -
- -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs-v2/searchindex.js b/docs-v2/searchindex.js deleted file mode 100644 index 7f03c77bf..000000000 --- a/docs-v2/searchindex.js +++ /dev/null @@ -1 +0,0 @@ -Search.setIndex({docnames:["about","auth","basic_usage","changelog","conversations","faq","index","metadata","real_time_messaging"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,sphinx:56},filenames:["about.rst","auth.rst","basic_usage.rst","changelog.rst","conversations.rst","faq.rst","index.rst","metadata.rst","real_time_messaging.rst"],objects:{},objnames:{},objtypes:{},terms:{"000002":[2,8],"000003":2,"0cb4bcd6e887b428e27e8059b6278b86ee661aaa":3,"1046cc2375a85a22e94573e2aad954ba7287c886":3,"111":1,"123456":2,"1234567890":2,"1358878749":8,"1476745373":2,"1476746830":2,"173":3,"1920":2,"200":2,"210":3,"216":3,"222":1,"223":3,"225":3,"233":3,"237":2,"245":3,"270":3,"3000":[1,2],"308":3,"309":3,"346":3,"347":3,"385":3,"400":3,"403":2,"404":2,"418":3,"428":3,"429":[2,3],"435":3,"440":3,"446":3,"453":3,"463":3,"473":3,"477":3,"478":3,"484":3,"490":3,"492":3,"497":3,"498":3,"500":3,"501":3,"512":3,"514":3,"515":3,"516":3,"517":3,"519":3,"521":3,"524":3,"525":3,"527":3,"530":3,"531":3,"536":3,"540":3,"542":3,"544":3,"554":3,"558":3,"560":3,"563":3,"564":3,"568":3,"569":3,"571":3,"577":3,"594":3,"599":3,"605":3,"613":3,"618":3,"619":3,"623":3,"626":3,"630":3,"631":3,"632":3,"633":3,"635":3,"639":3,"645":3,"652":3,"656":3,"659":3,"661":3,"667":3,"669":3,"670":3,"671":3,"672":3,"673":3,"676":3,"678":3,"680":3,"681":3,"682":3,"686":3,"692":3,"695":3,"699":3,"701":3,"704":3,"705":3,"707":3,"708":3,"709":3,"710":3,"712":3,"713":3,"714":3,"715":3,"716":3,"718":3,"723":3,"726":3,"727":3,"728":3,"729":3,"733":3,"738":3,"744":3,"745":3,"750319":2,"751":3,"752":3,"754":3,"757":3,"758":3,"765":3,"766":3,"767":3,"768":3,"769":3,"770":3,"771":3,"773":3,"778":3,"779":3,"786":3,"794":3,"795":3,"796":3,"7d01515cebc80918a29100b0e4793790eb83e7b9":3,"809":3,"810":3,"811":3,"820":3,"821":3,"822":3,"824":3,"829":3,"838":3,"841":3,"846":3,"851":3,"852":3,"853":3,"854":3,"857":3,"boolean":4,"break":[3,5],"byte":3,"case":[3,5],"char":3,"class":3,"default":[2,3,4,5,8],"export":[2,5],"final":1,"function":[1,3,8],"import":[1,2,3,4,5,6,8],"int":2,"long":2,"new":[1,2,3,4,5,6],"public":4,"return":[1,2,3,4],"short":[2,3],"static":3,"super":5,"switch":3,"true":[2,3,4,5],"try":[2,3,5,6],"while":[2,5,8],Added:3,Adding:3,And:6,But:5,For:[1,2,4,5],IDs:4,IMs:2,One:2,That:[2,5],The:[1,2,3,4,5,6,8],Then:[1,5],These:[3,6],UIs:6,Use:[3,4,6],__eq__:3,__main__:[1,2],__name__:[1,2],aadd:3,aaguilartablada:3,abhishekjiitr:3,abil:[1,3,8],abl:1,about:[1,2,3,4,5,6,8],abov:2,acabei:3,acair:3,acar:3,accept:[1,3],access:[0,1,2,3,6],access_token:1,accessori:2,accid:2,acquir:6,act:3,action:3,action_id:2,activ:5,actual:2,adamchainz:3,adaptor:8,add:[1,2,3,5],added:[3,5],adding:3,addit:[1,2,3,4],address:3,addteam:3,admin:3,affect:3,after:[1,2,3],agent:3,agre:1,agreement:0,aim:5,aiodn:3,aiohttp:[3,5],all:[1,2,4,5,6],allow:[2,3,6,8],along:[3,5,8],alreadi:[2,4,8],already_in_channel:2,also:[2,5,6,8],alt_text:2,alwai:[5,6],ambiti:5,ambro17:3,ani:[1,6,8],anoth:[2,3],anyon:6,aoberoi:3,api:[0,1,3,6],api_cal:[2,3],api_method:2,api_respons:[2,6],api_test:[5,6],app:[0,1,2,3,4,5,6,8],app_home_open:8,appear:2,appli:1,applic:[1,2,3,5,6],approach:3,appropri:5,architectur:8,archiv:2,aren:8,arg:[1,3],argument:2,around:5,arrai:4,articl:2,asherf:3,assert:2,assign:2,assist:6,assumpt:3,async:[3,5],asyncio:5,asyncwebcli:3,asyncwebhookcli:3,attach:2,attempt:3,attribut:[2,3,5],attributeerror:5,austinbutl:3,auth:[1,3],authent:[2,3],author:[1,3],auto_reconnect:3,automat:3,avail:[1,2,3],avanderm:3,averag:2,avoid:1,awesom:2,axe:2,back:8,backend:6,bad:3,base:8,basic:[1,3,8],basicconfig:[2,5,6],becaus:[3,6],becom:2,been:[1,2,3],befor:[2,3,6],begin:1,being:2,below:[2,8],benoitlavign:3,best:[2,6],better:3,between:2,bin:5,bit:2,bite:5,block:[3,5],block_id:2,blockattach:3,bodi:3,bond:6,bool:3,bot:[1,2,3,8],both:5,box:2,broadcast:2,bug:[3,6],bugfix:3,build:[0,1,2,3,6],builder:[2,3],built:[1,3,6],bunch:3,burst:2,busi:2,button:[1,2,3],bytearrai:3,c031415926:4,c0xxxxxx:2,c0xxxxxxx:2,c0xxxxxxy:2,c16180339:4,c27182818:4,c3ukjtqac:2,cach:3,call:[1,3,4,6,8],callback:[2,3,8],callback_id:2,callblock:3,calls_:3,can:[1,2,3,5,6,8],cancel:2,cannot:2,capabl:6,care:6,caus:3,cclauss:3,chang:[1,2,3],changelog:5,channel:[3,8],channel_id:[3,4,8],channel_nam:4,channel_not_found:2,channnel:3,charact:4,charset:3,chat:2,chat_delet:2,chat_postephemer:2,chat_postmessag:[2,8],chat_upd:2,check:[1,2,3],chubz:3,classic:8,clavin:3,clean:3,click:1,client:[1,2,3,4,5,6,8],client_id:1,client_secret:1,clone:6,close:[2,3],code:[0,1,2,3,5,6],code_param:1,collect:2,com:[1,2,3,6],combin:2,come:3,comma:4,command:5,comment:[2,3],commit:3,commun:[3,6,8],comparison:3,compat:3,complet:[1,3,5,8],complex:[2,6],compon:3,compos:2,concept:6,concret:5,conduct:0,configur:[1,2,3,6],connect:3,connect_method:8,consid:[5,6],consider:2,construct:3,consum:3,contain:[2,3,4,8],content:[3,5],context:[2,3],continu:[2,3,5],contribut:[0,3],contributor:[0,3,5],convers:[2,3,8],conversations_arch:4,conversations_cr:4,conversations_info:[2,4],conversations_join:2,conversations_leav:[2,4],conversations_list:[2,4],conversations_memb:4,conversations_open:4,conversations_select:3,convert:3,copyright:3,coroutin:3,correct:3,correspond:[1,3,8],could:5,counter:3,coupl:[3,5],cours:6,cover:2,coverag:5,creat:[3,5,8],createchild:3,credenti:[1,3,8],csaska:3,currenc:3,current:6,custom:[2,3],d45285d2f1025899dcd65e259624ee73771f94bb:3,dai:5,danialerfanian:3,danni:2,data:[1,2,3,4,6,8],databas:1,datepickerel:3,deal:2,debug:[2,5,6],decod:3,decomposit:3,dedic:5,def:[1,2,8],default_to_current_convers:3,default_typ:3,defin:[1,6],delai:2,demonstr:5,depend:[1,4],deprec:3,descend:2,describ:3,descript:3,detail:[2,3,8],determin:1,dev:3,develop:[0,2,6],differ:2,direct:[1,2],directli:[2,6],discuss:5,dispatch:3,displai:2,distribut:3,diurnalist:3,doc:[3,4,5,8],docstr:3,document:[1,2,3,8],doe:3,doesn:[3,5],domain:2,don:[1,3,5,8],done:[5,6],door:2,driven:8,drop:3,due:[2,3],duplic:3,dynam:2,dzudi941:3,e271828:3,each:[2,3],easi:3,easier:6,edit:5,effect:1,effici:5,either:[2,4,8],element:[2,3],els:2,email:3,empti:1,enabl:[2,3,6],encod:3,encount:[4,5],encourag:8,endpoint:[1,2,6],enforc:3,ensur:[3,5],entir:[1,3],env:[3,5],environ:[1,2,3,4,5,8],environment:1,eothr:3,ephemer:2,error:[2,3,5],establish:8,even:8,event:[2,3,5,6],everi:[1,5],everyon:3,exampl:[1,2,8],exce:2,excel:5,except:[2,3],exchang:[1,2],excit:[2,5],exclud:2,exclude_archiv:2,execut:8,exist:[2,3,4],expand:6,expect:5,expir:3,expos:3,extend:6,extras_requir:3,f7bb8889580cc34471ba1ddc05afc34d1a5efa23:3,facilit:1,fail:[2,3],failur:3,fallback:2,fals:[2,5],far:2,fatih:3,featur:[1,3,6],feedback:5,feel:[2,5],fellow:6,felt:2,fetch:2,few:[3,6],fewer:4,field:[2,3],file:[3,5],file_com:2,filenam:3,filepath:3,files_upload:[2,3],find:[2,5],finish:2,first:[3,5],fit:5,fix:[3,5],flask:[1,2,5],flask_env:2,flow:[1,3],flyte:3,focu:3,focus:[2,3],folder:5,follow:[2,3,5,6],forget:[1,5],fork:2,form:2,format:[3,8],found:1,framework:[5,6],from:[0,1,2,3,4,5,6,8],full:[1,2,6],fulli:2,fun:2,futur:5,fwump38:3,gener:[1,5,6],german:2,get:[1,3],get_data:2,git:6,github:[3,6],give:[3,8],given:5,global:2,going:5,good:[5,6],grace:2,grant:1,granular:3,great:[5,6],greater:2,grid:3,griffith:3,group:[2,3,4],guest:2,guid:[3,6],guidelin:[3,5],had:[2,3],handl:[1,2,3],happen:6,harlowja:3,has:[1,2,5,6],hash:2,haunt:2,have:[2,3,5,6,8],header:[2,3],headerblock:3,hello:[2,8],help:[3,5],helper:3,here:[2,3,6],higher:6,hint:3,hit:2,hole:2,home:3,hop:2,hotel:2,how:[1,2,3],howev:2,href:1,http:[1,2,3,6,8],http_proxi:3,https_proxi:3,hub:2,hurri:2,hyphen:4,iamtofr:3,identifi:3,ids:3,imag:2,image_url:2,importantli:5,improv:3,includ:[1,2,3,4,5],include_local:4,include_num_memb:4,incom:3,incorpor:5,incorrectli:3,increas:5,indent:3,index:3,indic:2,industri:1,info:[3,4],inform:[1,2,3,8],initi:[1,3],input:[2,3],inputblock:3,insert:6,insid:[2,5,8],install_requir:3,instanc:[3,5],instanti:8,instead:[2,3,8],integr:[2,3,6],intend:1,interact:[2,6],interest:4,interfac:[2,4],intern:3,introduc:3,invalid:[2,3],invalid_auth:2,invit:2,is_priv:4,is_valid_request:2,isn:6,issu:[3,5,6,8],item:[2,5],iter:3,iteract:3,its:[3,5,8],itself:2,jamim:3,jayalan:3,jeffbuswel:3,jeremyschulman:3,jkillian:3,joakimnordl:3,join:3,jourdanrodrigu:3,jpeg:2,json:[1,2,3],just:[1,2,5,6],kachanovski:3,kamushaden:3,keep:8,kei:[1,2],kelvintaywl:3,kian2attari:3,kind:2,kit:3,know:[1,3,5],kt5356:3,label:[2,3],lack:3,lambda:2,languag:6,larg:3,larger:8,later:1,layout:2,learn:[6,8],least:1,left:2,length:3,less:3,let:[0,1,2,5,6],letter:4,level:[2,5,6],librari:[2,3],licens:[0,3],like:[2,3,4,6,8],limit:3,line:6,linear:2,link:[1,3,8],linkbuttonel:3,lint:3,liorblob:3,list:[1,3,5,8],liter:2,live:3,load:[2,3,6],local:[3,4,6],localhost:[1,2],locat:3,lock:3,log:[2,3,5,6],logic:3,login:3,longer:[2,3],look:[2,5],loop:5,love:5,luden:3,made:3,mai:[2,3,4,5],maintain:0,mainten:3,major:3,make:[2,4,5,6],make_respons:2,malfunct:3,mani:[2,5],map:2,mark:3,marshallino16:3,match:3,mayb:2,messag:[3,6],metadata:4,method:[1,3,4],might:[2,6],migrat:3,mileston:3,miss:3,misscod:3,mode:[3,5],model:8,modifi:3,modul:[2,5],more:[1,2,5,8],most:[2,5,8],move:3,mpdm:3,mpim:[3,4],mrkdwn:2,much:5,multi:[3,4],must:[1,2,4,8],mwbrook:3,myapp:1,name:[2,3,4],nearli:2,need:[1,2,5,6,8],newer:8,newest:4,newli:3,noanylov:3,non:[3,5],none:3,note:[2,4,5,8],notif:2,now:3,number:[2,4],oauth:[1,2,3,6],oauth_redirect:1,oauth_scop:1,oauth_v2_access:[1,3],object:[2,3],occur:[3,8],off:2,onc:[1,2],one:[1,2,5],onli:[2,3,4],onto:2,open:[3,4,6],option:[2,3,4,8],order:1,org:[],origin:[2,3],other:[1,2,3],our:[1,2,3,4,5,6,8],out:[1,2,3],output:5,outsid:5,over:[2,3],overlook:2,own:2,packag:[3,5],page:[1,6,8],pagin:3,param:[1,3,4],paramet:[1,2,3,4],parent:[2,3],parser:3,part:3,parti:4,particip:3,particularli:5,pass:[1,2,3,8],password:[1,6],patch:3,path:6,paul:3,payload:[1,2,8],pbrackin:3,pdf:2,pedroma:3,peopl:[2,4,6],pep:3,per:[2,3],period:2,permiss:[1,3,6,8],persist:1,person:[2,4],pexel:2,phamk:3,photo:2,ping:3,pip:[5,6],place:[2,6],plain:8,plain_text:2,plain_text_input:2,platform:[0,8],pleas:[1,3,5],point:[2,3],possibl:[3,6],post:[2,6,8],post_instal:1,postephemer:2,postmessag:2,potenti:[1,6],practic:2,pre:1,pre_instal:1,prefer:[3,8],prematur:3,prevent:3,preview_imag:3,previou:2,previous:3,primari:2,print:[1,2],privat:[3,4],private_channel:4,private_metadata:2,program:5,programm:6,project:[3,5,6],properli:3,properti:[2,3],propos:5,protocol:1,prototyp:2,proudli:0,provid:[1,2,3,4,6,8],proxi:3,public_channel:[2,4],publish:[1,3],pull:[5,6],purpos:[2,6],push:[3,8],pypi:[5,6],python3:2,python:[1,2,3,5,8],queri:1,quick:3,quickli:[2,6],rais:2,random:2,randomli:1,rapid:3,rate:3,ratelimit:2,rather:[3,5,8],react:3,reactions_add:2,reactions_remov:2,read:[1,6,8],readm:3,reason:5,rebuild:5,receiv:[3,8],reciev:3,recommend:[1,5,6,8],reconnect:3,redesign:3,redirect:1,redirect_uri:3,refer:[2,3],reflect:2,refresh:3,refus:1,regress:3,regular:2,reinstal:[1,5],releas:[2,3],releg:2,remark:3,remot:3,remov:[2,3,5],renam:3,reopen:3,repl:[5,6],repli:[2,3],reply_broadcast:2,report:6,request:[1,2,3,4,5,6],requir:[1,2,3,4],res:5,resolv:3,respond:[2,6],respons:[1,2,3,4,8],response_url:3,responseparseerror:3,restrictaccess:3,restructuredtext:5,result:[2,3],resum:4,retri:2,retriev:[1,3,4],review:[1,2],rfc:3,right:5,roach:3,rodneyu215:3,roman:3,room:2,round:4,rout:[1,2],rowdi:2,rst:[3,5],rtm:3,rtm_client:8,rtm_connect:3,rtm_send_messag:3,rtmclient:[3,8],rubervulp:3,run:[1,2,5,6],run_on:[3,8],runtim:[1,5],sai:[2,5,8],said:2,salmanova:3,same:[2,4],sampart:3,sampl:5,save:[1,2,6],say_hello:8,schedul:3,schlueter:3,scope:[1,8],script:5,sdk:3,search:3,second:2,secret:1,section:[1,2,3,5],see:[1,2,4,8],semver:3,send:[3,8],send_messag:3,send_slack_messag:2,separ:[3,4],seratch:3,server:3,session:3,set:[1,2,3,4,5,6,8],setup:1,shanedewael:3,share:[1,4,5],shortcut:2,should:[2,6],show:2,signatur:[2,3],signature_verifi:2,signatureverifi:[2,3],silent:2,similar:5,simpl:[1,2],simpli:[2,8],simultan:5,sinc:[2,3],singl:[2,4,5],site:2,slack:[1,2,3,4,5,8],slack_api_token:[2,4,5,8],slack_app:2,slack_bot_token:1,slack_client_id:1,slack_client_secret:1,slack_scop:1,slack_sdk:3,slack_signing_secret:2,slack_token:[2,8],slackapi:[3,6],slackapierror:[2,3],slackclient:3,slackclienterror:3,slackrespons:3,sleep:2,slightli:2,slow:8,smaeda:3,smotko:3,snippet:3,social:2,sofya:3,some:[2,3,5,8],someth:5,sometim:2,sorri:3,sourc:[1,5,6],special:2,specif:[2,6],specifi:[2,3,4],sphinx:5,splinterif:3,split:3,src:5,ssl:3,stabl:3,standard:1,star:2,start:[1,2,3,5,6],stasfilin:3,state:[1,2],staticdev:3,statu:2,step:5,stevengil:3,store:[1,2],str:[2,3],string:[1,3,4],strip:3,stuck:[2,6],submiss:2,submit:[2,5],submitted_data:2,subsequ:4,succeed:1,success:[1,3],superfluous_charset:3,suppli:4,support:[3,8],sure:[2,5],surfac:2,sync:3,sys:6,tab:3,tada:2,take:[1,2],target:6,team:[0,1,3,6,8],tell:[2,3],temp:3,test:[2,3,5,6],text:[2,3,8],than:[2,3,4],thank:[3,5],thefrozenfir:3,thei:[2,3,5,6],them:[1,2],therefor:2,thi:[1,2,3,4,5,6,8],thing:[2,3,4,5,6],think:5,those:[2,3,8],though:2,thought:5,thread:3,thread_t:[2,8],through:[3,6],thumbsup:2,tidi:3,time:[1,2,4,5],timelin:2,timeout:3,timeouterror:3,timestamp:2,timfeirg:3,titl:2,togeth:2,token:[2,3,4,5,6,8],tomasreim:3,too:2,tool:0,torrenc:2,total:5,tox:[3,5],traceback:3,tracker:[5,6],transform:3,transmit:3,travi:3,treat:[1,6],trigger_id:2,turn:5,two:[3,5],type:[2,3,4,8],typo:3,u023becgf:8,u0xxxxxxx:2,u987654321:4,ubervulp:[],unclos:3,underscor:4,unexpect:3,unifi:4,uninstal:5,unit:5,unreli:8,until:2,unus:3,updat:[3,5],upgrad:8,upload:3,url:[2,3,8],urllib:3,usag:1,use:[1,2,3,4,5,6,8],used:[2,3],useful:4,user:[1,2,3,4,5,8],user_id:[2,4],usergroup:3,usernam:8,users_list:2,uses:[2,8],using:[2,3,5,6,8],valid:[1,2,3,4],valu:[1,2,3,4],variabl:[1,3,5],venv:5,veri:2,verif:3,verifi:[1,5,6],version:[3,6],via:1,view:[2,3],view_id:2,view_submiss:2,views_open:2,views_upd:2,virtual:5,virtualenv:5,visibl:2,visit:6,vote:2,vpetersson:3,vscode:3,w123456789:4,wai:[2,5,6],wait:2,want:[2,5],warn:3,watch:8,web:[0,3,8],web_client:8,webclient:[1,2,3,4,5,6],webhook:3,webhookcli:3,webserv:1,websit:3,websocket:[3,8],well:[2,3,6],were:3,what:[2,5],when:[2,3,8],where:[1,3,6],which:[1,2,3,4,8],whitespac:3,who:3,whole:2,why:5,window:5,wish:[1,4],without:3,won:2,word:3,work:[1,2,3,4,5,6],workflow:3,workspac:[4,6],world:2,would:[1,3,6],wrapper:2,write:[1,5,6],written:5,xoxb:[1,2,5],xxxxx:1,yield:1,you:[0,1,2,3,4,5,6,8],your:[0,1,2,3,4,5,6,8],yourself:5,yuji38kwmt:3},titles:["About","Tokens & Installation","Basic Usage","Changelog","Conversations API","Frequently Asked Questions","slackclient (Legacy Python Slack SDK)","<no title>","Real Time Messaging (RTM)"],titleterms:{"2016":3,"2017":3,"2018":3,"2019":3,"2020":3,"public":2,There:5,about:0,ani:2,api:[2,4,8],ask:5,basic:[2,6],block:2,bug:5,call:2,cannot:5,changelog:3,channel:[2,4],compil:5,configur:8,connect:8,contribut:5,convers:4,creat:4,delet:2,develop:[],direct:4,document:5,emoji:2,event:8,featur:5,file:2,format:2,found:5,frequent:5,get:[2,4,6],help:6,how:5,info:2,inform:4,instal:[1,5,6],join:2,keep:1,kit:2,leav:[2,4],legaci:[0,6],limit:2,list:[2,4],member:[2,4],messag:[2,4,8],method:2,miss:5,modal:2,more:4,multipl:1,open:2,platform:6,push:2,python:[0,6],question:5,rate:2,reaction:2,real:8,rtm:8,run_async:5,safe:1,sdk:[0,6],send:2,should:5,singl:1,slack:[0,6],slackclient:[0,5,6],start:8,team:2,thread:2,time:8,token:1,updat:2,upload:2,usag:2,web:2,workspac:1}}) \ No newline at end of file diff --git a/docs.sh b/docs.sh deleted file mode 100755 index 1d9dd2f80..000000000 --- a/docs.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env bash - -sphinx-build -E -c ./docs-src/_themes/slack/ -b html docs-src docs \ - && touch ./docs/.nojekyll \ - && cd docs/ \ - && mv _static/* assets/ \ - && find . -name '*.html' | xargs sed -i '' 's/_static/assets/'g \ - && cd - \ No newline at end of file diff --git a/docs/.buildinfo b/docs/.buildinfo deleted file mode 100644 index c11ed68dc..000000000 --- a/docs/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: f47751de68c8ee3f7e02d24a875601e0 -tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/about.html b/docs/about.html deleted file mode 100644 index 5e1aa61c0..000000000 --- a/docs/about.html +++ /dev/null @@ -1,233 +0,0 @@ - - - - - - About — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

AboutΒΆ

-
-

Python Slack SDKΒΆ

-

Access the Slack Platform from your Python app. Python Slack SDK lets you build on the Slack Web APIs pythonically.

-

Python Slack SDK is proudly maintained with πŸ’– by the Slack Developer Tools team

- -
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/assets/basic.css b/docs/assets/basic.css deleted file mode 100644 index 24bc73e7f..000000000 --- a/docs/assets/basic.css +++ /dev/null @@ -1,855 +0,0 @@ -/* - * basic.css - * ~~~~~~~~~ - * - * Sphinx stylesheet -- basic theme. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -/* -- main layout ----------------------------------------------------------- */ - -div.clearer { - clear: both; -} - -div.section::after { - display: block; - content: ''; - clear: left; -} - -/* -- relbar ---------------------------------------------------------------- */ - -div.related { - width: 100%; - font-size: 90%; -} - -div.related h3 { - display: none; -} - -div.related ul { - margin: 0; - padding: 0 0 0 10px; - list-style: none; -} - -div.related li { - display: inline; -} - -div.related li.right { - float: right; - margin-right: 5px; -} - -/* -- sidebar --------------------------------------------------------------- */ - -div.sphinxsidebarwrapper { - padding: 10px 5px 0 10px; -} - -div.sphinxsidebar { - float: left; - width: 230px; - margin-left: -100%; - font-size: 90%; - word-wrap: break-word; - overflow-wrap : break-word; -} - -div.sphinxsidebar ul { - list-style: none; -} - -div.sphinxsidebar ul ul, -div.sphinxsidebar ul.want-points { - margin-left: 20px; - list-style: square; -} - -div.sphinxsidebar ul ul { - margin-top: 0; - margin-bottom: 0; -} - -div.sphinxsidebar form { - margin-top: 10px; -} - -div.sphinxsidebar input { - border: 1px solid #98dbcc; - font-family: sans-serif; - font-size: 1em; -} - -div.sphinxsidebar #searchbox form.search { - overflow: hidden; -} - -div.sphinxsidebar #searchbox input[type="text"] { - float: left; - width: 80%; - padding: 0.25em; - box-sizing: border-box; -} - -div.sphinxsidebar #searchbox input[type="submit"] { - float: left; - width: 20%; - border-left: none; - padding: 0.25em; - box-sizing: border-box; -} - - -img { - border: 0; - max-width: 100%; -} - -/* -- search page ----------------------------------------------------------- */ - -ul.search { - margin: 10px 0 0 20px; - padding: 0; -} - -ul.search li { - padding: 5px 0 5px 20px; - background-image: url(file.png); - background-repeat: no-repeat; - background-position: 0 7px; -} - -ul.search li a { - font-weight: bold; -} - -ul.search li div.context { - color: #888; - margin: 2px 0 0 30px; - text-align: left; -} - -ul.keywordmatches li.goodmatch a { - font-weight: bold; -} - -/* -- index page ------------------------------------------------------------ */ - -table.contentstable { - width: 90%; - margin-left: auto; - margin-right: auto; -} - -table.contentstable p.biglink { - line-height: 150%; -} - -a.biglink { - font-size: 1.3em; -} - -span.linkdescr { - font-style: italic; - padding-top: 5px; - font-size: 90%; -} - -/* -- general index --------------------------------------------------------- */ - -table.indextable { - width: 100%; -} - -table.indextable td { - text-align: left; - vertical-align: top; -} - -table.indextable ul { - margin-top: 0; - margin-bottom: 0; - list-style-type: none; -} - -table.indextable > tbody > tr > td > ul { - padding-left: 0em; -} - -table.indextable tr.pcap { - height: 10px; -} - -table.indextable tr.cap { - margin-top: 10px; - background-color: #f2f2f2; -} - -img.toggler { - margin-right: 3px; - margin-top: 3px; - cursor: pointer; -} - -div.modindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -div.genindex-jumpbox { - border-top: 1px solid #ddd; - border-bottom: 1px solid #ddd; - margin: 1em 0 1em 0; - padding: 0.4em; -} - -/* -- domain module index --------------------------------------------------- */ - -table.modindextable td { - padding: 2px; - border-collapse: collapse; -} - -/* -- general body styles --------------------------------------------------- */ - -div.body { - min-width: 450px; - max-width: 800px; -} - -div.body p, div.body dd, div.body li, div.body blockquote { - -moz-hyphens: auto; - -ms-hyphens: auto; - -webkit-hyphens: auto; - hyphens: auto; -} - -a.headerlink { - visibility: hidden; -} - -a.brackets:before, -span.brackets > a:before{ - content: "["; -} - -a.brackets:after, -span.brackets > a:after { - content: "]"; -} - -h1:hover > a.headerlink, -h2:hover > a.headerlink, -h3:hover > a.headerlink, -h4:hover > a.headerlink, -h5:hover > a.headerlink, -h6:hover > a.headerlink, -dt:hover > a.headerlink, -caption:hover > a.headerlink, -p.caption:hover > a.headerlink, -div.code-block-caption:hover > a.headerlink { - visibility: visible; -} - -div.body p.caption { - text-align: inherit; -} - -div.body td { - text-align: left; -} - -.first { - margin-top: 0 !important; -} - -p.rubric { - margin-top: 30px; - font-weight: bold; -} - -img.align-left, .figure.align-left, object.align-left { - clear: left; - float: left; - margin-right: 1em; -} - -img.align-right, .figure.align-right, object.align-right { - clear: right; - float: right; - margin-left: 1em; -} - -img.align-center, .figure.align-center, object.align-center { - display: block; - margin-left: auto; - margin-right: auto; -} - -img.align-default, .figure.align-default { - display: block; - margin-left: auto; - margin-right: auto; -} - -.align-left { - text-align: left; -} - -.align-center { - text-align: center; -} - -.align-default { - text-align: center; -} - -.align-right { - text-align: right; -} - -/* -- sidebars -------------------------------------------------------------- */ - -div.sidebar { - margin: 0 0 0.5em 1em; - border: 1px solid #ddb; - padding: 7px; - background-color: #ffe; - width: 40%; - float: right; - clear: right; - overflow-x: auto; -} - -p.sidebar-title { - font-weight: bold; -} - -div.admonition, div.topic, blockquote { - clear: left; -} - -/* -- topics ---------------------------------------------------------------- */ - -div.topic { - border: 1px solid #ccc; - padding: 7px; - margin: 10px 0 10px 0; -} - -p.topic-title { - font-size: 1.1em; - font-weight: bold; - margin-top: 10px; -} - -/* -- admonitions ----------------------------------------------------------- */ - -div.admonition { - margin-top: 10px; - margin-bottom: 10px; - padding: 7px; -} - -div.admonition dt { - font-weight: bold; -} - -p.admonition-title { - margin: 0px 10px 5px 0px; - font-weight: bold; -} - -div.body p.centered { - text-align: center; - margin-top: 25px; -} - -/* -- content of sidebars/topics/admonitions -------------------------------- */ - -div.sidebar > :last-child, -div.topic > :last-child, -div.admonition > :last-child { - margin-bottom: 0; -} - -div.sidebar::after, -div.topic::after, -div.admonition::after, -blockquote::after { - display: block; - content: ''; - clear: both; -} - -/* -- tables ---------------------------------------------------------------- */ - -table.docutils { - margin-top: 10px; - margin-bottom: 10px; - border: 0; - border-collapse: collapse; -} - -table.align-center { - margin-left: auto; - margin-right: auto; -} - -table.align-default { - margin-left: auto; - margin-right: auto; -} - -table caption span.caption-number { - font-style: italic; -} - -table caption span.caption-text { -} - -table.docutils td, table.docutils th { - padding: 1px 8px 1px 5px; - border-top: 0; - border-left: 0; - border-right: 0; - border-bottom: 1px solid #aaa; -} - -table.footnote td, table.footnote th { - border: 0 !important; -} - -th { - text-align: left; - padding-right: 5px; -} - -table.citation { - border-left: solid 1px gray; - margin-left: 1px; -} - -table.citation td { - border-bottom: none; -} - -th > :first-child, -td > :first-child { - margin-top: 0px; -} - -th > :last-child, -td > :last-child { - margin-bottom: 0px; -} - -/* -- figures --------------------------------------------------------------- */ - -div.figure { - margin: 0.5em; - padding: 0.5em; -} - -div.figure p.caption { - padding: 0.3em; -} - -div.figure p.caption span.caption-number { - font-style: italic; -} - -div.figure p.caption span.caption-text { -} - -/* -- field list styles ----------------------------------------------------- */ - -table.field-list td, table.field-list th { - border: 0 !important; -} - -.field-list ul { - margin: 0; - padding-left: 1em; -} - -.field-list p { - margin: 0; -} - -.field-name { - -moz-hyphens: manual; - -ms-hyphens: manual; - -webkit-hyphens: manual; - hyphens: manual; -} - -/* -- hlist styles ---------------------------------------------------------- */ - -table.hlist { - margin: 1em 0; -} - -table.hlist td { - vertical-align: top; -} - - -/* -- other body styles ----------------------------------------------------- */ - -ol.arabic { - list-style: decimal; -} - -ol.loweralpha { - list-style: lower-alpha; -} - -ol.upperalpha { - list-style: upper-alpha; -} - -ol.lowerroman { - list-style: lower-roman; -} - -ol.upperroman { - list-style: upper-roman; -} - -:not(li) > ol > li:first-child > :first-child, -:not(li) > ul > li:first-child > :first-child { - margin-top: 0px; -} - -:not(li) > ol > li:last-child > :last-child, -:not(li) > ul > li:last-child > :last-child { - margin-bottom: 0px; -} - -ol.simple ol p, -ol.simple ul p, -ul.simple ol p, -ul.simple ul p { - margin-top: 0; -} - -ol.simple > li:not(:first-child) > p, -ul.simple > li:not(:first-child) > p { - margin-top: 0; -} - -ol.simple p, -ul.simple p { - margin-bottom: 0; -} - -dl.footnote > dt, -dl.citation > dt { - float: left; - margin-right: 0.5em; -} - -dl.footnote > dd, -dl.citation > dd { - margin-bottom: 0em; -} - -dl.footnote > dd:after, -dl.citation > dd:after { - content: ""; - clear: both; -} - -dl.field-list { - display: grid; - grid-template-columns: fit-content(30%) auto; -} - -dl.field-list > dt { - font-weight: bold; - word-break: break-word; - padding-left: 0.5em; - padding-right: 5px; -} - -dl.field-list > dt:after { - content: ":"; -} - -dl.field-list > dd { - padding-left: 0.5em; - margin-top: 0em; - margin-left: 0em; - margin-bottom: 0em; -} - -dl { - margin-bottom: 15px; -} - -dd > :first-child { - margin-top: 0px; -} - -dd ul, dd table { - margin-bottom: 10px; -} - -dd { - margin-top: 3px; - margin-bottom: 10px; - margin-left: 30px; -} - -dl > dd:last-child, -dl > dd:last-child > :last-child { - margin-bottom: 0; -} - -dt:target, span.highlighted { - background-color: #fbe54e; -} - -rect.highlighted { - fill: #fbe54e; -} - -dl.glossary dt { - font-weight: bold; - font-size: 1.1em; -} - -.optional { - font-size: 1.3em; -} - -.sig-paren { - font-size: larger; -} - -.versionmodified { - font-style: italic; -} - -.system-message { - background-color: #fda; - padding: 5px; - border: 3px solid red; -} - -.footnote:target { - background-color: #ffa; -} - -.line-block { - display: block; - margin-top: 1em; - margin-bottom: 1em; -} - -.line-block .line-block { - margin-top: 0; - margin-bottom: 0; - margin-left: 1.5em; -} - -.guilabel, .menuselection { - font-family: sans-serif; -} - -.accelerator { - text-decoration: underline; -} - -.classifier { - font-style: oblique; -} - -.classifier:before { - font-style: normal; - margin: 0.5em; - content: ":"; -} - -abbr, acronym { - border-bottom: dotted 1px; - cursor: help; -} - -/* -- code displays --------------------------------------------------------- */ - -pre { - overflow: auto; - overflow-y: hidden; /* fixes display issues on Chrome browsers */ -} - -pre, div[class*="highlight-"] { - clear: both; -} - -span.pre { - -moz-hyphens: none; - -ms-hyphens: none; - -webkit-hyphens: none; - hyphens: none; -} - -div[class*="highlight-"] { - margin: 1em 0; -} - -td.linenos pre { - border: 0; - background-color: transparent; - color: #aaa; -} - -table.highlighttable { - display: block; -} - -table.highlighttable tbody { - display: block; -} - -table.highlighttable tr { - display: flex; -} - -table.highlighttable td { - margin: 0; - padding: 0; -} - -table.highlighttable td.linenos { - padding-right: 0.5em; -} - -table.highlighttable td.code { - flex: 1; - overflow: hidden; -} - -.highlight .hll { - display: block; -} - -div.highlight pre, -table.highlighttable pre { - margin: 0; -} - -div.code-block-caption + div { - margin-top: 0; -} - -div.code-block-caption { - margin-top: 1em; - padding: 2px 5px; - font-size: small; -} - -div.code-block-caption code { - background-color: transparent; -} - -table.highlighttable td.linenos, -div.doctest > div.highlight span.gp { /* gp: Generic.Prompt */ - user-select: none; -} - -div.code-block-caption span.caption-number { - padding: 0.1em 0.3em; - font-style: italic; -} - -div.code-block-caption span.caption-text { -} - -div.literal-block-wrapper { - margin: 1em 0; -} - -code.descname { - background-color: transparent; - font-weight: bold; - font-size: 1.2em; -} - -code.descclassname { - background-color: transparent; -} - -code.xref, a code { - background-color: transparent; - font-weight: bold; -} - -h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { - background-color: transparent; -} - -.viewcode-link { - float: right; -} - -.viewcode-back { - float: right; - font-family: sans-serif; -} - -div.viewcode-block:target { - margin: -1px -10px; - padding: 0 10px; -} - -/* -- math display ---------------------------------------------------------- */ - -img.math { - vertical-align: middle; -} - -div.body div.math p { - text-align: center; -} - -span.eqno { - float: right; -} - -span.eqno a.headerlink { - position: absolute; - z-index: 1; -} - -div.math:hover a.headerlink { - visibility: visible; -} - -/* -- printout stylesheet --------------------------------------------------- */ - -@media print { - div.document, - div.documentwrapper, - div.bodywrapper { - margin: 0 !important; - width: 100%; - } - - div.sphinxsidebar, - div.related, - div.footer, - #top-link { - display: none; - } -} \ No newline at end of file diff --git a/docs/assets/classic.css b/docs/assets/classic.css deleted file mode 100644 index cceb67ac4..000000000 --- a/docs/assets/classic.css +++ /dev/null @@ -1,266 +0,0 @@ -/* - * classic.css_t - * ~~~~~~~~~~~~~ - * - * Sphinx stylesheet -- classic theme. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -html { - /* CSS hack for macOS's scrollbar (see #1125) */ - background-color: #FFFFFF; -} - -body { - font-family: sans-serif; - font-size: 100%; - background-color: #11303d; - color: #000; - margin: 0; - padding: 0; -} - -div.document { - background-color: #1c4e63; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 0 0 0 230px; -} - -div.body { - background-color: #ffffff; - color: #000000; - padding: 0 20px 30px 20px; -} - -div.footer { - color: #ffffff; - width: 100%; - padding: 9px 0 9px 0; - text-align: center; - font-size: 75%; -} - -div.footer a { - color: #ffffff; - text-decoration: underline; -} - -div.related { - background-color: #133f52; - line-height: 30px; - color: #ffffff; -} - -div.related a { - color: #ffffff; -} - -div.sphinxsidebar { -} - -div.sphinxsidebar h3 { - font-family: 'Trebuchet MS', sans-serif; - color: #ffffff; - font-size: 1.4em; - font-weight: normal; - margin: 0; - padding: 0; -} - -div.sphinxsidebar h3 a { - color: #ffffff; -} - -div.sphinxsidebar h4 { - font-family: 'Trebuchet MS', sans-serif; - color: #ffffff; - font-size: 1.3em; - font-weight: normal; - margin: 5px 0 0 0; - padding: 0; -} - -div.sphinxsidebar p { - color: #ffffff; -} - -div.sphinxsidebar p.topless { - margin: 5px 10px 10px 10px; -} - -div.sphinxsidebar ul { - margin: 10px; - padding: 0; - color: #ffffff; -} - -div.sphinxsidebar a { - color: #98dbcc; -} - -div.sphinxsidebar input { - border: 1px solid #98dbcc; - font-family: sans-serif; - font-size: 1em; -} - - - -/* -- hyperlink styles ------------------------------------------------------ */ - -a { - color: #355f7c; - text-decoration: none; -} - -a:visited { - color: #355f7c; - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} - - - -/* -- body styles ----------------------------------------------------------- */ - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: 'Trebuchet MS', sans-serif; - background-color: #f2f2f2; - font-weight: normal; - color: #20435c; - border-bottom: 1px solid #ccc; - margin: 20px -20px 10px -20px; - padding: 3px 0 3px 10px; -} - -div.body h1 { margin-top: 0; font-size: 200%; } -div.body h2 { font-size: 160%; } -div.body h3 { font-size: 140%; } -div.body h4 { font-size: 120%; } -div.body h5 { font-size: 110%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: #c60f0f; - font-size: 0.8em; - padding: 0 4px 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - background-color: #c60f0f; - color: white; -} - -div.body p, div.body dd, div.body li, div.body blockquote { - text-align: justify; - line-height: 130%; -} - -div.admonition p.admonition-title + p { - display: inline; -} - -div.admonition p { - margin-bottom: 5px; -} - -div.admonition pre { - margin-bottom: 5px; -} - -div.admonition ul, div.admonition ol { - margin-bottom: 5px; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -div.warning { - background-color: #ffe4e4; - border: 1px solid #f66; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre { - padding: 5px; - background-color: unset; - color: unset; - line-height: 120%; - border: 1px solid #ac9; - border-left: none; - border-right: none; -} - -code { - background-color: #ecf0f3; - padding: 0 1px 0 1px; - font-size: 0.95em; -} - -th, dl.field-list > dt { - background-color: #ede; -} - -.warning code { - background: #efc2c2; -} - -.note code { - background: #d6d6d6; -} - -.viewcode-back { - font-family: sans-serif; -} - -div.viewcode-block:target { - background-color: #f4debf; - border-top: 1px solid #ac9; - border-bottom: 1px solid #ac9; -} - -div.code-block-caption { - color: #efefef; - background-color: #1c4e63; -} \ No newline at end of file diff --git a/docs/assets/default.css b/docs/assets/default.css deleted file mode 100644 index b7aacd34c..000000000 --- a/docs/assets/default.css +++ /dev/null @@ -1,79 +0,0 @@ -a.headerlink { - display: none !important; -} - -h2 { - margin-top: -120px; - padding-top: 120px; -} - -.section-title { - font-size: 2rem; - line-height: 2.5rem; - letter-spacing: -1px; - font-weight: 700; - margin: 0 0 1rem; -} - -nav#api_nav .toctree-l1 { - margin-bottom: 1.5rem; -} - -nav#api_nav #api_sections ul { - list-style: none; - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l1>a { - color: #1264a3; - letter-spacing: 0; - font-size: .8rem; - font-weight: 800; - text-transform: uppercase; - border: none; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 { - margin: 0; - padding: 0; -} - -nav#api_nav #api_sections ul li.toctree-l2 a { - color: #1d1c1d; - text-transform: none; - font-weight: inherit; - padding: 0; - display: block; - text-overflow: ellipsis; - overflow: hidden; - white-space: nowrap; - font-size: 15px!important; - line-height:15px; - padding: 4px 8px; - border: 1px solid transparent; - border-radius: 4px; -} - -nav#api_nav #api_sections ul li.toctree-l2 a:hover { - cursor: pointer; - text-decoration: none; - background-color:#e8f5fa; - border-color:#dcf0fb; -} - -nav#api_nav #footer #footer_nav { - font-size: .9375rem; -} - -nav#api_nav #footer #footer_nav a { - border: none; - padding: 0; - color: #616061; -} - -nav#api_nav #footer #footer_nav a:hover { - text-decoration: none; - color: #1c1c1c; -} \ No newline at end of file diff --git a/docs/assets/docs.css b/docs/assets/docs.css deleted file mode 100644 index 12c715d28..000000000 --- a/docs/assets/docs.css +++ /dev/null @@ -1,34 +0,0 @@ -/* Updates body font */ -body { - font-family: Slack-Lato,appleLogo,sans-serif; -} - -/* Replaces old sidebar styled links */ -.sidebar_menu h5 { - font-size: 0.8rem; - font-weight: 800; - margin-bottom: 3px; -} - -/* Aligns footer navigation to the left of the sidebar */ -.footer_nav { - margin: 0 !important; -} - -/* Styles the signature all nice and pretty <3 */ -#footer_signature { - color:#e01e5a; - font-size:.9rem; - margin-top: 10px; -} - -/* Fixes link hover state */ -a:hover { - text-decoration: underline; -} - -/* Makes footer consistent */ -footer { - background-color: transparent; - border: 0; -} \ No newline at end of file diff --git a/docs/assets/doctools.js b/docs/assets/doctools.js deleted file mode 100644 index daccd209d..000000000 --- a/docs/assets/doctools.js +++ /dev/null @@ -1,315 +0,0 @@ -/* - * doctools.js - * ~~~~~~~~~~~ - * - * Sphinx JavaScript utilities for all documentation. - * - * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -/** - * select a different prefix for underscore - */ -$u = _.noConflict(); - -/** - * make the code below compatible with browsers without - * an installed firebug like debugger -if (!window.console || !console.firebug) { - var names = ["log", "debug", "info", "warn", "error", "assert", "dir", - "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", - "profile", "profileEnd"]; - window.console = {}; - for (var i = 0; i < names.length; ++i) - window.console[names[i]] = function() {}; -} - */ - -/** - * small helper function to urldecode strings - */ -jQuery.urldecode = function(x) { - return decodeURIComponent(x).replace(/\+/g, ' '); -}; - -/** - * small helper function to urlencode strings - */ -jQuery.urlencode = encodeURIComponent; - -/** - * This function returns the parsed url parameters of the - * current request. Multiple values per key are supported, - * it will always return arrays of strings for the value parts. - */ -jQuery.getQueryParameters = function(s) { - if (typeof s === 'undefined') - s = document.location.search; - var parts = s.substr(s.indexOf('?') + 1).split('&'); - var result = {}; - for (var i = 0; i < parts.length; i++) { - var tmp = parts[i].split('=', 2); - var key = jQuery.urldecode(tmp[0]); - var value = jQuery.urldecode(tmp[1]); - if (key in result) - result[key].push(value); - else - result[key] = [value]; - } - return result; -}; - -/** - * highlight a given string on a jquery object by wrapping it in - * span elements with the given class name. - */ -jQuery.fn.highlightText = function(text, className) { - function highlight(node, addItems) { - if (node.nodeType === 3) { - var val = node.nodeValue; - var pos = val.toLowerCase().indexOf(text); - if (pos >= 0 && - !jQuery(node.parentNode).hasClass(className) && - !jQuery(node.parentNode).hasClass("nohighlight")) { - var span; - var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); - if (isInSVG) { - span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); - } else { - span = document.createElement("span"); - span.className = className; - } - span.appendChild(document.createTextNode(val.substr(pos, text.length))); - node.parentNode.insertBefore(span, node.parentNode.insertBefore( - document.createTextNode(val.substr(pos + text.length)), - node.nextSibling)); - node.nodeValue = val.substr(0, pos); - if (isInSVG) { - var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); - var bbox = node.parentElement.getBBox(); - rect.x.baseVal.value = bbox.x; - rect.y.baseVal.value = bbox.y; - rect.width.baseVal.value = bbox.width; - rect.height.baseVal.value = bbox.height; - rect.setAttribute('class', className); - addItems.push({ - "parent": node.parentNode, - "target": rect}); - } - } - } - else if (!jQuery(node).is("button, select, textarea")) { - jQuery.each(node.childNodes, function() { - highlight(this, addItems); - }); - } - } - var addItems = []; - var result = this.each(function() { - highlight(this, addItems); - }); - for (var i = 0; i < addItems.length; ++i) { - jQuery(addItems[i].parent).before(addItems[i].target); - } - return result; -}; - -/* - * backward compatibility for jQuery.browser - * This will be supported until firefox bug is fixed. - */ -if (!jQuery.browser) { - jQuery.uaMatch = function(ua) { - ua = ua.toLowerCase(); - - var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || - /(webkit)[ \/]([\w.]+)/.exec(ua) || - /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || - /(msie) ([\w.]+)/.exec(ua) || - ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || - []; - - return { - browser: match[ 1 ] || "", - version: match[ 2 ] || "0" - }; - }; - jQuery.browser = {}; - jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; -} - -/** - * Small JavaScript module for the documentation. - */ -var Documentation = { - - init : function() { - this.fixFirefoxAnchorBug(); - this.highlightSearchWords(); - this.initIndexTable(); - if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { - this.initOnKeyListeners(); - } - }, - - /** - * i18n support - */ - TRANSLATIONS : {}, - PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, - LOCALE : 'unknown', - - // gettext and ngettext don't access this so that the functions - // can safely bound to a different name (_ = Documentation.gettext) - gettext : function(string) { - var translated = Documentation.TRANSLATIONS[string]; - if (typeof translated === 'undefined') - return string; - return (typeof translated === 'string') ? translated : translated[0]; - }, - - ngettext : function(singular, plural, n) { - var translated = Documentation.TRANSLATIONS[singular]; - if (typeof translated === 'undefined') - return (n == 1) ? singular : plural; - return translated[Documentation.PLURALEXPR(n)]; - }, - - addTranslations : function(catalog) { - for (var key in catalog.messages) - this.TRANSLATIONS[key] = catalog.messages[key]; - this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); - this.LOCALE = catalog.locale; - }, - - /** - * add context elements like header anchor links - */ - addContextElements : function() { - $('div[id] > :header:first').each(function() { - $('\u00B6'). - attr('href', '#' + this.id). - attr('title', _('Permalink to this headline')). - appendTo(this); - }); - $('dt[id]').each(function() { - $('\u00B6'). - attr('href', '#' + this.id). - attr('title', _('Permalink to this definition')). - appendTo(this); - }); - }, - - /** - * workaround a firefox stupidity - * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 - */ - fixFirefoxAnchorBug : function() { - if (document.location.hash && $.browser.mozilla) - window.setTimeout(function() { - document.location.href += ''; - }, 10); - }, - - /** - * highlight the search words provided in the url in the text - */ - highlightSearchWords : function() { - var params = $.getQueryParameters(); - var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; - if (terms.length) { - var body = $('div.body'); - if (!body.length) { - body = $('body'); - } - window.setTimeout(function() { - $.each(terms, function() { - body.highlightText(this.toLowerCase(), 'highlighted'); - }); - }, 10); - $('') - .appendTo($('#searchbox')); - } - }, - - /** - * init the domain index toggle buttons - */ - initIndexTable : function() { - var togglers = $('img.toggler').click(function() { - var src = $(this).attr('src'); - var idnum = $(this).attr('id').substr(7); - $('tr.cg-' + idnum).toggle(); - if (src.substr(-9) === 'minus.png') - $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); - else - $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); - }).css('display', ''); - if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { - togglers.click(); - } - }, - - /** - * helper function to hide the search marks again - */ - hideSearchWords : function() { - $('#searchbox .highlight-link').fadeOut(300); - $('span.highlighted').removeClass('highlighted'); - }, - - /** - * make the url absolute - */ - makeURL : function(relativeURL) { - return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; - }, - - /** - * get the current relative url - */ - getCurrentURL : function() { - var path = document.location.pathname; - var parts = path.split(/\//); - $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { - if (this === '..') - parts.pop(); - }); - var url = parts.join('/'); - return path.substring(url.lastIndexOf('/') + 1, path.length - 1); - }, - - initOnKeyListeners: function() { - $(document).keydown(function(event) { - var activeElementType = document.activeElement.tagName; - // don't navigate when in search box or textarea - if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' - && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { - switch (event.keyCode) { - case 37: // left - var prevHref = $('link[rel="prev"]').prop('href'); - if (prevHref) { - window.location.href = prevHref; - return false; - } - case 39: // right - var nextHref = $('link[rel="next"]').prop('href'); - if (nextHref) { - window.location.href = nextHref; - return false; - } - } - } - }); - } -}; - -// quick alias for translations -_ = Documentation.gettext; - -$(document).ready(function() { - Documentation.init(); -}); diff --git a/docs/assets/documentation_options.js b/docs/assets/documentation_options.js deleted file mode 100644 index 9fd31e439..000000000 --- a/docs/assets/documentation_options.js +++ /dev/null @@ -1,12 +0,0 @@ -var DOCUMENTATION_OPTIONS = { - URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), - VERSION: '1.0.1', - LANGUAGE: 'None', - COLLAPSE_INDEX: false, - BUILDER: 'html', - FILE_SUFFIX: '.html', - LINK_SUFFIX: '.html', - HAS_SOURCE: true, - SOURCELINK_SUFFIX: '.txt', - NAVIGATION_WITH_KEYS: false -}; \ No newline at end of file diff --git a/docs/assets/file.png b/docs/assets/file.png deleted file mode 100644 index a858a410e..000000000 Binary files a/docs/assets/file.png and /dev/null differ diff --git a/docs/assets/jquery-3.5.1.js b/docs/assets/jquery-3.5.1.js deleted file mode 100644 index 50937333b..000000000 --- a/docs/assets/jquery-3.5.1.js +++ /dev/null @@ -1,10872 +0,0 @@ -/*! - * jQuery JavaScript Library v3.5.1 - * https://jquery.com/ - * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://jquery.org/license - * - * Date: 2020-05-04T22:49Z - */ -( function( global, factory ) { - - "use strict"; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 -// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode -// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common -// enough that all such attempts are guarded in a try block. -"use strict"; - -var arr = []; - -var getProto = Object.getPrototypeOf; - -var slice = arr.slice; - -var flat = arr.flat ? function( array ) { - return arr.flat.call( array ); -} : function( array ) { - return arr.concat.apply( [], array ); -}; - - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var fnToString = hasOwn.toString; - -var ObjectFunctionString = fnToString.call( Object ); - -var support = {}; - -var isFunction = function isFunction( obj ) { - - // Support: Chrome <=57, Firefox <=52 - // In some browsers, typeof returns "function" for HTML elements - // (i.e., `typeof document.createElement( "object" ) === "function"`). - // We don't want to classify *any* DOM node as a function. - return typeof obj === "function" && typeof obj.nodeType !== "number"; - }; - - -var isWindow = function isWindow( obj ) { - return obj != null && obj === obj.window; - }; - - -var document = window.document; - - - - var preservedScriptAttributes = { - type: true, - src: true, - nonce: true, - noModule: true - }; - - function DOMEval( code, node, doc ) { - doc = doc || document; - - var i, val, - script = doc.createElement( "script" ); - - script.text = code; - if ( node ) { - for ( i in preservedScriptAttributes ) { - - // Support: Firefox 64+, Edge 18+ - // Some browsers don't support the "nonce" property on scripts. - // On the other hand, just using `getAttribute` is not enough as - // the `nonce` attribute is reset to an empty string whenever it - // becomes browsing-context connected. - // See https://github.com/whatwg/html/issues/2369 - // See https://html.spec.whatwg.org/#nonce-attributes - // The `node.getAttribute` check was added for the sake of - // `jQuery.globalEval` so that it can fake a nonce-containing node - // via an object. - val = node[ i ] || node.getAttribute && node.getAttribute( i ); - if ( val ) { - script.setAttribute( i, val ); - } - } - } - doc.head.appendChild( script ).parentNode.removeChild( script ); - } - - -function toType( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android <=2.3 only (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; -} -/* global Symbol */ -// Defining this global in .eslintrc.json would create a danger of using the global -// unguarded in another place, it seems safer to define global only for this module - - - -var - version = "3.5.1", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }; - -jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - - // Return all the elements in a clean array - if ( num == null ) { - return slice.call( this ); - } - - // Return just the one element from the set - return num < 0 ? this[ num + this.length ] : this[ num ]; - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - even: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return ( i + 1 ) % 2; - } ) ); - }, - - odd: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return i % 2; - } ) ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - copy = options[ name ]; - - // Prevent Object.prototype pollution - // Prevent never-ending loop - if ( name === "__proto__" || target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - src = target[ name ]; - - // Ensure proper type for the source value - if ( copyIsArray && !Array.isArray( src ) ) { - clone = []; - } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { - clone = {}; - } else { - clone = src; - } - copyIsArray = false; - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isPlainObject: function( obj ) { - var proto, Ctor; - - // Detect obvious negatives - // Use toString instead of jQuery.type to catch host objects - if ( !obj || toString.call( obj ) !== "[object Object]" ) { - return false; - } - - proto = getProto( obj ); - - // Objects with no prototype (e.g., `Object.create( null )`) are plain - if ( !proto ) { - return true; - } - - // Objects with prototype are plain iff they were constructed by a global Object function - Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; - return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; - }, - - isEmptyObject: function( obj ) { - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - // Evaluates a script in a provided context; falls back to the global one - // if not specified. - globalEval: function( code, options, doc ) { - DOMEval( code, { nonce: options && options.nonce }, doc ); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return flat( ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -} ); - -if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; -} - -// Populate the class2type map -jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), -function( _i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -} ); - -function isArrayLike( obj ) { - - // Support: real iOS 8.2 only (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = toType( obj ); - - if ( isFunction( obj ) || isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.3.5 - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://js.foundation/ - * - * Date: 2020-03-14 - */ -( function( window ) { -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - nonnativeSelectorCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // Instance methods - hasOwn = ( {} ).hasOwnProperty, - arr = [], - pop = arr.pop, - pushNative = arr.push, - push = arr.push, - slice = arr.slice, - - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[ i ] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + - "ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram - identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + - "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - - // "Attribute values must be CSS identifiers [capture 5] - // or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + - whitespace + "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + - whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + - "*" ), - rdescend = new RegExp( whitespace + "|>" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + - whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + - whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + - "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + - "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rhtml = /HTML$/i, - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - - // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), - funescape = function( escape, nonHex ) { - var high = "0x" + escape.slice( 1 ) - 0x10000; - - return nonHex ? - - // Strip the backslash prefix from a non-hex escape sequence - nonHex : - - // Replace a hexadecimal escape sequence with the encoded Unicode code point - // Support: IE <=11+ - // For values outside the Basic Multilingual Plane (BMP), manually construct a - // surrogate pair - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + - ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; - } - - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }, - - inDisabledFieldset = addCombinator( - function( elem ) { - return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; - }, - { dir: "parentNode", next: "legend" } - ); - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - ( arr = slice.call( preferredDoc.childNodes ) ), - preferredDoc.childNodes - ); - - // Support: Android<4.0 - // Detect silently failing push.apply - // eslint-disable-next-line no-unused-expressions - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - pushNative.apply( target, slice.call( els ) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - - // Can't trust NodeList.length - while ( ( target[ j++ ] = els[ i++ ] ) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - setDocument( context ); - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { - - // ID selector - if ( ( m = match[ 1 ] ) ) { - - // Document context - if ( nodeType === 9 ) { - if ( ( elem = context.getElementById( m ) ) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && ( elem = newContext.getElementById( m ) ) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[ 2 ] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !nonnativeSelectorCache[ selector + " " ] && - ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && - - // Support: IE 8 only - // Exclude object elements - ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { - - newSelector = selector; - newContext = context; - - // qSA considers elements outside a scoping root when evaluating child or - // descendant combinators, which is not what we want. - // In such cases, we work around the behavior by prefixing every selector in the - // list with an ID selector referencing the scope context. - // The technique has to be used as well when a leading combinator is used - // as such selectors are not recognized by querySelectorAll. - // Thanks to Andrew Dupont for this technique. - if ( nodeType === 1 && - ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - - // We can use :scope instead of the ID hack if the browser - // supports it & if we're not changing the context. - if ( newContext !== context || !support.scope ) { - - // Capture the context ID, setting it first if necessary - if ( ( nid = context.getAttribute( "id" ) ) ) { - nid = nid.replace( rcssescape, fcssescape ); - } else { - context.setAttribute( "id", ( nid = expando ) ); - } - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - while ( i-- ) { - groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + - toSelector( groups[ i ] ); - } - newSelector = groups.join( "," ); - } - - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - nonnativeSelectorCache( selector, true ); - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return ( cache[ key + " " ] = value ); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created element and returns a boolean result - */ -function assert( fn ) { - var el = document.createElement( "fieldset" ); - - try { - return !!fn( el ); - } catch ( e ) { - return false; - } finally { - - // Remove from its parent by default - if ( el.parentNode ) { - el.parentNode.removeChild( el ); - } - - // release memory in IE - el = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split( "|" ), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[ i ] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( ( cur = cur.nextSibling ) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return ( name === "input" || name === "button" ) && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for :enabled/:disabled - * @param {Boolean} disabled true for :disabled; false for :enabled - */ -function createDisabledPseudo( disabled ) { - - // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable - return function( elem ) { - - // Only certain elements can match :enabled or :disabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled - if ( "form" in elem ) { - - // Check for inherited disabledness on relevant non-disabled elements: - // * listed form-associated elements in a disabled fieldset - // https://html.spec.whatwg.org/multipage/forms.html#category-listed - // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled - // * option elements in a disabled optgroup - // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled - // All such elements have a "form" property. - if ( elem.parentNode && elem.disabled === false ) { - - // Option elements defer to a parent optgroup if present - if ( "label" in elem ) { - if ( "label" in elem.parentNode ) { - return elem.parentNode.disabled === disabled; - } else { - return elem.disabled === disabled; - } - } - - // Support: IE 6 - 11 - // Use the isDisabled shortcut property to check for disabled fieldset ancestors - return elem.isDisabled === disabled || - - // Where there is no isDisabled, check manually - /* jshint -W018 */ - elem.isDisabled !== !disabled && - inDisabledFieldset( elem ) === disabled; - } - - return elem.disabled === disabled; - - // Try to winnow out elements that can't be disabled before trusting the disabled property. - // Some victims get caught in our net (label, legend, menu, track), but it shouldn't - // even exist on them, let alone have a boolean value. - } else if ( "label" in elem ) { - return elem.disabled === disabled; - } - - // Remaining elements are neither :enabled nor :disabled - return false; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction( function( argument ) { - argument = +argument; - return markFunction( function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ ( j = matchIndexes[ i ] ) ] ) { - seed[ j ] = !( matches[ j ] = seed[ j ] ); - } - } - } ); - } ); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - var namespace = elem.namespaceURI, - docElem = ( elem.ownerDocument || elem ).documentElement; - - // Support: IE <=8 - // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes - // https://bugs.jquery.com/ticket/4833 - return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9 - 11+, Edge 12 - 18+ - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( preferredDoc != document && - ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { - - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } - } - - // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, - // Safari 4 - 5 only, Opera <=11.6 - 12.x only - // IE/Edge & older browsers don't support the :scope pseudo-class. - // Support: Safari 6.0 only - // Safari 6.0 supports :scope but it's an alias of :root there. - support.scope = assert( function( el ) { - docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); - return typeof el.querySelectorAll !== "undefined" && - !el.querySelectorAll( ":scope fieldset div" ).length; - } ); - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert( function( el ) { - el.className = "i"; - return !el.getAttribute( "className" ); - } ); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert( function( el ) { - el.appendChild( document.createComment( "" ) ); - return !el.getElementsByTagName( "*" ).length; - } ); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert( function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - } ); - - // ID filter and find - if ( support.getById ) { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute( "id" ) === attrId; - }; - }; - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var elem = context.getElementById( id ); - return elem ? [ elem ] : []; - } - }; - } else { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode( "id" ); - return node && node.value === attrId; - }; - }; - - // Support: IE 6 - 7 only - // getElementById is not reliable as a find shortcut - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var node, i, elems, - elem = context.getElementById( id ); - - if ( elem ) { - - // Verify the id attribute - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - - // Fall back on getElementsByName - elems = context.getElementsByName( id ); - i = 0; - while ( ( elem = elems[ i++ ] ) ) { - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - } - } - - return []; - } - }; - } - - // Tag - Expr.find[ "TAG" ] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { - - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert( function( el ) { - - var input; - - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll( "[selected]" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push( "~=" ); - } - - // Support: IE 11+, Edge 15 - 18+ - // IE 11/Edge don't find elements on a `[name='']` query in some cases. - // Adding a temporary attribute to the document before the selection works - // around the issue. - // Interestingly, IE 10 & older don't seem to have the issue. - input = document.createElement( "input" ); - input.setAttribute( "name", "" ); - el.appendChild( input ); - if ( !el.querySelectorAll( "[name='']" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + - whitespace + "*(?:''|\"\")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll( ":checked" ).length ) { - rbuggyQSA.push( ":checked" ); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push( ".#.+[+~]" ); - } - - // Support: Firefox <=3.6 - 5 only - // Old Firefox doesn't throw on a badly-escaped identifier. - el.querySelectorAll( "\\\f" ); - rbuggyQSA.push( "[\\r\\n\\f]" ); - } ); - - assert( function( el ) { - el.innerHTML = "" + - ""; - - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement( "input" ); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll( "[name=d]" ).length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: Opera 10 - 11 only - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll( "*,:x" ); - rbuggyQSA.push( ",.*:" ); - } ); - } - - if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector ) ) ) ) { - - assert( function( el ) { - - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - } ); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - ) ); - } : - function( a, b ) { - if ( b ) { - while ( ( b = b.parentNode ) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { - - // Choose the first element that is related to our preferred document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( a == document || a.ownerDocument == preferredDoc && - contains( preferredDoc, a ) ) { - return -1; - } - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( b == document || b.ownerDocument == preferredDoc && - contains( preferredDoc, b ) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - return a == document ? -1 : - b == document ? 1 : - /* eslint-enable eqeqeq */ - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( ( cur = cur.parentNode ) ) { - ap.unshift( cur ); - } - cur = b; - while ( ( cur = cur.parentNode ) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[ i ] === bp[ i ] ) { - i++; - } - - return i ? - - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[ i ], bp[ i ] ) : - - // Otherwise nodes in our document sort first - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - ap[ i ] == preferredDoc ? -1 : - bp[ i ] == preferredDoc ? 1 : - /* eslint-enable eqeqeq */ - 0; - }; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - setDocument( elem ); - - if ( support.matchesSelector && documentIsHTML && - !nonnativeSelectorCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch ( e ) { - nonnativeSelectorCache( expr, true ); - } - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( context.ownerDocument || context ) != document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( elem.ownerDocument || elem ) != document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; -}; - -Sizzle.escape = function( sel ) { - return ( sel + "" ).replace( rcssescape, fcssescape ); -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - - // If no nodeType, this is expected to be an array - while ( ( node = elem[ i++ ] ) ) { - - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[ 1 ] = match[ 1 ].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[ 3 ] = ( match[ 3 ] || match[ 4 ] || - match[ 5 ] || "" ).replace( runescape, funescape ); - - if ( match[ 2 ] === "~=" ) { - match[ 3 ] = " " + match[ 3 ] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[ 1 ] = match[ 1 ].toLowerCase(); - - if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { - - // nth-* requires argument - if ( !match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[ 4 ] = +( match[ 4 ] ? - match[ 5 ] + ( match[ 6 ] || 1 ) : - 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); - match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); - - // other types prohibit arguments - } else if ( match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[ 6 ] && match[ 2 ]; - - if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[ 3 ] ) { - match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - - // Get excess from tokenize (recursively) - ( excess = tokenize( unquoted, true ) ) && - - // advance to the next closing parenthesis - ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { - - // excess is a negative index - match[ 0 ] = match[ 0 ].slice( 0, excess ); - match[ 2 ] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { - return true; - } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - ( pattern = new RegExp( "(^|" + whitespace + - ")" + className + "(" + whitespace + "|$)" ) ) && classCache( - className, function( elem ) { - return pattern.test( - typeof elem.className === "string" && elem.className || - typeof elem.getAttribute !== "undefined" && - elem.getAttribute( "class" ) || - "" - ); - } ); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - /* eslint-disable max-len */ - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - /* eslint-enable max-len */ - - }; - }, - - "CHILD": function( type, what, _argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, _context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( ( node = node[ dir ] ) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( ( node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - - // Use previously-cached element index if available - if ( useCache ) { - - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - - // Use the same loop as above to seek `elem` from the start - while ( ( node = ++nodeIndex && node && node[ dir ] || - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || - ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction( function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[ i ] ); - seed[ idx ] = !( matches[ idx ] = matched[ i ] ); - } - } ) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - - // Potentially complex pseudos - "not": markFunction( function( selector ) { - - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction( function( seed, matches, _context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( ( elem = unmatched[ i ] ) ) { - seed[ i ] = !( matches[ i ] = elem ); - } - } - } ) : - function( elem, _context, xml ) { - input[ 0 ] = elem; - matcher( input, null, xml, results ); - - // Don't keep the element (issue #299) - input[ 0 ] = null; - return !results.pop(); - }; - } ), - - "has": markFunction( function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - } ), - - "contains": markFunction( function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; - }; - } ), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - - // lang value must be a valid identifier - if ( !ridentifier.test( lang || "" ) ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( ( elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); - return false; - }; - } ), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && - ( !document.hasFocus || document.hasFocus() ) && - !!( elem.type || elem.href || ~elem.tabIndex ); - }, - - // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), - - "checked": function( elem ) { - - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return ( nodeName === "input" && !!elem.checked ) || - ( nodeName === "option" && !!elem.selected ); - }, - - "selected": function( elem ) { - - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - // eslint-disable-next-line no-unused-expressions - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos[ "empty" ]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( ( attr = elem.getAttribute( "type" ) ) == null || - attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo( function() { - return [ 0 ]; - } ), - - "last": createPositionalPseudo( function( _matchIndexes, length ) { - return [ length - 1 ]; - } ), - - "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - } ), - - "even": createPositionalPseudo( function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "odd": createPositionalPseudo( function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? - argument + length : - argument > length ? - length : - argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ) - } -}; - -Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || ( match = rcomma.exec( soFar ) ) ) { - if ( match ) { - - // Don't consume trailing commas as valid - soFar = soFar.slice( match[ 0 ].length ) || soFar; - } - groups.push( ( tokens = [] ) ); - } - - matched = false; - - // Combinators - if ( ( match = rcombinators.exec( soFar ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - - // Cast descendant combinators to space - type: match[ 0 ].replace( rtrim, " " ) - } ); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || - ( match = preFilters[ type ]( match ) ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - type: type, - matches: match - } ); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[ i ].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - skip = combinator.next, - key = skip || dir, - checkNonElements = base && key === "parentNode", - doneName = done++; - - return combinator.first ? - - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - return false; - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || ( elem[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || - ( outerCache[ elem.uniqueID ] = {} ); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { - elem = elem[ dir ] || elem; - } else if ( ( oldCache = uniqueCache[ key ] ) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return ( newCache[ 2 ] = oldCache[ 2 ] ); - } else { - - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { - return true; - } - } - } - } - } - return false; - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[ i ]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[ 0 ]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[ i ], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( ( elem = unmatched[ i ] ) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction( function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( - selector || "*", - context.nodeType ? [ context ] : context, - [] - ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( ( elem = temp[ i ] ) ) { - matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) ) { - - // Restore matcherIn since elem is not yet a final match - temp.push( ( matcherIn[ i ] = elem ) ); - } - } - postFinder( null, ( matcherOut = [] ), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) && - ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { - - seed[ temp ] = !( results[ temp ] = elem ); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - } ); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[ 0 ].type ], - implicitRelative = leadingRelative || Expr.relative[ " " ], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - ( checkContext = context ).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { - matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; - } else { - matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[ j ].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens - .slice( 0, i - 1 ) - .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), - - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), - len = elems.length; - - if ( outermost ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - outermostContext = context == document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( !context && elem.ownerDocument != document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( ( matcher = elementMatchers[ j++ ] ) ) { - if ( matcher( elem, context || document, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - - // They will have gone through all possible matchers - if ( ( elem = !matcher && elem ) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( ( matcher = setMatchers[ j++ ] ) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !( unmatched[ i ] || setMatched[ i ] ) ) { - setMatched[ i ] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[ i ] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( - selector, - matcherFromGroupMatchers( elementMatchers, setMatchers ) - ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( ( selector = compiled.selector || selector ) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[ 0 ] = match[ 0 ].slice( 0 ); - if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { - - context = ( Expr.find[ "ID" ]( token.matches[ 0 ] - .replace( runescape, funescape ), context ) || [] )[ 0 ]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[ i ]; - - // Abort if we hit a combinator - if ( Expr.relative[ ( type = token.type ) ] ) { - break; - } - if ( ( find = Expr.find[ type ] ) ) { - - // Search, expanding context for leading sibling combinators - if ( ( seed = find( - token.matches[ 0 ].replace( runescape, funescape ), - rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || - context - ) ) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert( function( el ) { - - // Should return 1, but returns 4 (following) - return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; -} ); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert( function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute( "href" ) === "#"; -} ) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - } ); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert( function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; -} ) ) { - addHandle( "value", function( elem, _name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - } ); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert( function( el ) { - return el.getAttribute( "disabled" ) == null; -} ) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; - } - } ); -} - -return Sizzle; - -} )( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; - -// Deprecated -jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; -jQuery.escapeSelector = Sizzle.escape; - - - - -var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; -}; - - -var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; -}; - - -var rneedsContext = jQuery.expr.match.needsContext; - - - -function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - -}; -var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); - - - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) !== not; - } ); - } - - // Single element - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - } - - // Arraylike of elements (jQuery, arguments, Array) - if ( typeof qualifier !== "string" ) { - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); - } - - // Filtered directly for both simple and complex selectors - return jQuery.filter( qualifier, elements, not ); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - if ( elems.length === 1 && elem.nodeType === 1 ) { - return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; - } - - return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); -}; - -jQuery.fn.extend( { - find: function( selector ) { - var i, ret, - len = this.length, - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - ret = this.pushStack( [] ); - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - return len > 1 ? jQuery.uniqueSort( ret ) : ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -} ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - // Shortcut simple #id case for speed - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - if ( elem ) { - - // Inject the element directly into the jQuery object - this[ 0 ] = elem; - this.length = 1; - } - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - targets = typeof selectors !== "string" && jQuery( selectors ); - - // Positional selectors never match, since there's no _selection_ context - if ( !rneedsContext.test( selectors ) ) { - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( targets ? - targets.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } -} ); - -function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, _i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, _i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, _i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - if ( elem.contentDocument != null && - - // Support: IE 11+ - // elements with no `data` attribute has an object - // `contentDocument` with a `null` prototype. - getProto( elem.contentDocument ) ) { - - return elem.contentDocument; - } - - // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only - // Treat the template element as a regular one in browsers that - // don't support it. - if ( nodeName( elem, "template" ) ) { - elem = elem.content || elem; - } - - return jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -} ); -var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); - - - -// Convert String-formatted options into Object-formatted ones -function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = locked || options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && toType( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory && !firing ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -function Identity( v ) { - return v; -} -function Thrower( ex ) { - throw ex; -} - -function adoptValue( value, resolve, reject, noValue ) { - var method; - - try { - - // Check for promise aspect first to privilege synchronous behavior - if ( value && isFunction( ( method = value.promise ) ) ) { - method.call( value ).done( resolve ).fail( reject ); - - // Other thenables - } else if ( value && isFunction( ( method = value.then ) ) ) { - method.call( value, resolve, reject ); - - // Other non-thenables - } else { - - // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: - // * false: [ value ].slice( 0 ) => resolve( value ) - // * true: [ value ].slice( 1 ) => resolve() - resolve.apply( undefined, [ value ].slice( noValue ) ); - } - - // For Promises/A+, convert exceptions into rejections - // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in - // Deferred#then to conditionally suppress rejection. - } catch ( value ) { - - // Support: Android 4.0 only - // Strict mode functions invoked without .call/.apply get global-object context - reject.apply( undefined, [ value ] ); - } -} - -jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, callbacks, - // ... .then handlers, argument index, [final state] - [ "notify", "progress", jQuery.Callbacks( "memory" ), - jQuery.Callbacks( "memory" ), 2 ], - [ "resolve", "done", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 0, "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 1, "rejected" ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - "catch": function( fn ) { - return promise.then( null, fn ); - }, - - // Keep pipe for back-compat - pipe: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( _i, tuple ) { - - // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; - - // deferred.progress(function() { bind to newDefer or newDefer.notify }) - // deferred.done(function() { bind to newDefer or newDefer.resolve }) - // deferred.fail(function() { bind to newDefer or newDefer.reject }) - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - then: function( onFulfilled, onRejected, onProgress ) { - var maxDepth = 0; - function resolve( depth, deferred, handler, special ) { - return function() { - var that = this, - args = arguments, - mightThrow = function() { - var returned, then; - - // Support: Promises/A+ section 2.3.3.3.3 - // https://promisesaplus.com/#point-59 - // Ignore double-resolution attempts - if ( depth < maxDepth ) { - return; - } - - returned = handler.apply( that, args ); - - // Support: Promises/A+ section 2.3.1 - // https://promisesaplus.com/#point-48 - if ( returned === deferred.promise() ) { - throw new TypeError( "Thenable self-resolution" ); - } - - // Support: Promises/A+ sections 2.3.3.1, 3.5 - // https://promisesaplus.com/#point-54 - // https://promisesaplus.com/#point-75 - // Retrieve `then` only once - then = returned && - - // Support: Promises/A+ section 2.3.4 - // https://promisesaplus.com/#point-64 - // Only check objects and functions for thenability - ( typeof returned === "object" || - typeof returned === "function" ) && - returned.then; - - // Handle a returned thenable - if ( isFunction( then ) ) { - - // Special processors (notify) just wait for resolution - if ( special ) { - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ) - ); - - // Normal processors (resolve) also hook into progress - } else { - - // ...and disregard older resolution values - maxDepth++; - - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ), - resolve( maxDepth, deferred, Identity, - deferred.notifyWith ) - ); - } - - // Handle all other returned values - } else { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Identity ) { - that = undefined; - args = [ returned ]; - } - - // Process the value(s) - // Default process is resolve - ( special || deferred.resolveWith )( that, args ); - } - }, - - // Only normal processors (resolve) catch and reject exceptions - process = special ? - mightThrow : - function() { - try { - mightThrow(); - } catch ( e ) { - - if ( jQuery.Deferred.exceptionHook ) { - jQuery.Deferred.exceptionHook( e, - process.stackTrace ); - } - - // Support: Promises/A+ section 2.3.3.3.4.1 - // https://promisesaplus.com/#point-61 - // Ignore post-resolution exceptions - if ( depth + 1 >= maxDepth ) { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Thrower ) { - that = undefined; - args = [ e ]; - } - - deferred.rejectWith( that, args ); - } - } - }; - - // Support: Promises/A+ section 2.3.3.3.1 - // https://promisesaplus.com/#point-57 - // Re-resolve promises immediately to dodge false rejection from - // subsequent errors - if ( depth ) { - process(); - } else { - - // Call an optional hook to record the stack, in case of exception - // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); - } - window.setTimeout( process ); - } - }; - } - - return jQuery.Deferred( function( newDefer ) { - - // progress_handlers.add( ... ) - tuples[ 0 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onProgress ) ? - onProgress : - Identity, - newDefer.notifyWith - ) - ); - - // fulfilled_handlers.add( ... ) - tuples[ 1 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onFulfilled ) ? - onFulfilled : - Identity - ) - ); - - // rejected_handlers.add( ... ) - tuples[ 2 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onRejected ) ? - onRejected : - Thrower - ) - ); - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 5 ]; - - // promise.progress = list.add - // promise.done = list.add - // promise.fail = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( - function() { - - // state = "resolved" (i.e., fulfilled) - // state = "rejected" - state = stateString; - }, - - // rejected_callbacks.disable - // fulfilled_callbacks.disable - tuples[ 3 - i ][ 2 ].disable, - - // rejected_handlers.disable - // fulfilled_handlers.disable - tuples[ 3 - i ][ 3 ].disable, - - // progress_callbacks.lock - tuples[ 0 ][ 2 ].lock, - - // progress_handlers.lock - tuples[ 0 ][ 3 ].lock - ); - } - - // progress_handlers.fire - // fulfilled_handlers.fire - // rejected_handlers.fire - list.add( tuple[ 3 ].fire ); - - // deferred.notify = function() { deferred.notifyWith(...) } - // deferred.resolve = function() { deferred.resolveWith(...) } - // deferred.reject = function() { deferred.rejectWith(...) } - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); - return this; - }; - - // deferred.notifyWith = list.fireWith - // deferred.resolveWith = list.fireWith - // deferred.rejectWith = list.fireWith - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( singleValue ) { - var - - // count of uncompleted subordinates - remaining = arguments.length, - - // count of unprocessed arguments - i = remaining, - - // subordinate fulfillment data - resolveContexts = Array( i ), - resolveValues = slice.call( arguments ), - - // the master Deferred - master = jQuery.Deferred(), - - // subordinate callback factory - updateFunc = function( i ) { - return function( value ) { - resolveContexts[ i ] = this; - resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( !( --remaining ) ) { - master.resolveWith( resolveContexts, resolveValues ); - } - }; - }; - - // Single- and empty arguments are adopted like Promise.resolve - if ( remaining <= 1 ) { - adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, - !remaining ); - - // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( master.state() === "pending" || - isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - - return master.then(); - } - } - - // Multiple arguments are aggregated like Promise.all array elements - while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); - } - - return master.promise(); - } -} ); - - -// These usually indicate a programmer mistake during development, -// warn about them ASAP rather than swallowing them by default. -var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; - -jQuery.Deferred.exceptionHook = function( error, stack ) { - - // Support: IE 8 - 9 only - // Console exists when dev tools are open, which can happen at any time - if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); - } -}; - - - - -jQuery.readyException = function( error ) { - window.setTimeout( function() { - throw error; - } ); -}; - - - - -// The deferred used on DOM ready -var readyList = jQuery.Deferred(); - -jQuery.fn.ready = function( fn ) { - - readyList - .then( fn ) - - // Wrap jQuery.readyException in a function so that the lookup - // happens at the time of error handling instead of callback - // registration. - .catch( function( error ) { - jQuery.readyException( error ); - } ); - - return this; -}; - -jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - } -} ); - -jQuery.ready.then = readyList.then; - -// The ready event handler and self cleanup method -function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); -} - -// Catch cases where $(document).ready() is called -// after the browser event has already occurred. -// Support: IE <=9 - 10 only -// Older IE sometimes signals "interactive" too soon -if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - -} else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); -} - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( toType( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, _key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - if ( chainable ) { - return elems; - } - - // Gets - if ( bulk ) { - return fn.call( elems ); - } - - return len ? fn( elems[ 0 ], key ) : emptyGet; -}; - - -// Matches dashed string for camelizing -var rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g; - -// Used by camelCase as callback to replace() -function fcamelCase( _all, letter ) { - return letter.toUpperCase(); -} - -// Convert dashed to camelCase; used by the css and data modules -// Support: IE <=9 - 11, Edge 12 - 15 -// Microsoft forgot to hump their vendor prefix (#9572) -function camelCase( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); -} -var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - - - -function Data() { - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; - -Data.prototype = { - - cache: function( owner ) { - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - // Always use camelCase key (gh-2257) - if ( typeof data === "string" ) { - cache[ camelCase( data ) ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ camelCase( prop ) ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - - // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; - }, - access: function( owner, key, value ) { - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - return this.get( owner, key ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key !== undefined ) { - - // Support array or space separated string of keys - if ( Array.isArray( key ) ) { - - // If key is an array of keys... - // We always set camelCase keys, so remove that. - key = key.map( camelCase ); - } else { - key = camelCase( key ); - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - key = key in cache ? - [ key ] : - ( key.match( rnothtmlwhite ) || [] ); - } - - i = key.length; - - while ( i-- ) { - delete cache[ key[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <=35 - 45 - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } -}; -var dataPriv = new Data(); - -var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - -function getData( data ) { - if ( data === "true" ) { - return true; - } - - if ( data === "false" ) { - return false; - } - - if ( data === "null" ) { - return null; - } - - // Only convert to a number if it doesn't change the string - if ( data === +data + "" ) { - return +data; - } - - if ( rbrace.test( data ) ) { - return JSON.parse( data ); - } - - return data; -} - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = getData( data ); - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } -} ); - -jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE 11 only - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // The key will always be camelCased in Data - data = dataUser.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, key ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each( function() { - - // We always store the camelCased key - dataUser.set( this, key, value ); - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } -} ); - - -jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || Array.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } -} ); - -jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -} ); -var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - -var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var documentElement = document.documentElement; - - - - var isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ); - }, - composed = { composed: true }; - - // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only - // Check attachment across shadow DOM boundaries when possible (gh-3504) - // Support: iOS 10.0-10.2 only - // Early iOS 10 versions support `attachShadow` but not `getRootNode`, - // leading to errors. We need to check for `getRootNode`. - if ( documentElement.getRootNode ) { - isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ) || - elem.getRootNode( composed ) === elem.ownerDocument; - }; - } -var isHiddenWithinTree = function( elem, el ) { - - // isHiddenWithinTree might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - - // Inline style trumps all - return elem.style.display === "none" || - elem.style.display === "" && - - // Otherwise, check computed style - // Support: Firefox <=43 - 45 - // Disconnected elements can have computed display: none, so first confirm that elem is - // in the document. - isAttached( elem ) && - - jQuery.css( elem, "display" ) === "none"; - }; - - - -function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, scale, - maxIterations = 20, - currentValue = tween ? - function() { - return tween.cur(); - } : - function() { - return jQuery.css( elem, prop, "" ); - }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = elem.nodeType && - ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Support: Firefox <=54 - // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) - initial = initial / 2; - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - while ( maxIterations-- ) { - - // Evaluate and update our best guess (doubling guesses that zero out). - // Finish if the scale equals or crosses 1 (making the old*new product non-positive). - jQuery.style( elem, prop, initialInUnit + unit ); - if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { - maxIterations = 0; - } - initialInUnit = initialInUnit / scale; - - } - - initialInUnit = initialInUnit * 2; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; -} - - -var defaultDisplayMap = {}; - -function getDefaultDisplay( elem ) { - var temp, - doc = elem.ownerDocument, - nodeName = elem.nodeName, - display = defaultDisplayMap[ nodeName ]; - - if ( display ) { - return display; - } - - temp = doc.body.appendChild( doc.createElement( nodeName ) ); - display = jQuery.css( temp, "display" ); - - temp.parentNode.removeChild( temp ); - - if ( display === "none" ) { - display = "block"; - } - defaultDisplayMap[ nodeName ] = display; - - return display; -} - -function showHide( elements, show ) { - var display, elem, - values = [], - index = 0, - length = elements.length; - - // Determine new display value for elements that need to change - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - display = elem.style.display; - if ( show ) { - - // Since we force visibility upon cascade-hidden elements, an immediate (and slow) - // check is required in this first loop unless we have a nonempty display value (either - // inline or about-to-be-restored) - if ( display === "none" ) { - values[ index ] = dataPriv.get( elem, "display" ) || null; - if ( !values[ index ] ) { - elem.style.display = ""; - } - } - if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { - values[ index ] = getDefaultDisplay( elem ); - } - } else { - if ( display !== "none" ) { - values[ index ] = "none"; - - // Remember what we're overwriting - dataPriv.set( elem, "display", display ); - } - } - } - - // Set the display of the elements in a second loop to avoid constant reflow - for ( index = 0; index < length; index++ ) { - if ( values[ index ] != null ) { - elements[ index ].style.display = values[ index ]; - } - } - - return elements; -} - -jQuery.fn.extend( { - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - if ( typeof state === "boolean" ) { - return state ? this.show() : this.hide(); - } - - return this.each( function() { - if ( isHiddenWithinTree( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - } ); - } -} ); -var rcheckableType = ( /^(?:checkbox|radio)$/i ); - -var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); - -var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); - - - -( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Android <=4.1 only - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE <=11 only - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - - // Support: IE <=9 only - // IE <=9 replaces "; - support.option = !!div.lastChild; -} )(); - - -// We have to close these tags to support XHTML (#13200) -var wrapMap = { - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] -}; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// Support: IE <=9 only -if ( !support.option ) { - wrapMap.optgroup = wrapMap.option = [ 1, "" ]; -} - - -function getAll( context, tag ) { - - // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret; - - if ( typeof context.getElementsByTagName !== "undefined" ) { - ret = context.getElementsByTagName( tag || "*" ); - - } else if ( typeof context.querySelectorAll !== "undefined" ) { - ret = context.querySelectorAll( tag || "*" ); - - } else { - ret = []; - } - - if ( tag === undefined || tag && nodeName( context, tag ) ) { - return jQuery.merge( [ context ], ret ); - } - - return ret; -} - - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } -} - - -var rhtml = /<|&#?\w+;/; - -function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, attached, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( toType( elem ) === "object" ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - attached = isAttached( elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( attached ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; -} - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 - 11+ -// focus() and blur() are asynchronous, except when they are no-op. -// So expect focus to be synchronous when the element is already active, -// and blur to be synchronous when the element is not already active. -// (focus and blur are always synchronous in other supported browsers, -// this just defines when we can count on it). -function expectSync( elem, type ) { - return ( elem === safeActiveElement() ) === ( type === "focus" ); -} - -// Support: IE <=9 only -// Accessing document.activeElement can throw unexpectedly -// https://bugs.jquery.com/ticket/13393 -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Only attach events to objects that accept data - if ( !acceptData( elem ) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = Object.create( null ); - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( nativeEvent ), - - handlers = ( - dataPriv.get( this, "events" ) || Object.create( null ) - )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // If the event is namespaced, then each handler is only invoked if it is - // specially universal or its namespaces are a superset of the event's. - if ( !event.rnamespace || handleObj.namespace === false || - event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - click: { - - // Utilize native event to ensure correct state for checkable inputs - setup: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Claim the first handler - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - // dataPriv.set( el, "click", ... ) - leverageNative( el, "click", returnTrue ); - } - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Force setup before triggering a click - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - leverageNative( el, "click" ); - } - - // Return non-false to allow normal event-path propagation - return true; - }, - - // For cross-browser consistency, suppress native .click() on links - // Also prevent it if we're currently inside a leveraged native-event stack - _default: function( event ) { - var target = event.target; - return rcheckableType.test( target.type ) && - target.click && nodeName( target, "input" ) && - dataPriv.get( target, "click" ) || - nodeName( target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -// Ensure the presence of an event listener that handles manually-triggered -// synthetic events by interrupting progress until reinvoked in response to -// *native* events that it fires directly, ensuring that state changes have -// already occurred before other listeners are invoked. -function leverageNative( el, type, expectSync ) { - - // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add - if ( !expectSync ) { - if ( dataPriv.get( el, type ) === undefined ) { - jQuery.event.add( el, type, returnTrue ); - } - return; - } - - // Register the controller as a special universal handler for all event namespaces - dataPriv.set( el, type, false ); - jQuery.event.add( el, type, { - namespace: false, - handler: function( event ) { - var notAsync, result, - saved = dataPriv.get( this, type ); - - if ( ( event.isTrigger & 1 ) && this[ type ] ) { - - // Interrupt processing of the outer synthetic .trigger()ed event - // Saved data should be false in such cases, but might be a leftover capture object - // from an async native handler (gh-4350) - if ( !saved.length ) { - - // Store arguments for use when handling the inner native event - // There will always be at least one argument (an event object), so this array - // will not be confused with a leftover capture object. - saved = slice.call( arguments ); - dataPriv.set( this, type, saved ); - - // Trigger the native event and capture its result - // Support: IE <=9 - 11+ - // focus() and blur() are asynchronous - notAsync = expectSync( this, type ); - this[ type ](); - result = dataPriv.get( this, type ); - if ( saved !== result || notAsync ) { - dataPriv.set( this, type, false ); - } else { - result = {}; - } - if ( saved !== result ) { - - // Cancel the outer synthetic event - event.stopImmediatePropagation(); - event.preventDefault(); - return result.value; - } - - // If this is an inner synthetic event for an event with a bubbling surrogate - // (focus or blur), assume that the surrogate already propagated from triggering the - // native event and prevent that from happening again here. - // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the - // bubbling surrogate propagates *after* the non-bubbling base), but that seems - // less bad than duplication. - } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { - event.stopPropagation(); - } - - // If this is a native event triggered above, everything is now in order - // Fire an inner synthetic event with the original arguments - } else if ( saved.length ) { - - // ...and capture the result - dataPriv.set( this, type, { - value: jQuery.event.trigger( - - // Support: IE <=9 - 11+ - // Extend with the prototype to reset the above stopImmediatePropagation() - jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), - saved.slice( 1 ), - this - ) - } ); - - // Abort handling of the native event - event.stopImmediatePropagation(); - } - } - } ); -} - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || Date.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Includes all common event props including KeyEvent and MouseEvent specific props -jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - code: true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - - which: function( event ) { - var button = event.button; - - // Add which for key events - if ( event.which == null && rkeyEvent.test( event.type ) ) { - return event.charCode != null ? event.charCode : event.keyCode; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { - if ( button & 1 ) { - return 1; - } - - if ( button & 2 ) { - return 3; - } - - if ( button & 4 ) { - return 2; - } - - return 0; - } - - return event.which; - } -}, jQuery.event.addProp ); - -jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { - jQuery.event.special[ type ] = { - - // Utilize native event if possible so blur/focus sequence is correct - setup: function() { - - // Claim the first handler - // dataPriv.set( this, "focus", ... ) - // dataPriv.set( this, "blur", ... ) - leverageNative( this, type, expectSync ); - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function() { - - // Force setup before trigger - leverageNative( this, type ); - - // Return non-false to allow normal event-path propagation - return true; - }, - - delegateType: delegateType - }; -} ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - - // Support: IE <=10 - 11, Edge 12 - 13 only - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows -function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( elem ).children( "tbody" )[ 0 ] || elem; - } - - return elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { - elem.type = elem.type.slice( 5 ); - } else { - elem.removeAttribute( "type" ); - } - - return elem; -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.get( src ); - events = pdataOld.events; - - if ( events ) { - dataPriv.remove( dest, "handle events" ); - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = flat( args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - valueIsFunction = isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( valueIsFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( valueIsFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl && !node.noModule ) { - jQuery._evalUrl( node.src, { - nonce: node.nonce || node.getAttribute( "nonce" ) - }, doc ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); - } - } - } - } - } - } - - return collection; -} - -function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && isAttached( node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; -} - -jQuery.extend( { - htmlPrefilter: function( html ) { - return html; - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = isAttached( elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } -} ); - -jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } -} ); - -jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -} ); -var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - -var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - -var swap = function( elem, options, callback ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.call( elem ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; -}; - - -var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); - - - -( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - container.style.cssText = "position:absolute;left:-11111px;width:60px;" + - "margin-top:1px;padding:0;border:0"; - div.style.cssText = - "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + - "margin:auto;border:1px;padding:1px;" + - "width:60%;top:1%"; - documentElement.appendChild( container ).appendChild( div ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - - // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 - // Some styles come back with percentage values, even though they shouldn't - div.style.right = "60%"; - pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; - - // Support: IE 9 - 11 only - // Detect misreporting of content dimensions for box-sizing:border-box elements - boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; - - // Support: IE 9 only - // Detect overflow:scroll screwiness (gh-3699) - // Support: Chrome <=64 - // Don't get tricked when zoom affects offsetWidth (gh-4029) - div.style.position = "absolute"; - scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - function roundPixelMeasures( measure ) { - return Math.round( parseFloat( measure ) ); - } - - var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, - reliableTrDimensionsVal, reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - jQuery.extend( support, { - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelBoxStyles: function() { - computeStyleTests(); - return pixelBoxStylesVal; - }, - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - }, - scrollboxSize: function() { - computeStyleTests(); - return scrollboxSizeVal; - }, - - // Support: IE 9 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Behavior in IE 9 is more subtle than in newer versions & it passes - // some versions of this test; make sure not to make it pass there! - reliableTrDimensions: function() { - var table, tr, trChild, trStyle; - if ( reliableTrDimensionsVal == null ) { - table = document.createElement( "table" ); - tr = document.createElement( "tr" ); - trChild = document.createElement( "div" ); - - table.style.cssText = "position:absolute;left:-11111px"; - tr.style.height = "1px"; - trChild.style.height = "9px"; - - documentElement - .appendChild( table ) - .appendChild( tr ) - .appendChild( trChild ); - - trStyle = window.getComputedStyle( tr ); - reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; - - documentElement.removeChild( table ); - } - return reliableTrDimensionsVal; - } - } ); -} )(); - - -function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !isAttached( elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; -} - - -function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; -} - - -var cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style, - vendorProps = {}; - -// Return a vendor-prefixed property or undefined -function vendorPropName( name ) { - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } -} - -// Return a potentially-mapped jQuery.cssProps or vendor prefixed property -function finalPropName( name ) { - var final = jQuery.cssProps[ name ] || vendorProps[ name ]; - - if ( final ) { - return final; - } - if ( name in emptyStyle ) { - return name; - } - return vendorProps[ name ] = vendorPropName( name ) || name; -} - - -var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }; - -function setPositiveNumber( _elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; -} - -function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { - var i = dimension === "width" ? 1 : 0, - extra = 0, - delta = 0; - - // Adjustment may not be necessary - if ( box === ( isBorderBox ? "border" : "content" ) ) { - return 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin - if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); - } - - // If we get here with a content-box, we're seeking "padding" or "border" or "margin" - if ( !isBorderBox ) { - - // Add padding - delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // For "border" or "margin", add border - if ( box !== "padding" ) { - delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - - // But still keep track of it otherwise - } else { - extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - - // If we get here with a border-box (content + padding + border), we're seeking "content" or - // "padding" or "margin" - } else { - - // For "content", subtract padding - if ( box === "content" ) { - delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // For "content" or "padding", subtract border - if ( box !== "margin" ) { - delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - // Account for positive content-box scroll gutter when requested by providing computedVal - if ( !isBorderBox && computedVal >= 0 ) { - - // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border - // Assuming integer scroll gutter, subtract the rest and round down - delta += Math.max( 0, Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - computedVal - - delta - - extra - - 0.5 - - // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter - // Use an explicit zero to avoid NaN (gh-3964) - ) ) || 0; - } - - return delta; -} - -function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). - // Fake content-box until we know it's needed to know the true value. - boxSizingNeeded = !support.boxSizingReliable() || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox, - - val = curCSS( elem, dimension, styles ), - offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - - // Support: IE 9 - 11 only - // Use offsetWidth/offsetHeight for when box sizing is unreliable. - // In those cases, the computed value can be trusted to be border-box. - if ( ( !support.boxSizingReliable() && isBorderBox || - - // Support: IE 10 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Interestingly, in some cases IE 9 doesn't suffer from this issue. - !support.reliableTrDimensions() && nodeName( elem, "tr" ) || - - // Fall back to offsetWidth/offsetHeight when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - val === "auto" || - - // Support: Android <=4.1 - 4.3 only - // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && - - // Make sure the element is visible & connected - elem.getClientRects().length ) { - - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // Where available, offsetWidth/offsetHeight approximate border box dimensions. - // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the - // retrieved value as a content box dimension. - valueIsBorderBox = offsetProp in elem; - if ( valueIsBorderBox ) { - val = elem[ offsetProp ]; - } - } - - // Normalize "" and auto - val = parseFloat( val ) || 0; - - // Adjust for the element's box model - return ( val + - boxModelAdjustment( - elem, - dimension, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles, - - // Provide the current computed size to request scroll gutter calculation (gh-3589) - val - ) - ) + "px"; -} - -jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "gridArea": true, - "gridColumn": true, - "gridColumnEnd": true, - "gridColumnStart": true, - "gridRow": true, - "gridRowEnd": true, - "gridRowStart": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: {}, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append - // "px" to a few hardcoded values. - if ( type === "number" && !isCustomProp ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } -} ); - -jQuery.each( [ "height", "width" ], function( _i, dimension ) { - jQuery.cssHooks[ dimension ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = getStyles( elem ), - - // Only read styles.position if the test has a chance to fail - // to avoid forcing a reflow. - scrollboxSizeBuggy = !support.scrollboxSize() && - styles.position === "absolute", - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) - boxSizingNeeded = scrollboxSizeBuggy || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra ? - boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ) : - 0; - - // Account for unreliable border-box dimensions by comparing offset* to computed and - // faking a content-box to get border and padding (gh-3699) - if ( isBorderBox && scrollboxSizeBuggy ) { - subtract -= Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - parseFloat( styles[ dimension ] ) - - boxModelAdjustment( elem, dimension, "border", false, styles ) - - 0.5 - ); - } - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ dimension ] = value; - value = jQuery.css( elem, dimension ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; -} ); - -jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } -); - -// These hooks are used by animate to expand properties -jQuery.each( { - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( prefix !== "margin" ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -} ); - -jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } -} ); - - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && ( - jQuery.cssHooks[ tween.prop ] || - tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" -}; - -jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point -jQuery.fx.step = {}; - - - - -var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - -function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } -} - -// Animations created synchronously will run synchronously -function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = Date.now() ); -} - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } -} - -function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 15 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY and Edge just mirrors - // the overflowX value there. - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } -} - -function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - result.stop.bind( result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } -} ); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } -} ); - -jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -} ); - -// Generate shortcuts for custom animations -jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -} ); - -jQuery.timers = []; -jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = Date.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); -}; - -jQuery.fx.interval = 13; -jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); -}; - -jQuery.fx.stop = function() { - inProgress = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 -}; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ -jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); -}; - - -( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; -} )(); - - -var boolHook, - attrHandle = jQuery.expr.attrHandle; - -jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } -} ); - -jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } -} ); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; - -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; -} ); - - - - -var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - -jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } -} ); - -jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } -} ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop -if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; -} - -jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -} ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - -function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; -} - -function classesToArray( value ) { - if ( Array.isArray( value ) ) { - return value; - } - if ( typeof value === "string" ) { - return value.match( rnothtmlwhite ) || []; - } - return []; -} - -jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isValidValue = type === "string" || Array.isArray( value ); - - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( isValidValue ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = classesToArray( value ); - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } -} ); - - - - -var rreturn = /\r/g; - -jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, valueIsFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - valueIsFunction = isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( valueIsFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } -} ); - -jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } -} ); - -// Radios and checkboxes getter/setter -jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } -} ); - - - - -// Return jQuery for attributes-only inclusion - - -support.focusin = "onfocusin" in window; - - -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - stopPropagationCallback = function( e ) { - e.stopPropagation(); - }; - -jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = lastElement = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - lastElement = cur; - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( - dataPriv.get( cur, "events" ) || Object.create( null ) - )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - - if ( event.isPropagationStopped() ) { - lastElement.addEventListener( type, stopPropagationCallback ); - } - - elem[ type ](); - - if ( event.isPropagationStopped() ) { - lastElement.removeEventListener( type, stopPropagationCallback ); - } - - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - -} ); - -jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -} ); - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - - // Handle: regular nodes (via `this.ownerDocument`), window - // (via `this.document`) & document (via `this`). - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = { guid: Date.now() }; - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) { - xml = undefined; - } - - if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; -}; - - -var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && toType( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } -} - -// Serialize an array of form elements or a set of -// key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - if ( a == null ) { - return ""; - } - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); -}; - -jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ) - .filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ) - .map( function( _i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } -} ); - - -var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -/* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -/* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ -function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; -} - -jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() + " " ] = - ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) - .concat( match[ 2 ] ); - } - } - match = responseHeaders[ key.toLowerCase() + " " ]; - } - return match == null ? null : match.join( ", " ); - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 15 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available and should be processed, append data to url - if ( s.data && ( s.processData || typeof s.data === "string" ) ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + - uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Use a noop converter for missing script - if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { - s.converters[ "text script" ] = function() {}; - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } -} ); - -jQuery.each( [ "get", "post" ], function( _i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; -} ); - -jQuery.ajaxPrefilter( function( s ) { - var i; - for ( i in s.headers ) { - if ( i.toLowerCase() === "content-type" ) { - s.contentType = s.headers[ i ] || ""; - } - } -} ); - - -jQuery._evalUrl = function( url, options, doc ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - - // Only evaluate the response if it is successful (gh-4126) - // dataFilter is not invoked for failure responses, so using it instead - // of the default converter is kludgy but it works. - converters: { - "text script": function() {} - }, - dataFilter: function( response ) { - jQuery.globalEval( response, options, doc ); - } - } ); -}; - - -jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var htmlIsFunction = isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } -} ); - - -jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); -}; -jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); -}; - - - - -jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} -}; - -var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - -support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -support.ajax = xhrSupported = !!xhrSupported; - -jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.ontimeout = - xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } -} ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) -jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } -} ); - -// Install script dataType -jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -} ); - -// Handle cache's special case and crossDomain -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } -} ); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain or forced-by-attrs requests - if ( s.crossDomain || s.scriptAttrs ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

FAQΒΆ

-
-

Installation IssuesΒΆ

-

We recommend using virtualenv (venv) to set up your Python runtime.

-
# Create a dedicated virtual env for running your Python scripts
-python -m venv .venv
-
-# Run .venv\Scripts\activate on Windows OS
-source .venv/bin/activate
-
-# Install slack_sdk PyPI package
-pip install "slack_sdk>=3.0"
-
-# Set your token as an env variable (`set` command for Windows OS)
-export SLACK_BOT_TOKEN=xoxb-***
-
-
-

Then, verify the following code works on the Python REPL (you can start it by just python).

-
import os
-import logging
-from slack_sdk import WebClient
-logging.basicConfig(level=logging.DEBUG)
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-res = client.api_test()
-
-
-

As slack package is deprecated, we recommend switching to slack_sdk package. That being said, the code you’re working on may be still using the old package. If you encounter an error saying AttributeError: module 'slack' has no attribute 'WebClient', run pip list. If you find both slack_sdk and slack in the output, try removing slack by pip uninstall slack and reinstalling slack_sdk.

-
-
-

Bug ReportΒΆ

-

That’s great! Thank you. Let us know on the Issue Tracker. If you’re feeling particularly ambitious, why not submit a pull request with a bug fix?

-
-
-

Feature RequestsΒΆ

-

There’s always something more that could be added! You can let us know in the Issue Tracker to start a discussion around the proposed feature, that’s a good start. If you’re feeling particularly ambitious, why not write the feature yourself, and submit a pull request! We love feedback and we love help and we don’t bite. Much.

-
-
-

ContributionsΒΆ

-

What an excellent question. First of all, please have a look at our general contributing guidelines.

-

All done? Great! While we’re super excited to incorporate your new feature, there are a couple of things we want to make sure you’ve given thought to.

-
    -
  • Please write unit tests for your new code. But don’t just aim to increase the test coverage, rather, we expect you to have written thoughtful tests that ensure your new feature will continue to work as expected, and to help future contributors to ensure they don’t break it!

  • -
  • Please document your new feature. Think about concrete use cases for your feature, and add a section to the appropriate document, including a complete sample program that demonstrates your feature. Don’t forget to update the changelog in changelog.rst!

  • -
-

Including these two items with your pull request will totally make our dayβ€”and, more importantly, your future users’ days!

-

On that note…

-
-
-

DocumentationΒΆ

-

This project’s documentation is generated with Sphinx. If you are editing one of the many reStructuredText files in the docs-src folder, you’ll need to rebuild the documentation. It is recommended to run the following steps inside a virtualenv environment.

-
./docs-v3.sh
-
-
-

Do be sure to add the docs-v3 folder and its contents to your pull request!

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/genindex.html b/docs/genindex.html deleted file mode 100644 index 1bb8b7bcb..000000000 --- a/docs/genindex.html +++ /dev/null @@ -1,225 +0,0 @@ - - - - - - Index — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - - - -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index 1a58fbfd9..000000000 --- a/docs/index.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - - - Python Slack SDK — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-
-
-

Python Slack SDKΒΆ

-

The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slack’s APIs. They are small and powerful when used independently, and work seamlessly when used together, too.

- ----- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Feature

What its for

Package

Web API

Send data to or query data from Slack using any of over 200 methods.

slack_sdk.web -slack_sdk.web.async_client

Webhooks / response_url

Send a message using Incoming Webhooks or response_url

slack_sdk.webhook -slack_sdk.webhook.async_client

OAuth

Setup the authentication flow using V2 OAuth for Slack apps.

slack_sdk.oauth

RTM API

Listen for incoming messages and a limited set of events happening in Slack, using WebSocket.

slack_sdk.rtm`

Request Signature Verification

Verify incoming requests from the Slack API servers.

slack_sdk.signature

UI Builders

Construct UI components using easy-to-use builders.

slack_sdk.models

-
-

InstallationΒΆ

-

This package supports Python 3.6 and higher. We recommend using PyPI to install Python Slack SDK

-
pip install slack_sdk
-
-
-

Of course, you can always pull the source code directly into your project:

-
git clone https://github.com/slackapi/python-slack-sdk.git
-
-
-

And then, save a few lines of code as ./test.py.

-
# test.py
-import sys
-# Load the local source directly
-sys.path.insert(1, "./python-slack-sdk")
-# Enable debug logging
-import logging
-logging.basicConfig(level=logging.DEBUG)
-# Verify it works
-from slack_sdk import WebClient
-client = WebClient()
-api_response = client.api_test()
-
-
-

You can run the code this way.

-
python test.py
-
-
-

It’s also good to try on the Python REPL.

-
-
-

Getting HelpΒΆ

-

If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:

-
    -
  • GitHub Issue Tracker for questions, feature requests, bug reports and general discussion related to this package.

  • -
  • Visit the Slack Developer Community for getting help using Python Slack SDK or just generally bond with your fellow Slack developers.

  • -
-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/installation/index.html b/docs/installation/index.html deleted file mode 100644 index 7e76e25ae..000000000 --- a/docs/installation/index.html +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - Installation — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

InstallationΒΆ

-
-

Access TokensΒΆ

-

Keeping access tokens safe

-

The OAuth token you use to call the Slack API has access to the data on the workspace where it is installed.

-

Depending on the scopes granted to the token, it potentially has the ability to read and write data. Treat these tokens just as you would a password – don’t publish them, don’t check them into source code, don’t share them with others.

-

🚫Avoid this:

-
token = 'xoxb-111-222-xxxxx'
-
-
-

We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as:

-
SLACK_BOT_TOKEN="xoxb-111-222-xxxxx" python myapp.py
-
-
-

Then retrieve the key with:

-
import os
-SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
-
-
-

For additional information, please see our Safely Storing Credentials page.

-
-
-

Workspace InstallationsΒΆ

-

Single Workspace Install

-

If you’re building an application for a single Slack workspace, there’s no need to build out the entire OAuth flow.

-

Once you’ve setup your features, click on the Install App to Team button found on the Install App page. -If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to -your workspace for changes to take effect.

-

For additional information, see the Installing Apps of our Building Slack apps page.

-

Multiple Workspace Install

-

If you intend for an app to be installed on multiple Slack workspaces, you will need to handle this installation via the industry-standard OAuth protocol. You can read more about how Slack handles Oauth.

-

(The OAuth exchange is facilitated via HTTP and requires a webserver; in this example, we’ll use Flask.)

-

To configure your app for OAuth, you’ll need a client ID, a client secret, and a set of one or more scopes that will be applied to the token once it is granted. The client ID and client secret are available from your app’s configuration page. The scopes are determined by the functionality of the app – every method you wish to access has a corresponding scope and your app will need to request that scope in order to be able to access the method. Review Slack’s full list of OAuth scopes.

-
import os
-from slack_sdk import WebClient
-from flask import Flask, request
-
-client_id = os.environ["SLACK_CLIENT_ID"]
-client_secret = os.environ["SLACK_CLIENT_SECRET"]
-oauth_scope = os.environ["SLACK_SCOPES"]
-
-app = Flask(__name__)
-
-
-

The OAuth initiation link

-

To begin the OAuth flow that will install your app on a workspace, you’ll need to provide the user with a link to Slack’s OAuth page. This can be a simple link to https://slack.com/oauth/v2/authorize with scope and client_id query parameters, or you can use our pre-built Add to Slack button to do all the work for you.

-

This link directs the user to Slack’s OAuth acceptance page, where the user will review and accept or refuse the permissions your app is requesting as defined by the scope(s).

-
@app.route("/slack/install", methods=["GET"])
-def pre_install():
-    state = "randomly-generated-one-time-value"
-    return '<a href="https://slack.com/oauth/v2/authorize?' \
-        f'scope={oauth_scope}&client_id={client_id}&state={state}">' \
-        'Add to Slack</a>'
-
-
-

The OAuth completion page

-

Once the user has agreed to the permissions you’ve requested, Slack will redirect the user to your auth completion page, which includes a code query string param. You’ll use the code param to call the oauth.v2.access endpoint that will finally grant you the token.

-
@app.route("/slack/oauth_redirect", methods=["GET"])
-def post_install():
-    # Verify the "state" parameter
-
-    # Retrieve the auth code from the request params
-    code_param = request.args['code']
-
-    # An empty string is a valid token for this request
-    client = WebClient()
-
-    # Request the auth tokens from Slack
-    response = client.oauth_v2_access(
-        client_id=client_id,
-        client_secret=client_secret,
-        code=code_param
-    )
-
-
-

A successful request to oauth.v2.access will yield a JSON payload with at least one token, a bot token that begins with xoxb.

-
@app.route("/slack/oauth_redirect", methods=["GET"])
-def post_install():
-    # Verify the "state" parameter
-
-    # Retrieve the auth code from the request params
-    code_param = request.args['code']
-
-    # An empty string is a valid token for this request
-    client = WebClient()
-
-    # Request the auth tokens from Slack
-    response = client.oauth_v2_access(
-        client_id=client_id,
-        client_secret=client_secret,
-        code=code_param
-    )
-    print(response)
-
-    # Save the bot token to an environmental variable or to your data store
-    # for later use
-    os.environ["SLACK_BOT_TOKEN"] = response['access_token']
-
-    # Don't forget to let the user know that OAuth has succeeded!
-    return "Installation is completed!"
-
-if __name__ == "__main__":
-    app.run("localhost", 3000)
-
-
-

Once your user has completed the OAuth flow, you’ll be able to use the provided tokens to call any of Slack’s API methods that require an access token.

-

See the Basic Usage section of this documentation for usage examples.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/metadata.html b/docs/metadata.html deleted file mode 100644 index 763476d82..000000000 --- a/docs/metadata.html +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - <no title> — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - - - -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/oauth/index.html b/docs/oauth/index.html deleted file mode 100644 index 0e1fccd11..000000000 --- a/docs/oauth/index.html +++ /dev/null @@ -1,441 +0,0 @@ - - - - - - OAuth Modules — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

OAuth ModulesΒΆ

-

This section explains the details about how to handle Slack’s OAuth flow.

-

If you’re looking for a much easier way to do the same, check Bolt for Python, which is a full-stack Slack App framework. With Bolt, you don’t need to implement most of the following code on your own.

-
-

App Installation FlowΒΆ

-

OAuth lets a user in any Slack workspace install your app. At the end of OAuth, your app gains an access token. Refer to Installing with OAuth for details.

-

Python Slack SDK provides the necessary modules for building the OAuth flow.

-

Starting an OAuth flow

-

The first step of Slack OAuth flow is to redirect a Slack user to https://slack.com/oauth/v2/authorize with a valida state parameter. To implement this process, you can use the following modules.

- ----- - - - - - - - - - - - - - - - - - - -

Module

What its for

Default Implementation

InstallationStore

Persist installation data and lookup it by IDs.

FileInstallationStore

OAuthStateStore

Issue and consume state parameter value on the server-side.

FileOAuthStateStore

AuthorizeUrlGenerator

Build https://slack.com/oauth/v2/authorize with sufficient query parameters

(same)

-

The code snippet below demonstrates how to build it using Flask.

-
import os
-from slack_sdk.oauth import AuthorizeUrlGenerator
-from slack_sdk.oauth.installation_store import FileInstallationStore, Installation
-from slack_sdk.oauth.state_store import FileOAuthStateStore
-
-# Issue and consume state parameter value on the server-side.
-state_store = FileOAuthStateStore(expiration_seconds=300, base_dir="./data")
-# Persist installation data and lookup it by IDs.
-installation_store = FileInstallationStore(base_dir="./data")
-
-# Build https://slack.com/oauth/v2/authorize with sufficient query parameters
-authorize_url_generator = AuthorizeUrlGenerator(
-    client_id=os.environ["SLACK_CLIENT_ID"],
-    scopes=["app_mentions:read", "chat:write"],
-    user_scopes=["search:read"],
-)
-
-from flask import Flask, request, make_response
-app = Flask(__name__)
-
-@app.route("/slack/install", methods=["GET"])
-def oauth_start():
-    # Generate a random value and store it on the server-side
-    state = state_store.issue()
-    # https://slack.com/oauth/v2/authorize?state=(generated value)&client_id={client_id}&scope=app_mentions:read,chat:write&user_scope=search:read
-    url = authorize_url_generator.generate(state)
-    return f'<a href="{url}">' \
-           f'<img alt=""Add to Slack"" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>'
-
-
-

When accessing https://(your domain)/slack/install, you will see β€œAdd to Slack” button in the webpage. You can start the app’s installation flow by clicking the button.

-

Handling a callback request from Slack

-

If all’s well, a user goes through the Slack app installation UI and okays your app with all the scopes that it requests. After that happens, Slack redirects the user back to your specified Redirect URL.

-

The redirection gives you a code parameter. You can exchange the value for an access token by calling oauth.v2.access API method.

-
from slack_sdk.web import WebClient
-client_secret = os.environ["SLACK_CLIENT_SECRET"]
-
-# Redirect URL
-@app.route("/slack/oauth/callback", methods=["GET"])
-def oauth_callback():
-    # Retrieve the auth code and state from the request params
-    if "code" in request.args:
-        # Verify the state parameter
-        if state_store.consume(request.args["state"]):
-            client = WebClient()  # no prepared token needed for this
-            # Complete the installation by calling oauth.v2.access API method
-            oauth_response = client.oauth_v2_access(
-                client_id=client_id,
-                client_secret=client_secret,
-                redirect_uri=redirect_uri,
-                code=request.args["code"]
-            )
-
-            installed_enterprise = oauth_response.get("enterprise") or {}
-            installed_team = oauth_response.get("team") or {}
-            installer = oauth_response.get("authed_user") or {}
-            incoming_webhook = oauth_response.get("incoming_webhook") or {}
-            bot_token = oauth_response.get("access_token")
-            # NOTE: As oauth.v2.access doesn't include bot_id in response,
-            # we call bots.info for storing the installation data along with bot_id.
-            bot_id = None
-            if bot_token is not None:
-                auth_test = client.auth_test(token=bot_token)
-                bot_id = auth_test["bot_id"]
-
-            # Build an installation data
-            installation = Installation(
-                app_id=oauth_response.get("app_id"),
-                enterprise_id=installed_enterprise.get("id"),
-                team_id=installed_team.get("id"),
-                bot_token=bot_token,
-                bot_id=bot_id,
-                bot_user_id=oauth_response.get("bot_user_id"),
-                bot_scopes=oauth_response.get("scope"),  # comma-separated string
-                user_id=installer.get("id"),
-                user_token=installer.get("access_token"),
-                user_scopes=installer.get("scope"),  # comma-separated string
-                incoming_webhook_url=incoming_webhook.get("url"),
-                incoming_webhook_channel_id=incoming_webhook.get("channel_id"),
-                incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"),
-            )
-            # Store the installation
-            installation_store.save(installation)
-
-            return "Thanks for installing this app!"
-        else:
-            return make_response(f"Try the installation again (the state value is already expired)", 400)
-
-    error = request.args["error"] if "error" in request.args else ""
-    return make_response(f"Something is wrong with the installation (error: {error})", 400)
-
-
-
-
-

Token LookupΒΆ

-

Now that your Flask app can choose the right access token for incoming event requests, let’s add the Slack event handler endpoint.

-

You can use the same InstallationStore in the Slack event handler.

-
import json
-from slack_sdk.errors import SlackApiError
-
-from slack_sdk.signature import SignatureVerifier
-signing_secret = os.environ["SLACK_SIGNING_SECRET"]
-signature_verifier = SignatureVerifier(signing_secret=signing_secret)
-
-@app.route("/slack/events", methods=["POST"])
-def slack_app():
-    # Verify incoming requests from Slack
-    # https://api.slack.com/authentication/verifying-requests-from-slack
-    if not signature_verifier.is_valid(
-        body=request.get_data(),
-        timestamp=request.headers.get("X-Slack-Request-Timestamp"),
-        signature=request.headers.get("X-Slack-Signature")):
-        return make_response("invalid request", 403)
-
-    # Handle a slash command invocation
-    if "command" in request.form \
-        and request.form["command"] == "/open-modal":
-        try:
-            # in the case where this app gets a request from an Enterprise Grid workspace
-            enterprise_id = request.form.get("enterprise_id")
-            # The workspace's ID
-            team_id = request.form["team_id"]
-            # Lookup the stored bot token for this workspace
-            bot = installation_store.find_bot(
-                enterprise_id=enterprise_id,
-                team_id=team_id,
-            )
-            bot_token = bot.bot_token if bot else None
-            if not bot_token:
-                # The app may be uninstalled or be used in a shared channel
-                return make_response("Please install this app first!", 200)
-
-            # Open a modal using the valid bot token
-            client = WebClient(token=bot_token)
-            trigger_id = request.form["trigger_id"]
-            response = client.views_open(
-                trigger_id=trigger_id,
-                view={
-                    "type": "modal",
-                    "callback_id": "modal-id",
-                    "title": {
-                        "type": "plain_text",
-                        "text": "Awesome Modal"
-                    },
-                    "submit": {
-                        "type": "plain_text",
-                        "text": "Submit"
-                    },
-                    "blocks": [
-                        {
-                            "type": "input",
-                            "block_id": "b-id",
-                            "label": {
-                                "type": "plain_text",
-                                "text": "Input label",
-                            },
-                            "element": {
-                                "action_id": "a-id",
-                                "type": "plain_text_input",
-                            }
-                        }
-                    ]
-                }
-            )
-            return make_response("", 200)
-        except SlackApiError as e:
-            code = e.response["error"]
-            return make_response(f"Failed to open a modal due to {code}", 200)
-
-    elif "payload" in request.form:
-        # Data submission from the modal
-        payload = json.loads(request.form["payload"])
-        if payload["type"] == "view_submission" \
-            and payload["view"]["callback_id"] == "modal-id":
-            submitted_data = payload["view"]["state"]["values"]
-            print(submitted_data)  # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
-            # You can use WebClient with a valid token here too
-            return make_response("", 200)
-
-    # Indicate unsupported request patterns
-    return make_response("", 404)
-
-
-

Again, if you’re looking for an easier solution, take a look at Bolt for Python. With Bolt, you don’t need to implement most of the above code on your own.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/objects.inv b/docs/objects.inv deleted file mode 100644 index cc4d6d6ae..000000000 --- a/docs/objects.inv +++ /dev/null @@ -1,8 +0,0 @@ -# Sphinx inventory version 2 -# Project: Python Slack SDK -# Version: 1.0 -# The remainder of this file is compressed using zlib. -xΪ…‘AKΔ0…οω½Vo"BQ‘ΕΥ.x\¦ΝΨ†¦‰6Su½Ν¦Ω¦΄Λήχή73άtΔ-‰a -ž\qpΒEEβ©{²OψŽύώΣ»ι+QK-πoP£r‘ ϊά³{² -΄PR— ™΅R[₯€€Ρ—#zvΞΣ’@kωf±±Χ0LΤf½£Κhž)(jž=Ό°yΡ)ΉΨ²ŸvΤYƒb0h>~« 'I -οXcΔΒ.ΎvI0<±2’S8lΕ@GΥ|ΈHφΠkΪ jYTσD³a)“ž-‚JH6˜4ύj‘μ2­β[Ψαο›ΏW5±…Tό NJΔ%,B[TΣζ^σΡΜϋk(‘ύ\',Ϋ#ל»Γ²ƒΘŸ:)ύb>‡’g>0φNeL½ˆŒΖsR@Β 0 \ No newline at end of file diff --git a/docs/real_time_messaging.html b/docs/real_time_messaging.html deleted file mode 100644 index 6adc43268..000000000 --- a/docs/real_time_messaging.html +++ /dev/null @@ -1,303 +0,0 @@ - - - - - - RTM Client — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

RTM ClientΒΆ

-
-

Real Time Messaging (RTM)ΒΆ

-

The Real Time Messaging (RTM) API is a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users.

-

If you prefer events to be pushed to your app, we recommend using the HTTP-based Events API instead. -The Events API contains some events that aren’t supported in the RTM API (like app_home_opened event), -and it supports most of the event types in the RTM API. If you’d like to use the Events API, you can use the Python Slack Events Adaptor.

-

The RTMClient allows apps to communicate with the Slack Platform’s RTM API.

-

The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks.

-

In our example below, we watch for a message event that contains β€œHello” and if its received, we call the say_hello() function. We then issue a call to the web client to post back to the channel saying β€œHi” to the user.

-

Configuring the RTM API

-

Events using the RTM API must use a classic Slack app (with a plain bot scope).

-

If you already have a classic Slack app, you can use those credentials. If you don’t and need to use the RTM API, you can create a classic Slack app. You can learn more in the API documentation.

-

Also, even if the Slack app configuration pages encourage you to upgrade to the newer permission model, don’t upgrade it and keep using the β€œclassic” bot permission.

-

Connecting to the RTM API

-
import os
-from slack_sdk.rtm import RTMClient
-
-@RTMClient.run_on(event="message")
-def say_hello(**payload):
-    data = payload['data']
-    web_client = payload['web_client']
-
-    if 'Hello' in data['text']:
-        channel_id = data['channel']
-        thread_ts = data['ts']
-        user = data['user'] # This is not username but user ID (the format is either U*** or W***)
-
-        web_client.chat_postMessage(
-            channel=channel_id,
-            text=f"Hi <@{user}>!",
-            thread_ts=thread_ts
-        )
-
-slack_token = os.environ["SLACK_BOT_TOKEN"]
-rtm_client = RTMClient(token=slack_token)
-rtm_client.start()
-
-
-

rtm.start vs rtm.connect

-

By default, the RTM client uses rtm.connect to establish a WebSocket connection with Slack. The response contains basic information about the team and WebSocket url.

-

If you’d rather use rtm.start to establish the connection, which provides more information about the conversations and users on the team, you can set the connect_method option to rtm.start when instantiating the RTM Client. Note that on larger teams, use of rtm.start can be slow and unreliable.

-
import os
-from slack_sdk import RTMClient
-
-@RTMClient.run_on(event="message")
-def say_hello(**payload):
-    data = payload['data']
-    web_client = payload['web_client']
-    if 'text' in data and 'Hello' in data['text']:
-        channel_id = data['channel']
-        thread_ts = data['ts']
-        user = data['user'] # This is not username but user ID (the format is either U*** or W***)
-
-        web_client.chat_postMessage(
-            channel=channel_id,
-            text=f"Hi <@{user}>!",
-            thread_ts=thread_ts
-        )
-
-slack_token = os.environ["SLACK_BOT_TOKEN"]
-rtm_client = RTMClient(
-    token=slack_token,
-    connect_method='rtm.start'
-)
-rtm_client.start()
-
-
-

Read the rtm.connect docs and the rtm.start docs for more details.

-
-
-

RTM EventsΒΆ

-
{
-    'type': 'message',
-    'ts': '1358878749.000002',
-    'user': 'U023BECGF',
-    'text': 'Hello'
-}
-
-
-

See RTM Events for a complete list of events.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/reference/aiohttp_version_checker.html b/docs/reference/aiohttp_version_checker.html new file mode 100644 index 000000000..9430e24fa --- /dev/null +++ b/docs/reference/aiohttp_version_checker.html @@ -0,0 +1,100 @@ + + + + + + +slack_sdk.aiohttp_version_checker API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.aiohttp_version_checker

+
+
+

Internal module for checking aiohttp compatibility of async modules

+
+
+
+
+
+
+

Functions

+
+
+def validate_aiohttp_version(aiohttp_version:Β str,
print_warning:Β Callable[[str],Β None]Β =Β <function _print_warning_log>)
+
+
+
+ +Expand source code + +
def validate_aiohttp_version(
+    aiohttp_version: str,
+    print_warning: Callable[[str], None] = _print_warning_log,
+):
+    if aiohttp_version is not None:
+        elements = aiohttp_version.split(".")
+        if len(elements) >= 3:
+            # patch version can be a non-numeric value
+            major, minor, patch = int(elements[0]), int(elements[1]), elements[2]
+            if major <= 2 or (major == 3 and (minor == 6 or (minor == 7 and patch == "0"))):
+                print_warning(
+                    "We highly recommend upgrading aiohttp to 3.7.3 or higher versions."
+                    "An older version of the library may not work with the Slack server-side in the future."
+                )
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/async_client.html b/docs/reference/audit_logs/async_client.html new file mode 100644 index 000000000..600bb9c35 --- /dev/null +++ b/docs/reference/audit_logs/async_client.html @@ -0,0 +1,736 @@ + + + + + + +slack_sdk.audit_logs.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.async_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncAuditLogsClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/audit/v1/',
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
auth:Β aiohttp.helpers.BasicAuthΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncAuditLogsClient:
+    BASE_URL = "https://api.slack.com/audit/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    session: Optional[ClientSession]
+    trust_env_in_session: bool
+    auth: Optional[BasicAuth]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[AsyncRetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        session: Optional[ClientSession] = None,
+        trust_env_in_session: bool = False,
+        auth: Optional[BasicAuth] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        """API client for Audit Logs API
+        See https://docs.slack.dev/admins/audit-logs-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            session: `aiohttp.ClientSession` instance
+            trust_env_in_session: True/False for `aiohttp.ClientSession`
+            auth: Basic auth info for `aiohttp.ClientSession`
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.session = session
+        self.trust_env_in_session = trust_env_in_session
+        self.auth = auth
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    async def schemas(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of objects which the Audit Logs API
+        returns as a list of all objects and a short description.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+        Returns:
+            API response
+        """
+        return await self.api_call(
+            path="schemas",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def actions(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of actions that the Audit Logs API
+        returns as a list of all actions and a short description of each.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        return await self.api_call(
+            path="actions",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def logs(
+        self,
+        *,
+        latest: Optional[int] = None,
+        oldest: Optional[int] = None,
+        limit: Optional[int] = None,
+        action: Optional[str] = None,
+        actor: Optional[str] = None,
+        entity: Optional[str] = None,
+        cursor: Optional[str] = None,
+        additional_query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """This is the primary endpoint for retrieving actual audit events from your organization.
+        It will return a list of actions that have occurred on the installed workspace or grid organization.
+        Authentication required.
+
+        The following filters can be applied in order to narrow the range of actions returned.
+        Filters are added as query string parameters and can be combined together.
+        Multiple filter parameters are additive (a boolean AND) and are separated
+        with an ampersand (&) in the query string. Filtering is entirely optional.
+
+        Args:
+            latest: Unix timestamp of the most recent audit event to include (inclusive).
+            oldest: Unix timestamp of the least recent audit event to include (inclusive).
+                Data is not available prior to March 2018.
+            limit: Number of results to optimistically return, maximum 9999.
+            action: Name of the action.
+            actor: User ID who initiated the action.
+            entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+            cursor: The next page cursor of pagination
+            additional_query_params: Add anything else if you need to use the ones this library does not support
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        query_params = {
+            "latest": latest,
+            "oldest": oldest,
+            "limit": limit,
+            "action": action,
+            "actor": actor,
+            "entity": entity,
+            "cursor": cursor,
+        }
+        if additional_query_params is not None:
+            query_params.update(additional_query_params)
+        query_params = {k: v for k, v in query_params.items() if v is not None}
+        return await self.api_call(
+            path="logs",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def api_call(
+        self,
+        *,
+        http_verb: str = "GET",
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        url = f"{self.base_url}{path}"
+        return await self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            query_params=query_params,
+            body_params=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    async def _perform_http_request(
+        self,
+        *,
+        http_verb: str,
+        url: str,
+        query_params: Optional[Dict[str, Any]],
+        body_params: Optional[Dict[str, Any]],
+        headers: Dict[str, str],
+    ) -> AuditLogsResponse:
+        if body_params is not None:
+            body_params = json.dumps(body_params)  # type: ignore[assignment]
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        session: Optional[ClientSession] = None
+        use_running_session = self.session and not self.session.closed
+        if use_running_session:
+            session = self.session
+        else:
+            session = aiohttp.ClientSession(
+                timeout=aiohttp.ClientTimeout(total=self.timeout),
+                auth=self.auth,
+                trust_env=self.trust_env_in_session,
+            )
+
+        last_error = None
+        resp: Optional[AuditLogsResponse] = None
+        try:
+            request_kwargs = {
+                "headers": headers,
+                "params": query_params,
+                "data": body_params,
+                "ssl": self.ssl,
+                "proxy": self.proxy,
+            }
+            retry_request = RetryHttpRequest(
+                method=http_verb,
+                url=url,
+                headers=headers,  # type: ignore[arg-type]
+                body_params=body_params,
+            )
+
+            retry_state = RetryState()
+            counter_for_safety = 0
+            while counter_for_safety < 100:
+                counter_for_safety += 1
+                # If this is a retry, the next try started here. We can reset the flag.
+                retry_state.next_attempt_requested = False
+                retry_response: Optional[RetryHttpResponse] = None
+                response_body = ""
+
+                if self.logger.level <= logging.DEBUG:
+                    headers_for_logging = {
+                        k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()
+                    }
+                    self.logger.debug(
+                        f"Sending a request - "
+                        f"url: {url}, "
+                        f"params: {query_params}, "
+                        f"body: {body_params}, "
+                        f"headers: {headers_for_logging}"
+                    )
+
+                try:
+                    async with session.request(http_verb, url, **request_kwargs) as res:  # type: ignore[arg-type, union-attr] # noqa: E501
+                        try:
+                            response_body = await res.text()
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                                data=response_body.encode("utf-8") if response_body is not None else None,
+                            )
+                        except aiohttp.ContentTypeError:
+                            self.logger.debug(f"No response data returned from the following API call: {url}.")
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+                        except json.decoder.JSONDecodeError as e:
+                            message = f"Failed to parse the response body: {str(e)}"
+                            raise SlackApiError(message, res)
+
+                        if res.status == 429:
+                            for handler in self.retry_handlers:
+                                if await handler.can_retry_async(
+                                    state=retry_state,
+                                    request=retry_request,
+                                    response=retry_response,
+                                ):
+                                    if self.logger.level <= logging.DEBUG:
+                                        self.logger.info(
+                                            f"A retry handler found: {type(handler).__name__} "
+                                            f"for {http_verb} {url} - rate_limited"
+                                        )
+                                    await handler.prepare_for_next_attempt_async(
+                                        state=retry_state,
+                                        request=retry_request,
+                                        response=retry_response,
+                                    )
+                                    break
+
+                        if retry_state.next_attempt_requested is False:
+                            resp = AuditLogsResponse(
+                                url=url,
+                                status_code=res.status,
+                                raw_body=response_body,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+                            _debug_log_response(self.logger, resp)
+                            return resp
+
+                except Exception as e:
+                    last_error = e
+                    for handler in self.retry_handlers:
+                        if await handler.can_retry_async(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        ):
+                            if self.logger.level <= logging.DEBUG:
+                                self.logger.info(
+                                    f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}"
+                                )
+                            await handler.prepare_for_next_attempt_async(
+                                state=retry_state,
+                                request=retry_request,
+                                response=retry_response,
+                                error=e,
+                            )
+                            break
+
+                    if retry_state.next_attempt_requested is False:
+                        raise last_error
+
+            if resp is not None:
+                return resp
+            raise last_error  # type: ignore[misc]
+
+        finally:
+            if not use_running_session:
+                await session.close()  # type: ignore[union-attr]
+
+        return resp
+
+

API client for Audit Logs API +See https://docs.slack.dev/admins/audit-logs-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
session
+
aiohttp.ClientSession instance
+
trust_env_in_session
+
True/False for aiohttp.ClientSession
+
auth
+
Basic auth info for aiohttp.ClientSession
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var auth :Β aiohttp.helpers.BasicAuthΒ |Β None
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]
+
+

The type of the None singleton.

+
+
var session :Β aiohttp.client.ClientSessionΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
var trust_env_in_session :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def actions(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def actions(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of actions that the Audit Logs API
+    returns as a list of all actions and a short description of each.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    return await self.api_call(
+        path="actions",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of actions that the Audit Logs API +returns as a list of all actions and a short description of each. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+async def api_call(self,
*,
http_verb:Β strΒ =Β 'GET',
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def api_call(
+    self,
+    *,
+    http_verb: str = "GET",
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    url = f"{self.base_url}{path}"
+    return await self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        query_params=query_params,
+        body_params=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+
+
+
+async def logs(self,
*,
latest:Β intΒ |Β NoneΒ =Β None,
oldest:Β intΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
actor:Β strΒ |Β NoneΒ =Β None,
entity:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
additional_query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def logs(
+    self,
+    *,
+    latest: Optional[int] = None,
+    oldest: Optional[int] = None,
+    limit: Optional[int] = None,
+    action: Optional[str] = None,
+    actor: Optional[str] = None,
+    entity: Optional[str] = None,
+    cursor: Optional[str] = None,
+    additional_query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """This is the primary endpoint for retrieving actual audit events from your organization.
+    It will return a list of actions that have occurred on the installed workspace or grid organization.
+    Authentication required.
+
+    The following filters can be applied in order to narrow the range of actions returned.
+    Filters are added as query string parameters and can be combined together.
+    Multiple filter parameters are additive (a boolean AND) and are separated
+    with an ampersand (&) in the query string. Filtering is entirely optional.
+
+    Args:
+        latest: Unix timestamp of the most recent audit event to include (inclusive).
+        oldest: Unix timestamp of the least recent audit event to include (inclusive).
+            Data is not available prior to March 2018.
+        limit: Number of results to optimistically return, maximum 9999.
+        action: Name of the action.
+        actor: User ID who initiated the action.
+        entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+        cursor: The next page cursor of pagination
+        additional_query_params: Add anything else if you need to use the ones this library does not support
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    query_params = {
+        "latest": latest,
+        "oldest": oldest,
+        "limit": limit,
+        "action": action,
+        "actor": actor,
+        "entity": entity,
+        "cursor": cursor,
+    }
+    if additional_query_params is not None:
+        query_params.update(additional_query_params)
+    query_params = {k: v for k, v in query_params.items() if v is not None}
+    return await self.api_call(
+        path="logs",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

This is the primary endpoint for retrieving actual audit events from your organization. +It will return a list of actions that have occurred on the installed workspace or grid organization. +Authentication required.

+

The following filters can be applied in order to narrow the range of actions returned. +Filters are added as query string parameters and can be combined together. +Multiple filter parameters are additive (a boolean AND) and are separated +with an ampersand (&) in the query string. Filtering is entirely optional.

+

Args

+
+
latest
+
Unix timestamp of the most recent audit event to include (inclusive).
+
oldest
+
Unix timestamp of the least recent audit event to include (inclusive). +Data is not available prior to March 2018.
+
limit
+
Number of results to optimistically return, maximum 9999.
+
action
+
Name of the action.
+
actor
+
User ID who initiated the action.
+
entity
+
ID of the target entity of the action (such as a channel, workspace, organization, file).
+
cursor
+
The next page cursor of pagination
+
additional_query_params
+
Add anything else if you need to use the ones this library does not support
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+async def schemas(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def schemas(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of objects which the Audit Logs API
+    returns as a list of all objects and a short description.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+    Returns:
+        API response
+    """
+    return await self.api_call(
+        path="schemas",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of objects which the Audit Logs API +returns as a list of all objects and a short description. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/index.html b/docs/reference/audit_logs/index.html new file mode 100644 index 000000000..940d34e1c --- /dev/null +++ b/docs/reference/audit_logs/index.html @@ -0,0 +1,828 @@ + + + + + + +slack_sdk.audit_logs API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs

+
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details.

+
+
+

Sub-modules

+
+
slack_sdk.audit_logs.async_client
+
+
+
+
slack_sdk.audit_logs.v1
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization …

+
+
+
+
+
+
+
+
+

Classes

+
+
+class AuditLogsClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/audit/v1/',
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AuditLogsClient:
+    BASE_URL = "https://api.slack.com/audit/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for Audit Logs API
+        See https://docs.slack.dev/admins/audit-logs-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    def schemas(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of objects which the Audit Logs API
+        returns as a list of all objects and a short description.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+        Returns:
+            API response
+        """
+        return self.api_call(
+            path="schemas",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def actions(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of actions that the Audit Logs API
+        returns as a list of all actions and a short description of each.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        return self.api_call(
+            path="actions",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def logs(
+        self,
+        *,
+        latest: Optional[int] = None,
+        oldest: Optional[int] = None,
+        limit: Optional[int] = None,
+        action: Optional[str] = None,
+        actor: Optional[str] = None,
+        entity: Optional[str] = None,
+        cursor: Optional[str] = None,
+        additional_query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """This is the primary endpoint for retrieving actual audit events from your organization.
+        It will return a list of actions that have occurred on the installed workspace or grid organization.
+        Authentication required.
+
+        The following filters can be applied in order to narrow the range of actions returned.
+        Filters are added as query string parameters and can be combined together.
+        Multiple filter parameters are additive (a boolean AND) and are separated
+        with an ampersand (&) in the query string. Filtering is entirely optional.
+
+        Args:
+            latest: Unix timestamp of the most recent audit event to include (inclusive).
+            oldest: Unix timestamp of the least recent audit event to include (inclusive).
+                Data is not available prior to March 2018.
+            limit: Number of results to optimistically return, maximum 9999.
+            action: Name of the action.
+            actor: User ID who initiated the action.
+            entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+            cursor: The next page cursor of pagination
+            additional_query_params: Add anything else if you need to use the ones this library does not support
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        query_params = {
+            "latest": latest,
+            "oldest": oldest,
+            "limit": limit,
+            "action": action,
+            "actor": actor,
+            "entity": entity,
+            "cursor": cursor,
+        }
+        if additional_query_params is not None:
+            query_params.update(additional_query_params)
+        query_params = {k: v for k, v in query_params.items() if v is not None}
+        return self.api_call(
+            path="logs",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def api_call(
+        self,
+        *,
+        http_verb: str = "GET",
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Performs a Slack API request and returns the result."""
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+
+        return self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    def _perform_http_request(
+        self,
+        *,
+        http_verb: str = "GET",
+        url: str,
+        body: Optional[Dict[str, Any]] = None,
+        headers: Dict[str, str],
+    ) -> AuditLogsResponse:
+        if body is not None:
+            body = json.dumps(body)  # type: ignore[assignment]
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()}
+            self.logger.debug(f"Sending a request - url: {url}, body: {body}, headers: {headers_for_logging}")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(
+            method=http_verb,
+            url=url,
+            data=body.encode("utf-8") if body is not None else None,  # type: ignore[attr-defined]
+            headers=headers,
+        )
+        resp = None
+        last_error = None
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = AuditLogsResponse(
+                    url=url,
+                    status_code=e.code,
+                    raw_body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error  # type: ignore[misc]
+
+    def _perform_http_request_internal(self, url: str, req: Request) -> AuditLogsResponse:
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        http_resp: HTTPResponse
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = AuditLogsResponse(
+            url=url,
+            status_code=http_resp.status,
+            raw_body=response_body,
+            headers=http_resp.headers,  # type: ignore[arg-type]
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for Audit Logs API +See https://docs.slack.dev/admins/audit-logs-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def actions(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def actions(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of actions that the Audit Logs API
+    returns as a list of all actions and a short description of each.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    return self.api_call(
+        path="actions",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of actions that the Audit Logs API +returns as a list of all actions and a short description of each. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+def api_call(self,
*,
http_verb:Β strΒ =Β 'GET',
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    *,
+    http_verb: str = "GET",
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Performs a Slack API request and returns the result."""
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+
+    return self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+

Performs a Slack API request and returns the result.

+
+
+def logs(self,
*,
latest:Β intΒ |Β NoneΒ =Β None,
oldest:Β intΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
actor:Β strΒ |Β NoneΒ =Β None,
entity:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
additional_query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def logs(
+    self,
+    *,
+    latest: Optional[int] = None,
+    oldest: Optional[int] = None,
+    limit: Optional[int] = None,
+    action: Optional[str] = None,
+    actor: Optional[str] = None,
+    entity: Optional[str] = None,
+    cursor: Optional[str] = None,
+    additional_query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """This is the primary endpoint for retrieving actual audit events from your organization.
+    It will return a list of actions that have occurred on the installed workspace or grid organization.
+    Authentication required.
+
+    The following filters can be applied in order to narrow the range of actions returned.
+    Filters are added as query string parameters and can be combined together.
+    Multiple filter parameters are additive (a boolean AND) and are separated
+    with an ampersand (&) in the query string. Filtering is entirely optional.
+
+    Args:
+        latest: Unix timestamp of the most recent audit event to include (inclusive).
+        oldest: Unix timestamp of the least recent audit event to include (inclusive).
+            Data is not available prior to March 2018.
+        limit: Number of results to optimistically return, maximum 9999.
+        action: Name of the action.
+        actor: User ID who initiated the action.
+        entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+        cursor: The next page cursor of pagination
+        additional_query_params: Add anything else if you need to use the ones this library does not support
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    query_params = {
+        "latest": latest,
+        "oldest": oldest,
+        "limit": limit,
+        "action": action,
+        "actor": actor,
+        "entity": entity,
+        "cursor": cursor,
+    }
+    if additional_query_params is not None:
+        query_params.update(additional_query_params)
+    query_params = {k: v for k, v in query_params.items() if v is not None}
+    return self.api_call(
+        path="logs",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

This is the primary endpoint for retrieving actual audit events from your organization. +It will return a list of actions that have occurred on the installed workspace or grid organization. +Authentication required.

+

The following filters can be applied in order to narrow the range of actions returned. +Filters are added as query string parameters and can be combined together. +Multiple filter parameters are additive (a boolean AND) and are separated +with an ampersand (&) in the query string. Filtering is entirely optional.

+

Args

+
+
latest
+
Unix timestamp of the most recent audit event to include (inclusive).
+
oldest
+
Unix timestamp of the least recent audit event to include (inclusive). +Data is not available prior to March 2018.
+
limit
+
Number of results to optimistically return, maximum 9999.
+
action
+
Name of the action.
+
actor
+
User ID who initiated the action.
+
entity
+
ID of the target entity of the action (such as a channel, workspace, organization, file).
+
cursor
+
The next page cursor of pagination
+
additional_query_params
+
Add anything else if you need to use the ones this library does not support
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+def schemas(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def schemas(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of objects which the Audit Logs API
+    returns as a list of all objects and a short description.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+    Returns:
+        API response
+    """
+    return self.api_call(
+        path="schemas",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of objects which the Audit Logs API +returns as a list of all objects and a short description. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+
+
+class AuditLogsResponse +(*, url:Β str, status_code:Β int, raw_body:Β strΒ |Β None, headers:Β dict) +
+
+
+ +Expand source code + +
class AuditLogsResponse:
+    url: str
+    status_code: int
+    headers: Dict[str, Any]
+    raw_body: Optional[str]
+    body: Optional[Dict[str, Any]]
+    typed_body: Optional[LogsResponse]
+
+    @property  # type: ignore[no-redef]
+    def typed_body(self) -> Optional[LogsResponse]:
+        if self.body is None:
+            return None
+        return LogsResponse(**self.body)
+
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        raw_body: Optional[str],
+        headers: dict,
+    ):
+        self.url = url
+        self.status_code = status_code
+        self.headers = headers
+        self.raw_body = raw_body
+        self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None
+
+
+

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var raw_body :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop typed_body :Β LogsResponseΒ |Β None
+
+
+ +Expand source code + +
@property  # type: ignore[no-redef]
+def typed_body(self) -> Optional[LogsResponse]:
+    if self.body is None:
+        return None
+    return LogsResponse(**self.body)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/async_client.html b/docs/reference/audit_logs/v1/async_client.html new file mode 100644 index 000000000..e3f01fafc --- /dev/null +++ b/docs/reference/audit_logs/v1/async_client.html @@ -0,0 +1,738 @@ + + + + + + +slack_sdk.audit_logs.v1.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1.async_client

+
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncAuditLogsClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/audit/v1/',
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
auth:Β aiohttp.helpers.BasicAuthΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncAuditLogsClient:
+    BASE_URL = "https://api.slack.com/audit/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    session: Optional[ClientSession]
+    trust_env_in_session: bool
+    auth: Optional[BasicAuth]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[AsyncRetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        session: Optional[ClientSession] = None,
+        trust_env_in_session: bool = False,
+        auth: Optional[BasicAuth] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        """API client for Audit Logs API
+        See https://docs.slack.dev/admins/audit-logs-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            session: `aiohttp.ClientSession` instance
+            trust_env_in_session: True/False for `aiohttp.ClientSession`
+            auth: Basic auth info for `aiohttp.ClientSession`
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.session = session
+        self.trust_env_in_session = trust_env_in_session
+        self.auth = auth
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    async def schemas(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of objects which the Audit Logs API
+        returns as a list of all objects and a short description.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+        Returns:
+            API response
+        """
+        return await self.api_call(
+            path="schemas",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def actions(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of actions that the Audit Logs API
+        returns as a list of all actions and a short description of each.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        return await self.api_call(
+            path="actions",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def logs(
+        self,
+        *,
+        latest: Optional[int] = None,
+        oldest: Optional[int] = None,
+        limit: Optional[int] = None,
+        action: Optional[str] = None,
+        actor: Optional[str] = None,
+        entity: Optional[str] = None,
+        cursor: Optional[str] = None,
+        additional_query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """This is the primary endpoint for retrieving actual audit events from your organization.
+        It will return a list of actions that have occurred on the installed workspace or grid organization.
+        Authentication required.
+
+        The following filters can be applied in order to narrow the range of actions returned.
+        Filters are added as query string parameters and can be combined together.
+        Multiple filter parameters are additive (a boolean AND) and are separated
+        with an ampersand (&) in the query string. Filtering is entirely optional.
+
+        Args:
+            latest: Unix timestamp of the most recent audit event to include (inclusive).
+            oldest: Unix timestamp of the least recent audit event to include (inclusive).
+                Data is not available prior to March 2018.
+            limit: Number of results to optimistically return, maximum 9999.
+            action: Name of the action.
+            actor: User ID who initiated the action.
+            entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+            cursor: The next page cursor of pagination
+            additional_query_params: Add anything else if you need to use the ones this library does not support
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        query_params = {
+            "latest": latest,
+            "oldest": oldest,
+            "limit": limit,
+            "action": action,
+            "actor": actor,
+            "entity": entity,
+            "cursor": cursor,
+        }
+        if additional_query_params is not None:
+            query_params.update(additional_query_params)
+        query_params = {k: v for k, v in query_params.items() if v is not None}
+        return await self.api_call(
+            path="logs",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    async def api_call(
+        self,
+        *,
+        http_verb: str = "GET",
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        url = f"{self.base_url}{path}"
+        return await self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            query_params=query_params,
+            body_params=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    async def _perform_http_request(
+        self,
+        *,
+        http_verb: str,
+        url: str,
+        query_params: Optional[Dict[str, Any]],
+        body_params: Optional[Dict[str, Any]],
+        headers: Dict[str, str],
+    ) -> AuditLogsResponse:
+        if body_params is not None:
+            body_params = json.dumps(body_params)  # type: ignore[assignment]
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        session: Optional[ClientSession] = None
+        use_running_session = self.session and not self.session.closed
+        if use_running_session:
+            session = self.session
+        else:
+            session = aiohttp.ClientSession(
+                timeout=aiohttp.ClientTimeout(total=self.timeout),
+                auth=self.auth,
+                trust_env=self.trust_env_in_session,
+            )
+
+        last_error = None
+        resp: Optional[AuditLogsResponse] = None
+        try:
+            request_kwargs = {
+                "headers": headers,
+                "params": query_params,
+                "data": body_params,
+                "ssl": self.ssl,
+                "proxy": self.proxy,
+            }
+            retry_request = RetryHttpRequest(
+                method=http_verb,
+                url=url,
+                headers=headers,  # type: ignore[arg-type]
+                body_params=body_params,
+            )
+
+            retry_state = RetryState()
+            counter_for_safety = 0
+            while counter_for_safety < 100:
+                counter_for_safety += 1
+                # If this is a retry, the next try started here. We can reset the flag.
+                retry_state.next_attempt_requested = False
+                retry_response: Optional[RetryHttpResponse] = None
+                response_body = ""
+
+                if self.logger.level <= logging.DEBUG:
+                    headers_for_logging = {
+                        k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()
+                    }
+                    self.logger.debug(
+                        f"Sending a request - "
+                        f"url: {url}, "
+                        f"params: {query_params}, "
+                        f"body: {body_params}, "
+                        f"headers: {headers_for_logging}"
+                    )
+
+                try:
+                    async with session.request(http_verb, url, **request_kwargs) as res:  # type: ignore[arg-type, union-attr] # noqa: E501
+                        try:
+                            response_body = await res.text()
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                                data=response_body.encode("utf-8") if response_body is not None else None,
+                            )
+                        except aiohttp.ContentTypeError:
+                            self.logger.debug(f"No response data returned from the following API call: {url}.")
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+                        except json.decoder.JSONDecodeError as e:
+                            message = f"Failed to parse the response body: {str(e)}"
+                            raise SlackApiError(message, res)
+
+                        if res.status == 429:
+                            for handler in self.retry_handlers:
+                                if await handler.can_retry_async(
+                                    state=retry_state,
+                                    request=retry_request,
+                                    response=retry_response,
+                                ):
+                                    if self.logger.level <= logging.DEBUG:
+                                        self.logger.info(
+                                            f"A retry handler found: {type(handler).__name__} "
+                                            f"for {http_verb} {url} - rate_limited"
+                                        )
+                                    await handler.prepare_for_next_attempt_async(
+                                        state=retry_state,
+                                        request=retry_request,
+                                        response=retry_response,
+                                    )
+                                    break
+
+                        if retry_state.next_attempt_requested is False:
+                            resp = AuditLogsResponse(
+                                url=url,
+                                status_code=res.status,
+                                raw_body=response_body,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+                            _debug_log_response(self.logger, resp)
+                            return resp
+
+                except Exception as e:
+                    last_error = e
+                    for handler in self.retry_handlers:
+                        if await handler.can_retry_async(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        ):
+                            if self.logger.level <= logging.DEBUG:
+                                self.logger.info(
+                                    f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}"
+                                )
+                            await handler.prepare_for_next_attempt_async(
+                                state=retry_state,
+                                request=retry_request,
+                                response=retry_response,
+                                error=e,
+                            )
+                            break
+
+                    if retry_state.next_attempt_requested is False:
+                        raise last_error
+
+            if resp is not None:
+                return resp
+            raise last_error  # type: ignore[misc]
+
+        finally:
+            if not use_running_session:
+                await session.close()  # type: ignore[union-attr]
+
+        return resp
+
+

API client for Audit Logs API +See https://docs.slack.dev/admins/audit-logs-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
session
+
aiohttp.ClientSession instance
+
trust_env_in_session
+
True/False for aiohttp.ClientSession
+
auth
+
Basic auth info for aiohttp.ClientSession
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var auth :Β aiohttp.helpers.BasicAuthΒ |Β None
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]
+
+

The type of the None singleton.

+
+
var session :Β aiohttp.client.ClientSessionΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
var trust_env_in_session :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def actions(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def actions(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of actions that the Audit Logs API
+    returns as a list of all actions and a short description of each.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    return await self.api_call(
+        path="actions",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of actions that the Audit Logs API +returns as a list of all actions and a short description of each. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+async def api_call(self,
*,
http_verb:Β strΒ =Β 'GET',
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def api_call(
+    self,
+    *,
+    http_verb: str = "GET",
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    url = f"{self.base_url}{path}"
+    return await self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        query_params=query_params,
+        body_params=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+
+
+
+async def logs(self,
*,
latest:Β intΒ |Β NoneΒ =Β None,
oldest:Β intΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
actor:Β strΒ |Β NoneΒ =Β None,
entity:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
additional_query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def logs(
+    self,
+    *,
+    latest: Optional[int] = None,
+    oldest: Optional[int] = None,
+    limit: Optional[int] = None,
+    action: Optional[str] = None,
+    actor: Optional[str] = None,
+    entity: Optional[str] = None,
+    cursor: Optional[str] = None,
+    additional_query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """This is the primary endpoint for retrieving actual audit events from your organization.
+    It will return a list of actions that have occurred on the installed workspace or grid organization.
+    Authentication required.
+
+    The following filters can be applied in order to narrow the range of actions returned.
+    Filters are added as query string parameters and can be combined together.
+    Multiple filter parameters are additive (a boolean AND) and are separated
+    with an ampersand (&) in the query string. Filtering is entirely optional.
+
+    Args:
+        latest: Unix timestamp of the most recent audit event to include (inclusive).
+        oldest: Unix timestamp of the least recent audit event to include (inclusive).
+            Data is not available prior to March 2018.
+        limit: Number of results to optimistically return, maximum 9999.
+        action: Name of the action.
+        actor: User ID who initiated the action.
+        entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+        cursor: The next page cursor of pagination
+        additional_query_params: Add anything else if you need to use the ones this library does not support
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    query_params = {
+        "latest": latest,
+        "oldest": oldest,
+        "limit": limit,
+        "action": action,
+        "actor": actor,
+        "entity": entity,
+        "cursor": cursor,
+    }
+    if additional_query_params is not None:
+        query_params.update(additional_query_params)
+    query_params = {k: v for k, v in query_params.items() if v is not None}
+    return await self.api_call(
+        path="logs",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

This is the primary endpoint for retrieving actual audit events from your organization. +It will return a list of actions that have occurred on the installed workspace or grid organization. +Authentication required.

+

The following filters can be applied in order to narrow the range of actions returned. +Filters are added as query string parameters and can be combined together. +Multiple filter parameters are additive (a boolean AND) and are separated +with an ampersand (&) in the query string. Filtering is entirely optional.

+

Args

+
+
latest
+
Unix timestamp of the most recent audit event to include (inclusive).
+
oldest
+
Unix timestamp of the least recent audit event to include (inclusive). +Data is not available prior to March 2018.
+
limit
+
Number of results to optimistically return, maximum 9999.
+
action
+
Name of the action.
+
actor
+
User ID who initiated the action.
+
entity
+
ID of the target entity of the action (such as a channel, workspace, organization, file).
+
cursor
+
The next page cursor of pagination
+
additional_query_params
+
Add anything else if you need to use the ones this library does not support
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+async def schemas(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
async def schemas(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of objects which the Audit Logs API
+    returns as a list of all objects and a short description.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+    Returns:
+        API response
+    """
+    return await self.api_call(
+        path="schemas",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of objects which the Audit Logs API +returns as a list of all objects and a short description. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/client.html b/docs/reference/audit_logs/v1/client.html new file mode 100644 index 000000000..fb3939178 --- /dev/null +++ b/docs/reference/audit_logs/v1/client.html @@ -0,0 +1,721 @@ + + + + + + +slack_sdk.audit_logs.v1.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1.client

+
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class AuditLogsClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/audit/v1/',
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AuditLogsClient:
+    BASE_URL = "https://api.slack.com/audit/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for Audit Logs API
+        See https://docs.slack.dev/admins/audit-logs-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    def schemas(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of objects which the Audit Logs API
+        returns as a list of all objects and a short description.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+        Returns:
+            API response
+        """
+        return self.api_call(
+            path="schemas",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def actions(
+        self,
+        *,
+        query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Returns information about the kind of actions that the Audit Logs API
+        returns as a list of all actions and a short description of each.
+        Authentication not required.
+
+        Args:
+            query_params: Set any values if you want to add query params
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        return self.api_call(
+            path="actions",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def logs(
+        self,
+        *,
+        latest: Optional[int] = None,
+        oldest: Optional[int] = None,
+        limit: Optional[int] = None,
+        action: Optional[str] = None,
+        actor: Optional[str] = None,
+        entity: Optional[str] = None,
+        cursor: Optional[str] = None,
+        additional_query_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """This is the primary endpoint for retrieving actual audit events from your organization.
+        It will return a list of actions that have occurred on the installed workspace or grid organization.
+        Authentication required.
+
+        The following filters can be applied in order to narrow the range of actions returned.
+        Filters are added as query string parameters and can be combined together.
+        Multiple filter parameters are additive (a boolean AND) and are separated
+        with an ampersand (&) in the query string. Filtering is entirely optional.
+
+        Args:
+            latest: Unix timestamp of the most recent audit event to include (inclusive).
+            oldest: Unix timestamp of the least recent audit event to include (inclusive).
+                Data is not available prior to March 2018.
+            limit: Number of results to optimistically return, maximum 9999.
+            action: Name of the action.
+            actor: User ID who initiated the action.
+            entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+            cursor: The next page cursor of pagination
+            additional_query_params: Add anything else if you need to use the ones this library does not support
+            headers: Additional request headers
+
+        Returns:
+            API response
+        """
+        query_params = {
+            "latest": latest,
+            "oldest": oldest,
+            "limit": limit,
+            "action": action,
+            "actor": actor,
+            "entity": entity,
+            "cursor": cursor,
+        }
+        if additional_query_params is not None:
+            query_params.update(additional_query_params)
+        query_params = {k: v for k, v in query_params.items() if v is not None}
+        return self.api_call(
+            path="logs",
+            query_params=query_params,
+            headers=headers,
+        )
+
+    def api_call(
+        self,
+        *,
+        http_verb: str = "GET",
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> AuditLogsResponse:
+        """Performs a Slack API request and returns the result."""
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+
+        return self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    def _perform_http_request(
+        self,
+        *,
+        http_verb: str = "GET",
+        url: str,
+        body: Optional[Dict[str, Any]] = None,
+        headers: Dict[str, str],
+    ) -> AuditLogsResponse:
+        if body is not None:
+            body = json.dumps(body)  # type: ignore[assignment]
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()}
+            self.logger.debug(f"Sending a request - url: {url}, body: {body}, headers: {headers_for_logging}")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(
+            method=http_verb,
+            url=url,
+            data=body.encode("utf-8") if body is not None else None,  # type: ignore[attr-defined]
+            headers=headers,
+        )
+        resp = None
+        last_error = None
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = AuditLogsResponse(
+                    url=url,
+                    status_code=e.code,
+                    raw_body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error  # type: ignore[misc]
+
+    def _perform_http_request_internal(self, url: str, req: Request) -> AuditLogsResponse:
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        http_resp: HTTPResponse
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = AuditLogsResponse(
+            url=url,
+            status_code=http_resp.status,
+            raw_body=response_body,
+            headers=http_resp.headers,  # type: ignore[arg-type]
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for Audit Logs API +See https://docs.slack.dev/admins/audit-logs-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def actions(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def actions(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of actions that the Audit Logs API
+    returns as a list of all actions and a short description of each.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    return self.api_call(
+        path="actions",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of actions that the Audit Logs API +returns as a list of all actions and a short description of each. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+def api_call(self,
*,
http_verb:Β strΒ =Β 'GET',
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    *,
+    http_verb: str = "GET",
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Performs a Slack API request and returns the result."""
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+
+    return self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+

Performs a Slack API request and returns the result.

+
+
+def logs(self,
*,
latest:Β intΒ |Β NoneΒ =Β None,
oldest:Β intΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
actor:Β strΒ |Β NoneΒ =Β None,
entity:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
additional_query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def logs(
+    self,
+    *,
+    latest: Optional[int] = None,
+    oldest: Optional[int] = None,
+    limit: Optional[int] = None,
+    action: Optional[str] = None,
+    actor: Optional[str] = None,
+    entity: Optional[str] = None,
+    cursor: Optional[str] = None,
+    additional_query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """This is the primary endpoint for retrieving actual audit events from your organization.
+    It will return a list of actions that have occurred on the installed workspace or grid organization.
+    Authentication required.
+
+    The following filters can be applied in order to narrow the range of actions returned.
+    Filters are added as query string parameters and can be combined together.
+    Multiple filter parameters are additive (a boolean AND) and are separated
+    with an ampersand (&) in the query string. Filtering is entirely optional.
+
+    Args:
+        latest: Unix timestamp of the most recent audit event to include (inclusive).
+        oldest: Unix timestamp of the least recent audit event to include (inclusive).
+            Data is not available prior to March 2018.
+        limit: Number of results to optimistically return, maximum 9999.
+        action: Name of the action.
+        actor: User ID who initiated the action.
+        entity: ID of the target entity of the action (such as a channel, workspace, organization, file).
+        cursor: The next page cursor of pagination
+        additional_query_params: Add anything else if you need to use the ones this library does not support
+        headers: Additional request headers
+
+    Returns:
+        API response
+    """
+    query_params = {
+        "latest": latest,
+        "oldest": oldest,
+        "limit": limit,
+        "action": action,
+        "actor": actor,
+        "entity": entity,
+        "cursor": cursor,
+    }
+    if additional_query_params is not None:
+        query_params.update(additional_query_params)
+    query_params = {k: v for k, v in query_params.items() if v is not None}
+    return self.api_call(
+        path="logs",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

This is the primary endpoint for retrieving actual audit events from your organization. +It will return a list of actions that have occurred on the installed workspace or grid organization. +Authentication required.

+

The following filters can be applied in order to narrow the range of actions returned. +Filters are added as query string parameters and can be combined together. +Multiple filter parameters are additive (a boolean AND) and are separated +with an ampersand (&) in the query string. Filtering is entirely optional.

+

Args

+
+
latest
+
Unix timestamp of the most recent audit event to include (inclusive).
+
oldest
+
Unix timestamp of the least recent audit event to include (inclusive). +Data is not available prior to March 2018.
+
limit
+
Number of results to optimistically return, maximum 9999.
+
action
+
Name of the action.
+
actor
+
User ID who initiated the action.
+
entity
+
ID of the target entity of the action (such as a channel, workspace, organization, file).
+
cursor
+
The next page cursor of pagination
+
additional_query_params
+
Add anything else if you need to use the ones this library does not support
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+def schemas(self,
*,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β AuditLogsResponse
+
+
+
+ +Expand source code + +
def schemas(
+    self,
+    *,
+    query_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> AuditLogsResponse:
+    """Returns information about the kind of objects which the Audit Logs API
+    returns as a list of all objects and a short description.
+    Authentication not required.
+
+    Args:
+        query_params: Set any values if you want to add query params
+        headers: Additional request headers
+    Returns:
+        API response
+    """
+    return self.api_call(
+        path="schemas",
+        query_params=query_params,
+        headers=headers,
+    )
+
+

Returns information about the kind of objects which the Audit Logs API +returns as a list of all objects and a short description. +Authentication not required.

+

Args

+
+
query_params
+
Set any values if you want to add query params
+
headers
+
Additional request headers
+
+

Returns

+

API response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/index.html b/docs/reference/audit_logs/v1/index.html new file mode 100644 index 000000000..7c3def12a --- /dev/null +++ b/docs/reference/audit_logs/v1/index.html @@ -0,0 +1,100 @@ + + + + + + +slack_sdk.audit_logs.v1 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1

+
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details.

+
+
+

Sub-modules

+
+
slack_sdk.audit_logs.v1.async_client
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization …

+
+
slack_sdk.audit_logs.v1.client
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization …

+
+
slack_sdk.audit_logs.v1.internal_utils
+
+
+
+
slack_sdk.audit_logs.v1.logs
+
+
+
+
slack_sdk.audit_logs.v1.response
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/internal_utils.html b/docs/reference/audit_logs/v1/internal_utils.html new file mode 100644 index 000000000..38dd60513 --- /dev/null +++ b/docs/reference/audit_logs/v1/internal_utils.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.audit_logs.v1.internal_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1.internal_utils

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/logs.html b/docs/reference/audit_logs/v1/logs.html new file mode 100644 index 000000000..a36d22e5a --- /dev/null +++ b/docs/reference/audit_logs/v1/logs.html @@ -0,0 +1,3388 @@ + + + + + + +slack_sdk.audit_logs.v1.logs API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1.logs

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AAARequest +(*, id:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class AAARequest:
+    id: Optional[str]
+    team_id: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.team_id = team_id
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARule +(*,
id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
action:Β Dict[str,Β Any]Β |Β AAARuleActionΒ |Β NoneΒ =Β None,
condition:Β Dict[str,Β Any]Β |Β AAARuleConditionΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class AAARule:
+    id: Optional[str]
+    team_id: Optional[str]
+    title: Optional[str]
+    action: Optional[AAARuleAction]
+    condition: Optional[AAARuleCondition]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        title: Optional[str] = None,
+        action: Optional[Union[Dict[str, Any], AAARuleAction]] = None,
+        condition: Optional[Union[Dict[str, Any], AAARuleCondition]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.team_id = team_id
+        self.title = title
+        self.action = action if action is None or isinstance(action, AAARuleAction) else AAARuleAction(**action)
+        self.condition = (
+            condition if condition is None or isinstance(condition, AAARuleCondition) else AAARuleCondition(**condition)
+        )
+
+
+

Class variables

+
+
var action :Β AAARuleActionΒ |Β None
+
+

The type of the None singleton.

+
+
var condition :Β AAARuleConditionΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var title :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARuleAction +(*,
resolution:Β Dict[str,Β Any]Β |Β AAARuleActionResolutionΒ |Β NoneΒ =Β None,
notify:Β List[Dict[str,Β Any]Β |Β AAARuleActionNotify]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class AAARuleAction:
+    resolution: Optional[AAARuleActionResolution]
+    notify: Optional[List[AAARuleActionNotify]]
+
+    def __init__(
+        self,
+        *,
+        resolution: Optional[Union[Dict[str, Any], AAARuleActionResolution]] = None,
+        notify: Optional[List[Union[Dict[str, Any], AAARuleActionNotify]]] = None,
+        **kwargs,
+    ) -> None:
+        self.resolution = (
+            resolution
+            if resolution is None or isinstance(resolution, AAARuleActionResolution)
+            else AAARuleActionResolution(**resolution)
+        )
+        self.notify = None
+        if notify is not None:
+            self.notify = []
+            for a in notify:
+                if isinstance(a, dict):
+                    self.notify.append(AAARuleActionNotify(**a))
+                else:
+                    self.notify.append(a)
+
+
+

Class variables

+
+
var notify :Β List[AAARuleActionNotify]Β |Β None
+
+

The type of the None singleton.

+
+
var resolution :Β AAARuleActionResolutionΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARuleActionNotify +(*, entity_type:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class AAARuleActionNotify:
+    entity_type: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        entity_type: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.entity_type = entity_type
+
+
+

Class variables

+
+
var entity_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARuleActionResolution +(*, value:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class AAARuleActionResolution:
+    value: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        value: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.value = value
+
+
+

Class variables

+
+
var value :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARuleCondition +(*,
datatype:Β strΒ |Β NoneΒ =Β None,
operator:Β strΒ |Β NoneΒ =Β None,
values:Β List[Dict[str,Β Any]Β |Β AAARuleConditionValue]Β |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class AAARuleCondition:
+    datatype: Optional[str]
+    operator: Optional[str]
+    values: Optional[List[AAARuleConditionValue]]
+    entity_type: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        datatype: Optional[str] = None,
+        operator: Optional[str] = None,
+        values: Optional[List[Union[Dict[str, Any], AAARuleConditionValue]]] = None,
+        entity_type: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.datatype = datatype
+        self.operator = operator
+        self.values = None
+        if values is not None:
+            self.values = []
+            for a in values:
+                if isinstance(a, dict):
+                    self.values.append(AAARuleConditionValue(**a))
+                else:
+                    self.values.append(a)
+        self.entity_type = entity_type
+
+
+

Class variables

+
+
var datatype :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var entity_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var operator :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var values :Β List[AAARuleConditionValue]Β |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AAARuleConditionValue +(*,
field:Β strΒ |Β NoneΒ =Β None,
values:Β List[str]Β |Β NoneΒ =Β None,
datatype:Β strΒ |Β NoneΒ =Β None,
operator:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class AAARuleConditionValue:
+    field: Optional[str]
+    values: Optional[List[str]]
+    datatype: Optional[str]
+    operator: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        field: Optional[str] = None,
+        values: Optional[List[str]] = None,
+        datatype: Optional[str] = None,
+        operator: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.field = field
+        self.values = values
+        self.datatype = datatype
+        self.operator = operator
+
+
+

Class variables

+
+
var datatype :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var field :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var operator :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var values :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AccountTypeRole +(*, id:Β strΒ |Β NoneΒ =Β None, name:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class AccountTypeRole:
+    id: Optional[str]
+    name: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Actor +(type:Β strΒ |Β NoneΒ =Β None,
user:Β UserΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Actor:
+    type: Optional[str]
+    user: Optional[User]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        type: Optional[str] = None,
+        user: Optional[Union[User, Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.user = User(**user) if isinstance(user, dict) else user
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var user :Β UserΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class App +(*,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
is_distributed:Β boolΒ |Β NoneΒ =Β None,
is_directory_approved:Β boolΒ |Β NoneΒ =Β None,
is_workflow_app:Β boolΒ |Β NoneΒ =Β None,
scopes:Β List[str]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class App:
+    id: Optional[str]
+    name: Optional[str]
+    is_distributed: Optional[bool]
+    is_directory_approved: Optional[bool]
+    is_workflow_app: Optional[bool]
+    scopes: Optional[List[str]]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        is_distributed: Optional[bool] = None,
+        is_directory_approved: Optional[bool] = None,
+        is_workflow_app: Optional[bool] = None,
+        scopes: Optional[List[str]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.is_distributed = is_distributed
+        self.is_directory_approved = is_directory_approved
+        self.is_workflow_app = is_workflow_app
+        self.scopes = scopes
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var is_directory_approved :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_distributed :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_workflow_app :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Attribute +(*,
name:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
items:Β AttributeItemsΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Attribute:
+    name: Optional[str]
+    type: Optional[str]
+    items: Optional[AttributeItems]
+
+    def __init__(
+        self,
+        *,
+        name: Optional[str] = None,
+        type: Optional[str] = None,
+        items: Optional[AttributeItems] = None,
+        **kwargs,
+    ) -> None:
+        self.name = name
+        self.type = type
+        self.items = items
+
+
+

Class variables

+
+
var items :Β AttributeItemsΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class AttributeItems +(*, type:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class AttributeItems:
+    type: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+
+
+

Class variables

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class Channel +(*,
id:Β strΒ |Β NoneΒ =Β None,
privacy:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
is_shared:Β boolΒ |Β NoneΒ =Β None,
is_org_shared:Β boolΒ |Β NoneΒ =Β None,
teams_shared_with:Β List[str]Β |Β NoneΒ =Β None,
original_connected_channel_id:Β strΒ |Β NoneΒ =Β None,
is_salesforce_channel:Β boolΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Channel:
+    id: Optional[str]
+    privacy: Optional[str]
+    name: Optional[str]
+    is_shared: Optional[bool]
+    is_org_shared: Optional[bool]
+    teams_shared_with: Optional[List[str]]
+    original_connected_channel_id: Optional[str]
+    is_salesforce_channel: Optional[bool]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        privacy: Optional[str] = None,
+        name: Optional[str] = None,
+        is_shared: Optional[bool] = None,
+        is_org_shared: Optional[bool] = None,
+        teams_shared_with: Optional[List[str]] = None,
+        original_connected_channel_id: Optional[str] = None,
+        is_salesforce_channel: Optional[bool] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.privacy = privacy
+        self.name = name
+        self.is_shared = is_shared
+        self.is_org_shared = is_org_shared
+        self.teams_shared_with = teams_shared_with
+        self.original_connected_channel_id = original_connected_channel_id
+        self.is_salesforce_channel = is_salesforce_channel
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var is_org_shared :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_salesforce_channel :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_shared :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var original_connected_channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var privacy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var teams_shared_with :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Context +(*,
location:Β LocationΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
ua:Β strΒ |Β NoneΒ =Β None,
ip_address:Β strΒ |Β NoneΒ =Β None,
session_id:Β strΒ |Β NoneΒ =Β None,
app:Β AppΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Context:
+    location: Optional[Location]
+    ua: Optional[str]
+    ip_address: Optional[str]
+    session_id: Optional[str]
+    app: Optional[App]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        location: Optional[Union[Location, Dict[str, Any]]] = None,
+        ua: Optional[str] = None,
+        ip_address: Optional[str] = None,
+        session_id: Optional[str] = None,
+        app: Optional[Union[App, Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> None:
+        self.location = Location(**location) if isinstance(location, dict) else location
+        self.ua = ua
+        self.ip_address = ip_address
+        self.session_id = session_id
+        self.app = App(**app) if isinstance(app, dict) else app
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var app :Β AppΒ |Β None
+
+

The type of the None singleton.

+
+
var ip_address :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var location :Β LocationΒ |Β None
+
+

The type of the None singleton.

+
+
var session_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var ua :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class ConversationPref +(*, type:Β List[str]Β |Β NoneΒ =Β None, user:Β List[str]Β |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class ConversationPref:
+    type: Optional[List[str]]
+    user: Optional[List[str]]
+
+    def __init__(
+        self,
+        *,
+        type: Optional[List[str]] = None,
+        user: Optional[List[str]] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.user = user
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var type :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var user :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
+
+
+class Details +(*,
name:Β strΒ |Β NoneΒ =Β None,
new_value:Β strΒ |Β List[str]Β |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
previous_value:Β strΒ |Β List[str]Β |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
expires_on:Β intΒ |Β NoneΒ =Β None,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
non_sso_only:Β boolΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
is_workflow:Β boolΒ |Β NoneΒ =Β None,
inviter:Β UserΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
kicker:Β UserΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
shared_to:Β strΒ |Β NoneΒ =Β None,
reason:Β strΒ |Β NoneΒ =Β None,
origin_team:Β strΒ |Β NoneΒ =Β None,
target_team:Β strΒ |Β NoneΒ =Β None,
is_internal_integration:Β boolΒ |Β NoneΒ =Β None,
cleared_resolution:Β strΒ |Β NoneΒ =Β None,
app_owner_id:Β strΒ |Β NoneΒ =Β None,
bot_scopes:Β List[str]Β |Β NoneΒ =Β None,
new_scopes:Β List[str]Β |Β NoneΒ =Β None,
previous_scopes:Β List[str]Β |Β NoneΒ =Β None,
granular_bot_token:Β boolΒ |Β NoneΒ =Β None,
scopes:Β List[str]Β |Β NoneΒ =Β None,
scopes_bot:Β List[str]Β |Β NoneΒ =Β None,
resolution:Β strΒ |Β NoneΒ =Β None,
app_previously_resolved:Β boolΒ |Β NoneΒ =Β None,
admin_app_id:Β strΒ |Β NoneΒ =Β None,
bot_id:Β strΒ |Β NoneΒ =Β None,
installer_user_id:Β strΒ |Β NoneΒ =Β None,
approver_id:Β strΒ |Β NoneΒ =Β None,
approval_type:Β strΒ |Β NoneΒ =Β None,
app_previously_approved:Β boolΒ |Β NoneΒ =Β None,
old_scopes:Β List[str]Β |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
permissions:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
new_version_id:Β strΒ |Β NoneΒ =Β None,
trigger:Β strΒ |Β NoneΒ =Β None,
export_type:Β strΒ |Β NoneΒ =Β None,
export_start_ts:Β strΒ |Β NoneΒ =Β None,
export_end_ts:Β strΒ |Β NoneΒ =Β None,
barrier_id:Β strΒ |Β NoneΒ =Β None,
primary_usergroup_id:Β strΒ |Β NoneΒ =Β None,
barriered_from_usergroup_ids:Β List[str]Β |Β NoneΒ =Β None,
restricted_subjects:Β List[str]Β |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
external_organization_id:Β strΒ |Β NoneΒ =Β None,
external_organization_name:Β strΒ |Β NoneΒ =Β None,
external_user_id:Β strΒ |Β NoneΒ =Β None,
external_user_email:Β strΒ |Β NoneΒ =Β None,
channel_id:Β strΒ |Β NoneΒ =Β None,
added_team_id:Β strΒ |Β NoneΒ =Β None,
is_token_rotation_enabled_app:Β boolΒ |Β NoneΒ =Β None,
old_retention_policy:Β Dict[str,Β Any]Β |Β RetentionPolicyΒ |Β NoneΒ =Β None,
new_retention_policy:Β Dict[str,Β Any]Β |Β RetentionPolicyΒ |Β NoneΒ =Β None,
who_can_post:Β Dict[str,Β List[str]]Β |Β ConversationPrefΒ |Β NoneΒ =Β None,
can_thread:Β Dict[str,Β List[str]]Β |Β ConversationPrefΒ |Β NoneΒ =Β None,
is_external_limited:Β boolΒ |Β NoneΒ =Β None,
exporting_team_id:Β intΒ |Β NoneΒ =Β None,
session_search_start:Β intΒ |Β NoneΒ =Β None,
deprecation_search_end:Β intΒ |Β NoneΒ =Β None,
is_error:Β boolΒ |Β NoneΒ =Β None,
creator:Β strΒ |Β NoneΒ =Β None,
team:Β strΒ |Β NoneΒ =Β None,
app_id:Β strΒ |Β NoneΒ =Β None,
enable_at_here:Β Dict[str,Β Any]Β |Β FeatureEnablementΒ |Β NoneΒ =Β None,
enable_at_channel:Β Dict[str,Β Any]Β |Β FeatureEnablementΒ |Β NoneΒ =Β None,
can_huddle:Β Dict[str,Β Any]Β |Β FeatureEnablementΒ |Β NoneΒ =Β None,
url_private:Β strΒ |Β NoneΒ =Β None,
shared_with:Β Dict[str,Β Any]Β |Β SharedWithΒ |Β NoneΒ =Β None,
initiated_by:Β strΒ |Β NoneΒ =Β None,
source_team:Β strΒ |Β NoneΒ =Β None,
destination_team:Β strΒ |Β NoneΒ =Β None,
succeeded_users:Β List[str]Β |Β strΒ |Β NoneΒ =Β None,
failed_users:Β List[str]Β |Β strΒ |Β NoneΒ =Β None,
enterprise:Β strΒ |Β NoneΒ =Β None,
subteam:Β strΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
idp_group_member_count:Β intΒ |Β NoneΒ =Β None,
workspace_member_count:Β intΒ |Β NoneΒ =Β None,
added_user_count:Β intΒ |Β NoneΒ =Β None,
added_user_error_count:Β intΒ |Β NoneΒ =Β None,
reactivated_user_count:Β intΒ |Β NoneΒ =Β None,
removed_user_count:Β intΒ |Β NoneΒ =Β None,
removed_user_error_count:Β intΒ |Β NoneΒ =Β None,
total_removal_count:Β intΒ |Β NoneΒ =Β None,
is_flagged:Β strΒ |Β NoneΒ =Β None,
target_user:Β strΒ |Β NoneΒ =Β None,
idp_config_id:Β strΒ |Β NoneΒ =Β None,
config_type:Β strΒ |Β NoneΒ =Β None,
idp_entity_id_hash:Β strΒ |Β NoneΒ =Β None,
label:Β strΒ |Β NoneΒ =Β None,
previous_profile:Β Dict[str,Β Any]Β |Β ProfileΒ |Β NoneΒ =Β None,
new_profile:Β Dict[str,Β Any]Β |Β ProfileΒ |Β NoneΒ =Β None,
target_user_id:Β strΒ |Β NoneΒ =Β None,
space_file_id:Β Dict[str,Β Any]Β |Β SpaceFileIdΒ |Β NoneΒ =Β None,
target_entity:Β strΒ |Β NoneΒ =Β None,
target_entity_id:Β strΒ |Β NoneΒ =Β None,
changed_permissions:Β List[str]Β |Β NoneΒ =Β None,
datastore_name:Β strΒ |Β NoneΒ =Β None,
attributes:Β List[Dict[str,Β str]Β |Β Attribute]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
actor:Β strΒ |Β NoneΒ =Β None,
access_level:Β strΒ |Β NoneΒ =Β None,
functions:Β List[str]Β |Β NoneΒ =Β None,
workflows:Β List[str]Β |Β NoneΒ =Β None,
datastores:Β List[str]Β |Β NoneΒ =Β None,
permissions_updated:Β boolΒ |Β NoneΒ =Β None,
matched_rule:Β Dict[str,Β Any]Β |Β AAARuleΒ |Β NoneΒ =Β None,
request:Β Dict[str,Β Any]Β |Β AAARequestΒ |Β NoneΒ =Β None,
rules_checked:Β List[Dict[str,Β Any]Β |Β AAARule]Β |Β NoneΒ =Β None,
disconnecting_team:Β strΒ |Β NoneΒ =Β None,
is_channel_canvas:Β boolΒ |Β NoneΒ =Β None,
linked_channel_id:Β strΒ |Β NoneΒ =Β None,
column_id:Β strΒ |Β NoneΒ =Β None,
row_id:Β strΒ |Β NoneΒ =Β None,
cell_date_updated:Β intΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Details:
+    name: Optional[str]
+    new_value: Optional[Union[str, List[str], Dict[str, Any]]]
+    previous_value: Optional[Union[str, List[str], Dict[str, Any]]]
+    expires_on: Optional[int]
+    mobile_only: Optional[bool]
+    web_only: Optional[bool]
+    non_sso_only: Optional[bool]
+    type: Optional[str]
+    is_workflow: Optional[bool]
+    inviter: Optional[User]
+    kicker: Optional[User]
+    shared_to: Optional[str]
+    reason: Optional[str]
+    origin_team: Optional[str]
+    target_team: Optional[str]
+    is_internal_integration: Optional[bool]
+    cleared_resolution: Optional[str]
+    app_owner_id: Optional[str]
+    bot_scopes: Optional[List[str]]
+    new_scopes: Optional[List[str]]
+    previous_scopes: Optional[List[str]]
+    granular_bot_token: Optional[bool]
+    scopes: Optional[List[str]]
+    scopes_bot: Optional[List[str]]
+    resolution: Optional[str]
+    app_previously_resolved: Optional[bool]
+    admin_app_id: Optional[str]
+    bot_id: Optional[str]
+    installer_user_id: Optional[str]
+    approver_id: Optional[str]
+    approval_type: Optional[str]
+    app_previously_approved: Optional[bool]
+    old_scopes: Optional[List[str]]
+    channels: Optional[List[str]]
+    permissions: Optional[List[Dict[str, Any]]]
+    new_version_id: Optional[str]
+    trigger: Optional[str]
+    export_type: Optional[str]
+    export_start_ts: Optional[str]
+    export_end_ts: Optional[str]
+    barrier_id: Optional[str]
+    primary_usergroup_id: Optional[str]
+    barriered_from_usergroup_ids: Optional[List[str]]
+    restricted_subjects: Optional[List[str]]
+    duration: Optional[int]
+    desktop_app_browser_quit: Optional[bool]
+    invite_id: Optional[str]
+    external_organization_id: Optional[str]
+    external_organization_name: Optional[str]
+    external_user_id: Optional[str]
+    external_user_email: Optional[str]
+    channel_id: Optional[str]
+    added_team_id: Optional[str]
+    unknown_fields: Dict[str, Any]
+    is_token_rotation_enabled_app: Optional[bool]
+    old_retention_policy: Optional[RetentionPolicy]
+    new_retention_policy: Optional[RetentionPolicy]
+    who_can_post: Optional[ConversationPref]
+    can_thread: Optional[ConversationPref]
+    is_external_limited: Optional[bool]
+    exporting_team_id: Optional[int]
+    session_search_start: Optional[int]
+    deprecation_search_end: Optional[int]
+    is_error: Optional[bool]
+    creator: Optional[str]
+    team: Optional[str]
+    app_id: Optional[str]
+    enable_at_here: Optional[FeatureEnablement]
+    enable_at_channel: Optional[FeatureEnablement]
+    can_huddle: Optional[FeatureEnablement]
+    url_private: Optional[str]
+    shared_with: Optional[SharedWith]
+    initiated_by: Optional[str]
+    source_team: Optional[str]
+    destination_team: Optional[str]
+    succeeded_users: Optional[List[str]]
+    failed_users: Optional[List[str]]
+    enterprise: Optional[str]
+    subteam: Optional[str]
+    action: Optional[str]
+    idp_group_member_count: Optional[int]
+    workspace_member_count: Optional[int]
+    added_user_count: Optional[int]
+    added_user_error_count: Optional[int]
+    reactivated_user_count: Optional[int]
+    removed_user_count: Optional[int]
+    removed_user_error_count: Optional[int]
+    total_removal_count: Optional[int]
+    is_flagged: Optional[str]
+    target_user: Optional[str]
+    idp_config_id: Optional[str]
+    config_type: Optional[str]
+    idp_entity_id_hash: Optional[str]
+    label: Optional[str]
+    previous_profile: Optional[Profile]
+    new_profile: Optional[Profile]
+    target_user_id: Optional[str]
+    space_file_id: Optional[SpaceFileId]
+    target_entity: Optional[str]
+    target_entity_id: Optional[str]
+    changed_permissions: Optional[List[str]]
+    datastore_name: Optional[str]
+    attributes: Optional[List[Attribute]]
+    channel: Optional[str]
+    entity_type: Optional[str]
+    actor: Optional[str]
+    access_level: Optional[str]
+    functions: Optional[List[str]]
+    workflows: Optional[List[str]]
+    datastores: Optional[List[str]]
+    permissions_updated: Optional[bool]
+    matched_rule: Optional[AAARule]
+    request: Optional[AAARequest]
+    rules_checked: Optional[List[AAARule]]
+    disconnecting_team: Optional[str]
+    is_channel_canvas: Optional[bool]
+    linked_channel_id: Optional[str]
+    column_id: Optional[str]
+    row_id: Optional[str]
+    cell_date_updated: Optional[int]
+    view_id: Optional[str]
+    user: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        name: Optional[str] = None,
+        new_value: Optional[Union[str, List[str], Dict[str, Any]]] = None,
+        previous_value: Optional[Union[str, List[str], Dict[str, Any]]] = None,
+        expires_on: Optional[int] = None,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        non_sso_only: Optional[bool] = None,
+        type: Optional[str] = None,
+        is_workflow: Optional[bool] = None,
+        inviter: Optional[Union[Dict[str, Any], User]] = None,
+        kicker: Optional[Union[Dict[str, Any], User]] = None,
+        shared_to: Optional[str] = None,
+        reason: Optional[str] = None,
+        origin_team: Optional[str] = None,
+        target_team: Optional[str] = None,
+        is_internal_integration: Optional[bool] = None,
+        cleared_resolution: Optional[str] = None,
+        app_owner_id: Optional[str] = None,
+        bot_scopes: Optional[List[str]] = None,
+        new_scopes: Optional[List[str]] = None,
+        previous_scopes: Optional[List[str]] = None,
+        granular_bot_token: Optional[bool] = None,
+        scopes: Optional[List[str]] = None,
+        scopes_bot: Optional[List[str]] = None,
+        resolution: Optional[str] = None,
+        app_previously_resolved: Optional[bool] = None,
+        admin_app_id: Optional[str] = None,
+        bot_id: Optional[str] = None,
+        installer_user_id: Optional[str] = None,
+        approver_id: Optional[str] = None,
+        approval_type: Optional[str] = None,
+        app_previously_approved: Optional[bool] = None,
+        old_scopes: Optional[List[str]] = None,
+        channels: Optional[List[str]] = None,
+        permissions: Optional[List[Dict[str, Any]]] = None,
+        new_version_id: Optional[str] = None,
+        trigger: Optional[str] = None,
+        export_type: Optional[str] = None,
+        export_start_ts: Optional[str] = None,
+        export_end_ts: Optional[str] = None,
+        barrier_id: Optional[str] = None,
+        primary_usergroup_id: Optional[str] = None,
+        barriered_from_usergroup_ids: Optional[List[str]] = None,
+        restricted_subjects: Optional[List[str]] = None,
+        duration: Optional[int] = None,
+        desktop_app_browser_quit: Optional[bool] = None,
+        invite_id: Optional[str] = None,
+        external_organization_id: Optional[str] = None,
+        external_organization_name: Optional[str] = None,
+        external_user_id: Optional[str] = None,
+        external_user_email: Optional[str] = None,
+        channel_id: Optional[str] = None,
+        added_team_id: Optional[str] = None,
+        is_token_rotation_enabled_app: Optional[bool] = None,
+        old_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None,
+        new_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None,
+        who_can_post: Optional[Union[Dict[str, List[str]], ConversationPref]] = None,
+        can_thread: Optional[Union[Dict[str, List[str]], ConversationPref]] = None,
+        is_external_limited: Optional[bool] = None,
+        exporting_team_id: Optional[int] = None,
+        session_search_start: Optional[int] = None,
+        deprecation_search_end: Optional[int] = None,
+        is_error: Optional[bool] = None,
+        creator: Optional[str] = None,
+        team: Optional[str] = None,
+        app_id: Optional[str] = None,
+        enable_at_here: Optional[Union[Dict[str, Any], FeatureEnablement]] = None,
+        enable_at_channel: Optional[Union[Dict[str, Any], FeatureEnablement]] = None,
+        can_huddle: Optional[Union[Dict[str, Any], FeatureEnablement]] = None,
+        url_private: Optional[str] = None,
+        shared_with: Optional[Union[Dict[str, Any], SharedWith]] = None,
+        initiated_by: Optional[str] = None,
+        source_team: Optional[str] = None,
+        destination_team: Optional[str] = None,
+        succeeded_users: Optional[Union[List[str], str]] = None,
+        failed_users: Optional[Union[List[str], str]] = None,
+        enterprise: Optional[str] = None,
+        subteam: Optional[str] = None,
+        action: Optional[str] = None,
+        idp_group_member_count: Optional[int] = None,
+        workspace_member_count: Optional[int] = None,
+        added_user_count: Optional[int] = None,
+        added_user_error_count: Optional[int] = None,
+        reactivated_user_count: Optional[int] = None,
+        removed_user_count: Optional[int] = None,
+        removed_user_error_count: Optional[int] = None,
+        total_removal_count: Optional[int] = None,
+        is_flagged: Optional[str] = None,
+        target_user: Optional[str] = None,
+        idp_config_id: Optional[str] = None,
+        config_type: Optional[str] = None,
+        idp_entity_id_hash: Optional[str] = None,
+        label: Optional[str] = None,
+        previous_profile: Optional[Union[Dict[str, Any], Profile]] = None,
+        new_profile: Optional[Union[Dict[str, Any], Profile]] = None,
+        target_user_id: Optional[str] = None,
+        space_file_id: Optional[Union[Dict[str, Any], SpaceFileId]] = None,
+        target_entity: Optional[str] = None,
+        target_entity_id: Optional[str] = None,
+        changed_permissions: Optional[List[str]] = None,
+        datastore_name: Optional[str] = None,
+        attributes: Optional[List[Union[Dict[str, str], Attribute]]] = None,
+        channel: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        actor: Optional[str] = None,
+        access_level: Optional[str] = None,
+        functions: Optional[List[str]] = None,
+        workflows: Optional[List[str]] = None,
+        datastores: Optional[List[str]] = None,
+        permissions_updated: Optional[bool] = None,
+        matched_rule: Optional[Union[Dict[str, Any], AAARule]] = None,
+        request: Optional[Union[Dict[str, Any], AAARequest]] = None,
+        rules_checked: Optional[List[Union[Dict[str, Any], AAARule]]] = None,
+        disconnecting_team: Optional[str] = None,
+        is_channel_canvas: Optional[bool] = None,
+        linked_channel_id: Optional[str] = None,
+        column_id: Optional[str] = None,
+        row_id: Optional[str] = None,
+        cell_date_updated: Optional[int] = None,
+        view_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.name = name
+        self.new_value = new_value
+        self.previous_value = previous_value
+        self.expires_on = expires_on
+        self.mobile_only = mobile_only
+        self.web_only = web_only
+        self.non_sso_only = non_sso_only
+        self.type = type
+        self.is_workflow = is_workflow
+        self.inviter = inviter if inviter is None or isinstance(inviter, User) else User(**inviter)
+        self.kicker = kicker if kicker is None or isinstance(kicker, User) else User(**kicker)
+        self.shared_to = shared_to
+        self.reason = reason
+        self.origin_team = origin_team
+        self.target_team = target_team
+        self.is_internal_integration = is_internal_integration
+        self.cleared_resolution = cleared_resolution
+        self.app_owner_id = app_owner_id
+        self.bot_scopes = bot_scopes
+        self.new_scopes = new_scopes
+        self.previous_scopes = previous_scopes
+        self.granular_bot_token = granular_bot_token
+        self.scopes = scopes
+        self.scopes_bot = scopes_bot
+        self.resolution = resolution
+        self.app_previously_resolved = app_previously_resolved
+        self.admin_app_id = admin_app_id
+        self.bot_id = bot_id
+        self.unknown_fields = kwargs
+        self.installer_user_id = installer_user_id
+        self.approver_id = approver_id
+        self.approval_type = approval_type
+        self.app_previously_approved = app_previously_approved
+        self.old_scopes = old_scopes
+        self.channels = channels
+        self.permissions = permissions
+        self.new_version_id = new_version_id
+        self.trigger = trigger
+        self.export_type = export_type
+        self.export_start_ts = export_start_ts
+        self.export_end_ts = export_end_ts
+        self.barrier_id = barrier_id
+        self.primary_usergroup_id = primary_usergroup_id
+        self.barriered_from_usergroup_ids = barriered_from_usergroup_ids
+        self.restricted_subjects = restricted_subjects
+        self.duration = duration
+        self.desktop_app_browser_quit = desktop_app_browser_quit
+        self.invite_id = invite_id
+        self.external_organization_id = external_organization_id
+        self.external_organization_name = external_organization_name
+        self.external_user_id = external_user_id
+        self.external_user_email = external_user_email
+        self.channel_id = channel_id
+        self.added_team_id = added_team_id
+        self.is_token_rotation_enabled_app = is_token_rotation_enabled_app
+        self.old_retention_policy = (
+            old_retention_policy
+            if old_retention_policy is None or isinstance(old_retention_policy, RetentionPolicy)
+            else RetentionPolicy(**old_retention_policy)
+        )
+        self.new_retention_policy = (
+            new_retention_policy
+            if new_retention_policy is None or isinstance(new_retention_policy, RetentionPolicy)
+            else RetentionPolicy(**new_retention_policy)
+        )
+        self.who_can_post = (
+            who_can_post
+            if who_can_post is None or isinstance(who_can_post, ConversationPref)
+            else ConversationPref(**who_can_post)
+        )
+        self.can_thread = (
+            can_thread if can_thread is None or isinstance(can_thread, ConversationPref) else ConversationPref(**can_thread)
+        )
+        self.is_external_limited = is_external_limited
+        self.exporting_team_id = exporting_team_id
+        self.session_search_start = session_search_start
+        self.deprecation_search_end = deprecation_search_end
+        self.is_error = is_error
+        self.creator = creator
+        self.team = team
+        self.app_id = app_id
+        self.enable_at_here = (
+            enable_at_here
+            if enable_at_here is None or isinstance(enable_at_here, FeatureEnablement)
+            else FeatureEnablement(**enable_at_here)
+        )
+        self.enable_at_channel = (
+            enable_at_channel
+            if enable_at_channel is None or isinstance(enable_at_channel, FeatureEnablement)
+            else FeatureEnablement(**enable_at_channel)
+        )
+        self.can_huddle = (
+            can_huddle
+            if can_huddle is None or isinstance(can_huddle, FeatureEnablement)
+            else FeatureEnablement(**can_huddle)
+        )
+        self.url_private = url_private
+        self.shared_with = (
+            shared_with if shared_with is None or isinstance(shared_with, SharedWith) else SharedWith(**shared_with)
+        )
+        self.initiated_by = initiated_by
+        self.source_team = source_team
+        self.destination_team = destination_team
+        self.succeeded_users = (
+            succeeded_users if succeeded_users is None or isinstance(succeeded_users, list) else json.loads(succeeded_users)
+        )
+        self.failed_users = (
+            failed_users if failed_users is None or isinstance(failed_users, list) else json.loads(failed_users)
+        )
+        self.enterprise = enterprise
+        self.subteam = subteam
+        self.action = action
+        self.idp_group_member_count = idp_group_member_count
+        self.workspace_member_count = workspace_member_count
+        self.added_user_count = added_user_count
+        self.added_user_error_count = added_user_error_count
+        self.reactivated_user_count = reactivated_user_count
+        self.removed_user_count = removed_user_count
+        self.removed_user_error_count = removed_user_error_count
+        self.total_removal_count = total_removal_count
+        self.is_flagged = is_flagged
+        self.target_user = target_user
+        self.idp_config_id = idp_config_id
+        self.config_type = config_type
+        self.idp_entity_id_hash = idp_entity_id_hash
+        self.label = label
+        self.previous_profile = (
+            previous_profile
+            if previous_profile is None or isinstance(previous_profile, Profile)
+            else Profile(**previous_profile)
+        )
+        self.new_profile = new_profile if new_profile is None or isinstance(new_profile, Profile) else Profile(**new_profile)
+        self.target_user_id = target_user_id
+        self.space_file_id = (
+            space_file_id
+            if space_file_id is None or isinstance(space_file_id, SpaceFileId)
+            else SpaceFileId(**space_file_id)
+        )
+        self.target_entity = target_entity
+        self.target_entity_id = target_entity_id
+        self.changed_permissions = changed_permissions
+        self.datastore_name = datastore_name
+        self.attributes = None
+        if attributes is not None:
+            self.attributes = []
+            for a in attributes:
+                if isinstance(a, dict):
+                    self.attributes.append(Attribute(**a))  # type: ignore[arg-type]
+                else:
+                    self.attributes.append(a)
+        self.channel = channel
+        self.entity_type = entity_type
+        self.actor = actor
+        self.access_level = access_level
+        self.functions = functions
+        self.workflows = workflows
+        self.datastores = datastores
+        self.permissions_updated = permissions_updated
+        self.matched_rule = (
+            matched_rule if matched_rule is None or isinstance(matched_rule, AAARule) else AAARule(**matched_rule)
+        )
+        self.request = request if request is None or isinstance(request, AAARequest) else AAARequest(**request)
+        self.rules_checked = None
+        if rules_checked is not None:
+            self.rules_checked = []
+            for a in rules_checked:  # type: ignore[assignment]
+                if isinstance(a, dict):
+                    self.rules_checked.append(AAARule(**a))  # type: ignore[arg-type]
+                else:
+                    self.rules_checked.append(a)  # type: ignore[arg-type]
+        self.disconnecting_team = disconnecting_team
+        self.is_channel_canvas = is_channel_canvas
+        self.linked_channel_id = linked_channel_id
+        self.column_id = column_id
+        self.row_id = row_id
+        self.cell_date_updated = cell_date_updated
+        self.view_id = view_id
+        self.user = user
+
+
+

Class variables

+
+
var access_level :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var action :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var actor :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var added_team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var added_user_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var added_user_error_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var admin_app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var app_owner_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var app_previously_approved :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var app_previously_resolved :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var approval_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var approver_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var attributes :Β List[Attribute]Β |Β None
+
+

The type of the None singleton.

+
+
var barrier_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var barriered_from_usergroup_ids :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var can_huddle :Β FeatureEnablementΒ |Β None
+
+

The type of the None singleton.

+
+
var can_thread :Β ConversationPrefΒ |Β None
+
+

The type of the None singleton.

+
+
var cell_date_updated :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var changed_permissions :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var channel :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var channels :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var cleared_resolution :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var column_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var config_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var creator :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var datastore_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var datastores :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var deprecation_search_end :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var desktop_app_browser_quit :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var destination_team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var disconnecting_team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var duration :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var enable_at_channel :Β FeatureEnablementΒ |Β None
+
+

The type of the None singleton.

+
+
var enable_at_here :Β FeatureEnablementΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var entity_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var expires_on :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var export_end_ts :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var export_start_ts :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var export_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var exporting_team_id :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var external_organization_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var external_organization_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var external_user_email :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var external_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var failed_users :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var functions :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var granular_bot_token :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var idp_config_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var idp_entity_id_hash :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var idp_group_member_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var initiated_by :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installer_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var invite_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var inviter :Β UserΒ |Β None
+
+

The type of the None singleton.

+
+
var is_channel_canvas :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_error :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_external_limited :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_flagged :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var is_internal_integration :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_token_rotation_enabled_app :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var is_workflow :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var kicker :Β UserΒ |Β None
+
+

The type of the None singleton.

+
+
var label :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var linked_channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var matched_rule :Β AAARuleΒ |Β None
+
+

The type of the None singleton.

+
+
var mobile_only :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var new_profile :Β ProfileΒ |Β None
+
+

The type of the None singleton.

+
+
var new_retention_policy :Β RetentionPolicyΒ |Β None
+
+

The type of the None singleton.

+
+
var new_scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var new_value :Β strΒ |Β List[str]Β |Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var new_version_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var non_sso_only :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var old_retention_policy :Β RetentionPolicyΒ |Β None
+
+

The type of the None singleton.

+
+
var old_scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var origin_team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var permissions :Β List[Dict[str,Β Any]]Β |Β None
+
+

The type of the None singleton.

+
+
var permissions_updated :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var previous_profile :Β ProfileΒ |Β None
+
+

The type of the None singleton.

+
+
var previous_scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var previous_value :Β strΒ |Β List[str]Β |Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var primary_usergroup_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var reactivated_user_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var reason :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var removed_user_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var removed_user_error_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var request :Β AAARequestΒ |Β None
+
+

The type of the None singleton.

+
+
var resolution :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var restricted_subjects :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var row_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var rules_checked :Β List[AAARule]Β |Β None
+
+

The type of the None singleton.

+
+
var scopes :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var scopes_bot :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var session_search_start :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var shared_to :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var shared_with :Β SharedWithΒ |Β None
+
+

The type of the None singleton.

+
+
var source_team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var space_file_id :Β SpaceFileIdΒ |Β None
+
+

The type of the None singleton.

+
+
var subteam :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var succeeded_users :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var target_entity :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var target_entity_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var target_team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var target_user :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var target_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var total_removal_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var trigger :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var url_private :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var view_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var web_only :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var who_can_post :Β ConversationPrefΒ |Β None
+
+

The type of the None singleton.

+
+
var workflows :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var workspace_member_count :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class Entity +(*,
type:Β strΒ |Β NoneΒ =Β None,
user:Β UserΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workspace:Β LocationΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
enterprise:Β LocationΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
channel:Β ChannelΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
file:Β FileΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
app:Β AppΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
message:Β MessageΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
huddle:Β HuddleΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
role:Β RoleΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
usergroup:Β UsergroupΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow:Β WorkflowΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
barrier:Β InformationBarrierΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_v2:Β WorkflowV2Β |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
account_type_role:Β AccountTypeRoleΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
list:Β SlackListΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Entity:
+    type: Optional[str]
+    user: Optional[User]
+    workspace: Optional[Location]
+    enterprise: Optional[Location]
+    channel: Optional[Channel]
+    file: Optional[File]
+    app: Optional[App]
+    message: Optional[Message]
+    huddle: Optional[Huddle]
+    role: Optional[Role]
+    usergroup: Optional[Usergroup]
+    workflow: Optional[Workflow]
+    barrier: Optional[InformationBarrier]
+    workflow_v2: Optional[WorkflowV2]
+    account_type_role: Optional[AccountTypeRole]
+    list: Optional[SlackList]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        user: Optional[Union[User, Dict[str, Any]]] = None,
+        workspace: Optional[Union[Location, Dict[str, Any]]] = None,
+        enterprise: Optional[Union[Location, Dict[str, Any]]] = None,
+        channel: Optional[Union[Channel, Dict[str, Any]]] = None,
+        file: Optional[Union[File, Dict[str, Any]]] = None,
+        app: Optional[Union[App, Dict[str, Any]]] = None,
+        message: Optional[Union[Message, Dict[str, Any]]] = None,
+        huddle: Optional[Union[Huddle, Dict[str, Any]]] = None,
+        role: Optional[Union[Role, Dict[str, Any]]] = None,
+        usergroup: Optional[Union[Usergroup, Dict[str, Any]]] = None,
+        workflow: Optional[Union[Workflow, Dict[str, Any]]] = None,
+        barrier: Optional[Union[InformationBarrier, Dict[str, Any]]] = None,
+        workflow_v2: Optional[Union[WorkflowV2, Dict[str, Any]]] = None,
+        account_type_role: Optional[Union[AccountTypeRole, Dict[str, Any]]] = None,
+        list: Optional[Union[SlackList, Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.user = User(**user) if isinstance(user, dict) else user
+        self.workspace = Location(**workspace) if isinstance(workspace, dict) else workspace
+        self.enterprise = Location(**enterprise) if isinstance(enterprise, dict) else enterprise
+        self.channel = Channel(**channel) if isinstance(channel, dict) else channel
+        self.file = File(**file) if isinstance(file, dict) else file
+        self.app = App(**app) if isinstance(app, dict) else app
+        self.message = Message(**message) if isinstance(message, dict) else message
+        self.huddle = Huddle(**huddle) if isinstance(huddle, dict) else huddle
+        self.role = Role(**role) if isinstance(role, dict) else role
+        self.usergroup = Usergroup(**usergroup) if isinstance(usergroup, dict) else usergroup
+        self.workflow = Workflow(**workflow) if isinstance(workflow, dict) else workflow
+        self.barrier = InformationBarrier(**barrier) if isinstance(barrier, dict) else barrier
+        self.workflow_v2 = WorkflowV2(**workflow_v2) if isinstance(workflow_v2, dict) else workflow_v2
+        self.account_type_role = (
+            AccountTypeRole(**account_type_role) if isinstance(account_type_role, dict) else account_type_role
+        )
+        self.list = SlackList(**list) if isinstance(list, dict) else list
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var account_type_role :Β AccountTypeRoleΒ |Β None
+
+

The type of the None singleton.

+
+
var app :Β AppΒ |Β None
+
+

The type of the None singleton.

+
+
var barrier :Β InformationBarrierΒ |Β None
+
+

The type of the None singleton.

+
+
var channel :Β ChannelΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise :Β LocationΒ |Β None
+
+

The type of the None singleton.

+
+
var file :Β FileΒ |Β None
+
+

The type of the None singleton.

+
+
var huddle :Β HuddleΒ |Β None
+
+

The type of the None singleton.

+
+
var list :Β SlackListΒ |Β None
+
+

The type of the None singleton.

+
+
var message :Β MessageΒ |Β None
+
+

The type of the None singleton.

+
+
var role :Β RoleΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var user :Β UserΒ |Β None
+
+

The type of the None singleton.

+
+
var usergroup :Β UsergroupΒ |Β None
+
+

The type of the None singleton.

+
+
var workflow :Β WorkflowΒ |Β None
+
+

The type of the None singleton.

+
+
var workflow_v2 :Β WorkflowV2Β |Β None
+
+

The type of the None singleton.

+
+
var workspace :Β LocationΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class Entry +(*,
id:Β strΒ |Β NoneΒ =Β None,
date_create:Β intΒ |Β NoneΒ =Β None,
action:Β strΒ |Β NoneΒ =Β None,
actor:Β ActorΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
entity:Β EntityΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
context:Β ContextΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
details:Β DetailsΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Entry:
+    id: Optional[str]
+    date_create: Optional[int]
+    action: Optional[str]
+    actor: Optional[Actor]
+    entity: Optional[Entity]
+    context: Optional[Context]
+    details: Optional[Details]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        date_create: Optional[int] = None,
+        action: Optional[str] = None,
+        actor: Optional[Union[Actor, Dict[str, Any]]] = None,
+        entity: Optional[Union[Entity, Dict[str, Any]]] = None,
+        context: Optional[Union[Context, Dict[str, Any]]] = None,
+        details: Optional[Union[Details, Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.date_create = date_create
+        self.action = action
+        self.actor = Actor(**actor) if isinstance(actor, dict) else actor
+        self.entity = Entity(**entity) if isinstance(entity, dict) else entity
+        self.context = Context(**context) if isinstance(context, dict) else context
+        self.details = Details(**details) if isinstance(details, dict) else details
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var action :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var actor :Β ActorΒ |Β None
+
+

The type of the None singleton.

+
+
var context :Β ContextΒ |Β None
+
+

The type of the None singleton.

+
+
var date_create :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var details :Β DetailsΒ |Β None
+
+

The type of the None singleton.

+
+
var entity :Β EntityΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class FeatureEnablement +(*, enabled:Β boolΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class FeatureEnablement:
+    enabled: Optional[bool]
+
+    def __init__(
+        self,
+        *,
+        enabled: Optional[bool] = None,
+        **kwargs,
+    ) -> None:
+        self.enabled = enabled
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var enabled :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class File +(*,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class File:
+    id: Optional[str]
+    name: Optional[str]
+    filetype: Optional[str]
+    title: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        filetype: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.filetype = filetype
+        self.title = title
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var filetype :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var title :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Huddle +(*,
id:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
date_end:Β intΒ |Β NoneΒ =Β None,
participants:Β List[str]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Huddle:
+    id: Optional[str]
+    date_start: Optional[int]
+    date_end: Optional[int]
+    participants: Optional[List[str]]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        date_start: Optional[int] = None,
+        date_end: Optional[int] = None,
+        participants: Optional[List[str]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.date_start = date_start
+        self.date_end = date_end
+        self.participants = participants
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var date_end :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var date_start :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var participants :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class InformationBarrier +(*,
id:Β strΒ |Β NoneΒ =Β None,
primary_usergroup:Β strΒ |Β NoneΒ =Β None,
barriered_from_usergroups:Β List[str]Β |Β NoneΒ =Β None,
restricted_subjects:Β List[str]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class InformationBarrier:
+    id: Optional[str]
+    primary_usergroup: Optional[str]
+    barriered_from_usergroups: Optional[List[str]]
+    restricted_subjects: Optional[List[str]]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        primary_usergroup: Optional[str] = None,
+        barriered_from_usergroups: Optional[List[str]] = None,
+        restricted_subjects: Optional[List[str]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.primary_usergroup = primary_usergroup
+        self.barriered_from_usergroups = barriered_from_usergroups
+        self.restricted_subjects = restricted_subjects
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var barriered_from_usergroups :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var primary_usergroup :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var restricted_subjects :Β List[str]Β |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Location +(*,
type:Β strΒ |Β NoneΒ =Β None,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
domain:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Location:
+    type: Optional[str]
+    id: Optional[str]
+    name: Optional[str]
+    domain: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.id = id
+        self.name = name
+        self.domain = domain
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var domain :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class LogsResponse +(*,
entries:Β List[EntryΒ |Β Dict[str,Β Any]]Β |Β NoneΒ =Β None,
response_metadata:Β ResponseMetadataΒ |Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
ok:Β boolΒ |Β NoneΒ =Β None,
error:Β strΒ |Β NoneΒ =Β None,
needed:Β strΒ |Β NoneΒ =Β None,
provided:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class LogsResponse:
+    entries: Optional[List[Entry]]
+    response_metadata: Optional[ResponseMetadata]
+    ok: Optional[bool]
+    error: Optional[str]
+    needed: Optional[str]
+    provided: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        entries: Optional[List[Union[Entry, Dict[str, Any]]]] = None,
+        response_metadata: Optional[Union[ResponseMetadata, Dict[str, Any]]] = None,
+        ok: Optional[bool] = None,
+        error: Optional[str] = None,
+        needed: Optional[str] = None,
+        provided: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.entries = [Entry(**e) if isinstance(e, dict) else e for e in entries]  # type: ignore[union-attr]
+        self.response_metadata = (
+            ResponseMetadata(**response_metadata) if isinstance(response_metadata, dict) else response_metadata
+        )
+        self.ok = ok
+        self.error = error
+        self.needed = needed
+        self.provided = provided
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var entries :Β List[Entry]Β |Β None
+
+

The type of the None singleton.

+
+
var error :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var needed :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var ok :Β boolΒ |Β None
+
+

The type of the None singleton.

+
+
var provided :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var response_metadata :Β ResponseMetadataΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Message +(*,
channel:Β strΒ |Β NoneΒ =Β None,
team:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Message:
+    channel: Optional[str]
+    team: Optional[str]
+    timestamp: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        channel: Optional[str] = None,
+        team: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.channel = channel
+        self.team = team
+        self.timestamp = timestamp
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var channel :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var timestamp :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Profile +(*,
real_name:Β strΒ |Β NoneΒ =Β None,
first_name:Β strΒ |Β NoneΒ =Β None,
last_name:Β strΒ |Β NoneΒ =Β None,
display_name:Β strΒ |Β NoneΒ =Β None,
image_original:Β strΒ |Β NoneΒ =Β None,
image_24:Β strΒ |Β NoneΒ =Β None,
image_32:Β strΒ |Β NoneΒ =Β None,
image_48:Β strΒ |Β NoneΒ =Β None,
image_72:Β strΒ |Β NoneΒ =Β None,
image_192:Β strΒ |Β NoneΒ =Β None,
image_512:Β strΒ |Β NoneΒ =Β None,
image_1024:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Profile:
+    real_name: Optional[str]
+    first_name: Optional[str]
+    last_name: Optional[str]
+    display_name: Optional[str]
+    image_original: Optional[str]
+    image_24: Optional[str]
+    image_32: Optional[str]
+    image_48: Optional[str]
+    image_72: Optional[str]
+    image_192: Optional[str]
+    image_512: Optional[str]
+    image_1024: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        real_name: Optional[str] = None,
+        first_name: Optional[str] = None,
+        last_name: Optional[str] = None,
+        display_name: Optional[str] = None,
+        image_original: Optional[str] = None,
+        image_24: Optional[str] = None,
+        image_32: Optional[str] = None,
+        image_48: Optional[str] = None,
+        image_72: Optional[str] = None,
+        image_192: Optional[str] = None,
+        image_512: Optional[str] = None,
+        image_1024: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.real_name = real_name
+        self.first_name = first_name
+        self.last_name = last_name
+        self.display_name = display_name
+        self.image_original = image_original
+        self.image_24 = image_24
+        self.image_32 = image_32
+        self.image_48 = image_48
+        self.image_72 = image_72
+        self.image_192 = image_192
+        self.image_512 = image_512
+        self.image_1024 = image_1024
+
+
+

Class variables

+
+
var display_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var first_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_1024 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_192 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_24 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_32 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_48 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_512 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_72 :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var image_original :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var last_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var real_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class ResponseMetadata +(*, next_cursor:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class ResponseMetadata:
+    next_cursor: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        next_cursor: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.next_cursor = next_cursor
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var next_cursor :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class RetentionPolicy +(*, type:Β strΒ |Β NoneΒ =Β None, duration_days:Β intΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class RetentionPolicy:
+    type: Optional[str]
+    duration_days: Optional[int]
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        duration_days: Optional[int] = None,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.duration_days = duration_days
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var duration_days :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class Role +(*,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Role:
+    id: Optional[str]
+    name: Optional[str]
+    type: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        type: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.type = type
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class SharedWith +(*, channel_id:Β strΒ |Β NoneΒ =Β None, access_level:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class SharedWith:
+    channel_id: Optional[str]
+    access_level: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        channel_id: Optional[str] = None,
+        access_level: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.channel_id = channel_id
+        self.access_level = access_level
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var access_level :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class SlackList +(*, id:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class SlackList:
+    id: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class SpaceFileId +(*, payload:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class SpaceFileId:
+    payload: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        payload: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.payload = payload
+
+
+

Class variables

+
+
var payload :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class User +(*,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
email:Β strΒ |Β NoneΒ =Β None,
team:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class User:
+    id: Optional[str]
+    name: Optional[str]
+    email: Optional[str]
+    team: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        email: Optional[str] = None,
+        team: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.email = email
+        self.team = team
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var email :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Usergroup +(*, id:Β strΒ |Β NoneΒ =Β None, name:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class Usergroup:
+    id: Optional[str]
+    name: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class Workflow +(*,
id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
domain:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class Workflow:
+    id: Optional[str]
+    name: Optional[str]
+    domain: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        name: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.name = name
+        self.domain = domain
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var domain :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+class WorkflowV2 +(*,
id:Β strΒ |Β NoneΒ =Β None,
app_id:Β strΒ |Β NoneΒ =Β None,
date_updated:Β intΒ |Β NoneΒ =Β None,
callback_id:Β strΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
updated_by:Β strΒ |Β NoneΒ =Β None,
step_configuration:Β List[Dict[str,Β Any]Β |Β WorkflowV2StepConfiguration]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class WorkflowV2:
+    id: Optional[str]
+    app_id: Optional[str]
+    date_updated: Optional[int]
+    callback_id: Optional[str]
+    name: Optional[str]
+    updated_by: Optional[str]
+    step_configuration: Optional[List[WorkflowV2StepConfiguration]]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        app_id: Optional[str] = None,
+        date_updated: Optional[int] = None,
+        callback_id: Optional[str] = None,
+        name: Optional[str] = None,
+        updated_by: Optional[str] = None,
+        step_configuration: Optional[List[Union[Dict[str, Any], WorkflowV2StepConfiguration]]] = None,
+        **kwargs,
+    ) -> None:
+        self.id = id
+        self.app_id = app_id
+        self.date_updated = date_updated
+        self.callback_id = callback_id
+        self.name = name
+        self.updated_by = updated_by
+        self.step_configuration = None
+        if step_configuration is not None:
+            self.step_configuration = []
+            for a in step_configuration:
+                if isinstance(a, dict):
+                    self.step_configuration.append(WorkflowV2StepConfiguration(**a))
+                else:
+                    self.step_configuration.append(a)
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var callback_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var date_updated :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var step_configuration :Β List[WorkflowV2StepConfiguration]Β |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var updated_by :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+
+
+class WorkflowV2StepConfiguration +(*,
name:Β strΒ |Β NoneΒ =Β None,
step_function_type:Β strΒ |Β NoneΒ =Β None,
step_function_app_id:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class WorkflowV2StepConfiguration:
+    name: Optional[str]
+    step_function_type: Optional[str]
+    step_function_app_id: Optional[str]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        name: Optional[str] = None,
+        step_function_type: Optional[str] = None,
+        step_function_app_id: Optional[str] = None,
+        **kwargs,
+    ) -> None:
+        self.name = name
+        self.step_function_type = step_function_type
+        self.step_function_app_id = step_function_app_id
+        self.unknown_fields = kwargs
+
+
+

Class variables

+
+
var name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var step_function_app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var step_function_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/audit_logs/v1/response.html b/docs/reference/audit_logs/v1/response.html new file mode 100644 index 000000000..7d5c72853 --- /dev/null +++ b/docs/reference/audit_logs/v1/response.html @@ -0,0 +1,163 @@ + + + + + + +slack_sdk.audit_logs.v1.response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.audit_logs.v1.response

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AuditLogsResponse +(*, url:Β str, status_code:Β int, raw_body:Β strΒ |Β None, headers:Β dict) +
+
+
+ +Expand source code + +
class AuditLogsResponse:
+    url: str
+    status_code: int
+    headers: Dict[str, Any]
+    raw_body: Optional[str]
+    body: Optional[Dict[str, Any]]
+    typed_body: Optional[LogsResponse]
+
+    @property  # type: ignore[no-redef]
+    def typed_body(self) -> Optional[LogsResponse]:
+        if self.body is None:
+            return None
+        return LogsResponse(**self.body)
+
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        raw_body: Optional[str],
+        headers: dict,
+    ):
+        self.url = url
+        self.status_code = status_code
+        self.headers = headers
+        self.raw_body = raw_body
+        self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None
+
+
+

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var raw_body :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop typed_body :Β LogsResponseΒ |Β None
+
+
+ +Expand source code + +
@property  # type: ignore[no-redef]
+def typed_body(self) -> Optional[LogsResponse]:
+    if self.body is None:
+        return None
+    return LogsResponse(**self.body)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/errors/index.html b/docs/reference/errors/index.html new file mode 100644 index 000000000..569a2608e --- /dev/null +++ b/docs/reference/errors/index.html @@ -0,0 +1,315 @@ + + + + + + +slack_sdk.errors API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.errors

+
+
+

Errors that can be raised by this SDK

+
+
+
+
+
+
+
+
+

Classes

+
+
+class BotUserAccessError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class BotUserAccessError(SlackClientError):
+    """Error raised when an 'xoxb-*' token is
+    being used for a Slack API method that only accepts 'xoxp-*' tokens.
+    """
+
+

Error raised when an 'xoxb-' token is +being used for a Slack API method that only accepts 'xoxp-' tokens.

+

Ancestors

+ +
+
+class SlackApiError +(message, response) +
+
+
+ +Expand source code + +
class SlackApiError(SlackClientError):
+    """Error raised when Slack does not send the expected response.
+
+    Attributes:
+        response (SlackResponse): The SlackResponse object containing all of the data sent back from the API.
+
+    Note:
+        The message (str) passed into the exception is used when
+        a user converts the exception to a str.
+        i.e. str(SlackApiError("This text will be sent as a string."))
+    """
+
+    def __init__(self, message, response):
+        msg = f"{message}\nThe server responded with: {response}"
+        self.response = response
+        super(SlackApiError, self).__init__(msg)
+
+

Error raised when Slack does not send the expected response.

+

Attributes

+
+
response : SlackResponse
+
The SlackResponse object containing all of the data sent back from the API.
+
+

Note

+

The message (str) passed into the exception is used when +a user converts the exception to a str. +i.e. str(SlackApiError("This text will be sent as a string."))

+

Ancestors

+ +
+
+class SlackClientConfigurationError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class SlackClientConfigurationError(SlackClientError):
+    """Error raised because of invalid configuration on the client side:
+    * when attempting to send messages over the websocket when the connection is closed.
+    * when external system (e.g., Amazon S3) configuration / credentials are not correct
+    """
+
+

Error raised because of invalid configuration on the client side: +* when attempting to send messages over the websocket when the connection is closed. +* when external system (e.g., Amazon S3) configuration / credentials are not correct

+

Ancestors

+ +
+
+class SlackClientError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class SlackClientError(Exception):
+    """Base class for Client errors"""
+
+

Base class for Client errors

+

Ancestors

+
    +
  • builtins.Exception
  • +
  • builtins.BaseException
  • +
+

Subclasses

+ +
+
+class SlackClientNotConnectedError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class SlackClientNotConnectedError(SlackClientError):
+    """Error raised when attempting to send messages over the websocket when the
+    connection is closed."""
+
+

Error raised when attempting to send messages over the websocket when the +connection is closed.

+

Ancestors

+ +
+
+class SlackObjectFormationError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class SlackObjectFormationError(SlackClientError):
+    """Error raised when a constructed object is not valid/malformed"""
+
+

Error raised when a constructed object is not valid/malformed

+

Ancestors

+ +
+
+class SlackRequestError +(*args, **kwargs) +
+
+
+ +Expand source code + +
class SlackRequestError(SlackClientError):
+    """Error raised when there's a problem with the request that's being submitted."""
+
+

Error raised when there's a problem with the request that's being submitted.

+

Ancestors

+ +
+
+class SlackTokenRotationError +(api_error:Β SlackApiError) +
+
+
+ +Expand source code + +
class SlackTokenRotationError(SlackClientError):
+    """Error raised when the oauth.v2.access call for token rotation fails"""
+
+    api_error: SlackApiError
+
+    def __init__(self, api_error: SlackApiError):
+        self.api_error = api_error
+
+

Error raised when the oauth.v2.access call for token rotation fails

+

Ancestors

+ +

Class variables

+
+
var api_error :Β SlackApiError
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/async_handler.html b/docs/reference/http_retry/async_handler.html new file mode 100644 index 000000000..4f3889fcc --- /dev/null +++ b/docs/reference/http_retry/async_handler.html @@ -0,0 +1,431 @@ + + + + + + +slack_sdk.http_retry.async_handler API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.async_handler

+
+
+

asyncio compatible RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class BackoffRetryIntervalCalculator +(backoff_factor:Β floatΒ =Β 0.5,
jitter:Β JitterΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class BackoffRetryIntervalCalculator(RetryIntervalCalculator):
+    """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+    see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+    """
+
+    backoff_factor: float
+    jitter: Jitter
+
+    def __init__(self, backoff_factor: float = 0.5, jitter: Optional[Jitter] = None):
+        """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+
+        Args:
+            backoff_factor: The factor for the backoff interval calculation
+            jitter: The jitter logic implementation
+        """
+        self.backoff_factor = backoff_factor
+        self.jitter = jitter if jitter is not None else RandomJitter()
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        interval = self.backoff_factor * (2 ** (current_attempt))
+        sleep_duration = self.jitter.recalculate(interval)
+        return sleep_duration
+
+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter +see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter

+

Args

+
+
backoff_factor
+
The factor for the backoff interval calculation
+
jitter
+
The jitter logic implementation
+
+

Ancestors

+ +

Class variables

+
+
var backoff_factor :Β float
+
+

The type of the None singleton.

+
+
var jitter :Β Jitter
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class HttpRequest +(*,
method:Β str,
url:Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpRequest:
+    """HTTP request representation"""
+
+    method: str
+    url: str
+    headers: Dict[str, Union[str, List[str]]]
+    body_params: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        method: str,
+        url: str,
+        headers: Dict[str, Union[str, List[str]]],
+        body_params: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.method = method
+        self.url = url
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body_params = body_params
+        self.data = data
+
+    @classmethod
+    def from_urllib_http_request(cls, req: Request) -> "HttpRequest":
+        return HttpRequest(
+            method=req.method,  # type: ignore[arg-type]
+            url=req.full_url,
+            headers={k: v if isinstance(v, list) else [v] for k, v in req.headers.items()},
+            data=req.data,  # type: ignore[arg-type]
+        )
+
+

HTTP request representation

+

Class variables

+
+
var body_params :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var method :Β str
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_urllib_http_request(req:Β urllib.request.Request) ‑>Β HttpRequest +
+
+
+
+
+
+
+class HttpResponse +(*,
status_code:Β intΒ |Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpResponse:
+    """HTTP response representation"""
+
+    status_code: int
+    headers: Dict[str, Union[List[str], str]]
+    body: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        status_code: Union[int, str],
+        headers: Dict[str, Union[str, List[str]]],
+        body: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.status_code = int(status_code)
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body = body
+        self.data = data
+
+

HTTP response representation

+

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
+
+
+class RetryIntervalCalculator +
+
+
+ +Expand source code + +
class RetryIntervalCalculator:
+    """Retry interval calculator interface."""
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        """Calculates an interval duration in seconds.
+
+        Args:
+            current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+        Returns:
+            calculated interval duration in seconds
+        """
+        raise NotImplementedError()
+
+

Retry interval calculator interface.

+

Subclasses

+ +

Methods

+
+
+def calculate_sleep_duration(self, current_attempt:Β int) ‑>Β float +
+
+
+ +Expand source code + +
def calculate_sleep_duration(self, current_attempt: int) -> float:
+    """Calculates an interval duration in seconds.
+
+    Args:
+        current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+    Returns:
+        calculated interval duration in seconds
+    """
+    raise NotImplementedError()
+
+

Calculates an interval duration in seconds.

+

Args

+
+
current_attempt
+
the number of the current attempt (zero-origin; 0 means no retries are done so far)
+
+

Returns

+

calculated interval duration in seconds

+
+
+
+
+class RetryState +(*, current_attempt:Β intΒ =Β 0, custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class RetryState:
+    next_attempt_requested: bool
+    current_attempt: int  # zero-origin
+    custom_values: Optional[Dict[str, Any]]
+
+    def __init__(
+        self,
+        *,
+        current_attempt: int = 0,
+        custom_values: Optional[Dict[str, Any]] = None,
+    ):
+        self.next_attempt_requested = False
+        self.current_attempt = current_attempt
+        self.custom_values = custom_values
+
+    def increment_current_attempt(self) -> int:
+        self.current_attempt += 1
+        return self.current_attempt
+
+
+

Class variables

+
+
var current_attempt :Β int
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var next_attempt_requested :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def increment_current_attempt(self) ‑>Β int +
+
+
+ +Expand source code + +
def increment_current_attempt(self) -> int:
+    self.current_attempt += 1
+    return self.current_attempt
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/builtin_async_handlers.html b/docs/reference/http_retry/builtin_async_handlers.html new file mode 100644 index 000000000..206b27f53 --- /dev/null +++ b/docs/reference/http_retry/builtin_async_handlers.html @@ -0,0 +1,306 @@ + + + + + + +slack_sdk.http_retry.builtin_async_handlers API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.builtin_async_handlers

+
+
+
+
+
+
+
+
+

Functions

+
+
+def async_default_handlers() ‑>Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler] +
+
+
+ +Expand source code + +
def async_default_handlers() -> List[AsyncRetryHandler]:
+    return [AsyncConnectionErrorRetryHandler()]
+
+
+
+
+
+
+

Classes

+
+
+class AsyncConnectionErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>,
error_types:Β List[Type[Exception]]Β =Β [<class 'aiohttp.client_exceptions.ServerConnectionError'>, <class 'aiohttp.client_exceptions.ServerDisconnectedError'>, <class 'aiohttp.client_exceptions.ClientOSError'>])
+
+
+
+ +Expand source code + +
class AsyncConnectionErrorRetryHandler(AsyncRetryHandler):
+    """RetryHandler that does retries for connectivity issues."""
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+        error_types: List[Type[Exception]] = [
+            ServerConnectionError,
+            ServerDisconnectedError,
+            # ClientOSError: [Errno 104] Connection reset by peer
+            ClientOSError,
+        ],
+    ):
+        super().__init__(max_retry_count, interval_calculator)
+        self.error_types_to_do_retries = error_types
+
+    async def _can_retry_async(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        if error is None:
+            return False
+
+        for error_type in self.error_types_to_do_retries:
+            if isinstance(error, error_type):
+                return True
+        return False
+
+

RetryHandler that does retries for connectivity issues.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+
    +
  • slack_sdk.http_retry.async_handler.AsyncRetryHandler
  • +
+
+
+class AsyncRateLimitErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class AsyncRateLimitErrorRetryHandler(AsyncRetryHandler):
+    """RetryHandler that does retries for rate limited errors."""
+
+    async def _can_retry_async(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        return response is not None and response.status_code == 429
+
+    async def prepare_for_next_attempt_async(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> None:
+        if response is None:
+            raise error  # type: ignore[misc]
+
+        state.next_attempt_requested = True
+        retry_after_header_name: Optional[str] = None
+        for k in response.headers.keys():
+            if k.lower() == "retry-after":
+                retry_after_header_name = k
+                break
+        duration = 1
+        if retry_after_header_name is None:
+            # This situation usually does not arise. Just in case.
+            duration += random.random()  # type: ignore[assignment]
+        else:
+            duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[assignment, index] # noqa: E501
+        await asyncio.sleep(duration)
+        state.increment_current_attempt()
+
+

RetryHandler that does retries for rate limited errors.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+
    +
  • slack_sdk.http_retry.async_handler.AsyncRetryHandler
  • +
+

Methods

+
+
+async def prepare_for_next_attempt_async(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β None
+
+
+
+ +Expand source code + +
async def prepare_for_next_attempt_async(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> None:
+    if response is None:
+        raise error  # type: ignore[misc]
+
+    state.next_attempt_requested = True
+    retry_after_header_name: Optional[str] = None
+    for k in response.headers.keys():
+        if k.lower() == "retry-after":
+            retry_after_header_name = k
+            break
+    duration = 1
+    if retry_after_header_name is None:
+        # This situation usually does not arise. Just in case.
+        duration += random.random()  # type: ignore[assignment]
+    else:
+        duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[assignment, index] # noqa: E501
+    await asyncio.sleep(duration)
+    state.increment_current_attempt()
+
+
+
+
+
+
+class AsyncServerErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class AsyncServerErrorRetryHandler(AsyncRetryHandler):
+    """RetryHandler that does retries for server errors."""
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+    ):
+        super().__init__(max_retry_count, interval_calculator)
+
+    async def _can_retry_async(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        return response is not None and response.status_code in [500, 503]
+
+

RetryHandler that does retries for server errors.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+
    +
  • slack_sdk.http_retry.async_handler.AsyncRetryHandler
  • +
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/builtin_handlers.html b/docs/reference/http_retry/builtin_handlers.html new file mode 100644 index 000000000..0f36601ed --- /dev/null +++ b/docs/reference/http_retry/builtin_handlers.html @@ -0,0 +1,316 @@ + + + + + + +slack_sdk.http_retry.builtin_handlers API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.builtin_handlers

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class ConnectionErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>,
error_types:Β List[Type[Exception]]Β =Β [<class 'urllib.error.URLError'>, <class 'ConnectionResetError'>, <class 'http.client.RemoteDisconnected'>])
+
+
+
+ +Expand source code + +
class ConnectionErrorRetryHandler(RetryHandler):
+    """RetryHandler that does retries for connectivity issues."""
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+        error_types: List[Type[Exception]] = [
+            # To cover URLError: <urlopen error [Errno 104] Connection reset by peer>
+            URLError,
+            ConnectionResetError,
+            RemoteDisconnected,
+        ],
+    ):
+        super().__init__(max_retry_count, interval_calculator)
+        self.error_types_to_do_retries = error_types
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        if error is None:
+            return False
+
+        if isinstance(error, URLError):
+            if response is not None:
+                return False  # status 40x
+
+        for error_type in self.error_types_to_do_retries:
+            if isinstance(error, error_type):
+                return True
+        return False
+
+

RetryHandler that does retries for connectivity issues.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+ +

Inherited members

+ +
+
+class RateLimitErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class RateLimitErrorRetryHandler(RetryHandler):
+    """RetryHandler that does retries for rate limited errors."""
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        return response is not None and response.status_code == 429
+
+    def prepare_for_next_attempt(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> None:
+        if response is None:
+            raise error  # type: ignore[misc]
+
+        state.next_attempt_requested = True
+        retry_after_header_name: Optional[str] = None
+        for k in response.headers.keys():
+            if k.lower() == "retry-after":
+                retry_after_header_name = k
+                break
+        duration = 1
+        if retry_after_header_name is None:
+            # This situation usually does not arise. Just in case.
+            duration += random.random()  # type: ignore[assignment]
+        else:
+            duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[index, assignment] # noqa: E501
+        time.sleep(duration)
+        state.increment_current_attempt()
+
+

RetryHandler that does retries for rate limited errors.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+ +

Methods

+
+
+def prepare_for_next_attempt(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β None
+
+
+
+ +Expand source code + +
def prepare_for_next_attempt(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> None:
+    if response is None:
+        raise error  # type: ignore[misc]
+
+    state.next_attempt_requested = True
+    retry_after_header_name: Optional[str] = None
+    for k in response.headers.keys():
+        if k.lower() == "retry-after":
+            retry_after_header_name = k
+            break
+    duration = 1
+    if retry_after_header_name is None:
+        # This situation usually does not arise. Just in case.
+        duration += random.random()  # type: ignore[assignment]
+    else:
+        duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[index, assignment] # noqa: E501
+    time.sleep(duration)
+    state.increment_current_attempt()
+
+
+
+
+

Inherited members

+ +
+
+class ServerErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class ServerErrorRetryHandler(RetryHandler):
+    """RetryHandler that does retries for server errors."""
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+    ):
+        super().__init__(max_retry_count, interval_calculator)
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        return response is not None and response.status_code in [500, 503]
+
+

RetryHandler that does retries for server errors.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+ +

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/builtin_interval_calculators.html b/docs/reference/http_retry/builtin_interval_calculators.html new file mode 100644 index 000000000..cfa90cc7c --- /dev/null +++ b/docs/reference/http_retry/builtin_interval_calculators.html @@ -0,0 +1,204 @@ + + + + + + +slack_sdk.http_retry.builtin_interval_calculators API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.builtin_interval_calculators

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class BackoffRetryIntervalCalculator +(backoff_factor:Β floatΒ =Β 0.5,
jitter:Β JitterΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class BackoffRetryIntervalCalculator(RetryIntervalCalculator):
+    """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+    see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+    """
+
+    backoff_factor: float
+    jitter: Jitter
+
+    def __init__(self, backoff_factor: float = 0.5, jitter: Optional[Jitter] = None):
+        """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+
+        Args:
+            backoff_factor: The factor for the backoff interval calculation
+            jitter: The jitter logic implementation
+        """
+        self.backoff_factor = backoff_factor
+        self.jitter = jitter if jitter is not None else RandomJitter()
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        interval = self.backoff_factor * (2 ** (current_attempt))
+        sleep_duration = self.jitter.recalculate(interval)
+        return sleep_duration
+
+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter +see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter

+

Args

+
+
backoff_factor
+
The factor for the backoff interval calculation
+
jitter
+
The jitter logic implementation
+
+

Ancestors

+ +

Class variables

+
+
var backoff_factor :Β float
+
+

The type of the None singleton.

+
+
var jitter :Β Jitter
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FixedValueRetryIntervalCalculator +(fixed_internal:Β floatΒ =Β 0.5) +
+
+
+ +Expand source code + +
class FixedValueRetryIntervalCalculator(RetryIntervalCalculator):
+    """Retry interval calculator that uses a fixed value."""
+
+    fixed_interval: float
+
+    def __init__(self, fixed_internal: float = 0.5):
+        """Retry interval calculator that uses a fixed value.
+
+        Args:
+            fixed_internal: The fixed interval seconds
+        """
+        self.fixed_interval = fixed_internal
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        return self.fixed_interval
+
+

Retry interval calculator that uses a fixed value.

+

Retry interval calculator that uses a fixed value.

+

Args

+
+
fixed_internal
+
The fixed interval seconds
+
+

Ancestors

+ +

Class variables

+
+
var fixed_interval :Β float
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/handler.html b/docs/reference/http_retry/handler.html new file mode 100644 index 000000000..8f4cb0f08 --- /dev/null +++ b/docs/reference/http_retry/handler.html @@ -0,0 +1,237 @@ + + + + + + +slack_sdk.http_retry.handler API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.handler

+
+
+

RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class RetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class RetryHandler:
+    """RetryHandler interface.
+    You can pass an array of handlers to customize retry logics in supported API clients.
+    """
+
+    max_retry_count: int
+    interval_calculator: RetryIntervalCalculator
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+    ):
+        """RetryHandler interface.
+
+        Args:
+            max_retry_count: The maximum times to do retries
+            interval_calculator: Pass an interval calculator for customizing the logic
+        """
+        self.max_retry_count = max_retry_count
+        self.interval_calculator = interval_calculator
+
+    def can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        if state.current_attempt >= self.max_retry_count:
+            return False
+        return self._can_retry(
+            state=state,
+            request=request,
+            response=response,
+            error=error,
+        )
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        raise NotImplementedError()
+
+    def prepare_for_next_attempt(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> None:
+        state.next_attempt_requested = True
+        duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt)
+        time.sleep(duration)
+        state.increment_current_attempt()
+
+

RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Subclasses

+ +

Class variables

+
+
var interval_calculator :Β RetryIntervalCalculator
+
+

The type of the None singleton.

+
+
var max_retry_count :Β int
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def can_retry(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β bool
+
+
+
+ +Expand source code + +
def can_retry(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> bool:
+    if state.current_attempt >= self.max_retry_count:
+        return False
+    return self._can_retry(
+        state=state,
+        request=request,
+        response=response,
+        error=error,
+    )
+
+
+
+
+def prepare_for_next_attempt(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β None
+
+
+
+ +Expand source code + +
def prepare_for_next_attempt(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> None:
+    state.next_attempt_requested = True
+    duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt)
+    time.sleep(duration)
+    state.increment_current_attempt()
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/index.html b/docs/reference/http_retry/index.html new file mode 100644 index 000000000..501a62c9e --- /dev/null +++ b/docs/reference/http_retry/index.html @@ -0,0 +1,1000 @@ + + + + + + +slack_sdk.http_retry API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry

+
+
+
+
+

Sub-modules

+
+
slack_sdk.http_retry.async_handler
+
+

asyncio compatible RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+
+
slack_sdk.http_retry.builtin_async_handlers
+
+
+
+
slack_sdk.http_retry.builtin_handlers
+
+
+
+
slack_sdk.http_retry.builtin_interval_calculators
+
+
+
+
slack_sdk.http_retry.handler
+
+

RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+
+
slack_sdk.http_retry.interval_calculator
+
+
+
+
slack_sdk.http_retry.jitter
+
+
+
+
slack_sdk.http_retry.request
+
+
+
+
slack_sdk.http_retry.response
+
+
+
+
slack_sdk.http_retry.state
+
+
+
+
+
+
+
+
+

Functions

+
+
+def all_builtin_retry_handlers() ‑>Β List[RetryHandler] +
+
+
+ +Expand source code + +
def all_builtin_retry_handlers() -> List[RetryHandler]:
+    return [
+        connect_error_retry_handler,
+        rate_limit_error_retry_handler,
+    ]
+
+
+
+
+def default_retry_handlers() ‑>Β List[RetryHandler] +
+
+
+ +Expand source code + +
def default_retry_handlers() -> List[RetryHandler]:
+    return [connect_error_retry_handler]
+
+
+
+
+
+
+

Classes

+
+
+class BackoffRetryIntervalCalculator +(backoff_factor:Β floatΒ =Β 0.5,
jitter:Β JitterΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class BackoffRetryIntervalCalculator(RetryIntervalCalculator):
+    """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+    see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+    """
+
+    backoff_factor: float
+    jitter: Jitter
+
+    def __init__(self, backoff_factor: float = 0.5, jitter: Optional[Jitter] = None):
+        """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter
+
+        Args:
+            backoff_factor: The factor for the backoff interval calculation
+            jitter: The jitter logic implementation
+        """
+        self.backoff_factor = backoff_factor
+        self.jitter = jitter if jitter is not None else RandomJitter()
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        interval = self.backoff_factor * (2 ** (current_attempt))
+        sleep_duration = self.jitter.recalculate(interval)
+        return sleep_duration
+
+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter +see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

+

Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter

+

Args

+
+
backoff_factor
+
The factor for the backoff interval calculation
+
jitter
+
The jitter logic implementation
+
+

Ancestors

+ +

Class variables

+
+
var backoff_factor :Β float
+
+

The type of the None singleton.

+
+
var jitter :Β Jitter
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ConnectionErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>,
error_types:Β List[Type[Exception]]Β =Β [<class 'urllib.error.URLError'>, <class 'ConnectionResetError'>, <class 'http.client.RemoteDisconnected'>])
+
+
+
+ +Expand source code + +
class ConnectionErrorRetryHandler(RetryHandler):
+    """RetryHandler that does retries for connectivity issues."""
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+        error_types: List[Type[Exception]] = [
+            # To cover URLError: <urlopen error [Errno 104] Connection reset by peer>
+            URLError,
+            ConnectionResetError,
+            RemoteDisconnected,
+        ],
+    ):
+        super().__init__(max_retry_count, interval_calculator)
+        self.error_types_to_do_retries = error_types
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        if error is None:
+            return False
+
+        if isinstance(error, URLError):
+            if response is not None:
+                return False  # status 40x
+
+        for error_type in self.error_types_to_do_retries:
+            if isinstance(error, error_type):
+                return True
+        return False
+
+

RetryHandler that does retries for connectivity issues.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+ +

Inherited members

+ +
+
+class FixedValueRetryIntervalCalculator +(fixed_internal:Β floatΒ =Β 0.5) +
+
+
+ +Expand source code + +
class FixedValueRetryIntervalCalculator(RetryIntervalCalculator):
+    """Retry interval calculator that uses a fixed value."""
+
+    fixed_interval: float
+
+    def __init__(self, fixed_internal: float = 0.5):
+        """Retry interval calculator that uses a fixed value.
+
+        Args:
+            fixed_internal: The fixed interval seconds
+        """
+        self.fixed_interval = fixed_internal
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        return self.fixed_interval
+
+

Retry interval calculator that uses a fixed value.

+

Retry interval calculator that uses a fixed value.

+

Args

+
+
fixed_internal
+
The fixed interval seconds
+
+

Ancestors

+ +

Class variables

+
+
var fixed_interval :Β float
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class HttpRequest +(*,
method:Β str,
url:Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpRequest:
+    """HTTP request representation"""
+
+    method: str
+    url: str
+    headers: Dict[str, Union[str, List[str]]]
+    body_params: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        method: str,
+        url: str,
+        headers: Dict[str, Union[str, List[str]]],
+        body_params: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.method = method
+        self.url = url
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body_params = body_params
+        self.data = data
+
+    @classmethod
+    def from_urllib_http_request(cls, req: Request) -> "HttpRequest":
+        return HttpRequest(
+            method=req.method,  # type: ignore[arg-type]
+            url=req.full_url,
+            headers={k: v if isinstance(v, list) else [v] for k, v in req.headers.items()},
+            data=req.data,  # type: ignore[arg-type]
+        )
+
+

HTTP request representation

+

Class variables

+
+
var body_params :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var method :Β str
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_urllib_http_request(req:Β urllib.request.Request) ‑>Β HttpRequest +
+
+
+
+
+
+
+class HttpResponse +(*,
status_code:Β intΒ |Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpResponse:
+    """HTTP response representation"""
+
+    status_code: int
+    headers: Dict[str, Union[List[str], str]]
+    body: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        status_code: Union[int, str],
+        headers: Dict[str, Union[str, List[str]]],
+        body: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.status_code = int(status_code)
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body = body
+        self.data = data
+
+

HTTP response representation

+

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
+
+
+class Jitter +
+
+
+ +Expand source code + +
class Jitter:
+    """Jitter interface"""
+
+    def recalculate(self, duration: float) -> float:
+        """Recalculate the given duration.
+        see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+
+        Args:
+            duration: the duration in seconds
+
+        Returns:
+            A new duration that the jitter amount is added
+        """
+        raise NotImplementedError()
+
+

Jitter interface

+

Subclasses

+ +

Methods

+
+
+def recalculate(self, duration:Β float) ‑>Β float +
+
+
+ +Expand source code + +
def recalculate(self, duration: float) -> float:
+    """Recalculate the given duration.
+    see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+
+    Args:
+        duration: the duration in seconds
+
+    Returns:
+        A new duration that the jitter amount is added
+    """
+    raise NotImplementedError()
+
+

Recalculate the given duration. +see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

+

Args

+
+
duration
+
the duration in seconds
+
+

Returns

+

A new duration that the jitter amount is added

+
+
+
+
+class RateLimitErrorRetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class RateLimitErrorRetryHandler(RetryHandler):
+    """RetryHandler that does retries for rate limited errors."""
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        return response is not None and response.status_code == 429
+
+    def prepare_for_next_attempt(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> None:
+        if response is None:
+            raise error  # type: ignore[misc]
+
+        state.next_attempt_requested = True
+        retry_after_header_name: Optional[str] = None
+        for k in response.headers.keys():
+            if k.lower() == "retry-after":
+                retry_after_header_name = k
+                break
+        duration = 1
+        if retry_after_header_name is None:
+            # This situation usually does not arise. Just in case.
+            duration += random.random()  # type: ignore[assignment]
+        else:
+            duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[index, assignment] # noqa: E501
+        time.sleep(duration)
+        state.increment_current_attempt()
+
+

RetryHandler that does retries for rate limited errors.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Ancestors

+ +

Methods

+
+
+def prepare_for_next_attempt(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β None
+
+
+
+ +Expand source code + +
def prepare_for_next_attempt(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> None:
+    if response is None:
+        raise error  # type: ignore[misc]
+
+    state.next_attempt_requested = True
+    retry_after_header_name: Optional[str] = None
+    for k in response.headers.keys():
+        if k.lower() == "retry-after":
+            retry_after_header_name = k
+            break
+    duration = 1
+    if retry_after_header_name is None:
+        # This situation usually does not arise. Just in case.
+        duration += random.random()  # type: ignore[assignment]
+    else:
+        duration = int(response.headers.get(retry_after_header_name)[0]) + random.random()  # type: ignore[index, assignment] # noqa: E501
+    time.sleep(duration)
+    state.increment_current_attempt()
+
+
+
+
+

Inherited members

+ +
+
+class RetryHandler +(max_retry_count:Β intΒ =Β 1,
interval_calculator:Β RetryIntervalCalculatorΒ =Β <slack_sdk.http_retry.builtin_interval_calculators.BackoffRetryIntervalCalculator object>)
+
+
+
+ +Expand source code + +
class RetryHandler:
+    """RetryHandler interface.
+    You can pass an array of handlers to customize retry logics in supported API clients.
+    """
+
+    max_retry_count: int
+    interval_calculator: RetryIntervalCalculator
+
+    def __init__(
+        self,
+        max_retry_count: int = 1,
+        interval_calculator: RetryIntervalCalculator = default_interval_calculator,
+    ):
+        """RetryHandler interface.
+
+        Args:
+            max_retry_count: The maximum times to do retries
+            interval_calculator: Pass an interval calculator for customizing the logic
+        """
+        self.max_retry_count = max_retry_count
+        self.interval_calculator = interval_calculator
+
+    def can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        if state.current_attempt >= self.max_retry_count:
+            return False
+        return self._can_retry(
+            state=state,
+            request=request,
+            response=response,
+            error=error,
+        )
+
+    def _can_retry(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> bool:
+        raise NotImplementedError()
+
+    def prepare_for_next_attempt(
+        self,
+        *,
+        state: RetryState,
+        request: HttpRequest,
+        response: Optional[HttpResponse] = None,
+        error: Optional[Exception] = None,
+    ) -> None:
+        state.next_attempt_requested = True
+        duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt)
+        time.sleep(duration)
+        state.increment_current_attempt()
+
+

RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients.

+

RetryHandler interface.

+

Args

+
+
max_retry_count
+
The maximum times to do retries
+
interval_calculator
+
Pass an interval calculator for customizing the logic
+
+

Subclasses

+ +

Class variables

+
+
var interval_calculator :Β RetryIntervalCalculator
+
+

The type of the None singleton.

+
+
var max_retry_count :Β int
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def can_retry(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β bool
+
+
+
+ +Expand source code + +
def can_retry(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> bool:
+    if state.current_attempt >= self.max_retry_count:
+        return False
+    return self._can_retry(
+        state=state,
+        request=request,
+        response=response,
+        error=error,
+    )
+
+
+
+
+def prepare_for_next_attempt(self,
*,
state:Β RetryState,
request:Β HttpRequest,
response:Β HttpResponseΒ |Β NoneΒ =Β None,
error:Β ExceptionΒ |Β NoneΒ =Β None) ‑>Β None
+
+
+
+ +Expand source code + +
def prepare_for_next_attempt(
+    self,
+    *,
+    state: RetryState,
+    request: HttpRequest,
+    response: Optional[HttpResponse] = None,
+    error: Optional[Exception] = None,
+) -> None:
+    state.next_attempt_requested = True
+    duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt)
+    time.sleep(duration)
+    state.increment_current_attempt()
+
+
+
+
+
+
+class RetryIntervalCalculator +
+
+
+ +Expand source code + +
class RetryIntervalCalculator:
+    """Retry interval calculator interface."""
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        """Calculates an interval duration in seconds.
+
+        Args:
+            current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+        Returns:
+            calculated interval duration in seconds
+        """
+        raise NotImplementedError()
+
+

Retry interval calculator interface.

+

Subclasses

+ +

Methods

+
+
+def calculate_sleep_duration(self, current_attempt:Β int) ‑>Β float +
+
+
+ +Expand source code + +
def calculate_sleep_duration(self, current_attempt: int) -> float:
+    """Calculates an interval duration in seconds.
+
+    Args:
+        current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+    Returns:
+        calculated interval duration in seconds
+    """
+    raise NotImplementedError()
+
+

Calculates an interval duration in seconds.

+

Args

+
+
current_attempt
+
the number of the current attempt (zero-origin; 0 means no retries are done so far)
+
+

Returns

+

calculated interval duration in seconds

+
+
+
+
+class RetryState +(*, current_attempt:Β intΒ =Β 0, custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class RetryState:
+    next_attempt_requested: bool
+    current_attempt: int  # zero-origin
+    custom_values: Optional[Dict[str, Any]]
+
+    def __init__(
+        self,
+        *,
+        current_attempt: int = 0,
+        custom_values: Optional[Dict[str, Any]] = None,
+    ):
+        self.next_attempt_requested = False
+        self.current_attempt = current_attempt
+        self.custom_values = custom_values
+
+    def increment_current_attempt(self) -> int:
+        self.current_attempt += 1
+        return self.current_attempt
+
+
+

Class variables

+
+
var current_attempt :Β int
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var next_attempt_requested :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def increment_current_attempt(self) ‑>Β int +
+
+
+ +Expand source code + +
def increment_current_attempt(self) -> int:
+    self.current_attempt += 1
+    return self.current_attempt
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/interval_calculator.html b/docs/reference/http_retry/interval_calculator.html new file mode 100644 index 000000000..938799629 --- /dev/null +++ b/docs/reference/http_retry/interval_calculator.html @@ -0,0 +1,137 @@ + + + + + + +slack_sdk.http_retry.interval_calculator API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.interval_calculator

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RetryIntervalCalculator +
+
+
+ +Expand source code + +
class RetryIntervalCalculator:
+    """Retry interval calculator interface."""
+
+    def calculate_sleep_duration(self, current_attempt: int) -> float:
+        """Calculates an interval duration in seconds.
+
+        Args:
+            current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+        Returns:
+            calculated interval duration in seconds
+        """
+        raise NotImplementedError()
+
+

Retry interval calculator interface.

+

Subclasses

+ +

Methods

+
+
+def calculate_sleep_duration(self, current_attempt:Β int) ‑>Β float +
+
+
+ +Expand source code + +
def calculate_sleep_duration(self, current_attempt: int) -> float:
+    """Calculates an interval duration in seconds.
+
+    Args:
+        current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far)
+    Returns:
+        calculated interval duration in seconds
+    """
+    raise NotImplementedError()
+
+

Calculates an interval duration in seconds.

+

Args

+
+
current_attempt
+
the number of the current attempt (zero-origin; 0 means no retries are done so far)
+
+

Returns

+

calculated interval duration in seconds

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/jitter.html b/docs/reference/http_retry/jitter.html new file mode 100644 index 000000000..0268d2cce --- /dev/null +++ b/docs/reference/http_retry/jitter.html @@ -0,0 +1,172 @@ + + + + + + +slack_sdk.http_retry.jitter API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.jitter

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Jitter +
+
+
+ +Expand source code + +
class Jitter:
+    """Jitter interface"""
+
+    def recalculate(self, duration: float) -> float:
+        """Recalculate the given duration.
+        see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+
+        Args:
+            duration: the duration in seconds
+
+        Returns:
+            A new duration that the jitter amount is added
+        """
+        raise NotImplementedError()
+
+

Jitter interface

+

Subclasses

+ +

Methods

+
+
+def recalculate(self, duration:Β float) ‑>Β float +
+
+
+ +Expand source code + +
def recalculate(self, duration: float) -> float:
+    """Recalculate the given duration.
+    see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/
+
+    Args:
+        duration: the duration in seconds
+
+    Returns:
+        A new duration that the jitter amount is added
+    """
+    raise NotImplementedError()
+
+

Recalculate the given duration. +see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/

+

Args

+
+
duration
+
the duration in seconds
+
+

Returns

+

A new duration that the jitter amount is added

+
+
+
+
+class RandomJitter +
+
+
+ +Expand source code + +
class RandomJitter(Jitter):
+    """Random jitter implementation"""
+
+    def recalculate(self, duration: float) -> float:
+        return duration + random.random()
+
+

Random jitter implementation

+

Ancestors

+ +

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/request.html b/docs/reference/http_retry/request.html new file mode 100644 index 000000000..e088c7443 --- /dev/null +++ b/docs/reference/http_retry/request.html @@ -0,0 +1,160 @@ + + + + + + +slack_sdk.http_retry.request API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.request

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HttpRequest +(*,
method:Β str,
url:Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpRequest:
+    """HTTP request representation"""
+
+    method: str
+    url: str
+    headers: Dict[str, Union[str, List[str]]]
+    body_params: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        method: str,
+        url: str,
+        headers: Dict[str, Union[str, List[str]]],
+        body_params: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.method = method
+        self.url = url
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body_params = body_params
+        self.data = data
+
+    @classmethod
+    def from_urllib_http_request(cls, req: Request) -> "HttpRequest":
+        return HttpRequest(
+            method=req.method,  # type: ignore[arg-type]
+            url=req.full_url,
+            headers={k: v if isinstance(v, list) else [v] for k, v in req.headers.items()},
+            data=req.data,  # type: ignore[arg-type]
+        )
+
+

HTTP request representation

+

Class variables

+
+
var body_params :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var method :Β str
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_urllib_http_request(req:Β urllib.request.Request) ‑>Β HttpRequest +
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/response.html b/docs/reference/http_retry/response.html new file mode 100644 index 000000000..4a786ab78 --- /dev/null +++ b/docs/reference/http_retry/response.html @@ -0,0 +1,133 @@ + + + + + + +slack_sdk.http_retry.response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.response

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class HttpResponse +(*,
status_code:Β intΒ |Β str,
headers:Β Dict[str,Β strΒ |Β List[str]],
body:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
data:Β bytesΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class HttpResponse:
+    """HTTP response representation"""
+
+    status_code: int
+    headers: Dict[str, Union[List[str], str]]
+    body: Optional[Dict[str, Any]]
+    data: Optional[bytes]
+
+    def __init__(
+        self,
+        *,
+        status_code: Union[int, str],
+        headers: Dict[str, Union[str, List[str]]],
+        body: Optional[Dict[str, Any]] = None,
+        data: Optional[bytes] = None,
+    ):
+        self.status_code = int(status_code)
+        self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()}
+        self.body = body
+        self.data = data
+
+

HTTP response representation

+

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var data :Β bytesΒ |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β strΒ |Β List[str]]
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/http_retry/state.html b/docs/reference/http_retry/state.html new file mode 100644 index 000000000..3096592cc --- /dev/null +++ b/docs/reference/http_retry/state.html @@ -0,0 +1,144 @@ + + + + + + +slack_sdk.http_retry.state API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.http_retry.state

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RetryState +(*, current_attempt:Β intΒ =Β 0, custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class RetryState:
+    next_attempt_requested: bool
+    current_attempt: int  # zero-origin
+    custom_values: Optional[Dict[str, Any]]
+
+    def __init__(
+        self,
+        *,
+        current_attempt: int = 0,
+        custom_values: Optional[Dict[str, Any]] = None,
+    ):
+        self.next_attempt_requested = False
+        self.current_attempt = current_attempt
+        self.custom_values = custom_values
+
+    def increment_current_attempt(self) -> int:
+        self.current_attempt += 1
+        return self.current_attempt
+
+
+

Class variables

+
+
var current_attempt :Β int
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var next_attempt_requested :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def increment_current_attempt(self) ‑>Β int +
+
+
+ +Expand source code + +
def increment_current_attempt(self) -> int:
+    self.current_attempt += 1
+    return self.current_attempt
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/index.html b/docs/reference/index.html new file mode 100644 index 000000000..7cc7723c1 --- /dev/null +++ b/docs/reference/index.html @@ -0,0 +1,16366 @@ + + + + + + +slack_sdk API documentation + + + + + + + + + + + +
+
+
+

Package slack_sdk

+
+
+ +

Here is the list of key modules in this SDK:

+

Web API Client

+ +

Webhook / response_url Client

+ +

Socket Mode Client

+ +

OAuth

+ +

Audit Logs API Client

+ +

SCIM API Client

+ +
+
+

Sub-modules

+
+
slack_sdk.aiohttp_version_checker
+
+

Internal module for checking aiohttp compatibility of async modules

+
+
slack_sdk.audit_logs
+
+

Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization …

+
+
slack_sdk.errors
+
+

Errors that can be raised by this SDK

+
+
slack_sdk.http_retry
+
+
+
+
slack_sdk.models
+
+

Classes for constructing Slack-specific data structure

+
+
slack_sdk.oauth
+
+

Modules for implementing the Slack OAuth flow …

+
+
slack_sdk.proxy_env_variable_loader
+
+

Internal module for loading proxy-related env variables

+
+
slack_sdk.rtm
+
+

A Python module for interacting with Slack's RTM API.

+
+
slack_sdk.rtm_v2
+
+

A Python module for interacting with Slack's RTM API.

+
+
slack_sdk.scim
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers …

+
+
slack_sdk.signature
+
+

Slack request signature verifier

+
+
slack_sdk.socket_mode
+
+

Socket Mode is a method of connecting your app to Slack’s APIs using WebSockets instead of HTTP. +You can use slack_sdk.socket_mode.SocketModeClient …

+
+
slack_sdk.version
+
+

Check the latest version at https://pypi.org/project/slack-sdk/

+
+
slack_sdk.web
+
+

The Slack Web API allows you to build applications that interact with Slack +in more complex ways than the integrations we provide out of the box.

+
+
slack_sdk.webhook
+
+

You can use slack_sdk.webhook.WebhookClient for Incoming Webhooks +and message responses using response_url in payloads.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class WebClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebClient(BaseClient):
+    """A WebClient allows apps to communicate with the Slack Platform's Web API.
+
+    https://docs.slack.dev/reference/methods
+
+    The Slack Web API is an interface for querying information from
+    and enacting change in a Slack workspace.
+
+    This client handles constructing and sending HTTP requests to Slack
+    as well as parsing any responses received into a `SlackResponse`.
+
+    Attributes:
+        token (str): A string specifying an `xoxp-*` or `xoxb-*` token.
+        base_url (str): A string representing the Slack API base URL.
+            Default is `'https://slack.com/api/'`
+        timeout (int): The maximum number of seconds the client will wait
+            to connect and receive a response from Slack.
+            Default is 30 seconds.
+        ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying
+            your own custom certificate chain.
+        proxy (str): String representing a fully-qualified URL to a proxy through
+            which to route all requests to the Slack API. Even if this parameter
+            is not specified, if any of the following environment variables are
+            present, they will be loaded into this parameter: `HTTPS_PROXY`,
+            `https_proxy`, `HTTP_PROXY` or `http_proxy`.
+        headers (dict): Additional request headers to attach to all requests.
+
+    Methods:
+        `api_call`: Constructs a request and executes the API call to Slack.
+
+    Example of recommended usage:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.chat_postMessage(
+            channel='#random',
+            text="Hello world!")
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Example manually creating an API request:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.api_call(
+            api_method='chat.postMessage',
+            json={'channel': '#random','text': "Hello world!"}
+        )
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Note:
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+
+    [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
+    """
+
+    def admin_analytics_getFile(
+        self,
+        *,
+        type: str,
+        date: Optional[str] = None,
+        metadata_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve analytics data for a given date, presented as a compressed JSON file
+        https://docs.slack.dev/reference/methods/admin.analytics.getFile
+        """
+        kwargs.update({"type": type})
+        if date is not None:
+            kwargs.update({"date": date})
+        if metadata_only is not None:
+            kwargs.update({"metadata_only": metadata_only})
+        return self.api_call("admin.analytics.getFile", params=kwargs)
+
+    def admin_apps_approve(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve an app for installation on a workspace.
+        Either app_id or request_id is required.
+        These IDs can be obtained either directly via the app_requested event,
+        or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.approve
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approve", params=kwargs)
+
+    def admin_apps_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List approved apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_clearResolution(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear an app resolution
+        https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_cancel(
+        self,
+        *,
+        request_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+        """
+        kwargs.update(
+            {
+                "request_id": request_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_restrict(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Restrict an app for installation on a workspace.
+        Exactly one of the team_id or enterprise_id arguments is required, not both.
+        Either app_id or request_id is required. These IDs can be obtained either directly
+        via the app_requested event, or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.restrict
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restrict", params=kwargs)
+
+    def admin_apps_restricted_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List restricted apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_uninstall(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+        With an org-level token, enterprise_id or team_ids is required.
+        https://docs.slack.dev/reference/methods/admin.apps.uninstall
+        """
+        kwargs.update({"app_id": app_id})
+        if enterprise_id is not None:
+            kwargs.update({"enterprise_id": enterprise_id})
+        if team_ids is not None:
+            if isinstance(team_ids, (list, tuple)):
+                kwargs.update({"team_ids": ",".join(team_ids)})
+            else:
+                kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+    def admin_apps_activities_list(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        component_id: Optional[str] = None,
+        component_type: Optional[str] = None,
+        log_event_type: Optional[str] = None,
+        max_date_created: Optional[int] = None,
+        min_date_created: Optional[int] = None,
+        min_log_level: Optional[str] = None,
+        sort_direction: Optional[str] = None,
+        source: Optional[str] = None,
+        team_id: Optional[str] = None,
+        trace_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get logs for a specified team/org
+        https://docs.slack.dev/reference/methods/admin.apps.activities.list
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "component_id": component_id,
+                "component_type": component_type,
+                "log_event_type": log_event_type,
+                "max_date_created": max_date_created,
+                "min_date_created": min_date_created,
+                "min_log_level": min_log_level,
+                "sort_direction": sort_direction,
+                "source": source,
+                "team_id": team_id,
+                "trace_id": trace_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.apps.activities.list", params=kwargs)
+
+    def admin_apps_config_lookup(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the app config for connectors by their IDs
+        https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+    def admin_apps_config_set(
+        self,
+        *,
+        app_id: str,
+        domain_restrictions: Optional[Dict[str, Any]] = None,
+        workflow_auth_strategy: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the app config for a connector
+        https://docs.slack.dev/reference/methods/admin.apps.config.set
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "workflow_auth_strategy": workflow_auth_strategy,
+            }
+        )
+        if domain_restrictions is not None:
+            kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+        return self.api_call("admin.apps.config.set", params=kwargs)
+
+    def admin_auth_policy_getEntities(
+        self,
+        *,
+        policy_name: str,
+        cursor: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch all the entities assigned to a particular authentication policy by name.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+        """
+        kwargs.update({"policy_name": policy_name})
+        if cursor is not None:
+            kwargs.update({"cursor": cursor})
+        if entity_type is not None:
+            kwargs.update({"entity_type": entity_type})
+        if limit is not None:
+            kwargs.update({"limit": limit})
+        return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_assignEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Assign entities to a particular authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_removeEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove specified entities from a specified authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+    def admin_conversations_createForObjects(
+        self,
+        *,
+        object_id: str,
+        salesforce_org_id: str,
+        invite_object_team: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Salesforce channel for the corresponding object provided.
+        https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+        """
+        kwargs.update(
+            {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+        )
+        return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+    def admin_conversations_linkObjects(
+        self,
+        *,
+        channel: str,
+        record_id: str,
+        salesforce_org_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Link a Salesforce record to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "record_id": record_id,
+                "salesforce_org_id": salesforce_org_id,
+            }
+        )
+        return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+    def admin_conversations_unlinkObjects(
+        self,
+        *,
+        channel: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unlink a Salesforce record from a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "new_name": new_name,
+            }
+        )
+        return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+    def admin_barriers_create(
+        self,
+        *,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.create
+        """
+        kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+    def admin_barriers_delete(
+        self,
+        *,
+        barrier_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.delete
+        """
+        kwargs.update({"barrier_id": barrier_id})
+        return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+    def admin_barriers_update(
+        self,
+        *,
+        barrier_id: str,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.update
+        """
+        kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+    def admin_barriers_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get all Information Barriers for your organization
+        https://docs.slack.dev/reference/methods/admin.barriers.list"""
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+    def admin_conversations_create(
+        self,
+        *,
+        is_private: bool,
+        name: str,
+        description: Optional[str] = None,
+        org_wide: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a public or private channel-based conversation.
+        https://docs.slack.dev/reference/methods/admin.conversations.create
+        """
+        kwargs.update(
+            {
+                "is_private": is_private,
+                "name": name,
+                "description": description,
+                "org_wide": org_wide,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.conversations.create", params=kwargs)
+
+    def admin_conversations_delete(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.delete
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.delete", params=kwargs)
+
+    def admin_conversations_invite(
+        self,
+        *,
+        channel_id: str,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.invite
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+        return self.api_call("admin.conversations.invite", params=kwargs)
+
+    def admin_conversations_archive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.archive", params=kwargs)
+
+    def admin_conversations_unarchive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+    def admin_conversations_rename(
+        self,
+        *,
+        channel_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.rename
+        """
+        kwargs.update({"channel_id": channel_id, "name": name})
+        return self.api_call("admin.conversations.rename", params=kwargs)
+
+    def admin_conversations_search(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        query: Optional[str] = None,
+        search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search for public or private channels in an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.conversations.search
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+            }
+        )
+
+        if isinstance(search_channel_types, (list, tuple)):
+            kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+        else:
+            kwargs.update({"search_channel_types": search_channel_types})
+
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+
+        return self.api_call("admin.conversations.search", params=kwargs)
+
+    def admin_conversations_convertToPrivate(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a public channel to a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+    def admin_conversations_convertToPublic(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a privte channel to a public channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+    def admin_conversations_setConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        prefs: Union[str, Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the posting permissions for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(prefs, dict):
+            kwargs.update({"prefs": json.dumps(prefs)})
+        else:
+            kwargs.update({"prefs": prefs})
+        return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+    def admin_conversations_getConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get conversation preferences for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+    def admin_conversations_disconnectShared(
+        self,
+        *,
+        channel_id: str,
+        leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnect a connected channel from one or more workspaces.
+        https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(leaving_team_ids, (list, tuple)):
+            kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+        else:
+            kwargs.update({"leaving_team_ids": leaving_team_ids})
+        return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+    def admin_conversations_lookup(
+        self,
+        *,
+        last_message_activity_before: int,
+        team_ids: Union[str, Sequence[str]],
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        max_member_count: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns channels on the given team using the filters.
+        https://docs.slack.dev/reference/methods/admin.conversations.lookup
+        """
+        kwargs.update(
+            {
+                "last_message_activity_before": last_message_activity_before,
+                "cursor": cursor,
+                "limit": limit,
+                "max_member_count": max_member_count,
+            }
+        )
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.lookup", params=kwargs)
+
+    def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+        self,
+        *,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all disconnected channelsβ€”i.e.,
+        channels that were once connected to other workspaces and then disconnectedβ€”and
+        the corresponding original channel IDs for key revocation with EKM.
+        https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+    def admin_conversations_restrictAccess_addGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an allowlist of IDP groups for accessing a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.addGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_listGroups(
+        self,
+        *,
+        channel_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all IDP Groups linked to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.listGroups",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_removeGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a linked IDP group linked from a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.removeGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_setTeams(
+        self,
+        *,
+        channel_id: str,
+        org_channel: Optional[bool] = None,
+        target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "org_channel": org_channel,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(target_team_ids, (list, tuple)):
+            kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+        else:
+            kwargs.update({"target_team_ids": target_team_ids})
+        return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+    def admin_conversations_getTeams(
+        self,
+        *,
+        channel_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+    def admin_conversations_getCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+    def admin_conversations_removeCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+    def admin_conversations_setCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        duration_days: int,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+        return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+    def admin_conversations_bulkArchive(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+    def admin_conversations_bulkDelete(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete public or private channels in bulk.
+        https://slack.com/api/admin.conversations.bulkDelete
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+    def admin_conversations_bulkMove(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        target_team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Move public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+        """
+        kwargs.update(
+            {
+                "target_team_id": target_team_id,
+                "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+            }
+        )
+        return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+    def admin_emoji_add(
+        self,
+        *,
+        name: str,
+        url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.add
+        """
+        kwargs.update({"name": name, "url": url})
+        return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+    def admin_emoji_addAlias(
+        self,
+        *,
+        alias_for: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji alias.
+        https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+        """
+        kwargs.update({"alias_for": alias_for, "name": name})
+        return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+    def admin_emoji_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List emoji for an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+    def admin_emoji_remove(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove an emoji across an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.remove
+        """
+        kwargs.update({"name": name})
+        return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+    def admin_emoji_rename(
+        self,
+        *,
+        name: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.rename
+        """
+        kwargs.update({"name": name, "new_name": new_name})
+        return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+    def admin_functions_list(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up functions by a set of apps
+        https://docs.slack.dev/reference/methods/admin.functions.list
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.functions.list", params=kwargs)
+
+    def admin_functions_permissions_lookup(
+        self,
+        *,
+        function_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup the visibility of multiple Slack functions
+        and include the users if it is limited to particular named entities.
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+        """
+        if isinstance(function_ids, (list, tuple)):
+            kwargs.update({"function_ids": ",".join(function_ids)})
+        else:
+            kwargs.update({"function_ids": function_ids})
+        return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+    def admin_functions_permissions_set(
+        self,
+        *,
+        function_id: str,
+        visibility: str,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the visibility of a Slack function
+        and define the users or workspaces if it is set to named_entities
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+        """
+        kwargs.update(
+            {
+                "function_id": function_id,
+                "visibility": visibility,
+            }
+        )
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+    def admin_roles_addAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds members to the specified role with the specified scopes
+        https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+    def admin_roles_listAssignments(
+        self,
+        *,
+        role_ids: Optional[Union[str, Sequence[str]]] = None,
+        entity_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[Union[str, int]] = None,
+        sort_dir: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists assignments for all roles across entities.
+            Options to scope results by any combination of roles or entities
+        https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(role_ids, (list, tuple)):
+            kwargs.update({"role_ids": ",".join(role_ids)})
+        else:
+            kwargs.update({"role_ids": role_ids})
+        return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+    def admin_roles_removeAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a set of users from a role for the given scopes and entities
+        https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+    def admin_users_session_reset(
+        self,
+        *,
+        user_id: str,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Wipes all valid sessions on all devices for a given user.
+        https://docs.slack.dev/reference/methods/admin.users.session.reset
+        """
+        kwargs.update(
+            {
+                "user_id": user_id,
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.reset", params=kwargs)
+
+    def admin_users_session_resetBulk(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+        https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+    def admin_users_session_invalidate(
+        self,
+        *,
+        session_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invalidate a single session for a user by session_id.
+        https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+        """
+        kwargs.update({"session_id": session_id, "team_id": team_id})
+        return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+    def admin_users_session_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all active user sessions for an organization
+        https://docs.slack.dev/reference/methods/admin.users.session.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+                "user_id": user_id,
+            }
+        )
+        return self.api_call("admin.users.session.list", params=kwargs)
+
+    def admin_teams_settings_setDefaultChannels(
+        self,
+        *,
+        team_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the default channels of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+        """
+        kwargs.update({"team_id": team_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+    def admin_users_session_getSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Get user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”given a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+    def admin_users_session_setSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        desktop_app_browser_quit: Optional[bool] = None,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Configure the user-level session settingsβ€”the session duration
+        and what happens when the client closesβ€”for one or more users.
+        https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "desktop_app_browser_quit": desktop_app_browser_quit,
+                "duration": duration,
+            }
+        )
+        return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+    def admin_users_session_clearSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”for a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+    def admin_users_unsupportedVersions_export(
+        self,
+        *,
+        date_end_of_support: Optional[Union[str, int]] = None,
+        date_sessions_started: Optional[Union[str, int]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+        presented as a zipped CSV file.
+        https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+        """
+        kwargs.update(
+            {
+                "date_end_of_support": date_end_of_support,
+                "date_sessions_started": date_sessions_started,
+            }
+        )
+        return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+    def admin_inviteRequests_approve(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+    def admin_inviteRequests_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all approved workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+    def admin_inviteRequests_denied_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all denied workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+    def admin_inviteRequests_deny(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+    def admin_inviteRequests_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all pending workspace invite requests."""
+        return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+    def admin_teams_admins_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_create(
+        self,
+        *,
+        team_domain: str,
+        team_name: str,
+        team_description: Optional[str] = None,
+        team_discoverability: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Enterprise team.
+        https://docs.slack.dev/reference/methods/admin.teams.create
+        """
+        kwargs.update(
+            {
+                "team_domain": team_domain,
+                "team_name": team_name,
+                "team_description": team_description,
+                "team_discoverability": team_discoverability,
+            }
+        )
+        return self.api_call("admin.teams.create", params=kwargs)
+
+    def admin_teams_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all teams on an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.list", params=kwargs)
+
+    def admin_teams_owners_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.owners.list
+        """
+        kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_info(
+        self,
+        *,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch information about settings in a workspace
+        https://docs.slack.dev/reference/methods/admin.teams.settings.info
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("admin.teams.settings.info", params=kwargs)
+
+    def admin_teams_settings_setDescription(
+        self,
+        *,
+        team_id: str,
+        description: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the description of a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+        """
+        kwargs.update({"team_id": team_id, "description": description})
+        return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+    def admin_teams_settings_setDiscoverability(
+        self,
+        *,
+        team_id: str,
+        discoverability: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+        """
+        kwargs.update({"team_id": team_id, "discoverability": discoverability})
+        return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+    def admin_teams_settings_setIcon(
+        self,
+        *,
+        team_id: str,
+        image_url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+        """
+        kwargs.update({"team_id": team_id, "image_url": image_url})
+        return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_setName(
+        self,
+        *,
+        team_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+        """
+        kwargs.update({"team_id": team_id, "name": name})
+        return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+    def admin_usergroups_addChannels(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        usergroup_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+        """
+        kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+    def admin_usergroups_addTeams(
+        self,
+        *,
+        usergroup_id: str,
+        team_ids: Union[str, Sequence[str]],
+        auto_provision: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Associate one or more default workspaces with an organization-wide IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+        """
+        kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+    def admin_usergroups_listChannels(
+        self,
+        *,
+        usergroup_id: str,
+        include_num_members: Optional[bool] = None,
+        team_id: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+        """
+        kwargs.update(
+            {
+                "usergroup_id": usergroup_id,
+                "include_num_members": include_num_members,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+    def admin_usergroups_removeChannels(
+        self,
+        *,
+        usergroup_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+        """
+        kwargs.update({"usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+    def admin_users_assign(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an Enterprise user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.assign
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "user_id": user_id,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.assign", params=kwargs)
+
+    def admin_users_invite(
+        self,
+        *,
+        team_id: str,
+        email: str,
+        channel_ids: Union[str, Sequence[str]],
+        custom_message: Optional[str] = None,
+        email_password_policy_enabled: Optional[bool] = None,
+        guest_expiration_ts: Optional[Union[str, float]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        real_name: Optional[str] = None,
+        resend: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.invite
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "email": email,
+                "custom_message": custom_message,
+                "email_password_policy_enabled": email_password_policy_enabled,
+                "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+                "real_name": real_name,
+                "resend": resend,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.invite", params=kwargs)
+
+    def admin_users_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        include_deactivated_user_workspaces: Optional[bool] = None,
+        is_active: Optional[bool] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List users on a workspace
+        https://docs.slack.dev/reference/methods/admin.users.list
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+                "is_active": is_active,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.users.list", params=kwargs)
+
+    def admin_users_remove(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a user from a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.remove
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.remove", params=kwargs)
+
+    def admin_users_setAdmin(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or owner to be an admin user.
+        https://docs.slack.dev/reference/methods/admin.users.setAdmin
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setAdmin", params=kwargs)
+
+    def admin_users_setExpiration(
+        self,
+        *,
+        expiration_ts: int,
+        user_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an expiration for a guest user.
+        https://docs.slack.dev/reference/methods/admin.users.setExpiration
+        """
+        kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setExpiration", params=kwargs)
+
+    def admin_users_setOwner(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or admin user to be a workspace owner.
+        https://docs.slack.dev/reference/methods/admin.users.setOwner
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setOwner", params=kwargs)
+
+    def admin_users_setRegular(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest user, admin user, or owner to be a regular user.
+        https://docs.slack.dev/reference/methods/admin.users.setRegular
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setRegular", params=kwargs)
+
+    def admin_workflows_search(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        no_collaborators: Optional[bool] = None,
+        num_trigger_ids: Optional[int] = None,
+        query: Optional[str] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        source: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.search
+        """
+        if collaborator_ids is not None:
+            if isinstance(collaborator_ids, (list, tuple)):
+                kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+            else:
+                kwargs.update({"collaborator_ids": collaborator_ids})
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "cursor": cursor,
+                "limit": limit,
+                "no_collaborators": no_collaborators,
+                "num_trigger_ids": num_trigger_ids,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "source": source,
+            }
+        )
+        return self.api_call("admin.workflows.search", params=kwargs)
+
+    def admin_workflows_permissions_lookup(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        max_workflow_triggers: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the permissions for a set of workflows
+        https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        kwargs.update(
+            {
+                "max_workflow_triggers": max_workflow_triggers,
+            }
+        )
+        return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+    def admin_workflows_collaborators_add(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add collaborators to workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+    def admin_workflows_collaborators_remove(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove collaborators from workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+    def admin_workflows_unpublish(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Unpublish workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+    def api_test(
+        self,
+        *,
+        error: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks API calling code.
+        https://docs.slack.dev/reference/methods/api.test
+        """
+        kwargs.update({"error": error})
+        return self.api_call("api.test", params=kwargs)
+
+    def apps_connections_open(
+        self,
+        *,
+        app_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+        in order to receive events and interactive payloads
+        https://docs.slack.dev/reference/methods/apps.connections.open
+        """
+        kwargs.update({"token": app_token})
+        return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+    def apps_event_authorizations_list(
+        self,
+        *,
+        event_context: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a list of authorizations for the given event context.
+        Each authorization represents an app installation that the event is visible to.
+        https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+        """
+        kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+        return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+    def apps_uninstall(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstalls your app from a workspace.
+        https://docs.slack.dev/reference/methods/apps.uninstall
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret})
+        return self.api_call("apps.uninstall", params=kwargs)
+
+    def apps_manifest_create(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.create
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        return self.api_call("apps.manifest.create", params=kwargs)
+
+    def apps_manifest_delete(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Permanently deletes an app created through app manifests
+        https://docs.slack.dev/reference/methods/apps.manifest.delete
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.delete", params=kwargs)
+
+    def apps_manifest_export(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Export an app manifest from an existing app
+        https://docs.slack.dev/reference/methods/apps.manifest.export
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.export", params=kwargs)
+
+    def apps_manifest_update(
+        self,
+        *,
+        app_id: str,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.update
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.update", params=kwargs)
+
+    def apps_manifest_validate(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        app_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Validate an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.validate
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.validate", params=kwargs)
+
+    def tooling_tokens_rotate(
+        self,
+        *,
+        refresh_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a refresh token for a new app configuration token
+        https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+        """
+        kwargs.update({"refresh_token": refresh_token})
+        return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+    def assistant_threads_setStatus(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        status: str,
+        loading_messages: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the status for an AI assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+        """
+        kwargs.update(
+            {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+    def assistant_threads_setTitle(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the title for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+        return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+    def assistant_threads_setSuggestedPrompts(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: Optional[str] = None,
+        prompts: List[Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set suggested prompts for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+        if title is not None:
+            kwargs.update({"title": title})
+        return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+    def auth_revoke(
+        self,
+        *,
+        test: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes a token.
+        https://docs.slack.dev/reference/methods/auth.revoke
+        """
+        kwargs.update({"test": test})
+        return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+    def auth_test(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks authentication & identity.
+        https://docs.slack.dev/reference/methods/auth.test
+        """
+        return self.api_call("auth.test", params=kwargs)
+
+    def auth_teams_list(
+        self,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        include_icon: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List the workspaces a token can access.
+        https://docs.slack.dev/reference/methods/auth.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+        return self.api_call("auth.teams.list", params=kwargs)
+
+    def bookmarks_add(
+        self,
+        *,
+        channel_id: str,
+        title: str,
+        type: str,
+        emoji: Optional[str] = None,
+        entity_id: Optional[str] = None,
+        link: Optional[str] = None,  # include when type is 'link'
+        parent_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add bookmark to a channel.
+        https://docs.slack.dev/reference/methods/bookmarks.add
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "title": title,
+                "type": type,
+                "emoji": emoji,
+                "entity_id": entity_id,
+                "link": link,
+                "parent_id": parent_id,
+            }
+        )
+        return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+    def bookmarks_edit(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        emoji: Optional[str] = None,
+        link: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Edit bookmark.
+        https://docs.slack.dev/reference/methods/bookmarks.edit
+        """
+        kwargs.update(
+            {
+                "bookmark_id": bookmark_id,
+                "channel_id": channel_id,
+                "emoji": emoji,
+                "link": link,
+                "title": title,
+            }
+        )
+        return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+    def bookmarks_list(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """List bookmark for the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.list
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+    def bookmarks_remove(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove bookmark from the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.remove
+        """
+        kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+        return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+    def bots_info(
+        self,
+        *,
+        bot: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a bot user.
+        https://docs.slack.dev/reference/methods/bots.info
+        """
+        kwargs.update({"bot": bot, "team_id": team_id})
+        return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+    def calls_add(
+        self,
+        *,
+        external_unique_id: str,
+        join_url: str,
+        created_by: Optional[str] = None,
+        date_start: Optional[int] = None,
+        desktop_app_join_url: Optional[str] = None,
+        external_display_id: Optional[str] = None,
+        title: Optional[str] = None,
+        users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers a new Call.
+        https://docs.slack.dev/reference/methods/calls.add
+        """
+        kwargs.update(
+            {
+                "external_unique_id": external_unique_id,
+                "join_url": join_url,
+                "created_by": created_by,
+                "date_start": date_start,
+                "desktop_app_join_url": desktop_app_join_url,
+                "external_display_id": external_display_id,
+                "title": title,
+            }
+        )
+        _update_call_participants(
+            kwargs,
+            users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+        )
+        return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+    def calls_end(
+        self,
+        *,
+        id: str,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends a Call.
+        https://docs.slack.dev/reference/methods/calls.end
+        """
+        kwargs.update({"id": id, "duration": duration})
+        return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+    def calls_info(
+        self,
+        *,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns information about a Call.
+        https://docs.slack.dev/reference/methods/calls.info
+        """
+        kwargs.update({"id": id})
+        return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+    def calls_participants_add(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers new participants added to a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.add
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+    def calls_participants_remove(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers participants removed from a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.remove
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+    def calls_update(
+        self,
+        *,
+        id: str,
+        desktop_app_join_url: Optional[str] = None,
+        join_url: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates information about a Call.
+        https://docs.slack.dev/reference/methods/calls.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "desktop_app_join_url": desktop_app_join_url,
+                "join_url": join_url,
+                "title": title,
+            }
+        )
+        return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+    def canvases_create(
+        self,
+        *,
+        title: Optional[str] = None,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create Canvas for a user
+        https://docs.slack.dev/reference/methods/canvases.create
+        """
+        kwargs.update({"title": title, "document_content": document_content})
+        return self.api_call("canvases.create", json=kwargs)
+
+    def canvases_edit(
+        self,
+        *,
+        canvas_id: str,
+        changes: Sequence[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing canvas
+        https://docs.slack.dev/reference/methods/canvases.edit
+        """
+        kwargs.update({"canvas_id": canvas_id, "changes": changes})
+        return self.api_call("canvases.edit", json=kwargs)
+
+    def canvases_delete(
+        self,
+        *,
+        canvas_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a canvas
+        https://docs.slack.dev/reference/methods/canvases.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        return self.api_call("canvases.delete", params=kwargs)
+
+    def canvases_access_set(
+        self,
+        *,
+        canvas_id: str,
+        access_level: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the access level to a canvas for specified entities
+        https://docs.slack.dev/reference/methods/canvases.access.set
+        """
+        kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+
+        return self.api_call("canvases.access.set", params=kwargs)
+
+    def canvases_access_delete(
+        self,
+        *,
+        canvas_id: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/canvases.access.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("canvases.access.delete", params=kwargs)
+
+    def canvases_sections_lookup(
+        self,
+        *,
+        canvas_id: str,
+        criteria: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Find sections matching the provided criteria
+        https://docs.slack.dev/reference/methods/canvases.sections.lookup
+        """
+        kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+        return self.api_call("canvases.sections.lookup", params=kwargs)
+
+    # --------------------------
+    # Deprecated: channels.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def channels_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.archive", json=kwargs)
+
+    def channels_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.create", json=kwargs)
+
+    def channels_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+    def channels_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+    def channels_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.invite", json=kwargs)
+
+    def channels_join(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins a channel, creating it if needed."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.join", json=kwargs)
+
+    def channels_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.kick", json=kwargs)
+
+    def channels_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.leave", json=kwargs)
+
+    def channels_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team."""
+        return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+    def channels_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.mark", json=kwargs)
+
+    def channels_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.rename", json=kwargs)
+
+    def channels_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+    def channels_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setPurpose", json=kwargs)
+
+    def channels_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setTopic", json=kwargs)
+
+    def channels_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.unarchive", json=kwargs)
+
+    # --------------------------
+
+    def chat_appendStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Appends text to an existing streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.appendStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.appendStream", json=kwargs)
+
+    def chat_delete(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a message.
+        https://docs.slack.dev/reference/methods/chat.delete
+        """
+        kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+        return self.api_call("chat.delete", params=kwargs)
+
+    def chat_deleteScheduledMessage(
+        self,
+        *,
+        channel: str,
+        scheduled_message_id: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a scheduled message.
+        https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "scheduled_message_id": scheduled_message_id,
+                "as_user": as_user,
+            }
+        )
+        return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+    def chat_getPermalink(
+        self,
+        *,
+        channel: str,
+        message_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a permalink URL for a specific extant message
+        https://docs.slack.dev/reference/methods/chat.getPermalink
+        """
+        kwargs.update({"channel": channel, "message_ts": message_ts})
+        return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+    def chat_meMessage(
+        self,
+        *,
+        channel: str,
+        text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a me message into a channel.
+        https://docs.slack.dev/reference/methods/chat.meMessage
+        """
+        kwargs.update({"channel": channel, "text": text})
+        return self.api_call("chat.meMessage", params=kwargs)
+
+    def chat_postEphemeral(
+        self,
+        *,
+        channel: str,
+        user: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an ephemeral message to a user in a channel.
+        https://docs.slack.dev/reference/methods/chat.postEphemeral
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "user": user,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postEphemeral", json=kwargs)
+
+    def chat_postMessage(
+        self,
+        *,
+        channel: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        container_id: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        mrkdwn: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,  # none, full
+        metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends a message to a channel.
+        https://docs.slack.dev/reference/methods/chat.postMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "container_id": container_id,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "mrkdwn": mrkdwn,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postMessage", json=kwargs)
+
+    def chat_scheduleMessage(
+        self,
+        *,
+        channel: str,
+        post_at: Union[str, int],
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        parse: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Schedules a message.
+        https://docs.slack.dev/reference/methods/chat.scheduleMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "post_at": post_at,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "parse": parse,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "link_names": link_names,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.scheduleMessage", json=kwargs)
+
+    def chat_scheduledMessages_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all scheduled messages.
+        https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "latest": latest,
+                "limit": limit,
+                "oldest": oldest,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+    def chat_startStream(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        markdown_text: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a new streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.startStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "thread_ts": thread_ts,
+                "markdown_text": markdown_text,
+                "recipient_team_id": recipient_team_id,
+                "recipient_user_id": recipient_user_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.startStream", json=kwargs)
+
+    def chat_stopStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Stops a streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.stopStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+                "blocks": blocks,
+                "metadata": metadata,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.stopStream", json=kwargs)
+
+    def chat_stream(
+        self,
+        *,
+        buffer_size: int = 256,
+        channel: str,
+        thread_ts: str,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> ChatStream:
+        """Stream markdown text into a conversation.
+
+        This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+        the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+        The following methods are used:
+
+        - chat.startStream: Starts a new streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+        - chat.appendStream: Appends text to an existing streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+        - chat.stopStream: Stops a streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+        Args:
+            buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+              value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+              limits. Default: 256.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            ChatStream instance for managing the stream
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        return ChatStream(
+            self,
+            logger=self._logger,
+            channel=channel,
+            thread_ts=thread_ts,
+            recipient_team_id=recipient_team_id,
+            recipient_user_id=recipient_user_id,
+            buffer_size=buffer_size,
+            **kwargs,
+        )
+
+    def chat_unfurl(
+        self,
+        *,
+        channel: Optional[str] = None,
+        ts: Optional[str] = None,
+        source: Optional[str] = None,
+        unfurl_id: Optional[str] = None,
+        unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+        metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+        user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        user_auth_message: Optional[str] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provide custom unfurl behavior for user-posted URLs.
+        https://docs.slack.dev/reference/methods/chat.unfurl
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "source": source,
+                "unfurl_id": unfurl_id,
+                "unfurls": unfurls,
+                "metadata": metadata,
+                "user_auth_blocks": user_auth_blocks,
+                "user_auth_message": user_auth_message,
+                "user_auth_required": user_auth_required,
+                "user_auth_url": user_auth_url,
+            }
+        )
+        _parse_web_class_objects(kwargs)  # for user_auth_blocks
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.unfurl", json=kwargs)
+
+    def chat_update(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        text: Optional[str] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        as_user: Optional[bool] = None,
+        file_ids: Optional[Union[str, Sequence[str]]] = None,
+        link_names: Optional[bool] = None,
+        parse: Optional[str] = None,  # none, full
+        reply_broadcast: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates a message in a channel.
+        https://docs.slack.dev/reference/methods/chat.update
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "as_user": as_user,
+                "link_names": link_names,
+                "parse": parse,
+                "reply_broadcast": reply_broadcast,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        if isinstance(file_ids, (list, tuple)):
+            kwargs.update({"file_ids": ",".join(file_ids)})
+        else:
+            kwargs.update({"file_ids": file_ids})
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.update", kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.update", json=kwargs)
+
+    def conversations_acceptSharedInvite(
+        self,
+        *,
+        channel_name: str,
+        channel_id: Optional[str] = None,
+        invite_id: Optional[str] = None,
+        free_trial_accepted: Optional[bool] = None,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Accepts an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+        """
+        if channel_id is None and invite_id is None:
+            raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+        kwargs.update(
+            {
+                "channel_name": channel_name,
+                "channel_id": channel_id,
+                "invite_id": invite_id,
+                "free_trial_accepted": free_trial_accepted,
+                "is_private": is_private,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_approveSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approves an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a conversation.
+        https://docs.slack.dev/reference/methods/conversations.archive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.archive", params=kwargs)
+
+    def conversations_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.close
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.close", params=kwargs)
+
+    def conversations_create(
+        self,
+        *,
+        name: str,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiates a public or private channel-based conversation
+        https://docs.slack.dev/reference/methods/conversations.create
+        """
+        kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+        return self.api_call("conversations.create", params=kwargs)
+
+    def conversations_declineSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Declines a Slack Connect channel invite.
+        https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+    def conversations_externalInvitePermissions_set(
+        self, *, action: str, channel: str, target_team: str, **kwargs
+    ) -> SlackResponse:
+        """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+        https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+        """
+        kwargs.update(
+            {
+                "action": action,
+                "channel": channel,
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+    def conversations_history(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches a conversation's history of messages and events.
+        https://docs.slack.dev/reference/methods/conversations.history
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+    def conversations_info(
+        self,
+        *,
+        channel: str,
+        include_locale: Optional[bool] = None,
+        include_num_members: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a conversation.
+        https://docs.slack.dev/reference/methods/conversations.info
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "include_locale": include_locale,
+                "include_num_members": include_num_members,
+            }
+        )
+        return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+    def conversations_invite(
+        self,
+        *,
+        channel: str,
+        users: Union[str, Sequence[str]],
+        force: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites users to a channel.
+        https://docs.slack.dev/reference/methods/conversations.invite
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "force": force,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.invite", params=kwargs)
+
+    def conversations_inviteShared(
+        self,
+        *,
+        channel: str,
+        emails: Optional[Union[str, Sequence[str]]] = None,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.inviteShared
+        """
+        if emails is None and user_ids is None:
+            raise e.SlackRequestError("Either emails or user ids must be provided.")
+        kwargs.update({"channel": channel})
+        if isinstance(emails, (list, tuple)):
+            kwargs.update({"emails": ",".join(emails)})
+        else:
+            kwargs.update({"emails": emails})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+    def conversations_join(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins an existing conversation.
+        https://docs.slack.dev/reference/methods/conversations.join
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.join", params=kwargs)
+
+    def conversations_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a conversation.
+        https://docs.slack.dev/reference/methods/conversations.kick
+        """
+        kwargs.update({"channel": channel, "user": user})
+        return self.api_call("conversations.kick", params=kwargs)
+
+    def conversations_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a conversation.
+        https://docs.slack.dev/reference/methods/conversations.leave
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.leave", params=kwargs)
+
+    def conversations_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team.
+        https://docs.slack.dev/reference/methods/conversations.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+    def conversations_listConnectInvites(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List shared channel invites that have been generated
+        or received but have not yet been approved by all parties.
+        https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+        """
+        kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+        return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+    def conversations_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel.
+        https://docs.slack.dev/reference/methods/conversations.mark
+        """
+        kwargs.update({"channel": channel, "ts": ts})
+        return self.api_call("conversations.mark", params=kwargs)
+
+    def conversations_members(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve members of a conversation.
+        https://docs.slack.dev/reference/methods/conversations.members
+        """
+        kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+        return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+    def conversations_open(
+        self,
+        *,
+        channel: Optional[str] = None,
+        return_im: Optional[bool] = None,
+        users: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens or resumes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.open
+        """
+        if channel is None and users is None:
+            raise e.SlackRequestError("Either channel or users must be provided.")
+        kwargs.update({"channel": channel, "return_im": return_im})
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.open", params=kwargs)
+
+    def conversations_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a conversation.
+        https://docs.slack.dev/reference/methods/conversations.rename
+        """
+        kwargs.update({"channel": channel, "name": name})
+        return self.api_call("conversations.rename", params=kwargs)
+
+    def conversations_replies(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a conversation
+        https://docs.slack.dev/reference/methods/conversations.replies
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+    def conversations_requestSharedInvite_approve(
+        self,
+        *,
+        invite_id: str,
+        channel_id: Optional[str] = None,
+        is_external_limited: Optional[str] = None,
+        message: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+        """
+        kwargs.update(
+            {
+                "invite_id": invite_id,
+                "channel_id": channel_id,
+                "is_external_limited": is_external_limited,
+            }
+        )
+        if message is not None:
+            kwargs.update({"message": json.dumps(message)})
+        return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+    def conversations_requestSharedInvite_deny(
+        self,
+        *,
+        invite_id: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a request to invite an external user to a channel.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+        """
+        kwargs.update({"invite_id": invite_id, "message": message})
+        return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+    def conversations_requestSharedInvite_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_approved: Optional[bool] = None,
+        include_denied: Optional[bool] = None,
+        include_expired: Optional[bool] = None,
+        invite_ids: Optional[Union[str, Sequence[str]]] = None,
+        limit: Optional[int] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists requests to add external users to channels with ability to filter.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_approved": include_approved,
+                "include_denied": include_denied,
+                "include_expired": include_expired,
+                "limit": limit,
+                "user_id": user_id,
+            }
+        )
+        if invite_ids is not None:
+            if isinstance(invite_ids, (list, tuple)):
+                kwargs.update({"invite_ids": ",".join(invite_ids)})
+            else:
+                kwargs.update({"invite_ids": invite_ids})
+        return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+    def conversations_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setPurpose
+        """
+        kwargs.update({"channel": channel, "purpose": purpose})
+        return self.api_call("conversations.setPurpose", params=kwargs)
+
+    def conversations_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setTopic
+        """
+        kwargs.update({"channel": channel, "topic": topic})
+        return self.api_call("conversations.setTopic", params=kwargs)
+
+    def conversations_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reverses conversation archival.
+        https://docs.slack.dev/reference/methods/conversations.unarchive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.unarchive", params=kwargs)
+
+    def conversations_canvases_create(
+        self,
+        *,
+        channel_id: str,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/conversations.canvases.create
+        """
+        kwargs.update({"channel_id": channel_id, "document_content": document_content})
+        return self.api_call("conversations.canvases.create", json=kwargs)
+
+    def dialog_open(
+        self,
+        *,
+        dialog: Dict[str, Any],
+        trigger_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a dialog with a user.
+        https://docs.slack.dev/reference/methods/dialog.open
+        """
+        kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: As the dialog can be a dict, this API call works only with json format.
+        return self.api_call("dialog.open", json=kwargs)
+
+    def dnd_endDnd(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's Do Not Disturb session immediately.
+        https://docs.slack.dev/reference/methods/dnd.endDnd
+        """
+        return self.api_call("dnd.endDnd", params=kwargs)
+
+    def dnd_endSnooze(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's snooze mode immediately.
+        https://docs.slack.dev/reference/methods/dnd.endSnooze
+        """
+        return self.api_call("dnd.endSnooze", params=kwargs)
+
+    def dnd_info(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's current Do Not Disturb status.
+        https://docs.slack.dev/reference/methods/dnd.info
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+    def dnd_setSnooze(
+        self,
+        *,
+        num_minutes: Union[int, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Turns on Do Not Disturb mode for the current user, or changes its duration.
+        https://docs.slack.dev/reference/methods/dnd.setSnooze
+        """
+        kwargs.update({"num_minutes": num_minutes})
+        return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+    def dnd_teamInfo(
+        self,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves the Do Not Disturb status for users on a team.
+        https://docs.slack.dev/reference/methods/dnd.teamInfo
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id})
+        return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+    def emoji_list(
+        self,
+        include_categories: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists custom emoji for a team.
+        https://docs.slack.dev/reference/methods/emoji.list
+        """
+        kwargs.update({"include_categories": include_categories})
+        return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+    def entity_presentDetails(
+        self,
+        trigger_id: str,
+        metadata: Optional[Union[Dict, EntityMetadata]] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        error: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provides entity details for the flexpane.
+        https://docs.slack.dev/reference/methods/entity.presentDetails/
+        """
+        kwargs.update({"trigger_id": trigger_id})
+        if metadata is not None:
+            kwargs.update({"metadata": metadata})
+        if user_auth_required is not None:
+            kwargs.update({"user_auth_required": user_auth_required})
+        if user_auth_url is not None:
+            kwargs.update({"user_auth_url": user_auth_url})
+        if error is not None:
+            kwargs.update({"error": error})
+        _parse_web_class_objects(kwargs)
+        return self.api_call("entity.presentDetails", json=kwargs)
+
+    def files_comments_delete(
+        self,
+        *,
+        file: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an existing comment on a file.
+        https://docs.slack.dev/reference/methods/files.comments.delete
+        """
+        kwargs.update({"file": file, "id": id})
+        return self.api_call("files.comments.delete", params=kwargs)
+
+    def files_delete(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a file.
+        https://docs.slack.dev/reference/methods/files.delete
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.delete", params=kwargs)
+
+    def files_info(
+        self,
+        *,
+        file: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a team file.
+        https://docs.slack.dev/reference/methods/files.info
+        """
+        kwargs.update(
+            {
+                "file": file,
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+            }
+        )
+        return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+    def files_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        count: Optional[int] = None,
+        page: Optional[int] = None,
+        show_files_hidden_by_limit: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists & filters team files.
+        https://docs.slack.dev/reference/methods/files.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "count": count,
+                "page": page,
+                "show_files_hidden_by_limit": show_files_hidden_by_limit,
+                "team_id": team_id,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+    def files_remote_info(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.info
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+    def files_remote_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "limit": limit,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+            }
+        )
+        return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+    def files_remote_add(
+        self,
+        *,
+        external_id: str,
+        external_url: str,
+        title: str,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+        preview_image: Optional[Union[str, bytes, IOBase]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a file from a remote service.
+        https://docs.slack.dev/reference/methods/files.remote.add
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.add",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_update(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        external_url: Optional[str] = None,
+        file: Optional[str] = None,
+        title: Optional[str] = None,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[str] = None,
+        preview_image: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates an existing remote file.
+        https://docs.slack.dev/reference/methods/files.remote.update
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "file": file,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.update",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_remove(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a remote file.
+        https://docs.slack.dev/reference/methods/files.remote.remove
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+    def files_remote_share(
+        self,
+        *,
+        channels: Union[str, Sequence[str]],
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a remote file into a channel.
+        https://docs.slack.dev/reference/methods/files.remote.share
+        """
+        if external_id is None and file is None:
+            raise e.SlackRequestError("Either external_id or file must be provided.")
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+    def files_revokePublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes public/external sharing access for a file
+        https://docs.slack.dev/reference/methods/files.revokePublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.revokePublicURL", params=kwargs)
+
+    def files_sharedPublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enables a file for public/external sharing.
+        https://docs.slack.dev/reference/methods/files.sharedPublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.sharedPublicURL", params=kwargs)
+
+    def files_upload(
+        self,
+        *,
+        file: Optional[Union[str, bytes, IOBase]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        filename: Optional[str] = None,
+        filetype: Optional[str] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        title: Optional[str] = None,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uploads or creates a file.
+        https://docs.slack.dev/reference/methods/files.upload
+        """
+        _print_files_upload_v2_suggestion()
+
+        if file is None and content is None:
+            raise e.SlackRequestError("The file or content argument must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update(
+            {
+                "filename": filename,
+                "filetype": filetype,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+                "title": title,
+            }
+        )
+        if file:
+            if kwargs.get("filename") is None and isinstance(file, str):
+                # use the local filename if filename is missing
+                if kwargs.get("filename") is None:
+                    kwargs["filename"] = file.split(os.path.sep)[-1]
+            return self.api_call("files.upload", files={"file": file}, data=kwargs)
+        else:
+            kwargs["content"] = content
+            return self.api_call("files.upload", data=kwargs)
+
+    def files_upload_v2(
+        self,
+        *,
+        # for sending a single file
+        filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+        file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        title: Optional[str] = None,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        # To upload multiple files at a time
+        file_uploads: Optional[List[Dict[str, Any]]] = None,
+        channel: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+        **kwargs,
+    ) -> SlackResponse:
+        """This wrapper method provides an easy way to upload files using the following endpoints:
+
+        - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+        - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+        - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+            and https://docs.slack.dev/reference/methods/files.info
+
+        """
+        if file is None and content is None and file_uploads is None:
+            raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        # deprecated arguments:
+        filetype = kwargs.get("filetype")
+
+        if filetype is not None:
+            warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+        # step1: files.getUploadURLExternal per file
+        files: List[Dict[str, Any]] = []
+        if file_uploads is not None:
+            for f in file_uploads:
+                files.append(_to_v2_file_upload_item(f))
+        else:
+            f = _to_v2_file_upload_item(
+                {
+                    "filename": filename,
+                    "file": file,
+                    "content": content,
+                    "title": title,
+                    "alt_txt": alt_txt,
+                    "snippet_type": snippet_type,
+                }
+            )
+            files.append(f)
+
+        for f in files:
+            url_response = self.files_getUploadURLExternal(
+                filename=f.get("filename"),  # type: ignore[arg-type]
+                length=f.get("length"),  # type: ignore[arg-type]
+                alt_txt=f.get("alt_txt"),
+                snippet_type=f.get("snippet_type"),
+                token=kwargs.get("token"),
+            )
+            _validate_for_legacy_client(url_response)
+            f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+            f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+        # step2: "https://files.slack.com/upload/v1/..." per file
+        for f in files:
+            upload_result = self._upload_file(
+                url=f["upload_url"],
+                data=f["data"],
+                logger=self._logger,
+                timeout=self.timeout,
+                proxy=self.proxy,
+                ssl=self.ssl,
+            )
+            if upload_result.status != 200:
+                status = upload_result.status
+                body = upload_result.body
+                message = (
+                    "Failed to upload a file "
+                    f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+                )
+                raise e.SlackRequestError(message)
+
+        # step3: files.completeUploadExternal with all the sets of (file_id + title)
+        completion = self.files_completeUploadExternal(
+            files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+            channel_id=channel,
+            channels=channels,
+            initial_comment=initial_comment,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+        if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+            completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+        return completion
+
+    def files_getUploadURLExternal(
+        self,
+        *,
+        filename: str,
+        length: int,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets a URL for an edge external upload.
+        https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+        """
+        kwargs.update(
+            {
+                "filename": filename,
+                "length": length,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+    def files_completeUploadExternal(
+        self,
+        *,
+        files: List[Dict[str, str]],
+        channel_id: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Finishes an upload started with files.getUploadURLExternal.
+        https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        """
+        _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+        kwargs.update(
+            {
+                "files": json.dumps(_files),
+                "channel_id": channel_id,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+            }
+        )
+        if channels:
+            kwargs["channels"] = ",".join(channels)
+        return self.api_call("files.completeUploadExternal", params=kwargs)
+
+    def functions_completeSuccess(
+        self,
+        *,
+        function_execution_id: str,
+        outputs: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the successful completion of a function
+        https://docs.slack.dev/reference/methods/functions.completeSuccess
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+        return self.api_call("functions.completeSuccess", params=kwargs)
+
+    def functions_completeError(
+        self,
+        *,
+        function_execution_id: str,
+        error: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the failure to execute a function
+        https://docs.slack.dev/reference/methods/functions.completeError
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "error": error})
+        return self.api_call("functions.completeError", params=kwargs)
+
+    # --------------------------
+    # Deprecated: groups.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def groups_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.archive", json=kwargs)
+
+    def groups_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a private channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.create", json=kwargs)
+
+    def groups_createChild(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clones and archives a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+    def groups_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+    def groups_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+    def groups_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.invite", json=kwargs)
+
+    def groups_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.kick", json=kwargs)
+
+    def groups_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.leave", json=kwargs)
+
+    def groups_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists private channels that the calling user has access to."""
+        return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+    def groups_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a private channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.mark", json=kwargs)
+
+    def groups_open(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.open", json=kwargs)
+
+    def groups_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a private channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.rename", json=kwargs)
+
+    def groups_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a private channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+    def groups_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a private channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setPurpose", json=kwargs)
+
+    def groups_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a private channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setTopic", json=kwargs)
+
+    def groups_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.unarchive", json=kwargs)
+
+    # --------------------------
+    # Deprecated: im.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def im_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Close a direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.close", json=kwargs)
+
+    def im_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from direct message channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+    def im_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists direct message channels for the calling user."""
+        return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+    def im_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.mark", json=kwargs)
+
+    def im_open(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a direct message channel."""
+        kwargs.update({"user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.open", json=kwargs)
+
+    def im_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def migration_exchange(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        to_old: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """For Enterprise Grid workspaces, map local user IDs to global user IDs
+        https://docs.slack.dev/reference/methods/migration.exchange
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id, "to_old": to_old})
+        return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+    # --------------------------
+    # Deprecated: mpim.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def mpim_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a multiparty direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.close", json=kwargs)
+
+    def mpim_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a multiparty direct message."""
+        kwargs.update({"channel": channel})
+        return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+    def mpim_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists multiparty direct message channels for the calling user."""
+        return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+    def mpim_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a multiparty direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.mark", json=kwargs)
+
+    def mpim_open(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """This method opens a multiparty direct message."""
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("mpim.open", params=kwargs)
+
+    def mpim_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation from a
+        multiparty direct message.
+        """
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def oauth_v2_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        # This field is required when processing the OAuth redirect URL requests
+        # while it's absent for token rotation
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        # This field is required for token rotation
+        grant_type: Optional[str] = None,
+        # This field is required for token rotation
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.v2.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "oauth.v2.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        code: str,
+        redirect_uri: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        kwargs.update({"code": code})
+        return self.api_call(
+            "oauth.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_v2_exchange(
+        self,
+        *,
+        token: str,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a legacy access token for a new expiring access token and refresh token
+        https://docs.slack.dev/reference/methods/oauth.v2.exchange
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+        return self.api_call("oauth.v2.exchange", params=kwargs)
+
+    def openid_connect_token(
+        self,
+        client_id: str,
+        client_secret: str,
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        grant_type: Optional[str] = None,
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.token
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "openid.connect.token",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def openid_connect_userInfo(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get the identity of a user who has authorized Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.userInfo
+        """
+        return self.api_call("openid.connect.userInfo", params=kwargs)
+
+    def pins_add(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Pins an item to a channel.
+        https://docs.slack.dev/reference/methods/pins.add
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.add", params=kwargs)
+
+    def pins_list(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists items pinned to a channel.
+        https://docs.slack.dev/reference/methods/pins.list
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+    def pins_remove(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Un-pins an item from a channel.
+        https://docs.slack.dev/reference/methods/pins.remove
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.remove", params=kwargs)
+
+    def reactions_add(
+        self,
+        *,
+        channel: str,
+        name: str,
+        timestamp: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a reaction to an item.
+        https://docs.slack.dev/reference/methods/reactions.add
+        """
+        kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+        return self.api_call("reactions.add", params=kwargs)
+
+    def reactions_get(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        full: Optional[bool] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets reactions for an item.
+        https://docs.slack.dev/reference/methods/reactions.get
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "full": full,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+    def reactions_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        full: Optional[bool] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists reactions made by a user.
+        https://docs.slack.dev/reference/methods/reactions.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "full": full,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+    def reactions_remove(
+        self,
+        *,
+        name: str,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a reaction from an item.
+        https://docs.slack.dev/reference/methods/reactions.remove
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.remove", params=kwargs)
+
+    def reminders_add(
+        self,
+        *,
+        text: str,
+        time: str,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        recurrence: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a reminder.
+        https://docs.slack.dev/reference/methods/reminders.add
+        """
+        kwargs.update(
+            {
+                "text": text,
+                "time": time,
+                "team_id": team_id,
+                "user": user,
+                "recurrence": recurrence,
+            }
+        )
+        return self.api_call("reminders.add", params=kwargs)
+
+    def reminders_complete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Marks a reminder as complete.
+        https://docs.slack.dev/reference/methods/reminders.complete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.complete", params=kwargs)
+
+    def reminders_delete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a reminder.
+        https://docs.slack.dev/reference/methods/reminders.delete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.delete", params=kwargs)
+
+    def reminders_info(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a reminder.
+        https://docs.slack.dev/reference/methods/reminders.info
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+    def reminders_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all reminders created by or for a given user.
+        https://docs.slack.dev/reference/methods/reminders.list
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+    def rtm_connect(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.connect
+        """
+        kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+        return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+    def rtm_start(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        include_locale: Optional[bool] = None,
+        mpim_aware: Optional[bool] = None,
+        no_latest: Optional[bool] = None,
+        no_unreads: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        simple_latest: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.start
+        """
+        kwargs.update(
+            {
+                "batch_presence_aware": batch_presence_aware,
+                "include_locale": include_locale,
+                "mpim_aware": mpim_aware,
+                "no_latest": no_latest,
+                "no_unreads": no_unreads,
+                "presence_sub": presence_sub,
+                "simple_latest": simple_latest,
+            }
+        )
+        return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+    def search_all(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages and files matching a query.
+        https://docs.slack.dev/reference/methods/search.all
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+    def search_files(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for files matching a query.
+        https://docs.slack.dev/reference/methods/search.files
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+    def search_messages(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages matching a query.
+        https://docs.slack.dev/reference/methods/search.messages
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "cursor": cursor,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+    def slackLists_access_delete(
+        self,
+        *,
+        list_id: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revoke access to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.delete
+        """
+        kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.delete", json=kwargs)
+
+    def slackLists_access_set(
+        self,
+        *,
+        list_id: str,
+        access_level: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the access level to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.set
+        """
+        kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.set", json=kwargs)
+
+    def slackLists_create(
+        self,
+        *,
+        name: str,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        schema: Optional[List[Dict[str, Any]]] = None,
+        copy_from_list_id: Optional[str] = None,
+        include_copied_list_records: Optional[bool] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a List.
+        https://docs.slack.dev/reference/methods/slackLists.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description_blocks": description_blocks,
+                "schema": schema,
+                "copy_from_list_id": copy_from_list_id,
+                "include_copied_list_records": include_copied_list_records,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.create", json=kwargs)
+
+    def slackLists_download_get(
+        self,
+        *,
+        list_id: str,
+        job_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve List download URL from an export job to download List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.get
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "job_id": job_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.get", json=kwargs)
+
+    def slackLists_download_start(
+        self,
+        *,
+        list_id: str,
+        include_archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiate a job to export List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.start
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "include_archived": include_archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.start", json=kwargs)
+
+    def slackLists_items_create(
+        self,
+        *,
+        list_id: str,
+        duplicated_item_id: Optional[str] = None,
+        parent_item_id: Optional[str] = None,
+        initial_fields: Optional[List[Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add a new item to an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.create
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "duplicated_item_id": duplicated_item_id,
+                "parent_item_id": parent_item_id,
+                "initial_fields": initial_fields,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.create", json=kwargs)
+
+    def slackLists_items_delete(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an item from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.delete
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.delete", json=kwargs)
+
+    def slackLists_items_deleteMultiple(
+        self,
+        *,
+        list_id: str,
+        ids: List[str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes multiple items from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "ids": ids,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+    def slackLists_items_info(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        include_is_subscribed: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a row from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.info
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+                "include_is_subscribed": include_is_subscribed,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.info", json=kwargs)
+
+    def slackLists_items_list(
+        self,
+        *,
+        list_id: str,
+        limit: Optional[int] = None,
+        cursor: Optional[str] = None,
+        archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get records from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.list
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "limit": limit,
+                "cursor": cursor,
+                "archived": archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.list", json=kwargs)
+
+    def slackLists_items_update(
+        self,
+        *,
+        list_id: str,
+        cells: List[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates cells in a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.update
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "cells": cells,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.update", json=kwargs)
+
+    def slackLists_update(
+        self,
+        *,
+        id: str,
+        name: Optional[str] = None,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update a List.
+        https://docs.slack.dev/reference/methods/slackLists.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "name": name,
+                "description_blocks": description_blocks,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.update", json=kwargs)
+
+    def stars_add(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a star to an item.
+        https://docs.slack.dev/reference/methods/stars.add
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.add", params=kwargs)
+
+    def stars_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists stars for a user.
+        https://docs.slack.dev/reference/methods/stars.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+    def stars_remove(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a star from an item.
+        https://docs.slack.dev/reference/methods/stars.remove
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.remove", params=kwargs)
+
+    def team_accessLogs(
+        self,
+        *,
+        before: Optional[Union[int, str]] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the access logs for the current team.
+        https://docs.slack.dev/reference/methods/team.accessLogs
+        """
+        kwargs.update(
+            {
+                "before": before,
+                "count": count,
+                "page": page,
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+    def team_billableInfo(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets billable users information for the current team.
+        https://docs.slack.dev/reference/methods/team.billableInfo
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+    def team_billing_info(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reads a workspace's billing plan information.
+        https://docs.slack.dev/reference/methods/team.billing.info
+        """
+        return self.api_call("team.billing.info", params=kwargs)
+
+    def team_externalTeams_disconnect(
+        self,
+        *,
+        target_team: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnects an external organization.
+        https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+        """
+        kwargs.update(
+            {
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+    def team_externalTeams_list(
+        self,
+        *,
+        connection_status_filter: Optional[str] = None,
+        slack_connect_pref_filter: Optional[Sequence[str]] = None,
+        sort_direction: Optional[str] = None,
+        sort_field: Optional[str] = None,
+        workspace_filter: Optional[Sequence[str]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns a list of all the external teams connected and details about the connection.
+        https://docs.slack.dev/reference/methods/team.externalTeams.list
+        """
+        kwargs.update(
+            {
+                "connection_status_filter": connection_status_filter,
+                "sort_direction": sort_direction,
+                "sort_field": sort_field,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if slack_connect_pref_filter is not None:
+            if isinstance(slack_connect_pref_filter, (list, tuple)):
+                kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+            else:
+                kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+        if workspace_filter is not None:
+            if isinstance(workspace_filter, (list, tuple)):
+                kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+            else:
+                kwargs.update({"workspace_filter": workspace_filter})
+        return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+    def team_info(
+        self,
+        *,
+        team: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about the current team.
+        https://docs.slack.dev/reference/methods/team.info
+        """
+        kwargs.update({"team": team, "domain": domain})
+        return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+    def team_integrationLogs(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        change_type: Optional[str] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        service_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the integration logs for the current team.
+        https://docs.slack.dev/reference/methods/team.integrationLogs
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "change_type": change_type,
+                "count": count,
+                "page": page,
+                "service_id": service_id,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+    def team_profile_get(
+        self,
+        *,
+        visibility: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a team's profile.
+        https://docs.slack.dev/reference/methods/team.profile.get
+        """
+        kwargs.update({"visibility": visibility})
+        return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+    def team_preferences_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a list of a workspace's team preferences.
+        https://docs.slack.dev/reference/methods/team.preferences.list
+        """
+        return self.api_call("team.preferences.list", params=kwargs)
+
+    def usergroups_create(
+        self,
+        *,
+        name: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a User Group
+        https://docs.slack.dev/reference/methods/usergroups.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.create", params=kwargs)
+
+    def usergroups_disable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disable an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.disable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.disable", params=kwargs)
+
+    def usergroups_enable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enable a User Group
+        https://docs.slack.dev/reference/methods/usergroups.enable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.enable", params=kwargs)
+
+    def usergroups_list(
+        self,
+        *,
+        include_count: Optional[bool] = None,
+        include_disabled: Optional[bool] = None,
+        include_users: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all User Groups for a team
+        https://docs.slack.dev/reference/methods/usergroups.list
+        """
+        kwargs.update(
+            {
+                "include_count": include_count,
+                "include_disabled": include_disabled,
+                "include_users": include_users,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+    def usergroups_update(
+        self,
+        *,
+        usergroup: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "name": name,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.update", params=kwargs)
+
+    def usergroups_users_list(
+        self,
+        *,
+        usergroup: str,
+        include_disabled: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all users in a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.list
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_disabled": include_disabled,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+    def usergroups_users_update(
+        self,
+        *,
+        usergroup: str,
+        users: Union[str, Sequence[str]],
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the list of users for a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("usergroups.users.update", params=kwargs)
+
+    def users_conversations(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List conversations the calling user may access.
+        https://docs.slack.dev/reference/methods/users.conversations
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+    def users_deletePhoto(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete the user profile photo
+        https://docs.slack.dev/reference/methods/users.deletePhoto
+        """
+        return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+    def users_getPresence(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets user presence information.
+        https://docs.slack.dev/reference/methods/users.getPresence
+        """
+        kwargs.update({"user": user})
+        return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+    def users_identity(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a user's identity.
+        https://docs.slack.dev/reference/methods/users.identity
+        """
+        return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+    def users_info(
+        self,
+        *,
+        user: str,
+        include_locale: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a user.
+        https://docs.slack.dev/reference/methods/users.info
+        """
+        kwargs.update({"user": user, "include_locale": include_locale})
+        return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+    def users_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_locale: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all users in a Slack team.
+        https://docs.slack.dev/reference/methods/users.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_locale": include_locale,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+    def users_lookupByEmail(
+        self,
+        *,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Find a user with an email address.
+        https://docs.slack.dev/reference/methods/users.lookupByEmail
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+    def users_setPhoto(
+        self,
+        *,
+        image: Union[str, IOBase],
+        crop_w: Optional[Union[int, str]] = None,
+        crop_x: Optional[Union[int, str]] = None,
+        crop_y: Optional[Union[int, str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the user profile photo
+        https://docs.slack.dev/reference/methods/users.setPhoto
+        """
+        kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+        return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+    def users_setPresence(
+        self,
+        *,
+        presence: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Manually sets user presence.
+        https://docs.slack.dev/reference/methods/users.setPresence
+        """
+        kwargs.update({"presence": presence})
+        return self.api_call("users.setPresence", params=kwargs)
+
+    def users_discoverableContacts_lookup(
+        self,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup an email address to see if someone is on Slack
+        https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+    def users_profile_get(
+        self,
+        *,
+        user: Optional[str] = None,
+        include_labels: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's profile information.
+        https://docs.slack.dev/reference/methods/users.profile.get
+        """
+        kwargs.update({"user": user, "include_labels": include_labels})
+        return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+    def users_profile_set(
+        self,
+        *,
+        name: Optional[str] = None,
+        value: Optional[str] = None,
+        user: Optional[str] = None,
+        profile: Optional[Dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the profile information for a user.
+        https://docs.slack.dev/reference/methods/users.profile.set
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "profile": profile,
+                "user": user,
+                "value": value,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "profile" parameter
+        return self.api_call("users.profile.set", json=kwargs)
+
+    def views_open(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a view for a user.
+        https://docs.slack.dev/reference/methods/views.open
+        See https://docs.slack.dev/surfaces/modals/ for details.
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.open", json=kwargs)
+
+    def views_push(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Push a view onto the stack of a root view.
+        Push a new view onto the existing view stack by passing a view
+        payload and a valid trigger_id generated from an interaction
+        within the existing modal.
+        Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+        to learn more about the lifecycle and intricacies of views.
+        https://docs.slack.dev/reference/methods/views.push
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.push", json=kwargs)
+
+    def views_update(
+        self,
+        *,
+        view: Union[dict, View],
+        external_id: Optional[str] = None,
+        view_id: Optional[str] = None,
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing view.
+        Update a view by passing a new view definition along with the
+        view_id returned in views.open or the external_id.
+        See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+        to learn more about updating views and avoiding race conditions with the hash argument.
+        https://docs.slack.dev/reference/methods/views.update
+        """
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        if external_id:
+            kwargs.update({"external_id": external_id})
+        elif view_id:
+            kwargs.update({"view_id": view_id})
+        else:
+            raise e.SlackRequestError("Either view_id or external_id is required.")
+        kwargs.update({"hash": hash})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.update", json=kwargs)
+
+    def views_publish(
+        self,
+        *,
+        user_id: str,
+        view: Union[dict, View],
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Publish a static view for a User.
+        Create or update the view that comprises an
+        app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+        https://docs.slack.dev/reference/methods/views.publish
+        """
+        kwargs.update({"user_id": user_id, "hash": hash})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.publish", json=kwargs)
+
+    def workflows_featured_add(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add featured workflows to a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.add
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.add", params=kwargs)
+
+    def workflows_featured_list(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """List the featured workflows for specified channels.
+        https://docs.slack.dev/reference/methods/workflows.featured.list
+        """
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("workflows.featured.list", params=kwargs)
+
+    def workflows_featured_remove(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove featured workflows from a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.remove
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.remove", params=kwargs)
+
+    def workflows_featured_set(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set featured workflows for a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.set
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.set", params=kwargs)
+
+    def workflows_stepCompleted(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        outputs: Optional[dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate a successful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepCompleted
+        """
+        kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "outputs" parameter
+        return self.api_call("workflows.stepCompleted", json=kwargs)
+
+    def workflows_stepFailed(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        error: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate an unsuccessful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepFailed
+        """
+        kwargs.update(
+            {
+                "workflow_step_execute_id": workflow_step_execute_id,
+                "error": error,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "error" parameter
+        return self.api_call("workflows.stepFailed", json=kwargs)
+
+    def workflows_updateStep(
+        self,
+        *,
+        workflow_step_edit_id: str,
+        inputs: Optional[Dict[str, Any]] = None,
+        outputs: Optional[List[Dict[str, str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the configuration for a workflow extension step.
+        https://docs.slack.dev/reference/methods/workflows.updateStep
+        """
+        kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+        if inputs is not None:
+            kwargs.update({"inputs": inputs})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+        return self.api_call("workflows.updateStep", json=kwargs)
+
+

A WebClient allows apps to communicate with the Slack Platform's Web API.

+

https://docs.slack.dev/reference/methods

+

The Slack Web API is an interface for querying information from +and enacting change in a Slack workspace.

+

This client handles constructing and sending HTTP requests to Slack +as well as parsing any responses received into a SlackResponse.

+

Attributes

+
+
token : str
+
A string specifying an xoxp-* or xoxb-* token.
+
base_url : str
+
A string representing the Slack API base URL. +Default is 'https://slack.com/api/'
+
timeout : int
+
The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.
+
ssl : SSLContext
+
An ssl.SSLContext instance, helpful for specifying +your own custom certificate chain.
+
proxy : str
+
String representing a fully-qualified URL to a proxy through +which to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.
+
headers : dict
+
Additional request headers to attach to all requests.
+
+

Methods

+

api_call: Constructs a request and executes the API call to Slack.

+

Example of recommended usage:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.chat_postMessage(
+        channel='#random',
+        text="Hello world!")
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Example manually creating an API request:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.api_call(
+        api_method='chat.postMessage',
+        json={'channel': '#random','text': "Hello world!"}
+    )
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Note

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Ancestors

+ +

Methods

+
+
+def admin_analytics_getFile(self,
*,
type:Β str,
date:Β strΒ |Β NoneΒ =Β None,
metadata_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_analytics_getFile(
+    self,
+    *,
+    type: str,
+    date: Optional[str] = None,
+    metadata_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve analytics data for a given date, presented as a compressed JSON file
+    https://docs.slack.dev/reference/methods/admin.analytics.getFile
+    """
+    kwargs.update({"type": type})
+    if date is not None:
+        kwargs.update({"date": date})
+    if metadata_only is not None:
+        kwargs.update({"metadata_only": metadata_only})
+    return self.api_call("admin.analytics.getFile", params=kwargs)
+
+

Retrieve analytics data for a given date, presented as a compressed JSON file +https://docs.slack.dev/reference/methods/admin.analytics.getFile

+
+
+def admin_apps_activities_list(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
component_id:Β strΒ |Β NoneΒ =Β None,
component_type:Β strΒ |Β NoneΒ =Β None,
log_event_type:Β strΒ |Β NoneΒ =Β None,
max_date_created:Β intΒ |Β NoneΒ =Β None,
min_date_created:Β intΒ |Β NoneΒ =Β None,
min_log_level:Β strΒ |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
trace_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_activities_list(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    component_id: Optional[str] = None,
+    component_type: Optional[str] = None,
+    log_event_type: Optional[str] = None,
+    max_date_created: Optional[int] = None,
+    min_date_created: Optional[int] = None,
+    min_log_level: Optional[str] = None,
+    sort_direction: Optional[str] = None,
+    source: Optional[str] = None,
+    team_id: Optional[str] = None,
+    trace_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get logs for a specified team/org
+    https://docs.slack.dev/reference/methods/admin.apps.activities.list
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "component_id": component_id,
+            "component_type": component_type,
+            "log_event_type": log_event_type,
+            "max_date_created": max_date_created,
+            "min_date_created": min_date_created,
+            "min_log_level": min_log_level,
+            "sort_direction": sort_direction,
+            "source": source,
+            "team_id": team_id,
+            "trace_id": trace_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.apps.activities.list", params=kwargs)
+
+ +
+
+def admin_apps_approve(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approve(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve an app for installation on a workspace.
+    Either app_id or request_id is required.
+    These IDs can be obtained either directly via the app_requested event,
+    or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.approve
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approve", params=kwargs)
+
+

Approve an app for installation on a workspace. +Either app_id or request_id is required. +These IDs can be obtained either directly via the app_requested event, +or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.approve

+
+
+def admin_apps_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List approved apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+

List approved apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.approved.list

+
+
+def admin_apps_clearResolution(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_clearResolution(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Clear an app resolution
+    https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_config_lookup(self, *, app_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_apps_config_lookup(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Look up the app config for connectors by their IDs
+    https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+

Look up the app config for connectors by their IDs +https://docs.slack.dev/reference/methods/admin.apps.config.lookup

+
+
+def admin_apps_config_set(self,
*,
app_id:Β str,
domain_restrictions:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_auth_strategy:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_config_set(
+    self,
+    *,
+    app_id: str,
+    domain_restrictions: Optional[Dict[str, Any]] = None,
+    workflow_auth_strategy: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the app config for a connector
+    https://docs.slack.dev/reference/methods/admin.apps.config.set
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "workflow_auth_strategy": workflow_auth_strategy,
+        }
+    )
+    if domain_restrictions is not None:
+        kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+    return self.api_call("admin.apps.config.set", params=kwargs)
+
+ +
+
+def admin_apps_requests_cancel(self,
*,
request_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_cancel(
+    self,
+    *,
+    request_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+    """
+    kwargs.update(
+        {
+            "request_id": request_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_requests_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_apps_restrict(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restrict(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Restrict an app for installation on a workspace.
+    Exactly one of the team_id or enterprise_id arguments is required, not both.
+    Either app_id or request_id is required. These IDs can be obtained either directly
+    via the app_requested event, or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.restrict
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restrict", params=kwargs)
+
+

Restrict an app for installation on a workspace. +Exactly one of the team_id or enterprise_id arguments is required, not both. +Either app_id or request_id is required. These IDs can be obtained either directly +via the app_requested event, or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.restrict

+
+
+def admin_apps_restricted_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restricted_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List restricted apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+

List restricted apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.restricted.list

+
+
+def admin_apps_uninstall(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_uninstall(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+    With an org-level token, enterprise_id or team_ids is required.
+    https://docs.slack.dev/reference/methods/admin.apps.uninstall
+    """
+    kwargs.update({"app_id": app_id})
+    if enterprise_id is not None:
+        kwargs.update({"enterprise_id": enterprise_id})
+    if team_ids is not None:
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+

Uninstall an app from one or many workspaces, or an entire enterprise organization. +With an org-level token, enterprise_id or team_ids is required. +https://docs.slack.dev/reference/methods/admin.apps.uninstall

+
+
+def admin_auth_policy_assignEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_assignEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Assign entities to a particular authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+

Assign entities to a particular authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities

+
+
+def admin_auth_policy_getEntities(self,
*,
policy_name:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_getEntities(
+    self,
+    *,
+    policy_name: str,
+    cursor: Optional[str] = None,
+    entity_type: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch all the entities assigned to a particular authentication policy by name.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+    """
+    kwargs.update({"policy_name": policy_name})
+    if cursor is not None:
+        kwargs.update({"cursor": cursor})
+    if entity_type is not None:
+        kwargs.update({"entity_type": entity_type})
+    if limit is not None:
+        kwargs.update({"limit": limit})
+    return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+

Fetch all the entities assigned to a particular authentication policy by name. +https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities

+
+
+def admin_auth_policy_removeEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_removeEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove specified entities from a specified authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+

Remove specified entities from a specified authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities

+
+
+def admin_barriers_create(self,
*,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_create(
+    self,
+    *,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.create
+    """
+    kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_delete(self, *, barrier_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_delete(
+    self,
+    *,
+    barrier_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.delete
+    """
+    kwargs.update({"barrier_id": barrier_id})
+    return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get all Information Barriers for your organization
+    https://docs.slack.dev/reference/methods/admin.barriers.list"""
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+

Get all Information Barriers for your organization +https://docs.slack.dev/reference/methods/admin.barriers.list

+
+
+def admin_barriers_update(self,
*,
barrier_id:Β str,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_update(
+    self,
+    *,
+    barrier_id: str,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.update
+    """
+    kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_conversations_archive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_archive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.archive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkArchive(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkArchive(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Archive public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkDelete(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkDelete(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Delete public or private channels in bulk.
+    https://slack.com/api/admin.conversations.bulkDelete
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+

Delete public or private channels in bulk. +https://slack.com/api/admin.conversations.bulkDelete

+
+
+def admin_conversations_bulkMove(self, *, channel_ids:Β strΒ |Β Sequence[str], target_team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkMove(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    target_team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Move public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+    """
+    kwargs.update(
+        {
+            "target_team_id": target_team_id,
+            "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+        }
+    )
+    return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPrivate(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPrivate(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a public channel to a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPublic(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPublic(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a privte channel to a public channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+ +
+
+def admin_conversations_create(self,
*,
is_private:Β bool,
name:Β str,
description:Β strΒ |Β NoneΒ =Β None,
org_wide:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_create(
+    self,
+    *,
+    is_private: bool,
+    name: str,
+    description: Optional[str] = None,
+    org_wide: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a public or private channel-based conversation.
+    https://docs.slack.dev/reference/methods/admin.conversations.create
+    """
+    kwargs.update(
+        {
+            "is_private": is_private,
+            "name": name,
+            "description": description,
+            "org_wide": org_wide,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.conversations.create", params=kwargs)
+
+

Create a public or private channel-based conversation. +https://docs.slack.dev/reference/methods/admin.conversations.create

+
+
+def admin_conversations_createForObjects(self,
*,
object_id:Β str,
salesforce_org_id:Β str,
invite_object_team:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_createForObjects(
+    self,
+    *,
+    object_id: str,
+    salesforce_org_id: str,
+    invite_object_team: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Salesforce channel for the corresponding object provided.
+    https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+    """
+    kwargs.update(
+        {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+    )
+    return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+

Create a Salesforce channel for the corresponding object provided. +https://docs.slack.dev/reference/methods/admin.conversations.createForObjects

+
+
+def admin_conversations_delete(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_delete(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.delete
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.delete", params=kwargs)
+
+ +
+
+def admin_conversations_disconnectShared(self,
*,
channel_id:Β str,
leaving_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_disconnectShared(
+    self,
+    *,
+    channel_id: str,
+    leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnect a connected channel from one or more workspaces.
+    https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(leaving_team_ids, (list, tuple)):
+        kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+    else:
+        kwargs.update({"leaving_team_ids": leaving_team_ids})
+    return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+

Disconnect a connected channel from one or more workspaces. +https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared

+
+
+def admin_conversations_ekm_listOriginalConnectedChannelInfo(self,
*,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+    self,
+    *,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all disconnected channelsβ€”i.e.,
+    channels that were once connected to other workspaces and then disconnectedβ€”and
+    the corresponding original channel IDs for key revocation with EKM.
+    https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+

List all disconnected channelsβ€”i.e., +channels that were once connected to other workspaces and then disconnectedβ€”and +the corresponding original channel IDs for key revocation with EKM. +https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo

+
+
+def admin_conversations_getConversationPrefs(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get conversation preferences for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+

Get conversation preferences for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs

+
+
+def admin_conversations_getCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_getTeams(self,
*,
channel_id:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_getTeams(
+    self,
+    *,
+    channel_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a channel. +https://docs.slack.dev/reference/methods/admin.conversations.getTeams

+
+
+def admin_conversations_invite(self, *, channel_id:Β str, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_invite(
+    self,
+    *,
+    channel_id: str,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.invite
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+    return self.api_call("admin.conversations.invite", params=kwargs)
+
+

Invite a user to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.invite

+
+
+def admin_conversations_linkObjects(self, *, channel:Β str, record_id:Β str, salesforce_org_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_linkObjects(
+    self,
+    *,
+    channel: str,
+    record_id: str,
+    salesforce_org_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Link a Salesforce record to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "record_id": record_id,
+            "salesforce_org_id": salesforce_org_id,
+        }
+    )
+    return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+ +
+
+def admin_conversations_lookup(self,
*,
last_message_activity_before:Β int,
team_ids:Β strΒ |Β Sequence[str],
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
max_member_count:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_lookup(
+    self,
+    *,
+    last_message_activity_before: int,
+    team_ids: Union[str, Sequence[str]],
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    max_member_count: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns channels on the given team using the filters.
+    https://docs.slack.dev/reference/methods/admin.conversations.lookup
+    """
+    kwargs.update(
+        {
+            "last_message_activity_before": last_message_activity_before,
+            "cursor": cursor,
+            "limit": limit,
+            "max_member_count": max_member_count,
+        }
+    )
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.lookup", params=kwargs)
+
+

Returns channels on the given team using the filters. +https://docs.slack.dev/reference/methods/admin.conversations.lookup

+
+
+def admin_conversations_removeCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_removeCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_rename(self, *, channel_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_rename(
+    self,
+    *,
+    channel_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.rename
+    """
+    kwargs.update({"channel_id": channel_id, "name": name})
+    return self.api_call("admin.conversations.rename", params=kwargs)
+
+ +
+
+def admin_conversations_restrictAccess_addGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_addGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an allowlist of IDP groups for accessing a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.addGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Add an allowlist of IDP groups for accessing a channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup

+
+
+def admin_conversations_restrictAccess_listGroups(self, *, channel_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_listGroups(
+    self,
+    *,
+    channel_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all IDP Groups linked to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.listGroups",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+ +
+
+def admin_conversations_restrictAccess_removeGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_removeGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a linked IDP group linked from a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.removeGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Remove a linked IDP group linked from a private channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup

+
+ +
+
+ +Expand source code + +
def admin_conversations_search(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    query: Optional[str] = None,
+    search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search for public or private channels in an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.conversations.search
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+        }
+    )
+
+    if isinstance(search_channel_types, (list, tuple)):
+        kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+    else:
+        kwargs.update({"search_channel_types": search_channel_types})
+
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+
+    return self.api_call("admin.conversations.search", params=kwargs)
+
+

Search for public or private channels in an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.conversations.search

+
+
+def admin_conversations_setConversationPrefs(self, *, channel_id:Β str, prefs:Β strΒ |Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    prefs: Union[str, Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the posting permissions for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(prefs, dict):
+        kwargs.update({"prefs": json.dumps(prefs)})
+    else:
+        kwargs.update({"prefs": prefs})
+    return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+

Set the posting permissions for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs

+
+
+def admin_conversations_setCustomRetention(self, *, channel_id:Β str, duration_days:Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    duration_days: int,
+    **kwargs,
+) -> SlackResponse:
+    """Set a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+    return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_setTeams(self,
*,
channel_id:Β str,
org_channel:Β boolΒ |Β NoneΒ =Β None,
target_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_setTeams(
+    self,
+    *,
+    channel_id: str,
+    org_channel: Optional[bool] = None,
+    target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "org_channel": org_channel,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(target_team_ids, (list, tuple)):
+        kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+    else:
+        kwargs.update({"target_team_ids": target_team_ids})
+    return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setTeams

+
+
+def admin_conversations_unarchive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unarchive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+ +
+
+def admin_conversations_unlinkObjects(self, *, channel:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unlinkObjects(
+    self,
+    *,
+    channel: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unlink a Salesforce record from a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "new_name": new_name,
+        }
+    )
+    return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+ +
+
+def admin_emoji_add(self, *, name:Β str, url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_add(
+    self,
+    *,
+    name: str,
+    url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.add
+    """
+    kwargs.update({"name": name, "url": url})
+    return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_addAlias(self, *, alias_for:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_addAlias(
+    self,
+    *,
+    alias_for: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji alias.
+    https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+    """
+    kwargs.update({"alias_for": alias_for, "name": name})
+    return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List emoji for an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+

List emoji for an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.list

+
+
+def admin_emoji_remove(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_remove(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove an emoji across an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.remove
+    """
+    kwargs.update({"name": name})
+    return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+

Remove an emoji across an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.remove

+
+
+def admin_emoji_rename(self, *, name:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_rename(
+    self,
+    *,
+    name: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.rename
+    """
+    kwargs.update({"name": name, "new_name": new_name})
+    return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_functions_list(self,
*,
app_ids:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_list(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up functions by a set of apps
+    https://docs.slack.dev/reference/methods/admin.functions.list
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.functions.list", params=kwargs)
+
+ +
+
+def admin_functions_permissions_lookup(self, *, function_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_functions_permissions_lookup(
+    self,
+    *,
+    function_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Lookup the visibility of multiple Slack functions
+    and include the users if it is limited to particular named entities.
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+    """
+    if isinstance(function_ids, (list, tuple)):
+        kwargs.update({"function_ids": ",".join(function_ids)})
+    else:
+        kwargs.update({"function_ids": function_ids})
+    return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+

Lookup the visibility of multiple Slack functions +and include the users if it is limited to particular named entities. +https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup

+
+
+def admin_functions_permissions_set(self,
*,
function_id:Β str,
visibility:Β str,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_permissions_set(
+    self,
+    *,
+    function_id: str,
+    visibility: str,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the visibility of a Slack function
+    and define the users or workspaces if it is set to named_entities
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+    """
+    kwargs.update(
+        {
+            "function_id": function_id,
+            "visibility": visibility,
+        }
+    )
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+

Set the visibility of a Slack function +and define the users or workspaces if it is set to named_entities +https://docs.slack.dev/reference/methods/admin.functions.permissions.set

+
+
+def admin_inviteRequests_approve(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_approve(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+ +
+
+def admin_inviteRequests_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all approved workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_denied_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_denied_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all denied workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_deny(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_deny(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+ +
+
+def admin_inviteRequests_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """List all pending workspace invite requests."""
+    return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+

List all pending workspace invite requests.

+
+
+def admin_roles_addAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_addAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Adds members to the specified role with the specified scopes
+    https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+

Adds members to the specified role with the specified scopes +https://docs.slack.dev/reference/methods/admin.roles.addAssignments

+
+
+def admin_roles_listAssignments(self,
*,
role_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
entity_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β strΒ |Β intΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_listAssignments(
+    self,
+    *,
+    role_ids: Optional[Union[str, Sequence[str]]] = None,
+    entity_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[Union[str, int]] = None,
+    sort_dir: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists assignments for all roles across entities.
+        Options to scope results by any combination of roles or entities
+    https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(role_ids, (list, tuple)):
+        kwargs.update({"role_ids": ",".join(role_ids)})
+    else:
+        kwargs.update({"role_ids": role_ids})
+    return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+

Lists assignments for all roles across entities. +Options to scope results by any combination of roles or entities +https://docs.slack.dev/reference/methods/admin.roles.listAssignments

+
+
+def admin_roles_removeAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_removeAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Removes a set of users from a role for the given scopes and entities
+    https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+

Removes a set of users from a role for the given scopes and entities +https://docs.slack.dev/reference/methods/admin.roles.removeAssignments

+
+
+def admin_teams_admins_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_admins_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.inviteRequests.list

+
+
+def admin_teams_create(self,
*,
team_domain:Β str,
team_name:Β str,
team_description:Β strΒ |Β NoneΒ =Β None,
team_discoverability:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_teams_create(
+    self,
+    *,
+    team_domain: str,
+    team_name: str,
+    team_description: Optional[str] = None,
+    team_discoverability: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create an Enterprise team.
+    https://docs.slack.dev/reference/methods/admin.teams.create
+    """
+    kwargs.update(
+        {
+            "team_domain": team_domain,
+            "team_name": team_name,
+            "team_description": team_description,
+            "team_discoverability": team_discoverability,
+        }
+    )
+    return self.api_call("admin.teams.create", params=kwargs)
+
+ +
+
+def admin_teams_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all teams on an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.list", params=kwargs)
+
+

List all teams on an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.teams.list

+
+
+def admin_teams_owners_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_owners_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.owners.list
+    """
+    kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.teams.owners.list

+
+
+def admin_teams_settings_info(self, *, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_info(
+    self,
+    *,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch information about settings in a workspace
+    https://docs.slack.dev/reference/methods/admin.teams.settings.info
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("admin.teams.settings.info", params=kwargs)
+
+

Fetch information about settings in a workspace +https://docs.slack.dev/reference/methods/admin.teams.settings.info

+
+
+def admin_teams_settings_setDefaultChannels(self, *, team_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDefaultChannels(
+    self,
+    *,
+    team_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the default channels of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+    """
+    kwargs.update({"team_id": team_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDescription(self, *, team_id:Β str, description:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDescription(
+    self,
+    *,
+    team_id: str,
+    description: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the description of a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+    """
+    kwargs.update({"team_id": team_id, "description": description})
+    return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDiscoverability(self, *, team_id:Β str, discoverability:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDiscoverability(
+    self,
+    *,
+    team_id: str,
+    discoverability: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+    """
+    kwargs.update({"team_id": team_id, "discoverability": discoverability})
+    return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+ +
+
+def admin_teams_settings_setIcon(self, *, team_id:Β str, image_url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setIcon(
+    self,
+    *,
+    team_id: str,
+    image_url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+    """
+    kwargs.update({"team_id": team_id, "image_url": image_url})
+    return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setName(self, *, team_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setName(
+    self,
+    *,
+    team_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+    """
+    kwargs.update({"team_id": team_id, "name": name})
+    return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+ +
+
+def admin_usergroups_addChannels(self,
*,
channel_ids:Β strΒ |Β Sequence[str],
usergroup_id:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addChannels(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    usergroup_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+    """
+    kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addChannels

+
+
+def admin_usergroups_addTeams(self,
*,
usergroup_id:Β str,
team_ids:Β strΒ |Β Sequence[str],
auto_provision:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addTeams(
+    self,
+    *,
+    usergroup_id: str,
+    team_ids: Union[str, Sequence[str]],
+    auto_provision: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Associate one or more default workspaces with an organization-wide IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+    """
+    kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+

Associate one or more default workspaces with an organization-wide IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addTeams

+
+
+def admin_usergroups_listChannels(self,
*,
usergroup_id:Β str,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
team_id:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_listChannels(
+    self,
+    *,
+    usergroup_id: str,
+    include_num_members: Optional[bool] = None,
+    team_id: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+    """
+    kwargs.update(
+        {
+            "usergroup_id": usergroup_id,
+            "include_num_members": include_num_members,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.listChannels

+
+
+def admin_usergroups_removeChannels(self, *, usergroup_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_usergroups_removeChannels(
+    self,
+    *,
+    usergroup_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+    """
+    kwargs.update({"usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels

+
+
+def admin_users_assign(self,
*,
team_id:Β str,
user_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_assign(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an Enterprise user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.assign
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "user_id": user_id,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.assign", params=kwargs)
+
+

Add an Enterprise user to a workspace. +https://docs.slack.dev/reference/methods/admin.users.assign

+
+
+def admin_users_invite(self,
*,
team_id:Β str,
email:Β str,
channel_ids:Β strΒ |Β Sequence[str],
custom_message:Β strΒ |Β NoneΒ =Β None,
email_password_policy_enabled:Β boolΒ |Β NoneΒ =Β None,
guest_expiration_ts:Β strΒ |Β floatΒ |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
real_name:Β strΒ |Β NoneΒ =Β None,
resend:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_invite(
+    self,
+    *,
+    team_id: str,
+    email: str,
+    channel_ids: Union[str, Sequence[str]],
+    custom_message: Optional[str] = None,
+    email_password_policy_enabled: Optional[bool] = None,
+    guest_expiration_ts: Optional[Union[str, float]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    real_name: Optional[str] = None,
+    resend: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.invite
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "email": email,
+            "custom_message": custom_message,
+            "email_password_policy_enabled": email_password_policy_enabled,
+            "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+            "real_name": real_name,
+            "resend": resend,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.invite", params=kwargs)
+
+ +
+
+def admin_users_list(self,
*,
team_id:Β strΒ |Β NoneΒ =Β None,
include_deactivated_user_workspaces:Β boolΒ |Β NoneΒ =Β None,
is_active:Β boolΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    include_deactivated_user_workspaces: Optional[bool] = None,
+    is_active: Optional[bool] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List users on a workspace
+    https://docs.slack.dev/reference/methods/admin.users.list
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+            "is_active": is_active,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.users.list", params=kwargs)
+
+ +
+
+def admin_users_remove(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_remove(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a user from a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.remove
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.remove", params=kwargs)
+
+ +
+
+def admin_users_session_clearSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_clearSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Clear user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”for a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+

Clear user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”for a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.clearSettings

+
+
+def admin_users_session_getSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_getSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Get user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”given a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+

Get user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”given a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.getSettings

+
+
+def admin_users_session_invalidate(self, *, session_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_invalidate(
+    self,
+    *,
+    session_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invalidate a single session for a user by session_id.
+    https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+    """
+    kwargs.update({"session_id": session_id, "team_id": team_id})
+    return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+

Invalidate a single session for a user by session_id. +https://docs.slack.dev/reference/methods/admin.users.session.invalidate

+
+
+def admin_users_session_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all active user sessions for an organization
+    https://docs.slack.dev/reference/methods/admin.users.session.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+            "user_id": user_id,
+        }
+    )
+    return self.api_call("admin.users.session.list", params=kwargs)
+
+

Lists all active user sessions for an organization +https://docs.slack.dev/reference/methods/admin.users.session.list

+
+
+def admin_users_session_reset(self,
*,
user_id:Β str,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_reset(
+    self,
+    *,
+    user_id: str,
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Wipes all valid sessions on all devices for a given user.
+    https://docs.slack.dev/reference/methods/admin.users.session.reset
+    """
+    kwargs.update(
+        {
+            "user_id": user_id,
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.reset", params=kwargs)
+
+

Wipes all valid sessions on all devices for a given user. +https://docs.slack.dev/reference/methods/admin.users.session.reset

+
+
+def admin_users_session_resetBulk(self,
*,
user_ids:Β strΒ |Β Sequence[str],
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_resetBulk(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+    https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+

Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users +https://docs.slack.dev/reference/methods/admin.users.session.resetBulk

+
+
+def admin_users_session_setSettings(self,
*,
user_ids:Β strΒ |Β Sequence[str],
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_setSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    desktop_app_browser_quit: Optional[bool] = None,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Configure the user-level session settingsβ€”the session duration
+    and what happens when the client closesβ€”for one or more users.
+    https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "desktop_app_browser_quit": desktop_app_browser_quit,
+            "duration": duration,
+        }
+    )
+    return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+

Configure the user-level session settingsβ€”the session duration +and what happens when the client closesβ€”for one or more users. +https://docs.slack.dev/reference/methods/admin.users.session.setSettings

+
+
+def admin_users_setAdmin(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setAdmin(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or owner to be an admin user.
+    https://docs.slack.dev/reference/methods/admin.users.setAdmin
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setAdmin", params=kwargs)
+
+

Set an existing guest, regular user, or owner to be an admin user. +https://docs.slack.dev/reference/methods/admin.users.setAdmin

+
+
+def admin_users_setExpiration(self, *, expiration_ts:Β int, user_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setExpiration(
+    self,
+    *,
+    expiration_ts: int,
+    user_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set an expiration for a guest user.
+    https://docs.slack.dev/reference/methods/admin.users.setExpiration
+    """
+    kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setExpiration", params=kwargs)
+
+ +
+
+def admin_users_setOwner(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setOwner(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or admin user to be a workspace owner.
+    https://docs.slack.dev/reference/methods/admin.users.setOwner
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setOwner", params=kwargs)
+
+

Set an existing guest, regular user, or admin user to be a workspace owner. +https://docs.slack.dev/reference/methods/admin.users.setOwner

+
+
+def admin_users_setRegular(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setRegular(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest user, admin user, or owner to be a regular user.
+    https://docs.slack.dev/reference/methods/admin.users.setRegular
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setRegular", params=kwargs)
+
+

Set an existing guest user, admin user, or owner to be a regular user. +https://docs.slack.dev/reference/methods/admin.users.setRegular

+
+
+def admin_users_unsupportedVersions_export(self,
*,
date_end_of_support:Β strΒ |Β intΒ |Β NoneΒ =Β None,
date_sessions_started:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_unsupportedVersions_export(
+    self,
+    *,
+    date_end_of_support: Optional[Union[str, int]] = None,
+    date_sessions_started: Optional[Union[str, int]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+    presented as a zipped CSV file.
+    https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+    """
+    kwargs.update(
+        {
+            "date_end_of_support": date_end_of_support,
+            "date_sessions_started": date_sessions_started,
+        }
+    )
+    return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+

Ask Slackbot to send you an export listing all workspace members using unsupported software, +presented as a zipped CSV file. +https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export

+
+
+def admin_workflows_collaborators_add(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_add(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add collaborators to workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+

Add collaborators to workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add

+
+
+def admin_workflows_collaborators_remove(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_remove(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove collaborators from workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+

Remove collaborators from workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove

+
+
+def admin_workflows_permissions_lookup(self,
*,
workflow_ids:Β strΒ |Β Sequence[str],
max_workflow_triggers:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_permissions_lookup(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    max_workflow_triggers: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up the permissions for a set of workflows
+    https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    kwargs.update(
+        {
+            "max_workflow_triggers": max_workflow_triggers,
+        }
+    )
+    return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def admin_workflows_search(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    no_collaborators: Optional[bool] = None,
+    num_trigger_ids: Optional[int] = None,
+    query: Optional[str] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    source: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.search
+    """
+    if collaborator_ids is not None:
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "cursor": cursor,
+            "limit": limit,
+            "no_collaborators": no_collaborators,
+            "num_trigger_ids": num_trigger_ids,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "source": source,
+        }
+    )
+    return self.api_call("admin.workflows.search", params=kwargs)
+
+

Search workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.search

+
+
+def admin_workflows_unpublish(self, *, workflow_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_workflows_unpublish(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Unpublish workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+

Unpublish workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.unpublish

+
+
+def api_test(self, *, error:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def api_test(
+    self,
+    *,
+    error: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Checks API calling code.
+    https://docs.slack.dev/reference/methods/api.test
+    """
+    kwargs.update({"error": error})
+    return self.api_call("api.test", params=kwargs)
+
+ +
+
+def apps_connections_open(self, *, app_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_connections_open(
+    self,
+    *,
+    app_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+    in order to receive events and interactive payloads
+    https://docs.slack.dev/reference/methods/apps.connections.open
+    """
+    kwargs.update({"token": app_token})
+    return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+

Generate a temporary Socket Mode WebSocket URL that your app can connect to +in order to receive events and interactive payloads +https://docs.slack.dev/reference/methods/apps.connections.open

+
+
+def apps_event_authorizations_list(self,
*,
event_context:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def apps_event_authorizations_list(
+    self,
+    *,
+    event_context: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a list of authorizations for the given event context.
+    Each authorization represents an app installation that the event is visible to.
+    https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+    """
+    kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+    return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+

Get a list of authorizations for the given event context. +Each authorization represents an app installation that the event is visible to. +https://docs.slack.dev/reference/methods/apps.event.authorizations.list

+
+
+def apps_manifest_create(self, *, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_create(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.create
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    return self.api_call("apps.manifest.create", params=kwargs)
+
+ +
+
+def apps_manifest_delete(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_delete(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Permanently deletes an app created through app manifests
+    https://docs.slack.dev/reference/methods/apps.manifest.delete
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.delete", params=kwargs)
+
+

Permanently deletes an app created through app manifests +https://docs.slack.dev/reference/methods/apps.manifest.delete

+
+
+def apps_manifest_export(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_export(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Export an app manifest from an existing app
+    https://docs.slack.dev/reference/methods/apps.manifest.export
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.export", params=kwargs)
+
+

Export an app manifest from an existing app +https://docs.slack.dev/reference/methods/apps.manifest.export

+
+
+def apps_manifest_update(self, *, app_id:Β str, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_update(
+    self,
+    *,
+    app_id: str,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.update
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.update", params=kwargs)
+
+ +
+
+def apps_manifest_validate(self, *, manifest:Β strΒ |Β Dict[str,Β Any], app_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_validate(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    app_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Validate an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.validate
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.validate", params=kwargs)
+
+ +
+
+def apps_uninstall(self, *, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_uninstall(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstalls your app from a workspace.
+    https://docs.slack.dev/reference/methods/apps.uninstall
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret})
+    return self.api_call("apps.uninstall", params=kwargs)
+
+

Uninstalls your app from a workspace. +https://docs.slack.dev/reference/methods/apps.uninstall

+
+
+def assistant_threads_setStatus(self,
*,
channel_id:Β str,
thread_ts:Β str,
status:Β str,
loading_messages:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setStatus(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    status: str,
+    loading_messages: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the status for an AI assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+    """
+    kwargs.update(
+        {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+ +
+
+def assistant_threads_setSuggestedPrompts(self,
*,
channel_id:Β str,
thread_ts:Β str,
title:Β strΒ |Β NoneΒ =Β None,
prompts:Β List[Dict[str,Β str]],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setSuggestedPrompts(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: Optional[str] = None,
+    prompts: List[Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set suggested prompts for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+    if title is not None:
+        kwargs.update({"title": title})
+    return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+

Set suggested prompts for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts

+
+
+def assistant_threads_setTitle(self, *, channel_id:Β str, thread_ts:Β str, title:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def assistant_threads_setTitle(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the title for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+    return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+

Set the title for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setTitle

+
+
+def auth_revoke(self, *, test:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_revoke(
+    self,
+    *,
+    test: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes a token.
+    https://docs.slack.dev/reference/methods/auth.revoke
+    """
+    kwargs.update({"test": test})
+    return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+ +
+
+def auth_teams_list(self,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
include_icon:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def auth_teams_list(
+    self,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    include_icon: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List the workspaces a token can access.
+    https://docs.slack.dev/reference/methods/auth.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+    return self.api_call("auth.teams.list", params=kwargs)
+
+

List the workspaces a token can access. +https://docs.slack.dev/reference/methods/auth.teams.list

+
+
+def auth_test(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_test(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Checks authentication & identity.
+    https://docs.slack.dev/reference/methods/auth.test
+    """
+    return self.api_call("auth.test", params=kwargs)
+
+

Checks authentication & identity. +https://docs.slack.dev/reference/methods/auth.test

+
+
+def bookmarks_add(self,
*,
channel_id:Β str,
title:Β str,
type:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
entity_id:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
parent_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_add(
+    self,
+    *,
+    channel_id: str,
+    title: str,
+    type: str,
+    emoji: Optional[str] = None,
+    entity_id: Optional[str] = None,
+    link: Optional[str] = None,  # include when type is 'link'
+    parent_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add bookmark to a channel.
+    https://docs.slack.dev/reference/methods/bookmarks.add
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "title": title,
+            "type": type,
+            "emoji": emoji,
+            "entity_id": entity_id,
+            "link": link,
+            "parent_id": parent_id,
+        }
+    )
+    return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_edit(self,
*,
bookmark_id:Β str,
channel_id:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_edit(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    emoji: Optional[str] = None,
+    link: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Edit bookmark.
+    https://docs.slack.dev/reference/methods/bookmarks.edit
+    """
+    kwargs.update(
+        {
+            "bookmark_id": bookmark_id,
+            "channel_id": channel_id,
+            "emoji": emoji,
+            "link": link,
+            "title": title,
+        }
+    )
+    return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_list(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_list(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """List bookmark for the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.list
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_remove(self, *, bookmark_id:Β str, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_remove(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove bookmark from the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.remove
+    """
+    kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+    return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def bots_info(self, *, bot:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bots_info(
+    self,
+    *,
+    bot: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a bot user.
+    https://docs.slack.dev/reference/methods/bots.info
+    """
+    kwargs.update({"bot": bot, "team_id": team_id})
+    return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+

Gets information about a bot user. +https://docs.slack.dev/reference/methods/bots.info

+
+
+def calls_add(self,
*,
external_unique_id:Β str,
join_url:Β str,
created_by:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
external_display_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_add(
+    self,
+    *,
+    external_unique_id: str,
+    join_url: str,
+    created_by: Optional[str] = None,
+    date_start: Optional[int] = None,
+    desktop_app_join_url: Optional[str] = None,
+    external_display_id: Optional[str] = None,
+    title: Optional[str] = None,
+    users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Registers a new Call.
+    https://docs.slack.dev/reference/methods/calls.add
+    """
+    kwargs.update(
+        {
+            "external_unique_id": external_unique_id,
+            "join_url": join_url,
+            "created_by": created_by,
+            "date_start": date_start,
+            "desktop_app_join_url": desktop_app_join_url,
+            "external_display_id": external_display_id,
+            "title": title,
+        }
+    )
+    _update_call_participants(
+        kwargs,
+        users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+    )
+    return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_end(self, *, id:Β str, duration:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_end(
+    self,
+    *,
+    id: str,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ends a Call.
+    https://docs.slack.dev/reference/methods/calls.end
+    """
+    kwargs.update({"id": id, "duration": duration})
+    return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_info(self, *, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_info(
+    self,
+    *,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Returns information about a Call.
+    https://docs.slack.dev/reference/methods/calls.info
+    """
+    kwargs.update({"id": id})
+    return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+

Returns information about a Call. +https://docs.slack.dev/reference/methods/calls.info

+
+
+def calls_participants_add(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_add(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers new participants added to a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.add
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+

Registers new participants added to a Call. +https://docs.slack.dev/reference/methods/calls.participants.add

+
+
+def calls_participants_remove(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_remove(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers participants removed from a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.remove
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+

Registers participants removed from a Call. +https://docs.slack.dev/reference/methods/calls.participants.remove

+
+
+def calls_update(self,
*,
id:Β str,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
join_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_update(
+    self,
+    *,
+    id: str,
+    desktop_app_join_url: Optional[str] = None,
+    join_url: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates information about a Call.
+    https://docs.slack.dev/reference/methods/calls.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "desktop_app_join_url": desktop_app_join_url,
+            "join_url": join_url,
+            "title": title,
+        }
+    )
+    return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+ +
+
+def canvases_access_delete(self,
*,
canvas_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_delete(
+    self,
+    *,
+    canvas_id: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/canvases.access.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("canvases.access.delete", params=kwargs)
+
+ +
+
+def canvases_access_set(self,
*,
canvas_id:Β str,
access_level:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_set(
+    self,
+    *,
+    canvas_id: str,
+    access_level: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the access level to a canvas for specified entities
+    https://docs.slack.dev/reference/methods/canvases.access.set
+    """
+    kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+
+    return self.api_call("canvases.access.set", params=kwargs)
+
+

Sets the access level to a canvas for specified entities +https://docs.slack.dev/reference/methods/canvases.access.set

+
+
+def canvases_create(self, *, title:Β strΒ |Β NoneΒ =Β None, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_create(
+    self,
+    *,
+    title: Optional[str] = None,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create Canvas for a user
+    https://docs.slack.dev/reference/methods/canvases.create
+    """
+    kwargs.update({"title": title, "document_content": document_content})
+    return self.api_call("canvases.create", json=kwargs)
+
+ +
+
+def canvases_delete(self, *, canvas_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_delete(
+    self,
+    *,
+    canvas_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a canvas
+    https://docs.slack.dev/reference/methods/canvases.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    return self.api_call("canvases.delete", params=kwargs)
+
+ +
+
+def canvases_edit(self, *, canvas_id:Β str, changes:Β Sequence[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_edit(
+    self,
+    *,
+    canvas_id: str,
+    changes: Sequence[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing canvas
+    https://docs.slack.dev/reference/methods/canvases.edit
+    """
+    kwargs.update({"canvas_id": canvas_id, "changes": changes})
+    return self.api_call("canvases.edit", json=kwargs)
+
+ +
+
+def canvases_sections_lookup(self, *, canvas_id:Β str, criteria:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_sections_lookup(
+    self,
+    *,
+    canvas_id: str,
+    criteria: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Find sections matching the provided criteria
+    https://docs.slack.dev/reference/methods/canvases.sections.lookup
+    """
+    kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+    return self.api_call("canvases.sections.lookup", params=kwargs)
+
+

Find sections matching the provided criteria +https://docs.slack.dev/reference/methods/canvases.sections.lookup

+
+
+def channels_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.archive", json=kwargs)
+
+

Archives a channel.

+
+
+def channels_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.create", json=kwargs)
+
+

Creates a channel.

+
+
+def channels_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a channel.

+
+
+def channels_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+

Gets information about a channel.

+
+
+def channels_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.invite", json=kwargs)
+
+

Invites a user to a channel.

+
+
+def channels_join(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_join(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins a channel, creating it if needed."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.join", json=kwargs)
+
+

Joins a channel, creating it if needed.

+
+
+def channels_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.kick", json=kwargs)
+
+

Removes a user from a channel.

+
+
+def channels_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.leave", json=kwargs)
+
+

Leaves a channel.

+
+
+def channels_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team."""
+    return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+

Lists all channels in a Slack team.

+
+
+def channels_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.mark", json=kwargs)
+
+

Sets the read cursor in a channel.

+
+
+def channels_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.rename", json=kwargs)
+
+

Renames a channel.

+
+
+def channels_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a channel

+
+
+def channels_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setPurpose", json=kwargs)
+
+

Sets the purpose for a channel.

+
+
+def channels_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setTopic", json=kwargs)
+
+

Sets the topic for a channel.

+
+
+def channels_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.unarchive", json=kwargs)
+
+

Unarchives a channel.

+
+
+def chat_appendStream(self, *, channel:Β str, ts:Β str, markdown_text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_appendStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Appends text to an existing streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.appendStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.appendStream", json=kwargs)
+
+

Appends text to an existing streaming conversation. +https://docs.slack.dev/reference/methods/chat.appendStream

+
+
+def chat_delete(self, *, channel:Β str, ts:Β str, as_user:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_delete(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a message.
+    https://docs.slack.dev/reference/methods/chat.delete
+    """
+    kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+    return self.api_call("chat.delete", params=kwargs)
+
+ +
+
+def chat_deleteScheduledMessage(self,
*,
channel:Β str,
scheduled_message_id:Β str,
as_user:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_deleteScheduledMessage(
+    self,
+    *,
+    channel: str,
+    scheduled_message_id: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a scheduled message.
+    https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "scheduled_message_id": scheduled_message_id,
+            "as_user": as_user,
+        }
+    )
+    return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def chat_getPermalink(
+    self,
+    *,
+    channel: str,
+    message_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a permalink URL for a specific extant message
+    https://docs.slack.dev/reference/methods/chat.getPermalink
+    """
+    kwargs.update({"channel": channel, "message_ts": message_ts})
+    return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+

Retrieve a permalink URL for a specific extant message +https://docs.slack.dev/reference/methods/chat.getPermalink

+
+
+def chat_meMessage(self, *, channel:Β str, text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_meMessage(
+    self,
+    *,
+    channel: str,
+    text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Share a me message into a channel.
+    https://docs.slack.dev/reference/methods/chat.meMessage
+    """
+    kwargs.update({"channel": channel, "text": text})
+    return self.api_call("chat.meMessage", params=kwargs)
+
+ +
+
+def chat_postEphemeral(self,
*,
channel:Β str,
user:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postEphemeral(
+    self,
+    *,
+    channel: str,
+    user: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an ephemeral message to a user in a channel.
+    https://docs.slack.dev/reference/methods/chat.postEphemeral
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "user": user,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postEphemeral", json=kwargs)
+
+

Sends an ephemeral message to a user in a channel. +https://docs.slack.dev/reference/methods/chat.postEphemeral

+
+
+def chat_postMessage(self,
*,
channel:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
container_id:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
mrkdwn:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postMessage(
+    self,
+    *,
+    channel: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    container_id: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    mrkdwn: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,  # none, full
+    metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends a message to a channel.
+    https://docs.slack.dev/reference/methods/chat.postMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "container_id": container_id,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "mrkdwn": mrkdwn,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postMessage", json=kwargs)
+
+ +
+
+def chat_scheduleMessage(self,
*,
channel:Β str,
post_at:Β strΒ |Β int,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduleMessage(
+    self,
+    *,
+    channel: str,
+    post_at: Union[str, int],
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    parse: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Schedules a message.
+    https://docs.slack.dev/reference/methods/chat.scheduleMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "post_at": post_at,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "parse": parse,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "link_names": link_names,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.scheduleMessage", json=kwargs)
+
+ +
+
+def chat_scheduledMessages_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduledMessages_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all scheduled messages.
+    https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "latest": latest,
+            "limit": limit,
+            "oldest": oldest,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+ +
+
+def chat_startStream(self,
*,
channel:Β str,
thread_ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_startStream(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    markdown_text: Optional[str] = None,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a new streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.startStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "markdown_text": markdown_text,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.startStream", json=kwargs)
+
+

Starts a new streaming conversation. +https://docs.slack.dev/reference/methods/chat.startStream

+
+
+def chat_stopStream(self,
*,
channel:Β str,
ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_stopStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Stops a streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.stopStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+            "blocks": blocks,
+            "metadata": metadata,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.stopStream", json=kwargs)
+
+ +
+
+def chat_stream(self,
*,
buffer_size:Β intΒ =Β 256,
channel:Β str,
thread_ts:Β str,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β ChatStream
+
+
+
+ +Expand source code + +
def chat_stream(
+    self,
+    *,
+    buffer_size: int = 256,
+    channel: str,
+    thread_ts: str,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> ChatStream:
+    """Stream markdown text into a conversation.
+
+    This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+    the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+    The following methods are used:
+
+    - chat.startStream: Starts a new streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+    - chat.appendStream: Appends text to an existing streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+    - chat.stopStream: Stops a streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+    Args:
+        buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+          value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+          limits. Default: 256.
+        channel: An encoded ID that represents a channel, private group, or DM.
+        thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+          request.
+        recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+          streaming to channels.
+        recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        ChatStream instance for managing the stream
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    return ChatStream(
+        self,
+        logger=self._logger,
+        channel=channel,
+        thread_ts=thread_ts,
+        recipient_team_id=recipient_team_id,
+        recipient_user_id=recipient_user_id,
+        buffer_size=buffer_size,
+        **kwargs,
+    )
+
+

Stream markdown text into a conversation.

+

This method starts a new chat stream in a conversation that can be appended to. After appending an entire message, +the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.

+

The following methods are used:

+
    +
  • chat.startStream: Starts a new streaming conversation. +Reference.
  • +
  • chat.appendStream: Appends text to an existing streaming conversation. +Reference.
  • +
  • chat.stopStream: Stops a streaming conversation. +Reference.
  • +
+

Args

+
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a stream method. Increasing this +value decreases the number of method calls made for the same amount of text, which is useful to avoid rate +limits. Default: 256.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

ChatStream instance for managing the stream

+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+def chat_unfurl(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
ts:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
unfurl_id:Β strΒ |Β NoneΒ =Β None,
unfurls:Β Dict[str,Β Dict]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
user_auth_blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
user_auth_message:Β strΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_unfurl(
+    self,
+    *,
+    channel: Optional[str] = None,
+    ts: Optional[str] = None,
+    source: Optional[str] = None,
+    unfurl_id: Optional[str] = None,
+    unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+    metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+    user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    user_auth_message: Optional[str] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provide custom unfurl behavior for user-posted URLs.
+    https://docs.slack.dev/reference/methods/chat.unfurl
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "source": source,
+            "unfurl_id": unfurl_id,
+            "unfurls": unfurls,
+            "metadata": metadata,
+            "user_auth_blocks": user_auth_blocks,
+            "user_auth_message": user_auth_message,
+            "user_auth_required": user_auth_required,
+            "user_auth_url": user_auth_url,
+        }
+    )
+    _parse_web_class_objects(kwargs)  # for user_auth_blocks
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.unfurl", json=kwargs)
+
+

Provide custom unfurl behavior for user-posted URLs. +https://docs.slack.dev/reference/methods/chat.unfurl

+
+
+def chat_update(self,
*,
channel:Β str,
ts:Β str,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
file_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_update(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    text: Optional[str] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    as_user: Optional[bool] = None,
+    file_ids: Optional[Union[str, Sequence[str]]] = None,
+    link_names: Optional[bool] = None,
+    parse: Optional[str] = None,  # none, full
+    reply_broadcast: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates a message in a channel.
+    https://docs.slack.dev/reference/methods/chat.update
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "as_user": as_user,
+            "link_names": link_names,
+            "parse": parse,
+            "reply_broadcast": reply_broadcast,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    if isinstance(file_ids, (list, tuple)):
+        kwargs.update({"file_ids": ",".join(file_ids)})
+    else:
+        kwargs.update({"file_ids": file_ids})
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.update", kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.update", json=kwargs)
+
+ +
+
+def conversations_acceptSharedInvite(self,
*,
channel_name:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
free_trial_accepted:Β boolΒ |Β NoneΒ =Β None,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_acceptSharedInvite(
+    self,
+    *,
+    channel_name: str,
+    channel_id: Optional[str] = None,
+    invite_id: Optional[str] = None,
+    free_trial_accepted: Optional[bool] = None,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Accepts an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+    """
+    if channel_id is None and invite_id is None:
+        raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+    kwargs.update(
+        {
+            "channel_name": channel_name,
+            "channel_id": channel_id,
+            "invite_id": invite_id,
+            "free_trial_accepted": free_trial_accepted,
+            "is_private": is_private,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+

Accepts an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite

+
+
+def conversations_approveSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_approveSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approves an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+

Approves an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.approveSharedInvite

+
+
+def conversations_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a conversation.
+    https://docs.slack.dev/reference/methods/conversations.archive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.archive", params=kwargs)
+
+ +
+
+def conversations_canvases_create(self, *, channel_id:Β str, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_canvases_create(
+    self,
+    *,
+    channel_id: str,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/conversations.canvases.create
+    """
+    kwargs.update({"channel_id": channel_id, "document_content": document_content})
+    return self.api_call("conversations.canvases.create", json=kwargs)
+
+ +
+
+def conversations_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.close
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.close", params=kwargs)
+
+

Closes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.close

+
+
+def conversations_create(self,
*,
name:Β str,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_create(
+    self,
+    *,
+    name: str,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiates a public or private channel-based conversation
+    https://docs.slack.dev/reference/methods/conversations.create
+    """
+    kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+    return self.api_call("conversations.create", params=kwargs)
+
+

Initiates a public or private channel-based conversation +https://docs.slack.dev/reference/methods/conversations.create

+
+
+def conversations_declineSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_declineSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Declines a Slack Connect channel invite.
+    https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_externalInvitePermissions_set(self, *, action:Β str, channel:Β str, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_externalInvitePermissions_set(
+    self, *, action: str, channel: str, target_team: str, **kwargs
+) -> SlackResponse:
+    """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+    https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+    """
+    kwargs.update(
+        {
+            "action": action,
+            "channel": channel,
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+

Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa. +https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set

+
+
+def conversations_history(self,
*,
channel:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_history(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches a conversation's history of messages and events.
+    https://docs.slack.dev/reference/methods/conversations.history
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+

Fetches a conversation's history of messages and events. +https://docs.slack.dev/reference/methods/conversations.history

+
+
+def conversations_info(self,
*,
channel:Β str,
include_locale:Β boolΒ |Β NoneΒ =Β None,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_info(
+    self,
+    *,
+    channel: str,
+    include_locale: Optional[bool] = None,
+    include_num_members: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a conversation.
+    https://docs.slack.dev/reference/methods/conversations.info
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "include_locale": include_locale,
+            "include_num_members": include_num_members,
+        }
+    )
+    return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a conversation. +https://docs.slack.dev/reference/methods/conversations.info

+
+
+def conversations_invite(self,
*,
channel:Β str,
users:Β strΒ |Β Sequence[str],
force:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_invite(
+    self,
+    *,
+    channel: str,
+    users: Union[str, Sequence[str]],
+    force: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invites users to a channel.
+    https://docs.slack.dev/reference/methods/conversations.invite
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "force": force,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.invite", params=kwargs)
+
+ +
+
+def conversations_inviteShared(self,
*,
channel:Β str,
emails:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_inviteShared(
+    self,
+    *,
+    channel: str,
+    emails: Optional[Union[str, Sequence[str]]] = None,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.inviteShared
+    """
+    if emails is None and user_ids is None:
+        raise e.SlackRequestError("Either emails or user ids must be provided.")
+    kwargs.update({"channel": channel})
+    if isinstance(emails, (list, tuple)):
+        kwargs.update({"emails": ",".join(emails)})
+    else:
+        kwargs.update({"emails": emails})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+

Sends an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.inviteShared

+
+
+def conversations_join(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_join(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins an existing conversation.
+    https://docs.slack.dev/reference/methods/conversations.join
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.join", params=kwargs)
+
+ +
+
+def conversations_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a conversation.
+    https://docs.slack.dev/reference/methods/conversations.kick
+    """
+    kwargs.update({"channel": channel, "user": user})
+    return self.api_call("conversations.kick", params=kwargs)
+
+ +
+
+def conversations_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a conversation.
+    https://docs.slack.dev/reference/methods/conversations.leave
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.leave", params=kwargs)
+
+ +
+
+def conversations_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team.
+    https://docs.slack.dev/reference/methods/conversations.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_listConnectInvites(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_listConnectInvites(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List shared channel invites that have been generated
+    or received but have not yet been approved by all parties.
+    https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+    """
+    kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+    return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+

List shared channel invites that have been generated +or received but have not yet been approved by all parties. +https://docs.slack.dev/reference/methods/conversations.listConnectInvites

+
+
+def conversations_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel.
+    https://docs.slack.dev/reference/methods/conversations.mark
+    """
+    kwargs.update({"channel": channel, "ts": ts})
+    return self.api_call("conversations.mark", params=kwargs)
+
+ +
+
+def conversations_members(self, *, channel:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_members(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve members of a conversation.
+    https://docs.slack.dev/reference/methods/conversations.members
+    """
+    kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+    return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_open(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
return_im:Β boolΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_open(
+    self,
+    *,
+    channel: Optional[str] = None,
+    return_im: Optional[bool] = None,
+    users: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Opens or resumes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.open
+    """
+    if channel is None and users is None:
+        raise e.SlackRequestError("Either channel or users must be provided.")
+    kwargs.update({"channel": channel, "return_im": return_im})
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.open", params=kwargs)
+
+

Opens or resumes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.open

+
+
+def conversations_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a conversation.
+    https://docs.slack.dev/reference/methods/conversations.rename
+    """
+    kwargs.update({"channel": channel, "name": name})
+    return self.api_call("conversations.rename", params=kwargs)
+
+ +
+
+def conversations_replies(self,
*,
channel:Β str,
ts:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_replies(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a conversation
+    https://docs.slack.dev/reference/methods/conversations.replies
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a conversation +https://docs.slack.dev/reference/methods/conversations.replies

+
+
+def conversations_requestSharedInvite_approve(self,
*,
invite_id:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
is_external_limited:Β strΒ |Β NoneΒ =Β None,
message:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_approve(
+    self,
+    *,
+    invite_id: str,
+    channel_id: Optional[str] = None,
+    is_external_limited: Optional[str] = None,
+    message: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+    """
+    kwargs.update(
+        {
+            "invite_id": invite_id,
+            "channel_id": channel_id,
+            "is_external_limited": is_external_limited,
+        }
+    )
+    if message is not None:
+        kwargs.update({"message": json.dumps(message)})
+    return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+

Approve a request to add an external user to a channel. This also sends them a Slack Connect invite. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve

+
+
+def conversations_requestSharedInvite_deny(self, *, invite_id:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_deny(
+    self,
+    *,
+    invite_id: str,
+    message: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a request to invite an external user to a channel.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+    """
+    kwargs.update({"invite_id": invite_id, "message": message})
+    return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+

Deny a request to invite an external user to a channel. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny

+
+
+def conversations_requestSharedInvite_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_approved:Β boolΒ |Β NoneΒ =Β None,
include_denied:Β boolΒ |Β NoneΒ =Β None,
include_expired:Β boolΒ |Β NoneΒ =Β None,
invite_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_approved: Optional[bool] = None,
+    include_denied: Optional[bool] = None,
+    include_expired: Optional[bool] = None,
+    invite_ids: Optional[Union[str, Sequence[str]]] = None,
+    limit: Optional[int] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists requests to add external users to channels with ability to filter.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_approved": include_approved,
+            "include_denied": include_denied,
+            "include_expired": include_expired,
+            "limit": limit,
+            "user_id": user_id,
+        }
+    )
+    if invite_ids is not None:
+        if isinstance(invite_ids, (list, tuple)):
+            kwargs.update({"invite_ids": ",".join(invite_ids)})
+        else:
+            kwargs.update({"invite_ids": invite_ids})
+    return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+

Lists requests to add external users to channels with ability to filter. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list

+
+
+def conversations_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setPurpose
+    """
+    kwargs.update({"channel": channel, "purpose": purpose})
+    return self.api_call("conversations.setPurpose", params=kwargs)
+
+ +
+
+def conversations_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setTopic
+    """
+    kwargs.update({"channel": channel, "topic": topic})
+    return self.api_call("conversations.setTopic", params=kwargs)
+
+ +
+
+def conversations_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Reverses conversation archival.
+    https://docs.slack.dev/reference/methods/conversations.unarchive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.unarchive", params=kwargs)
+
+ +
+
+def dialog_open(self, *, dialog:Β Dict[str,Β Any], trigger_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dialog_open(
+    self,
+    *,
+    dialog: Dict[str, Any],
+    trigger_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Open a dialog with a user.
+    https://docs.slack.dev/reference/methods/dialog.open
+    """
+    kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: As the dialog can be a dict, this API call works only with json format.
+    return self.api_call("dialog.open", json=kwargs)
+
+ +
+
+def dnd_endDnd(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endDnd(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's Do Not Disturb session immediately.
+    https://docs.slack.dev/reference/methods/dnd.endDnd
+    """
+    return self.api_call("dnd.endDnd", params=kwargs)
+
+

Ends the current user's Do Not Disturb session immediately. +https://docs.slack.dev/reference/methods/dnd.endDnd

+
+
+def dnd_endSnooze(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endSnooze(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's snooze mode immediately.
+    https://docs.slack.dev/reference/methods/dnd.endSnooze
+    """
+    return self.api_call("dnd.endSnooze", params=kwargs)
+
+

Ends the current user's snooze mode immediately. +https://docs.slack.dev/reference/methods/dnd.endSnooze

+
+
+def dnd_info(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_info(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's current Do Not Disturb status.
+    https://docs.slack.dev/reference/methods/dnd.info
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+

Retrieves a user's current Do Not Disturb status. +https://docs.slack.dev/reference/methods/dnd.info

+
+
+def dnd_setSnooze(self, *, num_minutes:Β strΒ |Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_setSnooze(
+    self,
+    *,
+    num_minutes: Union[int, str],
+    **kwargs,
+) -> SlackResponse:
+    """Turns on Do Not Disturb mode for the current user, or changes its duration.
+    https://docs.slack.dev/reference/methods/dnd.setSnooze
+    """
+    kwargs.update({"num_minutes": num_minutes})
+    return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+

Turns on Do Not Disturb mode for the current user, or changes its duration. +https://docs.slack.dev/reference/methods/dnd.setSnooze

+
+
+def dnd_teamInfo(self, users:Β strΒ |Β Sequence[str], team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_teamInfo(
+    self,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves the Do Not Disturb status for users on a team.
+    https://docs.slack.dev/reference/methods/dnd.teamInfo
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id})
+    return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+

Retrieves the Do Not Disturb status for users on a team. +https://docs.slack.dev/reference/methods/dnd.teamInfo

+
+
+def emoji_list(self, include_categories:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def emoji_list(
+    self,
+    include_categories: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists custom emoji for a team.
+    https://docs.slack.dev/reference/methods/emoji.list
+    """
+    kwargs.update({"include_categories": include_categories})
+    return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+ +
+
+def entity_presentDetails(self,
trigger_id:Β str,
metadata:Β DictΒ |Β EntityMetadataΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def entity_presentDetails(
+    self,
+    trigger_id: str,
+    metadata: Optional[Union[Dict, EntityMetadata]] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    error: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provides entity details for the flexpane.
+    https://docs.slack.dev/reference/methods/entity.presentDetails/
+    """
+    kwargs.update({"trigger_id": trigger_id})
+    if metadata is not None:
+        kwargs.update({"metadata": metadata})
+    if user_auth_required is not None:
+        kwargs.update({"user_auth_required": user_auth_required})
+    if user_auth_url is not None:
+        kwargs.update({"user_auth_url": user_auth_url})
+    if error is not None:
+        kwargs.update({"error": error})
+    _parse_web_class_objects(kwargs)
+    return self.api_call("entity.presentDetails", json=kwargs)
+
+

Provides entity details for the flexpane. +https://docs.slack.dev/reference/methods/entity.presentDetails/

+
+
+def files_comments_delete(self, *, file:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_comments_delete(
+    self,
+    *,
+    file: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an existing comment on a file.
+    https://docs.slack.dev/reference/methods/files.comments.delete
+    """
+    kwargs.update({"file": file, "id": id})
+    return self.api_call("files.comments.delete", params=kwargs)
+
+ +
+
+def files_completeUploadExternal(self,
*,
files:Β List[Dict[str,Β str]],
channel_id:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_completeUploadExternal(
+    self,
+    *,
+    files: List[Dict[str, str]],
+    channel_id: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Finishes an upload started with files.getUploadURLExternal.
+    https://docs.slack.dev/reference/methods/files.completeUploadExternal
+    """
+    _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+    kwargs.update(
+        {
+            "files": json.dumps(_files),
+            "channel_id": channel_id,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+        }
+    )
+    if channels:
+        kwargs["channels"] = ",".join(channels)
+    return self.api_call("files.completeUploadExternal", params=kwargs)
+
+

Finishes an upload started with files.getUploadURLExternal. +https://docs.slack.dev/reference/methods/files.completeUploadExternal

+
+
+def files_delete(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_delete(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a file.
+    https://docs.slack.dev/reference/methods/files.delete
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.delete", params=kwargs)
+
+ +
+
+def files_getUploadURLExternal(self,
*,
filename:Β str,
length:Β int,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_getUploadURLExternal(
+    self,
+    *,
+    filename: str,
+    length: int,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets a URL for an edge external upload.
+    https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+    """
+    kwargs.update(
+        {
+            "filename": filename,
+            "length": length,
+            "alt_txt": alt_txt,
+            "snippet_type": snippet_type,
+        }
+    )
+    return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+ +
+
+def files_info(self,
*,
file:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_info(
+    self,
+    *,
+    file: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a team file.
+    https://docs.slack.dev/reference/methods/files.info
+    """
+    kwargs.update(
+        {
+            "file": file,
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+        }
+    )
+    return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+

Gets information about a team file. +https://docs.slack.dev/reference/methods/files.info

+
+
+def files_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
count:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
show_files_hidden_by_limit:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    count: Optional[int] = None,
+    page: Optional[int] = None,
+    show_files_hidden_by_limit: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists & filters team files.
+    https://docs.slack.dev/reference/methods/files.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "count": count,
+            "page": page,
+            "show_files_hidden_by_limit": show_files_hidden_by_limit,
+            "team_id": team_id,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_add(self,
*,
external_id:Β str,
external_url:Β str,
title:Β str,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_add(
+    self,
+    *,
+    external_id: str,
+    external_url: str,
+    title: str,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+    preview_image: Optional[Union[str, bytes, IOBase]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a file from a remote service.
+    https://docs.slack.dev/reference/methods/files.remote.add
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.add",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_remote_info(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_info(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.info
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.info

+
+
+def files_remote_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "limit": limit,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+        }
+    )
+    return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.list

+
+
+def files_remote_remove(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_remove(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a remote file.
+    https://docs.slack.dev/reference/methods/files.remote.remove
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def files_remote_share(self,
*,
channels:Β strΒ |Β Sequence[str],
external_id:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_share(
+    self,
+    *,
+    channels: Union[str, Sequence[str]],
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Share a remote file into a channel.
+    https://docs.slack.dev/reference/methods/files.remote.share
+    """
+    if external_id is None and file is None:
+        raise e.SlackRequestError("Either external_id or file must be provided.")
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_update(self,
*,
external_id:Β strΒ |Β NoneΒ =Β None,
external_url:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_update(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    external_url: Optional[str] = None,
+    file: Optional[str] = None,
+    title: Optional[str] = None,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[str] = None,
+    preview_image: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates an existing remote file.
+    https://docs.slack.dev/reference/methods/files.remote.update
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "file": file,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.update",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_revokePublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_revokePublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes public/external sharing access for a file
+    https://docs.slack.dev/reference/methods/files.revokePublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.revokePublicURL", params=kwargs)
+
+

Revokes public/external sharing access for a file +https://docs.slack.dev/reference/methods/files.revokePublicURL

+
+
+def files_sharedPublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_sharedPublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Enables a file for public/external sharing.
+    https://docs.slack.dev/reference/methods/files.sharedPublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.sharedPublicURL", params=kwargs)
+
+

Enables a file for public/external sharing. +https://docs.slack.dev/reference/methods/files.sharedPublicURL

+
+
+def files_upload(self,
*,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
filename:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload(
+    self,
+    *,
+    file: Optional[Union[str, bytes, IOBase]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    filename: Optional[str] = None,
+    filetype: Optional[str] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    title: Optional[str] = None,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uploads or creates a file.
+    https://docs.slack.dev/reference/methods/files.upload
+    """
+    _print_files_upload_v2_suggestion()
+
+    if file is None and content is None:
+        raise e.SlackRequestError("The file or content argument must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update(
+        {
+            "filename": filename,
+            "filetype": filetype,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+            "title": title,
+        }
+    )
+    if file:
+        if kwargs.get("filename") is None and isinstance(file, str):
+            # use the local filename if filename is missing
+            if kwargs.get("filename") is None:
+                kwargs["filename"] = file.split(os.path.sep)[-1]
+        return self.api_call("files.upload", files={"file": file}, data=kwargs)
+    else:
+        kwargs["content"] = content
+        return self.api_call("files.upload", data=kwargs)
+
+ +
+
+def files_upload_v2(self,
*,
filename:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β os.PathLikeΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
file_uploads:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
request_file_info:Β boolΒ =Β True,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload_v2(
+    self,
+    *,
+    # for sending a single file
+    filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+    file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    title: Optional[str] = None,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    # To upload multiple files at a time
+    file_uploads: Optional[List[Dict[str, Any]]] = None,
+    channel: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+    **kwargs,
+) -> SlackResponse:
+    """This wrapper method provides an easy way to upload files using the following endpoints:
+
+    - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+    - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+    - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        and https://docs.slack.dev/reference/methods/files.info
+
+    """
+    if file is None and content is None and file_uploads is None:
+        raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    # deprecated arguments:
+    filetype = kwargs.get("filetype")
+
+    if filetype is not None:
+        warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+    # step1: files.getUploadURLExternal per file
+    files: List[Dict[str, Any]] = []
+    if file_uploads is not None:
+        for f in file_uploads:
+            files.append(_to_v2_file_upload_item(f))
+    else:
+        f = _to_v2_file_upload_item(
+            {
+                "filename": filename,
+                "file": file,
+                "content": content,
+                "title": title,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        files.append(f)
+
+    for f in files:
+        url_response = self.files_getUploadURLExternal(
+            filename=f.get("filename"),  # type: ignore[arg-type]
+            length=f.get("length"),  # type: ignore[arg-type]
+            alt_txt=f.get("alt_txt"),
+            snippet_type=f.get("snippet_type"),
+            token=kwargs.get("token"),
+        )
+        _validate_for_legacy_client(url_response)
+        f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+        f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+    # step2: "https://files.slack.com/upload/v1/..." per file
+    for f in files:
+        upload_result = self._upload_file(
+            url=f["upload_url"],
+            data=f["data"],
+            logger=self._logger,
+            timeout=self.timeout,
+            proxy=self.proxy,
+            ssl=self.ssl,
+        )
+        if upload_result.status != 200:
+            status = upload_result.status
+            body = upload_result.body
+            message = (
+                "Failed to upload a file "
+                f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+            )
+            raise e.SlackRequestError(message)
+
+    # step3: files.completeUploadExternal with all the sets of (file_id + title)
+    completion = self.files_completeUploadExternal(
+        files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+        channel_id=channel,
+        channels=channels,
+        initial_comment=initial_comment,
+        thread_ts=thread_ts,
+        **kwargs,
+    )
+    if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+        completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+    return completion
+
+

This wrapper method provides an easy way to upload files using the following endpoints:

+
+
+
+def functions_completeError(self, *, function_execution_id:Β str, error:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeError(
+    self,
+    *,
+    function_execution_id: str,
+    error: str,
+    **kwargs,
+) -> SlackResponse:
+    """Signal the failure to execute a function
+    https://docs.slack.dev/reference/methods/functions.completeError
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "error": error})
+    return self.api_call("functions.completeError", params=kwargs)
+
+ +
+
+def functions_completeSuccess(self, *, function_execution_id:Β str, outputs:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeSuccess(
+    self,
+    *,
+    function_execution_id: str,
+    outputs: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Signal the successful completion of a function
+    https://docs.slack.dev/reference/methods/functions.completeSuccess
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+    return self.api_call("functions.completeSuccess", params=kwargs)
+
+

Signal the successful completion of a function +https://docs.slack.dev/reference/methods/functions.completeSuccess

+
+
+def groups_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.archive", json=kwargs)
+
+

Archives a private channel.

+
+
+def groups_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a private channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.create", json=kwargs)
+
+

Creates a private channel.

+
+
+def groups_createChild(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_createChild(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Clones and archives a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+

Clones and archives a private channel.

+
+
+def groups_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a private channel.

+
+
+def groups_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+

Gets information about a private channel.

+
+
+def groups_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.invite", json=kwargs)
+
+

Invites a user to a private channel.

+
+
+def groups_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.kick", json=kwargs)
+
+

Removes a user from a private channel.

+
+
+def groups_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.leave", json=kwargs)
+
+

Leaves a private channel.

+
+
+def groups_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists private channels that the calling user has access to."""
+    return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+

Lists private channels that the calling user has access to.

+
+
+def groups_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a private channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.mark", json=kwargs)
+
+

Sets the read cursor in a private channel.

+
+
+def groups_open(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_open(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.open", json=kwargs)
+
+

Opens a private channel.

+
+
+def groups_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a private channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.rename", json=kwargs)
+
+

Renames a private channel.

+
+
+def groups_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a private channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a private channel

+
+
+def groups_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a private channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setPurpose", json=kwargs)
+
+

Sets the purpose for a private channel.

+
+
+def groups_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a private channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setTopic", json=kwargs)
+
+

Sets the topic for a private channel.

+
+
+def groups_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.unarchive", json=kwargs)
+
+

Unarchives a private channel.

+
+
+def im_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Close a direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.close", json=kwargs)
+
+

Close a direct message channel.

+
+
+def im_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from direct message channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from direct message channel.

+
+
+def im_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists direct message channels for the calling user."""
+    return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+

Lists direct message channels for the calling user.

+
+
+def im_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.mark", json=kwargs)
+
+

Sets the read cursor in a direct message channel.

+
+
+def im_open(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_open(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a direct message channel."""
+    kwargs.update({"user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.open", json=kwargs)
+
+

Opens a direct message channel.

+
+
+def im_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation

+
+
+def migration_exchange(self,
*,
users:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
to_old:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def migration_exchange(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    to_old: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """For Enterprise Grid workspaces, map local user IDs to global user IDs
+    https://docs.slack.dev/reference/methods/migration.exchange
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id, "to_old": to_old})
+    return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+

For Enterprise Grid workspaces, map local user IDs to global user IDs +https://docs.slack.dev/reference/methods/migration.exchange

+
+
+def mpim_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a multiparty direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.close", json=kwargs)
+
+

Closes a multiparty direct message channel.

+
+
+def mpim_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a multiparty direct message."""
+    kwargs.update({"channel": channel})
+    return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a multiparty direct message.

+
+
+def mpim_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists multiparty direct message channels for the calling user."""
+    return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+

Lists multiparty direct message channels for the calling user.

+
+
+def mpim_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a multiparty direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.mark", json=kwargs)
+
+

Sets the read cursor in a multiparty direct message channel.

+
+
+def mpim_open(self, *, users:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_open(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """This method opens a multiparty direct message."""
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("mpim.open", params=kwargs)
+
+

This method opens a multiparty direct message.

+
+
+def mpim_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation from a
+    multiparty direct message.
+    """
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation from a +multiparty direct message.

+
+
+def oauth_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    code: str,
+    redirect_uri: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    kwargs.update({"code": code})
+    return self.api_call(
+        "oauth.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.access

+
+
+def oauth_v2_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_v2_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    # This field is required when processing the OAuth redirect URL requests
+    # while it's absent for token rotation
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    # This field is required for token rotation
+    grant_type: Optional[str] = None,
+    # This field is required for token rotation
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.v2.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "oauth.v2.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.v2.access

+
+
+def oauth_v2_exchange(self, *, token:Β str, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def oauth_v2_exchange(
+    self,
+    *,
+    token: str,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a legacy access token for a new expiring access token and refresh token
+    https://docs.slack.dev/reference/methods/oauth.v2.exchange
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+    return self.api_call("oauth.v2.exchange", params=kwargs)
+
+

Exchanges a legacy access token for a new expiring access token and refresh token +https://docs.slack.dev/reference/methods/oauth.v2.exchange

+
+
+def openid_connect_token(self,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def openid_connect_token(
+    self,
+    client_id: str,
+    client_secret: str,
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    grant_type: Optional[str] = None,
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.token
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "openid.connect.token",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.token

+
+
+def openid_connect_userInfo(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def openid_connect_userInfo(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get the identity of a user who has authorized Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.userInfo
+    """
+    return self.api_call("openid.connect.userInfo", params=kwargs)
+
+

Get the identity of a user who has authorized Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.userInfo

+
+
+def pins_add(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_add(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Pins an item to a channel.
+    https://docs.slack.dev/reference/methods/pins.add
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.add", params=kwargs)
+
+ +
+
+def pins_list(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_list(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lists items pinned to a channel.
+    https://docs.slack.dev/reference/methods/pins.list
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+

Lists items pinned to a channel. +https://docs.slack.dev/reference/methods/pins.list

+
+
+def pins_remove(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_remove(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Un-pins an item from a channel.
+    https://docs.slack.dev/reference/methods/pins.remove
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.remove", params=kwargs)
+
+ +
+
+def reactions_add(self, *, channel:Β str, name:Β str, timestamp:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reactions_add(
+    self,
+    *,
+    channel: str,
+    name: str,
+    timestamp: str,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a reaction to an item.
+    https://docs.slack.dev/reference/methods/reactions.add
+    """
+    kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+    return self.api_call("reactions.add", params=kwargs)
+
+ +
+
+def reactions_get(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_get(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    full: Optional[bool] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets reactions for an item.
+    https://docs.slack.dev/reference/methods/reactions.get
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "full": full,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    full: Optional[bool] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists reactions made by a user.
+    https://docs.slack.dev/reference/methods/reactions.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "full": full,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_remove(self,
*,
name:Β str,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_remove(
+    self,
+    *,
+    name: str,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a reaction from an item.
+    https://docs.slack.dev/reference/methods/reactions.remove
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.remove", params=kwargs)
+
+ +
+
+def reminders_add(self,
*,
text:Β str,
time:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
recurrence:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reminders_add(
+    self,
+    *,
+    text: str,
+    time: str,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    recurrence: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a reminder.
+    https://docs.slack.dev/reference/methods/reminders.add
+    """
+    kwargs.update(
+        {
+            "text": text,
+            "time": time,
+            "team_id": team_id,
+            "user": user,
+            "recurrence": recurrence,
+        }
+    )
+    return self.api_call("reminders.add", params=kwargs)
+
+ +
+
+def reminders_complete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_complete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Marks a reminder as complete.
+    https://docs.slack.dev/reference/methods/reminders.complete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.complete", params=kwargs)
+
+ +
+
+def reminders_delete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_delete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a reminder.
+    https://docs.slack.dev/reference/methods/reminders.delete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.delete", params=kwargs)
+
+ +
+
+def reminders_info(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_info(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a reminder.
+    https://docs.slack.dev/reference/methods/reminders.info
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+ +
+
+def reminders_list(self, *, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all reminders created by or for a given user.
+    https://docs.slack.dev/reference/methods/reminders.list
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+

Lists all reminders created by or for a given user. +https://docs.slack.dev/reference/methods/reminders.list

+
+
+def rtm_connect(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_connect(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.connect
+    """
+    kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+    return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.connect

+
+
+def rtm_start(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
mpim_aware:Β boolΒ |Β NoneΒ =Β None,
no_latest:Β boolΒ |Β NoneΒ =Β None,
no_unreads:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
simple_latest:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_start(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    include_locale: Optional[bool] = None,
+    mpim_aware: Optional[bool] = None,
+    no_latest: Optional[bool] = None,
+    no_unreads: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    simple_latest: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.start
+    """
+    kwargs.update(
+        {
+            "batch_presence_aware": batch_presence_aware,
+            "include_locale": include_locale,
+            "mpim_aware": mpim_aware,
+            "no_latest": no_latest,
+            "no_unreads": no_unreads,
+            "presence_sub": presence_sub,
+            "simple_latest": simple_latest,
+        }
+    )
+    return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.start

+
+
+def search_all(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_all(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages and files matching a query.
+    https://docs.slack.dev/reference/methods/search.all
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+

Searches for messages and files matching a query. +https://docs.slack.dev/reference/methods/search.all

+
+
+def search_files(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_files(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for files matching a query.
+    https://docs.slack.dev/reference/methods/search.files
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+

Searches for files matching a query. +https://docs.slack.dev/reference/methods/search.files

+
+
+def search_messages(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_messages(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages matching a query.
+    https://docs.slack.dev/reference/methods/search.messages
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "cursor": cursor,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+

Searches for messages matching a query. +https://docs.slack.dev/reference/methods/search.messages

+
+
+def slackLists_access_delete(self,
*,
list_id:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_delete(
+    self,
+    *,
+    list_id: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revoke access to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.delete
+    """
+    kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.delete", json=kwargs)
+
+

Revoke access to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.delete

+
+
+def slackLists_access_set(self,
*,
list_id:Β str,
access_level:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_set(
+    self,
+    *,
+    list_id: str,
+    access_level: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the access level to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.set
+    """
+    kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.set", json=kwargs)
+
+

Set the access level to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.set

+
+
+def slackLists_create(self,
*,
name:Β str,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
schema:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
copy_from_list_id:Β strΒ |Β NoneΒ =Β None,
include_copied_list_records:Β boolΒ |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_create(
+    self,
+    *,
+    name: str,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    schema: Optional[List[Dict[str, Any]]] = None,
+    copy_from_list_id: Optional[str] = None,
+    include_copied_list_records: Optional[bool] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a List.
+    https://docs.slack.dev/reference/methods/slackLists.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description_blocks": description_blocks,
+            "schema": schema,
+            "copy_from_list_id": copy_from_list_id,
+            "include_copied_list_records": include_copied_list_records,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.create", json=kwargs)
+
+ +
+
+def slackLists_download_get(self, *, list_id:Β str, job_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_get(
+    self,
+    *,
+    list_id: str,
+    job_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve List download URL from an export job to download List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.get
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "job_id": job_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.get", json=kwargs)
+
+

Retrieve List download URL from an export job to download List contents. +https://docs.slack.dev/reference/methods/slackLists.download.get

+
+
+def slackLists_download_start(self, *, list_id:Β str, include_archived:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_start(
+    self,
+    *,
+    list_id: str,
+    include_archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiate a job to export List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.start
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "include_archived": include_archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.start", json=kwargs)
+
+ +
+
+def slackLists_items_create(self,
*,
list_id:Β str,
duplicated_item_id:Β strΒ |Β NoneΒ =Β None,
parent_item_id:Β strΒ |Β NoneΒ =Β None,
initial_fields:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_create(
+    self,
+    *,
+    list_id: str,
+    duplicated_item_id: Optional[str] = None,
+    parent_item_id: Optional[str] = None,
+    initial_fields: Optional[List[Dict[str, Any]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add a new item to an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.create
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "duplicated_item_id": duplicated_item_id,
+            "parent_item_id": parent_item_id,
+            "initial_fields": initial_fields,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.create", json=kwargs)
+
+ +
+
+def slackLists_items_delete(self, *, list_id:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_delete(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an item from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.delete
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.delete", json=kwargs)
+
+ +
+
+def slackLists_items_deleteMultiple(self, *, list_id:Β str, ids:Β List[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_deleteMultiple(
+    self,
+    *,
+    list_id: str,
+    ids: List[str],
+    **kwargs,
+) -> SlackResponse:
+    """Deletes multiple items from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "ids": ids,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+ +
+
+def slackLists_items_info(self, *, list_id:Β str, id:Β str, include_is_subscribed:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_info(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    include_is_subscribed: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a row from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.info
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+            "include_is_subscribed": include_is_subscribed,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.info", json=kwargs)
+
+ +
+
+def slackLists_items_list(self,
*,
list_id:Β str,
limit:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
archived:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_list(
+    self,
+    *,
+    list_id: str,
+    limit: Optional[int] = None,
+    cursor: Optional[str] = None,
+    archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get records from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.list
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "limit": limit,
+            "cursor": cursor,
+            "archived": archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.list", json=kwargs)
+
+ +
+
+def slackLists_items_update(self, *, list_id:Β str, cells:Β List[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_update(
+    self,
+    *,
+    list_id: str,
+    cells: List[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Updates cells in a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.update
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "cells": cells,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.update", json=kwargs)
+
+ +
+
+def slackLists_update(self,
*,
id:Β str,
name:Β strΒ |Β NoneΒ =Β None,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_update(
+    self,
+    *,
+    id: str,
+    name: Optional[str] = None,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update a List.
+    https://docs.slack.dev/reference/methods/slackLists.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "name": name,
+            "description_blocks": description_blocks,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.update", json=kwargs)
+
+ +
+
+def stars_add(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_add(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a star to an item.
+    https://docs.slack.dev/reference/methods/stars.add
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.add", params=kwargs)
+
+ +
+
+def stars_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists stars for a user.
+    https://docs.slack.dev/reference/methods/stars.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+ +
+
+def stars_remove(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_remove(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a star from an item.
+    https://docs.slack.dev/reference/methods/stars.remove
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.remove", params=kwargs)
+
+ +
+
+def team_accessLogs(self,
*,
before:Β strΒ |Β intΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_accessLogs(
+    self,
+    *,
+    before: Optional[Union[int, str]] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the access logs for the current team.
+    https://docs.slack.dev/reference/methods/team.accessLogs
+    """
+    kwargs.update(
+        {
+            "before": before,
+            "count": count,
+            "page": page,
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+

Gets the access logs for the current team. +https://docs.slack.dev/reference/methods/team.accessLogs

+
+
+def team_billableInfo(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billableInfo(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets billable users information for the current team.
+    https://docs.slack.dev/reference/methods/team.billableInfo
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+

Gets billable users information for the current team. +https://docs.slack.dev/reference/methods/team.billableInfo

+
+
+def team_billing_info(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billing_info(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Reads a workspace's billing plan information.
+    https://docs.slack.dev/reference/methods/team.billing.info
+    """
+    return self.api_call("team.billing.info", params=kwargs)
+
+

Reads a workspace's billing plan information. +https://docs.slack.dev/reference/methods/team.billing.info

+
+
+def team_externalTeams_disconnect(self, *, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_externalTeams_disconnect(
+    self,
+    *,
+    target_team: str,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnects an external organization.
+    https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+    """
+    kwargs.update(
+        {
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+ +
+
+def team_externalTeams_list(self,
*,
connection_status_filter:Β strΒ |Β NoneΒ =Β None,
slack_connect_pref_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
sort_field:Β strΒ |Β NoneΒ =Β None,
workspace_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_externalTeams_list(
+    self,
+    *,
+    connection_status_filter: Optional[str] = None,
+    slack_connect_pref_filter: Optional[Sequence[str]] = None,
+    sort_direction: Optional[str] = None,
+    sort_field: Optional[str] = None,
+    workspace_filter: Optional[Sequence[str]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns a list of all the external teams connected and details about the connection.
+    https://docs.slack.dev/reference/methods/team.externalTeams.list
+    """
+    kwargs.update(
+        {
+            "connection_status_filter": connection_status_filter,
+            "sort_direction": sort_direction,
+            "sort_field": sort_field,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if slack_connect_pref_filter is not None:
+        if isinstance(slack_connect_pref_filter, (list, tuple)):
+            kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+        else:
+            kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+    if workspace_filter is not None:
+        if isinstance(workspace_filter, (list, tuple)):
+            kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+        else:
+            kwargs.update({"workspace_filter": workspace_filter})
+    return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+

Returns a list of all the external teams connected and details about the connection. +https://docs.slack.dev/reference/methods/team.externalTeams.list

+
+
+def team_info(self, *, team:Β strΒ |Β NoneΒ =Β None, domain:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_info(
+    self,
+    *,
+    team: Optional[str] = None,
+    domain: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about the current team.
+    https://docs.slack.dev/reference/methods/team.info
+    """
+    kwargs.update({"team": team, "domain": domain})
+    return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+

Gets information about the current team. +https://docs.slack.dev/reference/methods/team.info

+
+
+def team_integrationLogs(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
change_type:Β strΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
service_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_integrationLogs(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    change_type: Optional[str] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    service_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the integration logs for the current team.
+    https://docs.slack.dev/reference/methods/team.integrationLogs
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "change_type": change_type,
+            "count": count,
+            "page": page,
+            "service_id": service_id,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+

Gets the integration logs for the current team. +https://docs.slack.dev/reference/methods/team.integrationLogs

+
+
+def team_preferences_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_preferences_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a list of a workspace's team preferences.
+    https://docs.slack.dev/reference/methods/team.preferences.list
+    """
+    return self.api_call("team.preferences.list", params=kwargs)
+
+

Retrieve a list of a workspace's team preferences. +https://docs.slack.dev/reference/methods/team.preferences.list

+
+
+def team_profile_get(self, *, visibility:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_profile_get(
+    self,
+    *,
+    visibility: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a team's profile.
+    https://docs.slack.dev/reference/methods/team.profile.get
+    """
+    kwargs.update({"visibility": visibility})
+    return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+ +
+
+def tooling_tokens_rotate(self, *, refresh_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def tooling_tokens_rotate(
+    self,
+    *,
+    refresh_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a refresh token for a new app configuration token
+    https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+    """
+    kwargs.update({"refresh_token": refresh_token})
+    return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+

Exchanges a refresh token for a new app configuration token +https://docs.slack.dev/reference/methods/tooling.tokens.rotate

+
+
+def usergroups_create(self,
*,
name:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_create(
+    self,
+    *,
+    name: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a User Group
+    https://docs.slack.dev/reference/methods/usergroups.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.create", params=kwargs)
+
+ +
+
+def usergroups_disable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_disable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disable an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.disable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.disable", params=kwargs)
+
+ +
+
+def usergroups_enable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_enable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enable a User Group
+    https://docs.slack.dev/reference/methods/usergroups.enable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.enable", params=kwargs)
+
+ +
+
+def usergroups_list(self,
*,
include_count:Β boolΒ |Β NoneΒ =Β None,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
include_users:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_list(
+    self,
+    *,
+    include_count: Optional[bool] = None,
+    include_disabled: Optional[bool] = None,
+    include_users: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all User Groups for a team
+    https://docs.slack.dev/reference/methods/usergroups.list
+    """
+    kwargs.update(
+        {
+            "include_count": include_count,
+            "include_disabled": include_disabled,
+            "include_users": include_users,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_update(self,
*,
usergroup:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_update(
+    self,
+    *,
+    usergroup: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    name: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "name": name,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.update", params=kwargs)
+
+ +
+
+def usergroups_users_list(self,
*,
usergroup:Β str,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_list(
+    self,
+    *,
+    usergroup: str,
+    include_disabled: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all users in a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.list
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_disabled": include_disabled,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_users_update(self,
*,
usergroup:Β str,
users:Β strΒ |Β Sequence[str],
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_update(
+    self,
+    *,
+    usergroup: str,
+    users: Union[str, Sequence[str]],
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the list of users for a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("usergroups.users.update", params=kwargs)
+
+

Update the list of users for a User Group +https://docs.slack.dev/reference/methods/usergroups.users.update

+
+
+def users_conversations(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_conversations(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List conversations the calling user may access.
+    https://docs.slack.dev/reference/methods/users.conversations
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+

List conversations the calling user may access. +https://docs.slack.dev/reference/methods/users.conversations

+
+
+def users_deletePhoto(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_deletePhoto(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Delete the user profile photo
+    https://docs.slack.dev/reference/methods/users.deletePhoto
+    """
+    return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+ +
+
+def users_discoverableContacts_lookup(self, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_discoverableContacts_lookup(
+    self,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lookup an email address to see if someone is on Slack
+    https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+

Lookup an email address to see if someone is on Slack +https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup

+
+
+def users_getPresence(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_getPresence(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets user presence information.
+    https://docs.slack.dev/reference/methods/users.getPresence
+    """
+    kwargs.update({"user": user})
+    return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+ +
+
+def users_identity(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_identity(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get a user's identity.
+    https://docs.slack.dev/reference/methods/users.identity
+    """
+    return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+ +
+
+def users_info(self, *, user:Β str, include_locale:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_info(
+    self,
+    *,
+    user: str,
+    include_locale: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a user.
+    https://docs.slack.dev/reference/methods/users.info
+    """
+    kwargs.update({"user": user, "include_locale": include_locale})
+    return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+ +
+
+def users_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_locale: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all users in a Slack team.
+    https://docs.slack.dev/reference/methods/users.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_locale": include_locale,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+

Lists all users in a Slack team. +https://docs.slack.dev/reference/methods/users.list

+
+
+def users_lookupByEmail(self, *, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_lookupByEmail(
+    self,
+    *,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Find a user with an email address.
+    https://docs.slack.dev/reference/methods/users.lookupByEmail
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+ +
+
+def users_profile_get(self, *, user:Β strΒ |Β NoneΒ =Β None, include_labels:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_profile_get(
+    self,
+    *,
+    user: Optional[str] = None,
+    include_labels: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's profile information.
+    https://docs.slack.dev/reference/methods/users.profile.get
+    """
+    kwargs.update({"user": user, "include_labels": include_labels})
+    return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+

Retrieves a user's profile information. +https://docs.slack.dev/reference/methods/users.profile.get

+
+
+def users_profile_set(self,
*,
name:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
profile:Β DictΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_profile_set(
+    self,
+    *,
+    name: Optional[str] = None,
+    value: Optional[str] = None,
+    user: Optional[str] = None,
+    profile: Optional[Dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the profile information for a user.
+    https://docs.slack.dev/reference/methods/users.profile.set
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "profile": profile,
+            "user": user,
+            "value": value,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "profile" parameter
+    return self.api_call("users.profile.set", json=kwargs)
+
+

Set the profile information for a user. +https://docs.slack.dev/reference/methods/users.profile.set

+
+
+def users_setPhoto(self,
*,
image:Β strΒ |Β io.IOBase,
crop_w:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_x:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_y:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_setPhoto(
+    self,
+    *,
+    image: Union[str, IOBase],
+    crop_w: Optional[Union[int, str]] = None,
+    crop_x: Optional[Union[int, str]] = None,
+    crop_y: Optional[Union[int, str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the user profile photo
+    https://docs.slack.dev/reference/methods/users.setPhoto
+    """
+    kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+    return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+ +
+
+def users_setPresence(self, *, presence:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_setPresence(
+    self,
+    *,
+    presence: str,
+    **kwargs,
+) -> SlackResponse:
+    """Manually sets user presence.
+    https://docs.slack.dev/reference/methods/users.setPresence
+    """
+    kwargs.update({"presence": presence})
+    return self.api_call("users.setPresence", params=kwargs)
+
+ +
+
+def views_open(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_open(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Open a view for a user.
+    https://docs.slack.dev/reference/methods/views.open
+    See https://docs.slack.dev/surfaces/modals/ for details.
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.open", json=kwargs)
+
+ +
+
+def views_publish(self,
*,
user_id:Β str,
view:Β dictΒ |Β View,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_publish(
+    self,
+    *,
+    user_id: str,
+    view: Union[dict, View],
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Publish a static view for a User.
+    Create or update the view that comprises an
+    app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+    https://docs.slack.dev/reference/methods/views.publish
+    """
+    kwargs.update({"user_id": user_id, "hash": hash})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.publish", json=kwargs)
+
+

Publish a static view for a User. +Create or update the view that comprises an +app's Home tab (https://docs.slack.dev/surfaces/app-home/) +https://docs.slack.dev/reference/methods/views.publish

+
+
+def views_push(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_push(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Push a view onto the stack of a root view.
+    Push a new view onto the existing view stack by passing a view
+    payload and a valid trigger_id generated from an interaction
+    within the existing modal.
+    Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+    to learn more about the lifecycle and intricacies of views.
+    https://docs.slack.dev/reference/methods/views.push
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.push", json=kwargs)
+
+

Push a view onto the stack of a root view. +Push a new view onto the existing view stack by passing a view +payload and a valid trigger_id generated from an interaction +within the existing modal. +Read the modals documentation (https://docs.slack.dev/surfaces/modals/) +to learn more about the lifecycle and intricacies of views. +https://docs.slack.dev/reference/methods/views.push

+
+
+def views_update(self,
*,
view:Β dictΒ |Β View,
external_id:Β strΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_update(
+    self,
+    *,
+    view: Union[dict, View],
+    external_id: Optional[str] = None,
+    view_id: Optional[str] = None,
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing view.
+    Update a view by passing a new view definition along with the
+    view_id returned in views.open or the external_id.
+    See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+    to learn more about updating views and avoiding race conditions with the hash argument.
+    https://docs.slack.dev/reference/methods/views.update
+    """
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    if external_id:
+        kwargs.update({"external_id": external_id})
+    elif view_id:
+        kwargs.update({"view_id": view_id})
+    else:
+        raise e.SlackRequestError("Either view_id or external_id is required.")
+    kwargs.update({"hash": hash})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.update", json=kwargs)
+
+

Update an existing view. +Update a view by passing a new view definition along with the +view_id returned in views.open or the external_id. +See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views) +to learn more about updating views and avoiding race conditions with the hash argument. +https://docs.slack.dev/reference/methods/views.update

+
+ +
+
+ +Expand source code + +
def workflows_featured_add(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add featured workflows to a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.add
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.add", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_list(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """List the featured workflows for specified channels.
+    https://docs.slack.dev/reference/methods/workflows.featured.list
+    """
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("workflows.featured.list", params=kwargs)
+
+

List the featured workflows for specified channels. +https://docs.slack.dev/reference/methods/workflows.featured.list

+
+ +
+
+ +Expand source code + +
def workflows_featured_remove(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove featured workflows from a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.remove
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.remove", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_set(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set featured workflows for a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.set
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.set", params=kwargs)
+
+ +
+
+def workflows_stepCompleted(self, *, workflow_step_execute_id:Β str, outputs:Β dictΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepCompleted(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    outputs: Optional[dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Indicate a successful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepCompleted
+    """
+    kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "outputs" parameter
+    return self.api_call("workflows.stepCompleted", json=kwargs)
+
+

Indicate a successful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepCompleted

+
+
+def workflows_stepFailed(self, *, workflow_step_execute_id:Β str, error:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepFailed(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    error: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Indicate an unsuccessful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepFailed
+    """
+    kwargs.update(
+        {
+            "workflow_step_execute_id": workflow_step_execute_id,
+            "error": error,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "error" parameter
+    return self.api_call("workflows.stepFailed", json=kwargs)
+
+

Indicate an unsuccessful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepFailed

+
+
+def workflows_updateStep(self,
*,
workflow_step_edit_id:Β str,
inputs:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
outputs:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def workflows_updateStep(
+    self,
+    *,
+    workflow_step_edit_id: str,
+    inputs: Optional[Dict[str, Any]] = None,
+    outputs: Optional[List[Dict[str, str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the configuration for a workflow extension step.
+    https://docs.slack.dev/reference/methods/workflows.updateStep
+    """
+    kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+    if inputs is not None:
+        kwargs.update({"inputs": inputs})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+    return self.api_call("workflows.updateStep", json=kwargs)
+
+

Update the configuration for a workflow extension step. +https://docs.slack.dev/reference/methods/workflows.updateStep

+
+
+

Inherited members

+ +
+
+class WebhookClient +(url:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebhookClient:
+    url: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        url: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for Incoming Webhooks and `response_url`
+
+        https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/
+
+        Args:
+            url: Complete URL to send data (e.g., `https://hooks.slack.com/XXX`)
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.url = url
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    def send(
+        self,
+        *,
+        text: Optional[str] = None,
+        attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+        blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+        response_type: Optional[str] = None,
+        replace_original: Optional[bool] = None,
+        delete_original: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        metadata: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            text: The text message
+                (even when having blocks, setting this as well is recommended as it works as fallback)
+            attachments: A collection of attachments
+            blocks: A collection of Block Kit UI components
+            response_type: The type of message (either 'in_channel' or 'ephemeral')
+            replace_original: True if you use this option for response_url requests
+            delete_original: True if you use this option for response_url requests
+            unfurl_links: Option to indicate whether text url should unfurl
+            unfurl_media: Option to indicate whether media url should unfurl
+            metadata: Metadata attached to the message
+            headers: Request headers to append only for this request
+
+        Returns:
+            Webhook response
+        """
+        return self.send_dict(
+            # It's fine to have None value elements here
+            # because _build_body() filters them out when constructing the actual body data
+            body={
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "response_type": response_type,
+                "replace_original": replace_original,
+                "delete_original": delete_original,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "metadata": metadata,
+            },
+            headers=headers,
+        )
+
+    def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            headers: Request headers to append only for this request
+        Returns:
+            Webhook response
+        """
+        return self._perform_http_request(
+            body=_build_body(body),  # type: ignore[arg-type]
+            headers=_build_request_headers(self.default_headers, headers),
+        )
+
+    def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse:
+        raw_body = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a request - url: {self.url}, body: {raw_body}, headers: {headers}")
+
+        url = self.url
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(method="POST", url=url, data=raw_body.encode("utf-8"), headers=headers)
+        resp = None
+        last_error = Exception("undefined internal error")
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = WebhookResponse(
+                    url=url,
+                    status_code=e.code,
+                    body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error
+
+    def _perform_http_request_internal(self, url: str, req: Request):
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        http_resp: Optional[HTTPResponse] = None
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = WebhookResponse(
+            url=url,
+            status_code=http_resp.status,
+            body=response_body,
+            headers=http_resp.headers,  # type: ignore[arg-type]
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for Incoming Webhooks and response_url

+

https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/

+

Args

+
+
url
+
Complete URL to send data (e.g., https://hooks.slack.com/XXX)
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def send(self,
*,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β Sequence[Dict[str,Β Any]Β |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β Sequence[Dict[str,Β Any]Β |Β Block]Β |Β NoneΒ =Β None,
response_type:Β strΒ |Β NoneΒ =Β None,
replace_original:Β boolΒ |Β NoneΒ =Β None,
delete_original:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
metadata:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse
+
+
+
+ +Expand source code + +
def send(
+    self,
+    *,
+    text: Optional[str] = None,
+    attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+    blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+    response_type: Optional[str] = None,
+    replace_original: Optional[bool] = None,
+    delete_original: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    metadata: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        text: The text message
+            (even when having blocks, setting this as well is recommended as it works as fallback)
+        attachments: A collection of attachments
+        blocks: A collection of Block Kit UI components
+        response_type: The type of message (either 'in_channel' or 'ephemeral')
+        replace_original: True if you use this option for response_url requests
+        delete_original: True if you use this option for response_url requests
+        unfurl_links: Option to indicate whether text url should unfurl
+        unfurl_media: Option to indicate whether media url should unfurl
+        metadata: Metadata attached to the message
+        headers: Request headers to append only for this request
+
+    Returns:
+        Webhook response
+    """
+    return self.send_dict(
+        # It's fine to have None value elements here
+        # because _build_body() filters them out when constructing the actual body data
+        body={
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "response_type": response_type,
+            "replace_original": replace_original,
+            "delete_original": delete_original,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "metadata": metadata,
+        },
+        headers=headers,
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
text
+
The text message +(even when having blocks, setting this as well is recommended as it works as fallback)
+
attachments
+
A collection of attachments
+
blocks
+
A collection of Block Kit UI components
+
response_type
+
The type of message (either 'in_channel' or 'ephemeral')
+
replace_original
+
True if you use this option for response_url requests
+
delete_original
+
True if you use this option for response_url requests
+
unfurl_links
+
Option to indicate whether text url should unfurl
+
unfurl_media
+
Option to indicate whether media url should unfurl
+
metadata
+
Metadata attached to the message
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+def send_dict(self, body:Β Dict[str,Β Any], headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse +
+
+
+ +Expand source code + +
def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        body: JSON data structure (it's still a dict at this point),
+            if you give this argument, body_params and files will be skipped
+        headers: Request headers to append only for this request
+    Returns:
+        Webhook response
+    """
+    return self._perform_http_request(
+        body=_build_body(body),  # type: ignore[arg-type]
+        headers=_build_request_headers(self.default_headers, headers),
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
body
+
JSON data structure (it's still a dict at this point), +if you give this argument, body_params and files will be skipped
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/models/attachments/index.html b/docs/reference/models/attachments/index.html new file mode 100644 index 000000000..5a7d10c20 --- /dev/null +++ b/docs/reference/models/attachments/index.html @@ -0,0 +1,1737 @@ + + + + + + +slack_sdk.models.attachments API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.attachments

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AbstractActionSelector +(*,
name:Β str,
text:Β str,
selected_option:Β OptionΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AbstractActionSelector(Action, metaclass=ABCMeta):
+    DataSourceTypes = DynamicSelectElementTypes.union({"external", "static"})
+
+    attributes = {"data_source", "name", "text", "type"}
+
+    @property
+    @abstractmethod
+    def data_source(self) -> str:
+        pass
+
+    def __init__(self, *, name: str, text: str, selected_option: Optional[Option] = None):
+        super().__init__(text=text, name=name, subtype="select")
+        self.selected_option = selected_option
+
+    @EnumValidator("data_source", DataSourceTypes)
+    def data_source_valid(self):
+        return self.data_source in self.DataSourceTypes
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if self.selected_option is not None:
+            # this is a special case for ExternalActionSelectElement - in that case,
+            # you pass the initial value of the selector as a selected_options array
+            json["selected_options"] = extract_json([self.selected_option], "action")
+        return json
+
+ +

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var DataSourceTypes
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop data_source :Β str
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def data_source(self) -> str:
+    pass
+
+
+
+
+

Methods

+
+
+def data_source_valid(self) +
+
+
+ +Expand source code + +
@EnumValidator("data_source", DataSourceTypes)
+def data_source_valid(self):
+    return self.data_source in self.DataSourceTypes
+
+
+
+
+

Inherited members

+ +
+
+class Action +(*, text:Β str, subtype:Β str, name:Β strΒ |Β NoneΒ =Β None, url:Β strΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class Action(JsonObject):
+    """Action in attachments
+    https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts
+    https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields
+    """
+
+    attributes = {"name", "text", "url"}
+
+    def __init__(
+        self,
+        *,
+        text: str,
+        subtype: str,
+        name: Optional[str] = None,
+        url: Optional[str] = None,
+    ):
+        self.name = name
+        self.url = url
+        self.text = text
+        self.subtype = subtype
+
+    @JsonValidator("name or url attribute is required")
+    def name_or_url_present(self):
+        return self.name is not None or self.url is not None
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        json["type"] = self.subtype
+        return json
+
+ +

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def name_or_url_present(self) +
+
+
+ +Expand source code + +
@JsonValidator("name or url attribute is required")
+def name_or_url_present(self):
+    return self.name is not None or self.url is not None
+
+
+
+
+

Inherited members

+ +
+
+class ActionButton +(*,
name:Β str,
text:Β str,
value:Β str,
confirm:Β ConfirmObjectΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ActionButton(Action):
+    @property
+    def attributes(self):
+        return super().attributes.union({"style", "value"})
+
+    value_max_length = 2000
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        text: str,
+        value: str,
+        confirm: Optional[ConfirmObject] = None,
+        style: Optional[str] = None,
+    ):
+        """Simple button for use inside attachments
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/
+
+        Args:
+            name: Name this specific action. The name will be returned to your
+                Action URL along with the message's callback_id when this action is
+                invoked. Use it to identify this particular response path.
+            text: The user-facing label for the message button or menu
+                representing this action. Cannot contain markup.
+            value: Provide a string identifying this specific action. It will be
+                sent to your Action URL along with the name and attachment's
+                callback_id . If providing multiple actions with the same name, value
+                can be strategically used to differentiate intent. Cannot exceed 2000
+                characters.
+            confirm: a ConfirmObject that will appear in a dialog to confirm
+                user's choice.
+            style: Leave blank to indicate that this is an ordinary button. Use
+                "primary" or "danger" to mark important buttons.
+        """
+        super().__init__(name=name, text=text, subtype="button")
+        self.value = value
+        self.confirm = confirm
+        self.style = style
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def value_length(self):
+        return len(self.value) <= self.value_max_length
+
+    @EnumValidator("style", ButtonStyles)
+    def style_valid(self):
+        return self.style is None or self.style in ButtonStyles
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if self.confirm is not None:
+            json["confirm"] = extract_json(self.confirm, "action")
+        return json
+
+

Action in attachments +https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields

+

Simple button for use inside attachments

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/

+

Args

+
+
name
+
Name this specific action. The name will be returned to your +Action URL along with the message's callback_id when this action is +invoked. Use it to identify this particular response path.
+
text
+
The user-facing label for the message button or menu +representing this action. Cannot contain markup.
+
value
+
Provide a string identifying this specific action. It will be +sent to your Action URL along with the name and attachment's +callback_id . If providing multiple actions with the same name, value +can be strategically used to differentiate intent. Cannot exceed 2000 +characters.
+
confirm
+
a ConfirmObject that will appear in a dialog to confirm +user's choice.
+
style
+
Leave blank to indicate that this is an ordinary button. Use +"primary" or "danger" to mark important buttons.
+
+

Ancestors

+ +

Class variables

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes
+
+
+ +Expand source code + +
@property
+def attributes(self):
+    return super().attributes.union({"style", "value"})
+
+

Build an unordered collection of unique elements.

+
+
+

Methods

+
+
+def style_valid(self) +
+
+
+ +Expand source code + +
@EnumValidator("style", ButtonStyles)
+def style_valid(self):
+    return self.style is None or self.style in ButtonStyles
+
+
+
+
+def value_length(self) +
+
+
+ +Expand source code + +
@JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+def value_length(self):
+    return len(self.value) <= self.value_max_length
+
+
+
+
+

Inherited members

+ +
+
+class ActionChannelSelector +(name:Β str,
text:Β str,
selected_channel:Β OptionΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ActionChannelSelector(AbstractActionSelector):
+    data_source = "channels"
+
+    def __init__(self, name: str, text: str, selected_channel: Optional[Option] = None):
+        """
+        Automatically populate the selector with a list of public channels in the
+        workspace.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_channels
+
+        Args:
+            name: Name this specific action. The name will be returned to your
+                Action URL along with the message's callback_id when this action is
+                invoked. Use it to identify this particular response path.
+            text: The user-facing label for the message button or menu
+                representing this action. Cannot contain markup.
+            selected_channel: An Option object to pre-select as the default
+                value.
+        """
+        super().__init__(name=name, text=text, selected_option=selected_channel)
+
+

Action in attachments +https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields

+

Automatically populate the selector with a list of public channels in the +workspace.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_channels

+

Args

+
+
name
+
Name this specific action. The name will be returned to your +Action URL along with the message's callback_id when this action is +invoked. Use it to identify this particular response path.
+
text
+
The user-facing label for the message button or menu +representing this action. Cannot contain markup.
+
selected_channel
+
An Option object to pre-select as the default +value.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ActionConversationSelector +(name:Β str,
text:Β str,
selected_conversation:Β OptionΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ActionConversationSelector(AbstractActionSelector):
+    data_source = "conversations"
+
+    def __init__(self, name: str, text: str, selected_conversation: Optional[Option] = None):
+        """
+        Automatically populate the selector with a list of conversations they have in
+        the workspace.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_conversations
+
+        Args:
+            name: Name this specific action. The name will be returned to your
+                Action URL along with the message's callback_id when this action is
+                invoked. Use it to identify this particular response path.
+            text: The user-facing label for the message button or menu
+                representing this action. Cannot contain markup.
+            selected_conversation: An Option object to pre-select as the default
+                value.
+        """
+        super().__init__(name=name, text=text, selected_option=selected_conversation)
+
+

Action in attachments +https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields

+

Automatically populate the selector with a list of conversations they have in +the workspace.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_conversations

+

Args

+
+
name
+
Name this specific action. The name will be returned to your +Action URL along with the message's callback_id when this action is +invoked. Use it to identify this particular response path.
+
text
+
The user-facing label for the message button or menu +representing this action. Cannot contain markup.
+
selected_conversation
+
An Option object to pre-select as the default +value.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ActionExternalSelector +(*,
name:Β str,
text:Β str,
selected_option:Β OptionΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ActionExternalSelector(AbstractActionSelector):
+    data_source = "external"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length"})
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        text: str,
+        selected_option: Optional[Option] = None,
+        min_query_length: Optional[int] = None,
+    ):
+        """
+        Populate a message select menu from your own application dynamically.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_dynamic
+
+        Args:
+            name: Name this specific action. The name will be returned to your
+                Action URL along with the message's callback_id when this action is
+                invoked. Use it to identify this particular response path.
+            text: The user-facing label for the message button or menu
+                representing this action. Cannot contain markup.
+            selected_option: An Option object to pre-select as the default
+                value.
+            min_query_length: Specify the number of characters that must be typed
+                by a user into a dynamic select menu before dispatching to the app.
+        """
+        super().__init__(name=name, text=text, selected_option=selected_option)
+        self.min_query_length = min_query_length
+
+

Action in attachments +https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields

+

Populate a message select menu from your own application dynamically.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_dynamic

+

Args

+
+
name
+
Name this specific action. The name will be returned to your +Action URL along with the message's callback_id when this action is +invoked. Use it to identify this particular response path.
+
text
+
The user-facing label for the message button or menu +representing this action. Cannot contain markup.
+
selected_option
+
An Option object to pre-select as the default +value.
+
min_query_length
+
Specify the number of characters that must be typed +by a user into a dynamic select menu before dispatching to the app.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ActionLinkButton +(*, text:Β str, url:Β str) +
+
+
+ +Expand source code + +
class ActionLinkButton(Action):
+    def __init__(self, *, text: str, url: str):
+        """A simple interactive button that just opens a URL
+
+        https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts
+
+        Args:
+          text: text to display on the button, eg 'Click Me!"
+          url: the URL to open
+        """
+        super().__init__(text=text, url=url, subtype="button")
+
+ +

Ancestors

+ +

Inherited members

+ +
+
+class ActionUserSelector +(name:Β str,
text:Β str,
selected_user:Β OptionΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ActionUserSelector(AbstractActionSelector):
+    data_source = "users"
+
+    def __init__(self, name: str, text: str, selected_user: Optional[Option] = None):
+        """Automatically populate the selector with a list of users in the workspace.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_team_members
+
+        Args:
+            name: Name this specific action. The name will be returned to your
+                Action URL along with the message's callback_id when this action is
+                invoked. Use it to identify this particular response path.
+            text: The user-facing label for the message button or menu
+                representing this action. Cannot contain markup.
+            selected_user: An Option object to pre-select as the default
+                value.
+        """
+        super().__init__(name=name, text=text, selected_option=selected_user)
+
+

Action in attachments +https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields

+

Automatically populate the selector with a list of users in the workspace.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_team_members

+

Args

+
+
name
+
Name this specific action. The name will be returned to your +Action URL along with the message's callback_id when this action is +invoked. Use it to identify this particular response path.
+
text
+
The user-facing label for the message button or menu +representing this action. Cannot contain markup.
+
selected_user
+
An Option object to pre-select as the default +value.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class Attachment +(*,
text:Β str,
fallback:Β strΒ |Β NoneΒ =Β None,
fields:Β Sequence[AttachmentField]Β |Β NoneΒ =Β None,
color:Β strΒ |Β NoneΒ =Β None,
markdown_in:Β Sequence[str]Β |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
title_link:Β strΒ |Β NoneΒ =Β None,
pretext:Β strΒ |Β NoneΒ =Β None,
author_name:Β strΒ |Β NoneΒ =Β None,
author_subname:Β strΒ |Β NoneΒ =Β None,
author_link:Β strΒ |Β NoneΒ =Β None,
author_icon:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
thumb_url:Β strΒ |Β NoneΒ =Β None,
footer:Β strΒ |Β NoneΒ =Β None,
footer_icon:Β strΒ |Β NoneΒ =Β None,
ts:Β intΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Attachment(JsonObject):
+    attributes = {
+        "author_icon",
+        "author_link",
+        "author_name",
+        "author_subname",
+        "color",
+        "fallback",
+        "fields",
+        "footer",
+        "footer_icon",
+        "image_url",
+        "pretext",
+        "text",
+        "thumb_url",
+        "title",
+        "title_link",
+        "ts",
+    }
+
+    fields: Sequence[AttachmentField]
+
+    MarkdownFields = {"fields", "pretext", "text"}
+
+    footer_max_length = 300
+
+    def __init__(
+        self,
+        *,
+        text: str,
+        fallback: Optional[str] = None,
+        fields: Optional[Sequence[AttachmentField]] = None,
+        color: Optional[str] = None,
+        markdown_in: Optional[Sequence[str]] = None,
+        title: Optional[str] = None,
+        title_link: Optional[str] = None,
+        pretext: Optional[str] = None,
+        author_name: Optional[str] = None,
+        author_subname: Optional[str] = None,
+        author_link: Optional[str] = None,
+        author_icon: Optional[str] = None,
+        image_url: Optional[str] = None,
+        thumb_url: Optional[str] = None,
+        footer: Optional[str] = None,
+        footer_icon: Optional[str] = None,
+        ts: Optional[int] = None,
+    ):
+        """
+        A supplemental object that will display after the rest of the message.
+        Considered legacy - recommended replacement is to use message blocks instead.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields
+
+        Args:
+            text: The main body text of the attachment. It can be formatted as
+                plain text, or with markdown by including it in the markdown_in
+                parameter. The content will automatically collapse if it contains 700+
+                characters or 5+ linebreaks, and will display a "Show more..." link to
+                expand the content.
+            fallback: A plain text summary of the attachment used in clients that
+                don't show formatted text (eg. IRC, mobile notifications).
+            fields: An array of AttachmentField objects that get displayed in a
+                table-like way. For best results, include no more than 2-3 field
+                objects.
+            color: Changes the color of the border on the left side of this attachment
+                from the default gray. Can be any hex color code (eg. #439FE0)
+            markdown_in: An array of field names that should be formatted by
+                markdown syntax - allowed values: "pretext", "text", "fields"
+            title: Large title text near the top of the attachment.
+            title_link: A valid URL that turns the title text into a hyperlink.
+            pretext: Text that appears above the message attachment block. It can
+                be formatted as plain text, or with markdown by including it in the
+                markdown_in parameter.
+            author_name: Small text used to display the author's name.
+            author_subname: Small text used to display the author's sub name.
+            author_link: A valid URL that will hyperlink the author_name text.
+                Will only work if author_name is present.
+            author_icon: A valid URL that displays a small 16px by 16px image to
+                the left of the author_name text. Will only work if author_name is
+                present.
+            image_url: A valid URL to an image file that will be displayed at the
+                bottom of the attachment. We support GIF, JPEG, PNG, and BMP formats.
+                Large images will be resized to a maximum width of 360px or a maximum
+                height of 500px, while still maintaining the original aspect ratio.
+                Cannot be used with thumb_url.
+            thumb_url: A valid URL to an image file that will be displayed as a
+                thumbnail on the right side of a message attachment. We currently
+                support the following formats: GIF, JPEG, PNG, and BMP. The thumbnail's
+                longest dimension will be scaled down to 75px while maintaining the
+                aspect ratio of the image. The filesize of the image must also be less
+                than 500 KB. For best results, please use images that are already 75px
+                by 75px.
+            footer: Some brief text to help contextualize and identify an
+                attachment. Limited to 300 characters, and may be truncated further when
+                displayed to users in environments with limited screen real estate.
+            footer_icon: A valid URL to an image file that will be displayed
+                beside the footer text. Will only work if footer is present. We'll
+                render what you provide at 16px by 16px. It's best to use an image that
+                is similarly sized.
+            ts: An integer Unix timestamp that is used to related your attachment
+                to a specific time. The attachment will display the additional timestamp
+                value as part of the attachment's footer. Your message's timestamp will
+                be displayed in varying ways, depending on how far in the past or future
+                 it is, relative to the present. Form factors, like mobile versus
+                 desktop may also transform its rendered appearance.
+        """
+        self.text = text
+        self.title = title
+        self.fallback = fallback
+        self.pretext = pretext
+        self.title_link = title_link
+        self.color = color
+        self.author_name = author_name
+        self.author_subname = author_subname
+        self.author_link = author_link
+        self.author_icon = author_icon
+        self.image_url = image_url
+        self.thumb_url = thumb_url
+        self.footer = footer
+        self.footer_icon = footer_icon
+        self.ts = ts
+        self.fields = fields or []
+        self.markdown_in = markdown_in or []
+
+    @JsonValidator(f"footer attribute cannot exceed {footer_max_length} characters")
+    def footer_length(self) -> bool:
+        return self.footer is None or len(self.footer) <= self.footer_max_length
+
+    @JsonValidator("ts attribute cannot be present if footer attribute is absent")
+    def ts_without_footer(self) -> bool:
+        return self.ts is None or self.footer is not None
+
+    @EnumValidator("markdown_in", MarkdownFields)
+    def markdown_in_valid(self):
+        return not self.markdown_in or all(e in self.MarkdownFields for e in self.markdown_in)
+
+    @JsonValidator("color attribute must be 'good', 'warning', 'danger', or a hex color code")
+    def color_valid(self) -> bool:
+        return (
+            self.color is None
+            or self.color in SeededColors
+            or re.match("^#(?:[0-9A-F]{2}){3}$", self.color, re.IGNORECASE) is not None
+        )
+
+    @JsonValidator("image_url attribute cannot be present if thumb_url is populated")
+    def image_url_and_thumb_url_populated(self) -> bool:
+        return self.image_url is None or self.thumb_url is None
+
+    @JsonValidator("name must be present if link is present")
+    def author_link_without_author_name(self) -> bool:
+        return self.author_link is None or self.author_name is not None
+
+    @JsonValidator("icon must be present if link is present")
+    def author_link_without_author_icon(self) -> bool:
+        return self.author_link is None or self.author_icon is not None
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if self.fields is not None:
+            json["fields"] = extract_json(self.fields)
+        if self.markdown_in:
+            json["mrkdwn_in"] = self.markdown_in
+        return json
+
+

The base class for JSON serializable class objects

+

A supplemental object that will display after the rest of the message. +Considered legacy - recommended replacement is to use message blocks instead.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields

+

Args

+
+
text
+
The main body text of the attachment. It can be formatted as +plain text, or with markdown by including it in the markdown_in +parameter. The content will automatically collapse if it contains 700+ +characters or 5+ linebreaks, and will display a "Show more…" link to +expand the content.
+
fallback
+
A plain text summary of the attachment used in clients that +don't show formatted text (eg. IRC, mobile notifications).
+
fields
+
An array of AttachmentField objects that get displayed in a +table-like way. For best results, include no more than 2-3 field +objects.
+
color
+
Changes the color of the border on the left side of this attachment +from the default gray. Can be any hex color code (eg. #439FE0)
+
markdown_in
+
An array of field names that should be formatted by +markdown syntax - allowed values: "pretext", "text", "fields"
+
title
+
Large title text near the top of the attachment.
+
title_link
+
A valid URL that turns the title text into a hyperlink.
+
pretext
+
Text that appears above the message attachment block. It can +be formatted as plain text, or with markdown by including it in the +markdown_in parameter.
+
author_name
+
Small text used to display the author's name.
+
author_subname
+
Small text used to display the author's sub name.
+
author_link
+
A valid URL that will hyperlink the author_name text. +Will only work if author_name is present.
+
author_icon
+
A valid URL that displays a small 16px by 16px image to +the left of the author_name text. Will only work if author_name is +present.
+
image_url
+
A valid URL to an image file that will be displayed at the +bottom of the attachment. We support GIF, JPEG, PNG, and BMP formats. +Large images will be resized to a maximum width of 360px or a maximum +height of 500px, while still maintaining the original aspect ratio. +Cannot be used with thumb_url.
+
thumb_url
+
A valid URL to an image file that will be displayed as a +thumbnail on the right side of a message attachment. We currently +support the following formats: GIF, JPEG, PNG, and BMP. The thumbnail's +longest dimension will be scaled down to 75px while maintaining the +aspect ratio of the image. The filesize of the image must also be less +than 500 KB. For best results, please use images that are already 75px +by 75px.
+
footer
+
Some brief text to help contextualize and identify an +attachment. Limited to 300 characters, and may be truncated further when +displayed to users in environments with limited screen real estate.
+
footer_icon
+
A valid URL to an image file that will be displayed +beside the footer text. Will only work if footer is present. We'll +render what you provide at 16px by 16px. It's best to use an image that +is similarly sized.
+
ts
+
An integer Unix timestamp that is used to related your attachment +to a specific time. The attachment will display the additional timestamp +value as part of the attachment's footer. Your message's timestamp will +be displayed in varying ways, depending on how far in the past or future +it is, relative to the present. Form factors, like mobile versus +desktop may also transform its rendered appearance.
+
+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var MarkdownFields
+
+

The type of the None singleton.

+
+
var attributes
+
+

The type of the None singleton.

+
+
var fields :Β Sequence[AttachmentField]
+
+

The type of the None singleton.

+
+
var footer_max_length
+
+

The type of the None singleton.

+
+
+

Methods

+
+ +
+
+ +Expand source code + +
@JsonValidator("icon must be present if link is present")
+def author_link_without_author_icon(self) -> bool:
+    return self.author_link is None or self.author_icon is not None
+
+
+
+ +
+
+ +Expand source code + +
@JsonValidator("name must be present if link is present")
+def author_link_without_author_name(self) -> bool:
+    return self.author_link is None or self.author_name is not None
+
+
+
+
+def color_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("color attribute must be 'good', 'warning', 'danger', or a hex color code")
+def color_valid(self) -> bool:
+    return (
+        self.color is None
+        or self.color in SeededColors
+        or re.match("^#(?:[0-9A-F]{2}){3}$", self.color, re.IGNORECASE) is not None
+    )
+
+
+
+
+def footer_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"footer attribute cannot exceed {footer_max_length} characters")
+def footer_length(self) -> bool:
+    return self.footer is None or len(self.footer) <= self.footer_max_length
+
+
+
+
+def image_url_and_thumb_url_populated(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("image_url attribute cannot be present if thumb_url is populated")
+def image_url_and_thumb_url_populated(self) -> bool:
+    return self.image_url is None or self.thumb_url is None
+
+
+
+
+def markdown_in_valid(self) +
+
+
+ +Expand source code + +
@EnumValidator("markdown_in", MarkdownFields)
+def markdown_in_valid(self):
+    return not self.markdown_in or all(e in self.MarkdownFields for e in self.markdown_in)
+
+
+
+ +
+
+ +Expand source code + +
@JsonValidator("ts attribute cannot be present if footer attribute is absent")
+def ts_without_footer(self) -> bool:
+    return self.ts is None or self.footer is not None
+
+
+
+
+

Inherited members

+ +
+
+class AttachmentField +(*, title:Β strΒ |Β NoneΒ =Β None, value:Β strΒ |Β NoneΒ =Β None, short:Β boolΒ =Β True) +
+
+
+ +Expand source code + +
class AttachmentField(JsonObject):
+    attributes = {"short", "title", "value"}
+
+    def __init__(
+        self,
+        *,
+        title: Optional[str] = None,
+        value: Optional[str] = None,
+        short: bool = True,
+    ):
+        self.title = title
+        self.value = value
+        self.short = short
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class BlockAttachment +(*,
blocks:Β Sequence[Block],
color:Β strΒ |Β NoneΒ =Β None,
fallback:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class BlockAttachment(Attachment):
+    blocks: List[Block]
+
+    @property
+    def attributes(self):
+        return super().attributes.union({"blocks", "color"})
+
+    def __init__(
+        self,
+        *,
+        blocks: Sequence[Block],
+        color: Optional[str] = None,
+        fallback: Optional[str] = None,
+    ):
+        """
+        A bridge between legacy attachments and Block Kit formatting - pass a list of
+        Block objects directly to this attachment.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields
+
+        Args:
+            blocks: a sequence of Block objects
+            color: Changes the color of the border on the left side of this
+                attachment from the default gray. Can either be one of "good" (green),
+                "warning" (yellow), "danger" (red), or any hex color code (eg. #439FE0)
+            fallback: fallback text
+        """
+        super().__init__(text="", fallback=fallback, color=color)
+        self.blocks = list(blocks)
+
+    @JsonValidator("fields attribute cannot be populated on BlockAttachment")
+    def fields_attribute_absent(self) -> bool:
+        return not self.fields
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        json.update({"blocks": extract_json(self.blocks)})
+        del json["fields"]  # cannot supply fields and blocks at the same time
+        return json
+
+

The base class for JSON serializable class objects

+

A bridge between legacy attachments and Block Kit formatting - pass a list of +Block objects directly to this attachment.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields

+

Args

+
+
blocks
+
a sequence of Block objects
+
color
+
Changes the color of the border on the left side of this +attachment from the default gray. Can either be one of "good" (green), +"warning" (yellow), "danger" (red), or any hex color code (eg. #439FE0)
+
fallback
+
fallback text
+
+

Ancestors

+ +

Class variables

+
+
var blocks :Β List[Block]
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes
+
+
+ +Expand source code + +
@property
+def attributes(self):
+    return super().attributes.union({"blocks", "color"})
+
+

Build an unordered collection of unique elements.

+
+
+

Methods

+
+
+def fields_attribute_absent(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("fields attribute cannot be populated on BlockAttachment")
+def fields_attribute_absent(self) -> bool:
+    return not self.fields
+
+
+
+
+

Inherited members

+ +
+
+class InteractiveAttachment +(*,
actions:Β Sequence[Action],
callback_id:Β str,
text:Β str,
fallback:Β strΒ |Β NoneΒ =Β None,
fields:Β Sequence[AttachmentField]Β |Β NoneΒ =Β None,
color:Β strΒ |Β NoneΒ =Β None,
markdown_in:Β Sequence[str]Β |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
title_link:Β strΒ |Β NoneΒ =Β None,
pretext:Β strΒ |Β NoneΒ =Β None,
author_name:Β strΒ |Β NoneΒ =Β None,
author_subname:Β strΒ |Β NoneΒ =Β None,
author_link:Β strΒ |Β NoneΒ =Β None,
author_icon:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
thumb_url:Β strΒ |Β NoneΒ =Β None,
footer:Β strΒ |Β NoneΒ =Β None,
footer_icon:Β strΒ |Β NoneΒ =Β None,
ts:Β intΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class InteractiveAttachment(Attachment):
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"callback_id"})
+
+    actions_max_length = 5
+
+    def __init__(
+        self,
+        *,
+        actions: Sequence[Action],
+        callback_id: str,
+        text: str,
+        fallback: Optional[str] = None,
+        fields: Optional[Sequence[AttachmentField]] = None,
+        color: Optional[str] = None,
+        markdown_in: Optional[Sequence[str]] = None,
+        title: Optional[str] = None,
+        title_link: Optional[str] = None,
+        pretext: Optional[str] = None,
+        author_name: Optional[str] = None,
+        author_subname: Optional[str] = None,
+        author_link: Optional[str] = None,
+        author_icon: Optional[str] = None,
+        image_url: Optional[str] = None,
+        thumb_url: Optional[str] = None,
+        footer: Optional[str] = None,
+        footer_icon: Optional[str] = None,
+        ts: Optional[int] = None,
+    ):
+        """
+        An Attachment, but designed to contain interactive Actions
+        Considered legacy - recommended replacement is to use message blocks instead.
+
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#attachment_fields
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields
+
+        Args:
+            actions: A collection of Action objects to include in the attachment.
+                Cannot exceed 5 elements.
+            callback_id: The ID used to identify this attachment. Will be part of the
+                payload sent back to your application.
+            text: The main body text of the attachment. It can be formatted as
+                plain text, or with markdown by including it in the markdown_in
+                parameter. The content will automatically collapse if it contains 700+
+                characters or 5+ linebreaks, and will display a "Show more..." link to
+                expand the content.
+            fallback: A plain text summary of the attachment used in clients that
+                don't show formatted text (eg. IRC, mobile notifications).
+            fields: An array of AttachmentField objects that get displayed in a
+                table-like way. For best results, include no more than 2-3 field
+                objects.
+            color: Changes the color of the border on the left side of this attachment
+                from the default gray. Can either be one of "good" (green), "warning"
+                (yellow), "danger" (red), or any hex color code (eg. #439FE0)
+            markdown_in: An array of field names that should be formatted by
+                markdown syntax - allowed values: "pretext", "text", "fields"
+            title: Large title text near the top of the attachment.
+            title_link: A valid URL that turns the title text into a hyperlink.
+            pretext: Text that appears above the message attachment block. It can
+                be formatted as plain text, or with markdown by including it in the
+                markdown_in parameter.
+            author_name: Small text used to display the author's name.
+            author_subname: Small text used to display the author's sub name.
+            author_link: A valid URL that will hyperlink the author_name text.
+                Will only work if author_name is present.
+            author_icon: A valid URL that displays a small 16px by 16px image to
+                the left of the author_name text. Will only work if author_name is
+                present.
+            image_url: A valid URL to an image file that will be displayed at the
+                bottom of the attachment. We support GIF, JPEG, PNG, and BMP formats.
+                Large images will be resized to a maximum width of 360px or a maximum
+                height of 500px, while still maintaining the original aspect ratio.
+                Cannot be used with thumb_url.
+            thumb_url: A valid URL to an image file that will be displayed as a
+                thumbnail on the right side of a message attachment. We currently
+                support the following formats: GIF, JPEG, PNG, and BMP. The thumbnail's
+                longest dimension will be scaled down to 75px while maintaining the
+                aspect ratio of the image. The filesize of the image must also be less
+                than 500 KB. For best results, please use images that are already 75px
+                by 75px.
+            footer: Some brief text to help contextualize and identify an
+                attachment. Limited to 300 characters, and may be truncated further when
+                displayed to users in environments with limited screen real estate.
+            footer_icon: A valid URL to an image file that will be displayed
+                beside the footer text. Will only work if footer is present. We'll
+                render what you provide at 16px by 16px. It's best to use an image that
+                is similarly sized.
+            ts: An integer Unix timestamp that is used to related your attachment
+                to a specific time. The attachment will display the additional timestamp
+                value as part of the attachment's footer. Your message's timestamp will
+                be displayed in varying ways, depending on how far in the past or future
+                 it is, relative to the present. Form factors, like mobile versus
+                 desktop may also transform its rendered appearance.
+        """
+        super().__init__(
+            text=text,
+            title=title,
+            fallback=fallback,
+            fields=fields,
+            pretext=pretext,
+            title_link=title_link,
+            color=color,
+            author_name=author_name,
+            author_subname=author_subname,
+            author_link=author_link,
+            author_icon=author_icon,
+            image_url=image_url,
+            thumb_url=thumb_url,
+            footer=footer,
+            footer_icon=footer_icon,
+            ts=ts,
+            markdown_in=markdown_in,
+        )
+        self.callback_id = callback_id
+        self.actions = actions or []
+
+    @JsonValidator(f"actions attribute cannot exceed {actions_max_length} elements")
+    def actions_length(self) -> bool:
+        return len(self.actions) <= self.actions_max_length
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        json["actions"] = extract_json(self.actions)
+        return json
+
+

The base class for JSON serializable class objects

+

An Attachment, but designed to contain interactive Actions +Considered legacy - recommended replacement is to use message blocks instead.

+

https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#attachment_fields +https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields

+

Args

+
+
actions
+
A collection of Action objects to include in the attachment. +Cannot exceed 5 elements.
+
callback_id
+
The ID used to identify this attachment. Will be part of the +payload sent back to your application.
+
text
+
The main body text of the attachment. It can be formatted as +plain text, or with markdown by including it in the markdown_in +parameter. The content will automatically collapse if it contains 700+ +characters or 5+ linebreaks, and will display a "Show more…" link to +expand the content.
+
fallback
+
A plain text summary of the attachment used in clients that +don't show formatted text (eg. IRC, mobile notifications).
+
fields
+
An array of AttachmentField objects that get displayed in a +table-like way. For best results, include no more than 2-3 field +objects.
+
color
+
Changes the color of the border on the left side of this attachment +from the default gray. Can either be one of "good" (green), "warning" +(yellow), "danger" (red), or any hex color code (eg. #439FE0)
+
markdown_in
+
An array of field names that should be formatted by +markdown syntax - allowed values: "pretext", "text", "fields"
+
title
+
Large title text near the top of the attachment.
+
title_link
+
A valid URL that turns the title text into a hyperlink.
+
pretext
+
Text that appears above the message attachment block. It can +be formatted as plain text, or with markdown by including it in the +markdown_in parameter.
+
author_name
+
Small text used to display the author's name.
+
author_subname
+
Small text used to display the author's sub name.
+
author_link
+
A valid URL that will hyperlink the author_name text. +Will only work if author_name is present.
+
author_icon
+
A valid URL that displays a small 16px by 16px image to +the left of the author_name text. Will only work if author_name is +present.
+
image_url
+
A valid URL to an image file that will be displayed at the +bottom of the attachment. We support GIF, JPEG, PNG, and BMP formats. +Large images will be resized to a maximum width of 360px or a maximum +height of 500px, while still maintaining the original aspect ratio. +Cannot be used with thumb_url.
+
thumb_url
+
A valid URL to an image file that will be displayed as a +thumbnail on the right side of a message attachment. We currently +support the following formats: GIF, JPEG, PNG, and BMP. The thumbnail's +longest dimension will be scaled down to 75px while maintaining the +aspect ratio of the image. The filesize of the image must also be less +than 500 KB. For best results, please use images that are already 75px +by 75px.
+
footer
+
Some brief text to help contextualize and identify an +attachment. Limited to 300 characters, and may be truncated further when +displayed to users in environments with limited screen real estate.
+
footer_icon
+
A valid URL to an image file that will be displayed +beside the footer text. Will only work if footer is present. We'll +render what you provide at 16px by 16px. It's best to use an image that +is similarly sized.
+
ts
+
An integer Unix timestamp that is used to related your attachment +to a specific time. The attachment will display the additional timestamp +value as part of the attachment's footer. Your message's timestamp will +be displayed in varying ways, depending on how far in the past or future +it is, relative to the present. Form factors, like mobile versus +desktop may also transform its rendered appearance.
+
+

Ancestors

+ +

Class variables

+
+
var actions_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"callback_id"})
+
+

Build an unordered collection of unique elements.

+
+
+

Methods

+
+
+def actions_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"actions attribute cannot exceed {actions_max_length} elements")
+def actions_length(self) -> bool:
+    return len(self.actions) <= self.actions_max_length
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/basic_objects.html b/docs/reference/models/basic_objects.html new file mode 100644 index 000000000..193200f84 --- /dev/null +++ b/docs/reference/models/basic_objects.html @@ -0,0 +1,474 @@ + + + + + + +slack_sdk.models.basic_objects API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.basic_objects

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class BaseObject +
+
+
+ +Expand source code + +
class BaseObject:
+    """The base class for all model objects in this module"""
+
+    def __str__(self):
+        return f"<slack_sdk.{self.__class__.__name__}>"
+
+

The base class for all model objects in this module

+

Subclasses

+ +
+
+class EnumValidator +(attribute:Β str, enum:Β Iterable[str]) +
+
+
+ +Expand source code + +
class EnumValidator(JsonValidator):
+    def __init__(self, attribute: str, enum: Iterable[str]):
+        super().__init__(f"{attribute} attribute must be one of the following values: " f"{', '.join(enum)}")
+
+

Decorate a method on a class to mark it as a JSON validator. Validation +functions should return true if valid, false if not.

+

Args

+
+
message
+
Message to be attached to the thrown SlackObjectFormationError
+
+

Ancestors

+ +
+
+class JsonObject +
+
+
+ +Expand source code + +
class JsonObject(BaseObject, metaclass=ABCMeta):
+    """The base class for JSON serializable class objects"""
+
+    @property
+    @abstractmethod
+    def attributes(self) -> Set[str]:
+        """Provide a set of attributes of this object that will make up its JSON structure"""
+        return set()
+
+    def validate_json(self) -> None:
+        """
+        Raises:
+          SlackObjectFormationError if the object was not valid
+        """
+        for attribute in (func for func in dir(self) if not func.startswith("__")):
+            method = getattr(self, attribute, None)
+            if callable(method) and hasattr(method, "validator"):
+                method()
+
+    def get_object_attribute(self, key: str):
+        return getattr(self, key, None)
+
+    def get_non_null_attributes(self) -> dict:
+        """
+        Construct a dictionary out of non-null keys (from attributes property)
+        present on this object
+        """
+
+        def to_dict_compatible(value: Union[dict, list, object, tuple]) -> Union[dict, list, Any]:
+            if isinstance(value, (list, tuple)):
+                return [to_dict_compatible(v) for v in value]
+            else:
+                to_dict = getattr(value, "to_dict", None)
+                if to_dict and callable(to_dict):
+                    return {k: to_dict_compatible(v) for k, v in value.to_dict().items()}  # type: ignore[attr-defined]
+                else:
+                    return value
+
+        def is_not_empty(self, key: str) -> bool:
+            value = self.get_object_attribute(key)
+            if value is None:
+                return False
+
+            # Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions.
+            # The following code deals with these exceptions:
+            type_value = getattr(self, "type", None)
+            for empty_allowed in EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST:
+                if type_value == empty_allowed["type"] and key == empty_allowed["property"]:
+                    return True
+
+            has_len = getattr(value, "__len__", None) is not None
+            if has_len:
+                return len(value) > 0
+            else:
+                return value is not None
+
+        return {
+            key: to_dict_compatible(value=self.get_object_attribute(key))
+            for key in sorted(self.attributes)
+            if is_not_empty(self, key)
+        }
+
+    def to_dict(self, *args) -> dict:
+        """
+        Extract this object as a JSON-compatible, Slack-API-valid dictionary
+
+        Args:
+          *args: Any specific formatting args (rare; generally not required)
+
+        Raises:
+          SlackObjectFormationError if the object was not valid
+        """
+        self.validate_json()
+        return self.get_non_null_attributes()
+
+    def __repr__(self):
+        dict_value = self.get_non_null_attributes()
+        if dict_value:
+            return f"<slack_sdk.{self.__class__.__name__}: {dict_value}>"
+        else:
+            return self.__str__()
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, JsonObject):
+            return False
+        return self.to_dict() == other.to_dict()
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def attributes(self) -> Set[str]:
+    """Provide a set of attributes of this object that will make up its JSON structure"""
+    return set()
+
+

Provide a set of attributes of this object that will make up its JSON structure

+
+
+

Methods

+
+
+def get_non_null_attributes(self) ‑>Β dict +
+
+
+ +Expand source code + +
def get_non_null_attributes(self) -> dict:
+    """
+    Construct a dictionary out of non-null keys (from attributes property)
+    present on this object
+    """
+
+    def to_dict_compatible(value: Union[dict, list, object, tuple]) -> Union[dict, list, Any]:
+        if isinstance(value, (list, tuple)):
+            return [to_dict_compatible(v) for v in value]
+        else:
+            to_dict = getattr(value, "to_dict", None)
+            if to_dict and callable(to_dict):
+                return {k: to_dict_compatible(v) for k, v in value.to_dict().items()}  # type: ignore[attr-defined]
+            else:
+                return value
+
+    def is_not_empty(self, key: str) -> bool:
+        value = self.get_object_attribute(key)
+        if value is None:
+            return False
+
+        # Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions.
+        # The following code deals with these exceptions:
+        type_value = getattr(self, "type", None)
+        for empty_allowed in EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST:
+            if type_value == empty_allowed["type"] and key == empty_allowed["property"]:
+                return True
+
+        has_len = getattr(value, "__len__", None) is not None
+        if has_len:
+            return len(value) > 0
+        else:
+            return value is not None
+
+    return {
+        key: to_dict_compatible(value=self.get_object_attribute(key))
+        for key in sorted(self.attributes)
+        if is_not_empty(self, key)
+    }
+
+

Construct a dictionary out of non-null keys (from attributes property) +present on this object

+
+
+def get_object_attribute(self, key:Β str) +
+
+
+ +Expand source code + +
def get_object_attribute(self, key: str):
+    return getattr(self, key, None)
+
+
+
+
+def to_dict(self, *args) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self, *args) -> dict:
+    """
+    Extract this object as a JSON-compatible, Slack-API-valid dictionary
+
+    Args:
+      *args: Any specific formatting args (rare; generally not required)
+
+    Raises:
+      SlackObjectFormationError if the object was not valid
+    """
+    self.validate_json()
+    return self.get_non_null_attributes()
+
+

Extract this object as a JSON-compatible, Slack-API-valid dictionary

+

Args

+
+
*args
+
Any specific formatting args (rare; generally not required)
+
+

Raises

+

SlackObjectFormationError if the object was not valid

+
+
+def validate_json(self) ‑>Β None +
+
+
+ +Expand source code + +
def validate_json(self) -> None:
+    """
+    Raises:
+      SlackObjectFormationError if the object was not valid
+    """
+    for attribute in (func for func in dir(self) if not func.startswith("__")):
+        method = getattr(self, attribute, None)
+        if callable(method) and hasattr(method, "validator"):
+            method()
+
+

Raises

+

SlackObjectFormationError if the object was not valid

+
+
+
+
+class JsonValidator +(message:Β str) +
+
+
+ +Expand source code + +
class JsonValidator:
+    def __init__(self, message: str):
+        """
+        Decorate a method on a class to mark it as a JSON validator. Validation
+            functions should return true if valid, false if not.
+
+        Args:
+            message: Message to be attached to the thrown SlackObjectFormationError
+        """
+        self.message = message
+
+    def __call__(self, func: Callable) -> Callable[..., None]:
+        @wraps(func)
+        def wrapped_f(*args, **kwargs):
+            if not func(*args, **kwargs):
+                raise SlackObjectFormationError(self.message)
+
+        wrapped_f.validator = True  # type: ignore[attr-defined]
+        return wrapped_f
+
+

Decorate a method on a class to mark it as a JSON validator. Validation +functions should return true if valid, false if not.

+

Args

+
+
message
+
Message to be attached to the thrown SlackObjectFormationError
+
+

Subclasses

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/blocks/basic_components.html b/docs/reference/models/blocks/basic_components.html new file mode 100644 index 000000000..2821b6a4b --- /dev/null +++ b/docs/reference/models/blocks/basic_components.html @@ -0,0 +1,1805 @@ + + + + + + +slack_sdk.models.blocks.basic_components API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.blocks.basic_components

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class ConfirmObject +(*,
title:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObject,
text:Β strΒ |Β Dict[str,Β Any]Β |Β TextObject,
confirm:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObjectΒ =Β 'Yes',
deny:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObjectΒ =Β 'No',
style:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ConfirmObject(JsonObject):
+    attributes: Set[str] = set()
+
+    title_max_length = 100
+    text_max_length = 300
+    confirm_max_length = 30
+    deny_max_length = 30
+
+    @classmethod
+    def parse(cls, confirm: Union["ConfirmObject", Dict[str, Any]]):
+        if confirm:
+            if isinstance(confirm, ConfirmObject):
+                return confirm
+            elif isinstance(confirm, dict):
+                return ConfirmObject(**confirm)
+            else:
+                # Not yet implemented: show some warning here
+                return None
+        return None
+
+    def __init__(
+        self,
+        *,
+        title: Union[str, Dict[str, Any], PlainTextObject],
+        text: Union[str, Dict[str, Any], TextObject],
+        confirm: Union[str, Dict[str, Any], PlainTextObject] = "Yes",
+        deny: Union[str, Dict[str, Any], PlainTextObject] = "No",
+        style: Optional[str] = None,
+    ):
+        """
+        An object that defines a dialog that provides a confirmation step to any
+        interactive element. This dialog will ask the user to confirm their action by
+        offering a confirm and deny button.
+        https://docs.slack.dev/reference/block-kit/composition-objects/confirmation-dialog-object/
+        """
+        self._title = TextObject.parse(title, default_type=PlainTextObject.type)
+        self._text = TextObject.parse(text, default_type=MarkdownTextObject.type)
+        self._confirm = TextObject.parse(confirm, default_type=PlainTextObject.type)
+        self._deny = TextObject.parse(deny, default_type=PlainTextObject.type)
+        self._style = style
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        self.title = self._title.text if self._title else None
+        self.text = self._text.text if self._text else None
+        self.confirm = self._confirm.text if self._confirm else None
+        self.deny = self._deny.text if self._deny else None
+        self.style = self._style
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def title_length(self) -> bool:
+        return self._title is None or len(self._title.text) <= self.title_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def text_length(self) -> bool:
+        return self._text is None or len(self._text.text) <= self.text_max_length
+
+    @JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters")
+    def confirm_length(self) -> bool:
+        return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length
+
+    @JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters")
+    def deny_length(self) -> bool:
+        return self._deny is None or len(self._deny.text) <= self.deny_max_length
+
+    @JsonValidator('style for confirm must be either "primary" or "danger"')
+    def _validate_confirm_style(self) -> bool:
+        return self._style is None or self._style in ["primary", "danger"]
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        if option_type == "action":
+            # deliberately skipping JSON validators here - can't find documentation
+            # on actual limits here
+            json: Dict[str, Union[str, dict]] = {
+                "ok_text": self._confirm.text if self._confirm and self._confirm.text != "Yes" else "Okay",
+                "dismiss_text": self._deny.text if self._deny and self._deny.text != "No" else "Cancel",
+            }
+            if self._title:
+                json["title"] = self._title.text
+            if self._text:
+                json["text"] = self._text.text
+            return json
+
+        else:
+            self.validate_json()
+            json = {}
+            if self._title:
+                json["title"] = self._title.to_dict()
+            if self._text:
+                json["text"] = self._text.to_dict()
+            if self._confirm:
+                json["confirm"] = self._confirm.to_dict()
+            if self._deny:
+                json["deny"] = self._deny.to_dict()
+            if self._style:
+                json["style"] = self._style
+            return json
+
+

The base class for JSON serializable class objects

+

An object that defines a dialog that provides a confirmation step to any +interactive element. This dialog will ask the user to confirm their action by +offering a confirm and deny button. +https://docs.slack.dev/reference/block-kit/composition-objects/confirmation-dialog-object/

+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var confirm_max_length
+
+

The type of the None singleton.

+
+
var deny_max_length
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(confirm:Β ForwardRef('ConfirmObject')Β |Β Dict[str,Β Any]) +
+
+
+
+
+

Methods

+
+
+def confirm_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters")
+def confirm_length(self) -> bool:
+    return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length
+
+
+
+
+def deny_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters")
+def deny_length(self) -> bool:
+    return self._deny is None or len(self._deny.text) <= self.deny_max_length
+
+
+
+
+def text_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+def text_length(self) -> bool:
+    return self._text is None or len(self._text.text) <= self.text_max_length
+
+
+
+
+def title_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+def title_length(self) -> bool:
+    return self._title is None or len(self._title.text) <= self.title_max_length
+
+
+
+
+

Inherited members

+ +
+
+class DispatchActionConfig +(*, trigger_actions_on:Β List[Any]Β |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class DispatchActionConfig(JsonObject):
+    attributes = {"trigger_actions_on"}
+
+    @classmethod
+    def parse(cls, config: Union["DispatchActionConfig", Dict[str, Any]]):
+        if config:
+            if isinstance(config, DispatchActionConfig):
+                return config
+            elif isinstance(config, dict):
+                return DispatchActionConfig(**config)
+            else:
+                # Not yet implemented: show some warning here
+                return None
+        return None
+
+    def __init__(
+        self,
+        *,
+        trigger_actions_on: Optional[List[Any]] = None,
+    ):
+        """
+        Determines when a plain-text input element will return a block_actions interaction payload.
+        https://docs.slack.dev/reference/block-kit/composition-objects/dispatch-action-configuration-object
+        """
+        self._trigger_actions_on = trigger_actions_on or []
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json = {}
+        if self._trigger_actions_on:
+            json["trigger_actions_on"] = self._trigger_actions_on
+        return json
+
+

The base class for JSON serializable class objects

+

Determines when a plain-text input element will return a block_actions interaction payload. +https://docs.slack.dev/reference/block-kit/composition-objects/dispatch-action-configuration-object

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(config:Β ForwardRef('DispatchActionConfig')Β |Β Dict[str,Β Any]) +
+
+
+
+
+

Inherited members

+ +
+
+class FeedbackButtonObject +(*,
text:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObject,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
value:Β str,
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class FeedbackButtonObject(JsonObject):
+    attributes: Set[str] = set()
+
+    text_max_length = 75
+    value_max_length = 2000
+
+    @classmethod
+    def parse(cls, feedback_button: Union["FeedbackButtonObject", Dict[str, Any]]):
+        if feedback_button:
+            if isinstance(feedback_button, FeedbackButtonObject):
+                return feedback_button
+            elif isinstance(feedback_button, dict):
+                return FeedbackButtonObject(**feedback_button)
+            else:
+                # Not yet implemented: show some warning here
+                return None
+        return None
+
+    def __init__(
+        self,
+        *,
+        text: Union[str, Dict[str, Any], PlainTextObject],
+        accessibility_label: Optional[str] = None,
+        value: str,
+        **others: Dict[str, Any],
+    ):
+        """
+        A feedback button element object for either positive or negative feedback.
+        https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element#button-object-fields
+
+        Args:
+            text (required): An object containing some text. Maximum length for this field is 75 characters.
+            accessibility_label: A label for longer descriptive text about a button element. This label will be read out by
+                screen readers instead of the button `text` object.
+            value (required): The button value. Maximum length for this field is 2000 characters.
+        """
+        self._text: Optional[TextObject] = PlainTextObject.parse(text, default_type=PlainTextObject.type)
+        self._accessibility_label: Optional[str] = accessibility_label
+        self._value: Optional[str] = value
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def text_length(self) -> bool:
+        return self._text is None or len(self._text.text) <= self.text_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def value_length(self) -> bool:
+        return self._value is None or len(self._value) <= self.value_max_length
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json: Dict[str, Union[str, dict]] = {}
+        if self._text:
+            json["text"] = self._text.to_dict()
+        if self._accessibility_label:
+            json["accessibility_label"] = self._accessibility_label
+        if self._value:
+            json["value"] = self._value
+        return json
+
+

The base class for JSON serializable class objects

+

A feedback button element object for either positive or negative feedback. +https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element#button-object-fields

+

Args

+
+
text : required
+
An object containing some text. Maximum length for this field is 75 characters.
+
accessibility_label
+
A label for longer descriptive text about a button element. This label will be read out by +screen readers instead of the button text object.
+
value : required
+
The button value. Maximum length for this field is 2000 characters.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(feedback_button:Β ForwardRef('FeedbackButtonObject')Β |Β Dict[str,Β Any]) +
+
+
+
+
+

Methods

+
+
+def text_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+def text_length(self) -> bool:
+    return self._text is None or len(self._text.text) <= self.text_max_length
+
+
+
+
+def value_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+def value_length(self) -> bool:
+    return self._value is None or len(self._value) <= self.value_max_length
+
+
+
+
+

Inherited members

+ +
+
+class MarkdownTextObject +(*, text:Β str, verbatim:Β boolΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class MarkdownTextObject(TextObject):
+    """mrkdwn typed text object"""
+
+    type = "mrkdwn"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"verbatim"})
+
+    def __init__(self, *, text: str, verbatim: Optional[bool] = None):
+        """A Markdown text object, meaning markdown characters will be parsed as
+        formatting information.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object
+
+        Args:
+            text (required): The text for the block. This field accepts any of the standard text formatting markup
+                when type is mrkdwn.
+            verbatim: When set to false (as is default) URLs will be auto-converted into links,
+                conversation names will be link-ified, and certain mentions will be automatically parsed.
+                Using a value of true will skip any preprocessing of this nature,
+                although you can still include manual parsing strings. This field is only usable when type is mrkdwn.
+        """
+        super().__init__(text=text, type=self.type)
+        self.verbatim = verbatim
+
+    @staticmethod
+    def from_str(text: str) -> "MarkdownTextObject":
+        """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+        return MarkdownTextObject(text=text)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+        return MarkdownTextObject.from_str(text).to_dict()
+
+    @staticmethod
+    def from_link(link: Link, title: str = "") -> "MarkdownTextObject":
+        """
+        Transform a Link object directly into the required object shape
+        to act as a MarkdownTextObject
+        """
+        if title:
+            title = f": {title}"
+        return MarkdownTextObject(text=f"{link}{title}")
+
+    @staticmethod
+    def direct_from_link(link: Link, title: str = "") -> Dict[str, Any]:
+        """
+        Transform a Link object directly into the required object shape
+        to act as a MarkdownTextObject
+        """
+        return MarkdownTextObject.from_link(link, title).to_dict()
+
+

mrkdwn typed text object

+

A Markdown text object, meaning markdown characters will be parsed as +formatting information. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object

+

Args

+
+
text : required
+
The text for the block. This field accepts any of the standard text formatting markup +when type is mrkdwn.
+
verbatim
+
When set to false (as is default) URLs will be auto-converted into links, +conversation names will be link-ified, and certain mentions will be automatically parsed. +Using a value of true will skip any preprocessing of this nature, +although you can still include manual parsing strings. This field is only usable when type is mrkdwn.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+ +
+
+ +Expand source code + +
@staticmethod
+def direct_from_link(link: Link, title: str = "") -> Dict[str, Any]:
+    """
+    Transform a Link object directly into the required object shape
+    to act as a MarkdownTextObject
+    """
+    return MarkdownTextObject.from_link(link, title).to_dict()
+
+

Transform a Link object directly into the required object shape +to act as a MarkdownTextObject

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+    return MarkdownTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a MarkdownTextObject

+
+ +
+
+ +Expand source code + +
@staticmethod
+def from_link(link: Link, title: str = "") -> "MarkdownTextObject":
+    """
+    Transform a Link object directly into the required object shape
+    to act as a MarkdownTextObject
+    """
+    if title:
+        title = f": {title}"
+    return MarkdownTextObject(text=f"{link}{title}")
+
+

Transform a Link object directly into the required object shape +to act as a MarkdownTextObject

+
+
+def from_str(text:Β str) ‑>Β MarkdownTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "MarkdownTextObject":
+    """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+    return MarkdownTextObject(text=text)
+
+

Transforms a string into the required object shape to act as a MarkdownTextObject

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"verbatim"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class Option +(*,
value:Β str,
label:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
description:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
url:Β strΒ |Β NoneΒ =Β None,
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class Option(JsonObject):
+    """Option object used in dialogs, legacy message actions (interactivity in attachments),
+    and blocks. JSON must be retrieved with an explicit option_type - the Slack API has
+    different required formats in different situations
+    """
+
+    attributes: Set[str] = set()
+    logger = logging.getLogger(__name__)
+
+    label_max_length = 75
+    value_max_length = 150
+
+    def __init__(
+        self,
+        *,
+        value: str,
+        label: Optional[str] = None,
+        text: Optional[Union[str, Dict[str, Any], TextObject]] = None,  # Block Kit
+        description: Optional[Union[str, Dict[str, Any], TextObject]] = None,
+        url: Optional[str] = None,
+        **others: Dict[str, Any],
+    ):
+        """
+        An object that represents a single selectable item in a block element (
+        SelectElement, OverflowMenuElement) or dialog element
+        (StaticDialogSelectElement)
+
+        Blocks:
+        https://docs.slack.dev/reference/block-kit/composition-objects/option-object
+
+        Dialogs:
+        https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+
+        Legacy interactive attachments:
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_fields
+
+        Args:
+            label: A short, user-facing string to label this option to users.
+                Cannot exceed 75 characters.
+            value: A short string that identifies this particular option to your
+                application. It will be part of the payload when this option is selected
+                . Cannot exceed 150 characters.
+            description: A user-facing string that provides more details about
+                this option. Only supported in legacy message actions, not in blocks or
+                dialogs.
+        """
+        if text:
+            # For better compatibility with Block Kit ("mrkdwn" does not work for it),
+            # we've changed the default text object type to plain_text since version 3.10.0
+            self._text: Optional[TextObject] = TextObject.parse(
+                text=text,  # "text" here can be either a str or a TextObject
+                default_type=PlainTextObject.type,
+            )
+            self._label: Optional[str] = None
+        else:
+            self._text = None
+            self._label = label
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        self.text: Optional[str] = self._text.text if self._text else None
+        self.label: Optional[str] = self._label
+
+        self.value: str = value
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        if isinstance(description, str):
+            self.description = description
+            self._block_description = PlainTextObject.from_str(description)
+        elif isinstance(description, dict):
+            self.description = description["text"]
+            self._block_description = TextObject.parse(description)  # type: ignore[assignment]
+        elif isinstance(description, TextObject):
+            self.description = description.text
+            self._block_description = description  # type: ignore[assignment]
+        else:
+            self.description = None  # type: ignore[assignment]
+            self._block_description = None  # type: ignore[assignment]
+
+        # A URL to load in the user's browser when the option is clicked.
+        # The url attribute is only available in overflow menus.
+        # Maximum length for this field is 3000 characters.
+        # If you're using url, you'll still receive an interaction payload
+        # and will need to send an acknowledgement response.
+        self.url: Optional[str] = url
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self) -> bool:
+        return self._label is None or len(self._label) <= self.label_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {label_max_length} characters")
+    def _validate_text_length(self) -> bool:
+        return self._text is None or self._text.text is None or len(self._text.text) <= self.label_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def _validate_value_length(self) -> bool:
+        return len(self.value) <= self.value_max_length
+
+    @classmethod
+    def parse_all(cls, options: Optional[Sequence[Union[Dict[str, Any], "Option"]]]) -> Optional[List["Option"]]:
+        if options is None:
+            return None
+        option_objects: List[Option] = []
+        for o in options:
+            if isinstance(o, dict):
+                d = copy.copy(o)
+                option_objects.append(Option(**d))
+            elif isinstance(o, Option):
+                option_objects.append(o)
+            else:
+                cls.logger.warning(f"Unknown option object detected and skipped ({o})")
+        return option_objects
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        """
+        Different parent classes must call this with a valid value from OptionTypes -
+        either "dialog", "action", or "block", so that JSON is returned in the
+        correct shape.
+        """
+        self.validate_json()
+        if option_type == "dialog":
+            return {"label": self.label, "value": self.value}
+        elif option_type == "action" or option_type == "attachment":
+            # "action" can be confusing but it means a legacy message action in attachments
+            # we don't remove the type name for backward compatibility though
+            json: Dict[str, Any] = {"text": self.label, "value": self.value}
+            if self.description is not None:
+                json["description"] = self.description
+            return json
+        else:  # if option_type == "block"; this should be the most common case
+            text: TextObject = self._text or PlainTextObject.from_str(self.label)  # type: ignore[arg-type]
+            json = {
+                "text": text.to_dict(),
+                "value": self.value,
+            }
+            if self._block_description:
+                json["description"] = self._block_description.to_dict()
+            if self.url:
+                json["url"] = self.url
+            return json
+
+    @staticmethod
+    def from_single_value(value_and_label: str):
+        """Creates a simple Option instance with the same value and label"""
+        return Option(value=value_and_label, label=value_and_label)
+
+

Option object used in dialogs, legacy message actions (interactivity in attachments), +and blocks. JSON must be retrieved with an explicit option_type - the Slack API has +different required formats in different situations

+

An object that represents a single selectable item in a block element ( +SelectElement, OverflowMenuElement) or dialog element +(StaticDialogSelectElement)

+

Blocks: +https://docs.slack.dev/reference/block-kit/composition-objects/option-object

+

Dialogs: +https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Legacy interactive attachments: +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_fields

+

Args

+
+
label
+
A short, user-facing string to label this option to users. +Cannot exceed 75 characters.
+
value
+
A short string that identifies this particular option to your +application. It will be part of the payload when this option is selected +. Cannot exceed 150 characters.
+
description
+
A user-facing string that provides more details about +this option. Only supported in legacy message actions, not in blocks or +dialogs.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_single_value(value_and_label:Β str) +
+
+
+ +Expand source code + +
@staticmethod
+def from_single_value(value_and_label: str):
+    """Creates a simple Option instance with the same value and label"""
+    return Option(value=value_and_label, label=value_and_label)
+
+

Creates a simple Option instance with the same value and label

+
+
+def parse_all(options:Β Sequence[Dict[str,Β Any]Β |Β ForwardRef('Option')]Β |Β None) ‑>Β List[Option]Β |Β None +
+
+
+
+
+

Methods

+
+
+def to_dict(self, option_type:Β strΒ =Β 'block') ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+    """
+    Different parent classes must call this with a valid value from OptionTypes -
+    either "dialog", "action", or "block", so that JSON is returned in the
+    correct shape.
+    """
+    self.validate_json()
+    if option_type == "dialog":
+        return {"label": self.label, "value": self.value}
+    elif option_type == "action" or option_type == "attachment":
+        # "action" can be confusing but it means a legacy message action in attachments
+        # we don't remove the type name for backward compatibility though
+        json: Dict[str, Any] = {"text": self.label, "value": self.value}
+        if self.description is not None:
+            json["description"] = self.description
+        return json
+    else:  # if option_type == "block"; this should be the most common case
+        text: TextObject = self._text or PlainTextObject.from_str(self.label)  # type: ignore[arg-type]
+        json = {
+            "text": text.to_dict(),
+            "value": self.value,
+        }
+        if self._block_description:
+            json["description"] = self._block_description.to_dict()
+        if self.url:
+            json["url"] = self.url
+        return json
+
+

Different parent classes must call this with a valid value from OptionTypes - +either "dialog", "action", or "block", so that JSON is returned in the +correct shape.

+
+
+

Inherited members

+ +
+
+class OptionGroup +(*,
label:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
options:Β Sequence[Dict[str,Β Any]Β |Β Option],
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class OptionGroup(JsonObject):
+    """
+    JSON must be retrieved with an explicit option_type - the Slack API has
+    different required formats in different situations
+    """
+
+    attributes: Set[str] = set()
+    label_max_length = 75
+    options_max_length = 100
+    logger = logging.getLogger(__name__)
+
+    def __init__(
+        self,
+        *,
+        label: Optional[Union[str, Dict[str, Any], TextObject]] = None,
+        options: Sequence[Union[Dict[str, Any], Option]],
+        **others: Dict[str, Any],
+    ):
+        """
+        Create a group of Option objects - pass in a label (that will be part of the
+        UI) and a list of Option objects.
+
+        Blocks:
+        https://docs.slack.dev/reference/block-kit/composition-objects/option-group-object
+
+        Dialogs:
+        https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+
+        Legacy interactive attachments:
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_groups
+
+        Args:
+            label: Text to display at the top of this group of options.
+            options: A list of no more than 100 Option objects.
+        """  # noqa prevent flake8 blowing up on the long URL
+        # default_type=PlainTextObject.type is for backward-compatibility
+        self._label: Optional[TextObject] = TextObject.parse(label, default_type=PlainTextObject.type)  # type: ignore[arg-type] # noqa: E501
+        self.label: Optional[str] = self._label.text if self._label else None
+        self.options = Option.parse_all(options)  # compatible with version 2.5
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self):
+        return self.label is None or len(self.label) <= self.label_max_length
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self):
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @classmethod
+    def parse_all(
+        cls, option_groups: Optional[Sequence[Union[Dict[str, Any], "OptionGroup"]]]
+    ) -> Optional[List["OptionGroup"]]:
+        if option_groups is None:
+            return None
+        option_group_objects = []
+        for o in option_groups:
+            if isinstance(o, dict):
+                d = copy.copy(o)
+                option_group_objects.append(OptionGroup(**d))
+            elif isinstance(o, OptionGroup):
+                option_group_objects.append(o)
+            else:
+                cls.logger.warning(f"Unknown option group object detected and skipped ({o})")
+        return option_group_objects
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        self.validate_json()
+        dict_options = [o.to_dict(option_type) for o in self.options]  # type: ignore[union-attr]
+        if option_type == "dialog":
+            return {
+                "label": self.label,
+                "options": dict_options,
+            }
+        elif option_type == "action":
+            return {
+                "text": self.label,
+                "options": dict_options,
+            }
+        else:  # if option_type == "block"; this should be the most common case
+            dict_label: Dict[str, Any] = self._label.to_dict()  # type: ignore[union-attr]
+            return {
+                "label": dict_label,
+                "options": dict_options,
+            }
+
+

JSON must be retrieved with an explicit option_type - the Slack API has +different required formats in different situations

+

Create a group of Option objects - pass in a label (that will be part of the +UI) and a list of Option objects.

+

Blocks: +https://docs.slack.dev/reference/block-kit/composition-objects/option-group-object

+

Dialogs: +https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Legacy interactive attachments: +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_groups

+

Args

+
+
label
+
Text to display at the top of this group of options.
+
options
+
A list of no more than 100 Option objects.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse_all(option_groups:Β Sequence[Dict[str,Β Any]Β |Β ForwardRef('OptionGroup')]Β |Β None) ‑>Β List[OptionGroup]Β |Β None +
+
+
+
+
+

Inherited members

+ +
+
+class PlainTextObject +(*, text:Β str, emoji:Β boolΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class PlainTextObject(TextObject):
+    """plain_text typed text object"""
+
+    type = "plain_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"emoji"})
+
+    def __init__(self, *, text: str, emoji: Optional[bool] = None):
+        """A plain text object, meaning markdown characters will not be parsed as
+        formatting information.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object
+
+        Args:
+            text (required): The text for the block. This field accepts any of the standard text formatting markup
+                when type is mrkdwn.
+            emoji: Indicates whether emojis in a text field should be escaped into the colon emoji format.
+                This field is only usable when type is plain_text.
+        """
+        super().__init__(text=text, type=self.type)
+        self.emoji = emoji
+
+    @staticmethod
+    def from_str(text: str) -> "PlainTextObject":
+        return PlainTextObject(text=text, emoji=True)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a PlainTextObject"""
+        return PlainTextObject.from_str(text).to_dict()
+
+

plain_text typed text object

+

A plain text object, meaning markdown characters will not be parsed as +formatting information. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object

+

Args

+
+
text : required
+
The text for the block. This field accepts any of the standard text formatting markup +when type is mrkdwn.
+
emoji
+
Indicates whether emojis in a text field should be escaped into the colon emoji format. +This field is only usable when type is plain_text.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a PlainTextObject"""
+    return PlainTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a PlainTextObject

+
+
+def from_str(text:Β str) ‑>Β PlainTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "PlainTextObject":
+    return PlainTextObject(text=text, emoji=True)
+
+
+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"emoji"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RawTextObject +(*, text:Β str) +
+
+
+ +Expand source code + +
class RawTextObject(TextObject):
+    """raw_text typed text object"""
+
+    type = "raw_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return {"text", "type"}
+
+    def __init__(self, *, text: str):
+        """A raw text object used in table block cells.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object/
+        https://docs.slack.dev/reference/block-kit/blocks/table-block
+
+        Args:
+            text (required): The text content for the table block cell.
+        """
+        super().__init__(text=text, type=self.type)
+
+    @staticmethod
+    def from_str(text: str) -> "RawTextObject":
+        """Transforms a string into a RawTextObject"""
+        return RawTextObject(text=text)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a RawTextObject"""
+        return RawTextObject.from_str(text).to_dict()
+
+    @JsonValidator("text attribute must have at least 1 character")
+    def _validate_text_min_length(self):
+        return len(self.text) >= 1
+
+

raw_text typed text object

+

A raw text object used in table block cells. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object/ +https://docs.slack.dev/reference/block-kit/blocks/table-block

+

Args

+
+
text : required
+
The text content for the table block cell.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a RawTextObject"""
+    return RawTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a RawTextObject

+
+
+def from_str(text:Β str) ‑>Β RawTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "RawTextObject":
+    """Transforms a string into a RawTextObject"""
+    return RawTextObject(text=text)
+
+

Transforms a string into a RawTextObject

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return {"text", "type"}
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class SlackFile +(*, id:Β strΒ |Β NoneΒ =Β None, url:Β strΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class SlackFile(JsonObject):
+    attributes = {"id", "url"}
+
+    def __init__(
+        self,
+        *,
+        id: Optional[str] = None,
+        url: Optional[str] = None,
+    ):
+        """An object containing Slack file information to be used in an image block or image element.
+        https://docs.slack.dev/reference/block-kit/composition-objects/slack-file-object
+
+        Args:
+            id: Slack ID of the file.
+            url: This URL can be the url_private or the permalink of the Slack file.
+        """
+        self._id = id
+        self._url = url
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json = {}
+        if self._id is not None:
+            json["id"] = self._id
+        if self._url is not None:
+            json["url"] = self._url
+        return json
+
+

The base class for JSON serializable class objects

+

An object containing Slack file information to be used in an image block or image element. +https://docs.slack.dev/reference/block-kit/composition-objects/slack-file-object

+

Args

+
+
id
+
Slack ID of the file.
+
url
+
This URL can be the url_private or the permalink of the Slack file.
+
+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class TextObject +(text:Β str,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
emoji:Β boolΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class TextObject(JsonObject):
+    """The interface for text objects (types: plain_text, mrkdwn)"""
+
+    attributes = {"text", "type", "emoji"}
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    @classmethod
+    def parse(
+        cls,
+        text: Union[str, Dict[str, Any], "TextObject"],
+        default_type: str = "mrkdwn",
+    ) -> Optional["TextObject"]:
+        if not text:
+            return None
+        elif isinstance(text, str):
+            if default_type == PlainTextObject.type:
+                return PlainTextObject.from_str(text)
+            else:
+                return MarkdownTextObject.from_str(text)
+        elif isinstance(text, dict):
+            d = copy.copy(text)
+            t = d.pop("type")
+            if t == PlainTextObject.type:
+                return PlainTextObject(**d)
+            else:
+                return MarkdownTextObject(**d)
+        elif isinstance(text, TextObject):
+            return text
+        else:
+            cls.logger.warning(f"Unknown type ({type(text)}) detected when parsing a TextObject")
+            return None
+
+    def __init__(
+        self,
+        text: str,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        emoji: Optional[bool] = None,
+        **kwargs,
+    ):
+        """Super class for new text "objects" used in Block kit"""
+        if subtype:
+            self._subtype_warning()
+
+        self.text = text
+        self.type = type if type else subtype
+        self.emoji = emoji
+
+

The interface for text objects (types: plain_text, mrkdwn)

+

Super class for new text "objects" used in Block kit

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(text:Β strΒ |Β Dict[str,Β Any]Β |Β ForwardRef('TextObject'),
default_type:Β strΒ =Β 'mrkdwn') ‑>Β TextObjectΒ |Β None
+
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class Workflow +(*,
trigger:Β WorkflowTriggerΒ |Β dict)
+
+
+
+ +Expand source code + +
class Workflow(JsonObject):
+    attributes = {"trigger"}
+
+    def __init__(
+        self,
+        *,
+        trigger: Union[WorkflowTrigger, dict],
+    ):
+        self._trigger = trigger
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json = {}
+        if isinstance(self._trigger, WorkflowTrigger):
+            json["trigger"] = self._trigger.to_dict()
+        else:
+            json["trigger"] = self._trigger
+        return json
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class WorkflowTrigger +(*, url:Β str, customizable_input_parameters:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class WorkflowTrigger(JsonObject):
+    attributes = {"trigger"}
+
+    def __init__(self, *, url: str, customizable_input_parameters: Optional[List[Dict[str, str]]] = None):
+        self._url = url
+        self._customizable_input_parameters = customizable_input_parameters
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json = {"url": self._url}
+        if self._customizable_input_parameters is not None:
+            json.update({"customizable_input_parameters": self._customizable_input_parameters})  # type: ignore[dict-item]
+        return json
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/blocks/block_elements.html b/docs/reference/models/blocks/block_elements.html new file mode 100644 index 000000000..375ee07ce --- /dev/null +++ b/docs/reference/models/blocks/block_elements.html @@ -0,0 +1,5350 @@ + + + + + + +slack_sdk.models.blocks.block_elements API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.blocks.block_elements

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class BlockElement +(*, type:Β strΒ |Β NoneΒ =Β None, subtype:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class BlockElement(JsonObject, metaclass=ABCMeta):
+    """Block Elements are things that exists inside of your Blocks.
+    https://docs.slack.dev/reference/block-kit/block-elements/
+    """
+
+    attributes = {"type"}
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        **others: dict,
+    ):
+        if subtype:
+            self._subtype_warning()
+        self.type = type if type else subtype
+        show_unknown_key_warning(self, others)
+
+    @classmethod
+    def parse(cls, block_element: Union[dict, "BlockElement"]) -> Optional[Union["BlockElement", TextObject]]:
+        if block_element is None:
+            return None
+        elif isinstance(block_element, dict):
+            if "type" in block_element:
+                d = copy.copy(block_element)
+                t = d.pop("type")
+                for subclass in cls._get_sub_block_elements():
+                    if t == subclass.type:
+                        return subclass(**d)
+                if t == PlainTextObject.type:
+                    return PlainTextObject(**d)
+                elif t == MarkdownTextObject.type:
+                    return MarkdownTextObject(**d)
+        elif isinstance(block_element, (TextObject, BlockElement)):
+            return block_element
+        cls.logger.warning(f"Unknown element detected and skipped ({block_element})")
+        return None
+
+    @classmethod
+    def parse_all(
+        cls, block_elements: Sequence[Union[dict, "BlockElement", TextObject]]
+    ) -> List[Union["BlockElement", TextObject]]:
+        return [cls.parse(e) for e in block_elements or []]  # type: ignore[arg-type, misc]
+
+    @classmethod
+    def _get_sub_block_elements(cls: Type["BlockElement"]) -> Iterator[Type["BlockElement"]]:
+        for subclass in cls.__subclasses__():
+            if hasattr(subclass, "type"):
+                yield subclass
+            yield from subclass._get_sub_block_elements()
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(block_element:Β dictΒ |Β ForwardRef('BlockElement')) ‑>Β BlockElementΒ |Β TextObjectΒ |Β None +
+
+
+
+
+def parse_all(block_elements:Β Sequence[dictΒ |Β ForwardRef('BlockElement')Β |Β TextObject]) ‑>Β List[BlockElementΒ |Β TextObject] +
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class ButtonElement +(*,
text:Β strΒ |Β dictΒ |Β TextObject,
action_id:Β strΒ |Β NoneΒ =Β None,
url:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ButtonElement(InteractiveElement):
+    type = "button"
+    text_max_length = 75
+    url_max_length = 3000
+    value_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text", "url", "value", "style", "confirm", "accessibility_label"})
+
+    def __init__(
+        self,
+        *,
+        text: Union[str, dict, TextObject],
+        action_id: Optional[str] = None,
+        url: Optional[str] = None,
+        value: Optional[str] = None,
+        style: Optional[str] = None,  # primary, danger
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        accessibility_label: Optional[str] = None,
+        **others: dict,
+    ):
+        """An interactive element that inserts a button. The button can be a trigger for
+        anything from opening a simple link to starting a complex workflow.
+        https://docs.slack.dev/reference/block-kit/block-elements/button-element/
+
+        Args:
+            text (required): A text object that defines the button's text.
+                Can only be of type: plain_text.
+                Maximum length for the text in this field is 75 characters.
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            url: A URL to load in the user's browser when the button is clicked.
+                Maximum length for this field is 3000 characters.
+                If you're using url, you'll still receive an interaction payload
+                and will need to send an acknowledgement response.
+            value: The value to send along with the interaction payload.
+                Maximum length for this field is 2000 characters.
+            style: Decorates buttons with alternative visual color schemes. Use this option with restraint.
+                "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions.
+                "primary" should only be used for one button within a set.
+                "danger" gives buttons a red outline and text, and should be used when the action is destructive.
+                Use "danger" even more sparingly than "primary".
+                If you don't include this field, the default button style will be used.
+            confirm: A confirm object that defines an optional confirmation dialog after the button is clicked.
+            accessibility_label: A label for longer descriptive text about a button element.
+                This label will be read out by screen readers instead of the button text object.
+                Maximum length for this field is 75 characters.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        # NOTE: default_type=PlainTextObject.type here is only for backward-compatibility with version 2.5.0
+        self.text = TextObject.parse(text, default_type=PlainTextObject.type)
+        self.url = url
+        self.value = value
+        self.style = style
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+        self.accessibility_label = accessibility_label
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_text_length(self) -> bool:
+        return self.text is None or self.text.text is None or len(self.text.text) <= self.text_max_length
+
+    @JsonValidator(f"url attribute cannot exceed {url_max_length} characters")
+    def _validate_url_length(self) -> bool:
+        return self.url is None or len(self.url) <= self.url_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def _validate_value_length(self) -> bool:
+        return self.value is None or len(self.value) <= self.value_max_length
+
+    @EnumValidator("style", ButtonStyles)
+    def _validate_style_valid(self):
+        return self.style is None or self.style in ButtonStyles
+
+    @JsonValidator(f"accessibility_label attribute cannot exceed {text_max_length} characters")
+    def _validate_accessibility_label_length(self) -> bool:
+        return self.accessibility_label is None or len(self.accessibility_label) <= self.text_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An interactive element that inserts a button. The button can be a trigger for +anything from opening a simple link to starting a complex workflow. +https://docs.slack.dev/reference/block-kit/block-elements/button-element/

+

Args

+
+
text : required
+
A text object that defines the button's text. +Can only be of type: plain_text. +Maximum length for the text in this field is 75 characters.
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
url
+
A URL to load in the user's browser when the button is clicked. +Maximum length for this field is 3000 characters. +If you're using url, you'll still receive an interaction payload +and will need to send an acknowledgement response.
+
value
+
The value to send along with the interaction payload. +Maximum length for this field is 2000 characters.
+
style
+
Decorates buttons with alternative visual color schemes. Use this option with restraint. +"primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. +"primary" should only be used for one button within a set. +"danger" gives buttons a red outline and text, and should be used when the action is destructive. +Use "danger" even more sparingly than "primary". +If you don't include this field, the default button style will be used.
+
confirm
+
A confirm object that defines an optional confirmation dialog after the button is clicked.
+
accessibility_label
+
A label for longer descriptive text about a button element. +This label will be read out by screen readers instead of the button text object. +Maximum length for this field is 75 characters.
+
+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
var url_max_length
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ChannelMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_channels:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ChannelMultiSelectElement(InputInteractiveElement):
+    type = "multi_channels_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_channels", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_channels: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This multi-select menu will populate its options with a list of public channels visible
+        to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#channel_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_channels: An array of one or more IDs of any valid public channel
+                to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_channels = initial_channels
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This multi-select menu will populate its options with a list of public channels visible +to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#channel_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_channels
+
An array of one or more IDs of any valid public channel +to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_channels", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ChannelSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_channel:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
response_url_enabled:Β boolΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ChannelSelectElement(InputInteractiveElement):
+    type = "channels_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_channel", "response_url_enabled"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_channel: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        response_url_enabled: Optional[bool] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of public channels
+        visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#channels_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_channel: The ID of any valid public channel to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after a menu item is selected.
+            response_url_enabled: This field only works with menus in input blocks in modals.
+                When set to true, the view_submission payload from the menu's parent view will contain a response_url.
+                This response_url can be used for message responses.
+                The target channel for the message will be determined by the value of this select menu
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_channel = initial_channel
+        self.response_url_enabled = response_url_enabled
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of public channels +visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#channels_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_channel
+
The ID of any valid public channel to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after a menu item is selected.
+
response_url_enabled
+
This field only works with menus in input blocks in modals. +When set to true, the view_submission payload from the menu's parent view will contain a response_url. +This response_url can be used for message responses. +The target channel for the message will be determined by the value of this select menu
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_channel", "response_url_enabled"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class CheckboxesElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
initial_options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class CheckboxesElement(InputInteractiveElement):
+    type = "checkboxes"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "initial_options"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        initial_options: Optional[Sequence[Union[dict, Option]]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A checkbox group that allows a user to choose multiple items from a list of possible options.
+        https://docs.slack.dev/reference/block-kit/block-elements/checkboxes-element/
+
+        Args:
+            action_id (required): An identifier for the action triggered when the checkbox group is changed.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects. A maximum of 10 options are allowed.
+            initial_options: An array of option objects that exactly matches one or more of the options.
+                These options will be selected when the checkbox group initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after clicking one of the checkboxes in this element.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = Option.parse_all(options)
+        self.initial_options = Option.parse_all(initial_options)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A checkbox group that allows a user to choose multiple items from a list of possible options. +https://docs.slack.dev/reference/block-kit/block-elements/checkboxes-element/

+

Args

+
+
action_id : required
+
An identifier for the action triggered when the checkbox group is changed. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects. A maximum of 10 options are allowed.
+
initial_options
+
An array of option objects that exactly matches one or more of the options. +These options will be selected when the checkbox group initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after clicking one of the checkboxes in this element.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "initial_options"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ConversationFilter +(*,
include:Β Sequence[str]Β |Β NoneΒ =Β None,
exclude_bot_users:Β boolΒ |Β NoneΒ =Β None,
exclude_external_shared_channels:Β boolΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ConversationFilter(JsonObject):
+    attributes = {"include", "exclude_bot_users", "exclude_external_shared_channels"}
+    logger = logging.getLogger(__name__)
+
+    def __init__(
+        self,
+        *,
+        include: Optional[Sequence[str]] = None,
+        exclude_bot_users: Optional[bool] = None,
+        exclude_external_shared_channels: Optional[bool] = None,
+    ):
+        """Provides a way to filter the list of options in a conversations select menu
+        or conversations multi-select menu.
+        https://docs.slack.dev/reference/block-kit/composition-objects/conversation-filter-object
+
+        Args:
+            include: Indicates which type of conversations should be included in the list.
+                When this field is provided, any conversations that do not match will be excluded.
+                You should provide an array of strings from the following options:
+                "im", "mpim", "private", and "public". The array cannot be empty.
+            exclude_bot_users: Indicates whether to exclude bot users from conversation lists. Defaults to false.
+            exclude_external_shared_channels: Indicates whether to exclude external shared channels
+                from conversation lists. Defaults to false.
+        """
+        self.include = include
+        self.exclude_bot_users = exclude_bot_users
+        self.exclude_external_shared_channels = exclude_external_shared_channels
+
+    @classmethod
+    def parse(cls, filter: Union[dict, "ConversationFilter"]):
+        if filter is None:
+            return None
+        elif isinstance(filter, ConversationFilter):
+            return filter
+        elif isinstance(filter, dict):
+            d = copy.copy(filter)
+            return ConversationFilter(**d)
+        else:
+            cls.logger.warning(f"Unknown conversation filter object detected and skipped ({filter})")
+            return None
+
+

The base class for JSON serializable class objects

+

Provides a way to filter the list of options in a conversations select menu +or conversations multi-select menu. +https://docs.slack.dev/reference/block-kit/composition-objects/conversation-filter-object

+

Args

+
+
include
+
Indicates which type of conversations should be included in the list. +When this field is provided, any conversations that do not match will be excluded. +You should provide an array of strings from the following options: +"im", "mpim", "private", and "public". The array cannot be empty.
+
exclude_bot_users
+
Indicates whether to exclude bot users from conversation lists. Defaults to false.
+
exclude_external_shared_channels
+
Indicates whether to exclude external shared channels +from conversation lists. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(filter:Β dictΒ |Β ForwardRef('ConversationFilter')) +
+
+
+
+
+

Inherited members

+ +
+
+class ConversationMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_conversations:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
default_to_current_conversation:Β boolΒ |Β NoneΒ =Β None,
filter:Β dictΒ |Β ConversationFilterΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ConversationMultiSelectElement(InputInteractiveElement):
+    type = "multi_conversations_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_conversations",
+                "max_selected_items",
+                "default_to_current_conversation",
+                "filter",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_conversations: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        default_to_current_conversation: Optional[bool] = None,
+        filter: Optional[Union[dict, ConversationFilter]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This multi-select menu will populate its options with a list of public and private channels,
+        DMs, and MPIMs visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element/#conversation_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_conversations: An array of one or more IDs of any valid conversations to be pre-selected
+                when the menu loads. If default_to_current_conversation is also supplied,
+                initial_conversations will be ignored.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            default_to_current_conversation: Pre-populates the select menu with the conversation that
+                the user was viewing when they opened the modal, if available. Default is false.
+            filter: A filter object that reduces the list of available conversations using the specified criteria.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_conversations = initial_conversations
+        self.max_selected_items = max_selected_items
+        self.default_to_current_conversation = default_to_current_conversation
+        self.filter = ConversationFilter.parse(filter)  # type: ignore[arg-type]
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This multi-select menu will populate its options with a list of public and private channels, +DMs, and MPIMs visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element/#conversation_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_conversations
+
An array of one or more IDs of any valid conversations to be pre-selected +when the menu loads. If default_to_current_conversation is also supplied, +initial_conversations will be ignored.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
default_to_current_conversation
+
Pre-populates the select menu with the conversation that +the user was viewing when they opened the modal, if available. Default is false.
+
filter
+
A filter object that reduces the list of available conversations using the specified criteria.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_conversations",
+            "max_selected_items",
+            "default_to_current_conversation",
+            "filter",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ConversationSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_conversation:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
response_url_enabled:Β boolΒ |Β NoneΒ =Β None,
default_to_current_conversation:Β boolΒ |Β NoneΒ =Β None,
filter:Β ConversationFilterΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ConversationSelectElement(InputInteractiveElement):
+    type = "conversations_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_conversation",
+                "response_url_enabled",
+                "filter",
+                "default_to_current_conversation",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_conversation: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        response_url_enabled: Optional[bool] = None,
+        default_to_current_conversation: Optional[bool] = None,
+        filter: Optional[ConversationFilter] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of public and private
+        channels, DMs, and MPIMs visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#conversations_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_conversation: The ID of any valid conversation to be pre-selected when the menu loads.
+                If default_to_current_conversation is also supplied, initial_conversation will take precedence.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            response_url_enabled: This field only works with menus in input blocks in modals.
+                When set to true, the view_submission payload from the menu's parent view will contain a response_url.
+                This response_url can be used for message responses. The target conversation for the message
+                will be determined by the value of this select menu.
+            default_to_current_conversation: Pre-populates the select menu with the conversation
+                that the user was viewing when they opened the modal, if available. Default is false.
+            filter: A filter object that reduces the list of available conversations using the specified criteria.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_conversation = initial_conversation
+        self.response_url_enabled = response_url_enabled
+        self.default_to_current_conversation = default_to_current_conversation
+        self.filter = filter
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of public and private +channels, DMs, and MPIMs visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#conversations_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_conversation
+
The ID of any valid conversation to be pre-selected when the menu loads. +If default_to_current_conversation is also supplied, initial_conversation will take precedence.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
response_url_enabled
+
This field only works with menus in input blocks in modals. +When set to true, the view_submission payload from the menu's parent view will contain a response_url. +This response_url can be used for message responses. The target conversation for the message +will be determined by the value of this select menu.
+
default_to_current_conversation
+
Pre-populates the select menu with the conversation +that the user was viewing when they opened the modal, if available. Default is false.
+
filter
+
A filter object that reduces the list of available conversations using the specified criteria.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_conversation",
+            "response_url_enabled",
+            "filter",
+            "default_to_current_conversation",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DatePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_date:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class DatePickerElement(InputInteractiveElement):
+    type = "datepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_date"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_date: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        An element which lets users easily select a date from a calendar style UI.
+        Date picker elements can be used inside of SectionBlocks and ActionsBlocks.
+        https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown on the datepicker.
+                Maximum length for the text in this field is 150 characters.
+            initial_date: The initial date that is selected when the element is loaded.
+                This should be in the format YYYY-MM-DD.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a date is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_date = initial_date
+
+    @JsonValidator("initial_date attribute must be in format 'YYYY-MM-DD'")
+    def _validate_initial_date_valid(self) -> bool:
+        return (
+            self.initial_date is None
+            or re.match(r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date) is not None
+        )
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element which lets users easily select a date from a calendar style UI. +Date picker elements can be used inside of SectionBlocks and ActionsBlocks. +https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown on the datepicker. +Maximum length for the text in this field is 150 characters.
+
initial_date
+
The initial date that is selected when the element is loaded. +This should be in the format YYYY-MM-DD.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a date is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_date"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DateTimePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_date_time:Β intΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class DateTimePickerElement(InputInteractiveElement):
+    type = "datetimepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_date_time"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_date_time: Optional[int] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        An element that allows the selection of a time of day formatted as a UNIX timestamp.
+        On desktop clients, this time picker will take the form of a dropdown list and the
+        date picker will take the form of a dropdown calendar. Both options will have free-text
+        entry for precise choices. On mobile clients, the time picker and date
+        picker will use native UIs.
+        https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element/
+
+        Args:
+            action_id (required): An identifier for the action triggered when a time is selected. You can use this
+                when you receive an interaction payload to identify the source of the action. Should be unique among
+                all other action_ids in the containing block. Maximum length for this field is 255 characters.
+            initial_date_time: The initial date and time that is selected when the element is loaded, represented as
+                a UNIX timestamp in seconds. This should be in the format of 10 digits, for example 1628633820
+                represents the date and time August 10th, 2021 at 03:17pm PST.
+                and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a time is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_date_time = initial_date_time
+
+    @JsonValidator("initial_date_time attribute must be between 0 and 99999999 seconds")
+    def _validate_initial_date_time_valid(self) -> bool:
+        return self.initial_date_time is None or (0 <= self.initial_date_time <= 9999999999)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element that allows the selection of a time of day formatted as a UNIX timestamp. +On desktop clients, this time picker will take the form of a dropdown list and the +date picker will take the form of a dropdown calendar. Both options will have free-text +entry for precise choices. On mobile clients, the time picker and date +picker will use native UIs. +https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element/

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a time is selected. You can use this +when you receive an interaction payload to identify the source of the action. Should be unique among +all other action_ids in the containing block. Maximum length for this field is 255 characters.
+
initial_date_time
+
The initial date and time that is selected when the element is loaded, represented as +a UNIX timestamp in seconds. This should be in the format of 10 digits, for example 1628633820 +represents the date and time August 10th, 2021 at 03:17pm PST. +and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a time is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_date_time"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class EmailInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class EmailInputElement(InputInteractiveElement):
+    type = "email_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_value: Optional[str] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        https://docs.slack.dev/reference/block-kit/block-elements/email-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_value: The initial value in the email input when it is loaded.
+            dispatch_action_config:  dispatch configuration object that determines when during
+                text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown in the
+                email input. Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

https://docs.slack.dev/reference/block-kit/block-elements/email-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_value
+
The initial value in the email input when it is loaded.
+
dispatch_action_config
+
dispatch configuration object that determines when during +text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown in the +email input. Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ExternalDataMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
initial_options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ExternalDataMultiSelectElement(InputInteractiveElement):
+    type = "multi_external_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        min_query_length: Optional[int] = None,
+        initial_options: Optional[Sequence[Union[dict, Option]]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will load its options from an external data source, allowing
+        for a dynamic list of options.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            min_query_length: When the typeahead field is used, a request will be sent on every character change.
+                If you prefer fewer requests or more fully ideated queries,
+                use the min_query_length attribute to tell Slack
+                the fewest number of typed characters required before dispatch.
+                The default value is 3
+            initial_options: An array of option objects that exactly match one or more of the options
+                within options or option_groups. These options will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.min_query_length = min_query_length
+        self.initial_options = Option.parse_all(initial_options)
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will load its options from an external data source, allowing +for a dynamic list of options. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
min_query_length
+
When the typeahead field is used, a request will be sent on every character change. +If you prefer fewer requests or more fully ideated queries, +use the min_query_length attribute to tell Slack +the fewest number of typed characters required before dispatch. +The default value is 3
+
initial_options
+
An array of option objects that exactly match one or more of the options +within options or option_groups. These options will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ExternalDataSelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_option:Β OptionΒ |Β OptionGroupΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ExternalDataSelectElement(InputInteractiveElement):
+    type = "external_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, TextObject]] = None,
+        initial_option: Union[Optional[Option], Optional[OptionGroup]] = None,
+        min_query_length: Optional[int] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will load its options from an external data source, allowing
+        for a dynamic list of options.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#external_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            initial_option: A single option that exactly matches one of the options
+                within the options or option_groups loaded from the external data source.
+                This option will be selected when the menu initially loads.
+            min_query_length: When the typeahead field is used, a request will be sent on every character change.
+                If you prefer fewer requests or more fully ideated queries,
+                use the min_query_length attribute to tell Slack
+                the fewest number of typed characters required before dispatch.
+                The default value is 3.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.min_query_length = min_query_length
+        self.initial_option = initial_option
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will load its options from an external data source, allowing +for a dynamic list of options. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#external_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
initial_option
+
A single option that exactly matches one of the options +within the options or option_groups loaded from the external data source. +This option will be selected when the menu initially loads.
+
min_query_length
+
When the typeahead field is used, a request will be sent on every character change. +If you prefer fewer requests or more fully ideated queries, +use the min_query_length attribute to tell Slack +the fewest number of typed characters required before dispatch. +The default value is 3.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class FeedbackButtonsElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
positive_button:Β dictΒ |Β FeedbackButtonObject,
negative_button:Β dictΒ |Β FeedbackButtonObject,
**others:Β dict)
+
+
+
+ +Expand source code + +
class FeedbackButtonsElement(InteractiveElement):
+    type = "feedback_buttons"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"positive_button", "negative_button"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        positive_button: Union[dict, FeedbackButtonObject],
+        negative_button: Union[dict, FeedbackButtonObject],
+        **others: dict,
+    ):
+        """Buttons to indicate positive or negative feedback.
+        https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element
+
+        Args:
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            positive_button (required): A button to indicate positive feedback.
+            negative_button (required): A button to indicate negative feedback.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.positive_button = FeedbackButtonObject.parse(positive_button)
+        self.negative_button = FeedbackButtonObject.parse(negative_button)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Buttons to indicate positive or negative feedback. +https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element

+

Args

+
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
positive_button : required
+
A button to indicate positive feedback.
+
negative_button : required
+
A button to indicate negative feedback.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FileInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
filetypes:Β List[str]Β |Β NoneΒ =Β None,
max_files:Β intΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class FileInputElement(InputInteractiveElement):
+    type = "file_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "filetypes",
+                "max_files",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        filetypes: Optional[List[str]] = None,
+        max_files: Optional[int] = None,
+        **others: dict,
+    ):
+        """
+        https://docs.slack.dev/reference/block-kit/block-elements/file-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block. Maximum length is 255 characters.
+            filetypes: An array of valid file extensions that will be accepted for this element.
+                All file extensions will be accepted if filetypes is not specified.
+                This validation is provided for convenience only,
+                and you should perform your own file type validation based on what you expect to receive.
+            max_files: Maximum number of files that can be uploaded for this file_input element.
+                Minimum of 1, maximum of 10. Defaults to 10 if not specified.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.filetypes = filetypes
+        self.max_files = max_files
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

https://docs.slack.dev/reference/block-kit/block-elements/file-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. Maximum length is 255 characters.
+
filetypes
+
An array of valid file extensions that will be accepted for this element. +All file extensions will be accepted if filetypes is not specified. +This validation is provided for convenience only, +and you should perform your own file type validation based on what you expect to receive.
+
max_files
+
Maximum number of files that can be uploaded for this file_input element. +Minimum of 1, maximum of 10. Defaults to 10 if not specified.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "filetypes",
+            "max_files",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class IconButtonElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
icon:Β str,
text:Β strΒ |Β dictΒ |Β TextObject,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
visible_to_user_ids:Β List[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class IconButtonElement(InteractiveElement):
+    type = "icon_button"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"icon", "text", "accessibility_label", "value", "visible_to_user_ids", "confirm"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        icon: str,
+        text: Union[str, dict, TextObject],
+        accessibility_label: Optional[str] = None,
+        value: Optional[str] = None,
+        visible_to_user_ids: Optional[List[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        **others: dict,
+    ):
+        """An icon button to perform actions.
+        https://docs.slack.dev/reference/block-kit/block-elements/icon-button-element
+
+        Args:
+            action_id: An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            icon (required): The icon to show (e.g., 'trash').
+            text (required): Defines an object containing some text.
+            accessibility_label: A label for longer descriptive text about a button element.
+                This label will be read out by screen readers instead of the button text object.
+                Maximum length for this field is 75 characters.
+            value: The button value.
+                Maximum length for this field is 2000 characters.
+            visible_to_user_ids: User IDs for which the icon appears.
+                Maximum length for this field is 10 user IDs.
+            confirm: A confirm object that defines an optional confirmation dialog after the button is clicked.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.icon = icon
+        self.text = TextObject.parse(text, PlainTextObject.type)
+        self.accessibility_label = accessibility_label
+        self.value = value
+        self.visible_to_user_ids = visible_to_user_ids
+        self.confirm = ConfirmObject.parse(confirm) if confirm else None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An icon button to perform actions. +https://docs.slack.dev/reference/block-kit/block-elements/icon-button-element

+

Args

+
+
action_id
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
icon : required
+
The icon to show (e.g., 'trash').
+
text : required
+
Defines an object containing some text.
+
accessibility_label
+
A label for longer descriptive text about a button element. +This label will be read out by screen readers instead of the button text object. +Maximum length for this field is 75 characters.
+
value
+
The button value. +Maximum length for this field is 2000 characters.
+
visible_to_user_ids
+
User IDs for which the icon appears. +Maximum length for this field is 10 user IDs.
+
confirm
+
A confirm object that defines an optional confirmation dialog after the button is clicked.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ImageElement +(*,
alt_text:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β SlackFileΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ImageElement(BlockElement):
+    type = "image"
+    image_url_max_length = 3000
+    alt_text_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "image_url", "slack_file"})
+
+    def __init__(
+        self,
+        *,
+        alt_text: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None,
+        **others: dict,
+    ):
+        """An element to insert an image - this element can be used in section and
+        context blocks only. If you want a block with only an image in it,
+        you're looking for the image block.
+        https://docs.slack.dev/reference/block-kit/block-elements/image-element
+
+        Args:
+            alt_text (required): A plain-text summary of the image. This should not contain any markup.
+            image_url: The URL of the image to be displayed.
+            slack_file: A Slack image file object that defines the source of the image.
+        """
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.image_url = image_url
+        self.alt_text = alt_text
+        self.slack_file = slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file)
+
+    @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters")
+    def _validate_image_url_length(self) -> bool:
+        return self.image_url is None or len(self.image_url) <= self.image_url_max_length
+
+    @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters")
+    def _validate_alt_text_length(self) -> bool:
+        return len(self.alt_text) <= self.alt_text_max_length  # type: ignore[arg-type]
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element to insert an image - this element can be used in section and +context blocks only. If you want a block with only an image in it, +you're looking for the image block. +https://docs.slack.dev/reference/block-kit/block-elements/image-element

+

Args

+
+
alt_text : required
+
A plain-text summary of the image. This should not contain any markup.
+
image_url
+
The URL of the image to be displayed.
+
slack_file
+
A Slack image file object that defines the source of the image.
+
+

Ancestors

+ +

Class variables

+
+
var alt_text_max_length
+
+

The type of the None singleton.

+
+
var image_url_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "image_url", "slack_file"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class InputInteractiveElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β TextObjectΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InputInteractiveElement(InteractiveElement, metaclass=ABCMeta):
+    placeholder_max_length = 150
+
+    attributes = {"type", "action_id", "placeholder", "confirm", "focus_on_load"}
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, TextObject]] = None,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """InteractiveElement that is usable in input blocks
+
+        We generally recommend using the concrete subclasses for better supports of available properties.
+        """
+        if subtype:
+            self._subtype_warning()
+        super().__init__(action_id=action_id, type=type or subtype)
+
+        # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here.
+        # It's fine to pass any kwargs to the held dict here although the class does not do any validation.
+        # show_unknown_key_warning(self, others)
+
+        self.placeholder = TextObject.parse(placeholder)  # type: ignore[arg-type]
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+        self.focus_on_load = focus_on_load
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def _validate_placeholder_length(self) -> bool:
+        return (
+            self.placeholder is None
+            or self.placeholder.text is None
+            or len(self.placeholder.text) <= self.placeholder_max_length
+        )
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

InteractiveElement that is usable in input blocks

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class InteractiveElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InteractiveElement(BlockElement):
+    action_id_max_length = 255
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "action_id"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        **others: dict,
+    ):
+        """An interactive block element.
+
+        We generally recommend using the concrete subclasses for better supports of available properties.
+        """
+        if subtype:
+            self._subtype_warning()
+        super().__init__(type=type or subtype)
+
+        # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here.
+        # It's fine to pass any kwargs to the held dict here although the class does not do any validation.
+        # show_unknown_key_warning(self, others)
+
+        self.action_id = action_id
+
+    @JsonValidator(f"action_id attribute cannot exceed {action_id_max_length} characters")
+    def _validate_action_id_length(self) -> bool:
+        return self.action_id is None or len(self.action_id) <= self.action_id_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An interactive block element.

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var action_id_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "action_id"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class LinkButtonElement +(*,
text:Β strΒ |Β dictΒ |Β PlainTextObject,
url:Β str,
action_id:Β strΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class LinkButtonElement(ButtonElement):
+    def __init__(
+        self,
+        *,
+        text: Union[str, dict, PlainTextObject],
+        url: str,
+        action_id: Optional[str] = None,
+        style: Optional[str] = None,
+        **others: dict,
+    ):
+        """A simple button that simply opens a given URL. You will still receive an
+        interaction payload and will need to send an acknowledgement response.
+        This is a helper class that makes creating links simpler.
+        https://docs.slack.dev/reference/block-kit/block-elements/button-element/
+
+        Args:
+            text (required): A text object that defines the button's text.
+                Can only be of type: plain_text.
+                Maximum length for the text in this field is 75 characters.
+            url (required): A URL to load in the user's browser when the button is clicked.
+                Maximum length for this field is 3000 characters.
+                If you're using url, you'll still receive an interaction payload
+                and will need to send an acknowledgement response.
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            style: Decorates buttons with alternative visual color schemes. Use this option with restraint.
+                "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions.
+                "primary" should only be used for one button within a set.
+                "danger" gives buttons a red outline and text, and should be used when the action is destructive.
+                Use "danger" even more sparingly than "primary".
+                If you don't include this field, the default button style will be used.
+        """
+        super().__init__(
+            # NOTE: value must be always absent
+            text=text,
+            url=url,
+            action_id=action_id,
+            value=None,
+            style=style,
+        )
+        show_unknown_key_warning(self, others)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A simple button that simply opens a given URL. You will still receive an +interaction payload and will need to send an acknowledgement response. +This is a helper class that makes creating links simpler. +https://docs.slack.dev/reference/block-kit/block-elements/button-element/

+

Args

+
+
text : required
+
A text object that defines the button's text. +Can only be of type: plain_text. +Maximum length for the text in this field is 75 characters.
+
url : required
+
A URL to load in the user's browser when the button is clicked. +Maximum length for this field is 3000 characters. +If you're using url, you'll still receive an interaction payload +and will need to send an acknowledgement response.
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
style
+
Decorates buttons with alternative visual color schemes. Use this option with restraint. +"primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. +"primary" should only be used for one button within a set. +"danger" gives buttons a red outline and text, and should be used when the action is destructive. +Use "danger" even more sparingly than "primary". +If you don't include this field, the default button style will be used.
+
+

Ancestors

+ +

Inherited members

+ +
+
+class NumberInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
is_decimal_allowed:Β boolΒ |Β NoneΒ =Β False,
initial_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
min_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
max_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class NumberInputElement(InputInteractiveElement):
+    type = "number_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "is_decimal_allowed",
+                "min_value",
+                "max_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        is_decimal_allowed: Optional[bool] = False,
+        initial_value: Optional[Union[int, float, str]] = None,
+        min_value: Optional[Union[int, float, str]] = None,
+        max_value: Optional[Union[int, float, str]] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        https://docs.slack.dev/reference/block-kit/block-elements/number-input-element/
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            is_decimal_allowed (required): Decimal numbers are allowed if is_decimal_allowed= true, set the value to
+                false otherwise.
+            initial_value: The initial value in the number input when it is loaded.
+            min_value: The minimum value, cannot be greater than max_value.
+            max_value: The maximum value, cannot be less than min_value.
+            dispatch_action_config: A dispatch configuration object that determines when
+                during text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown
+                in the plain-text input. Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = str(initial_value) if initial_value is not None else None
+        self.is_decimal_allowed = is_decimal_allowed
+        self.min_value = str(min_value) if min_value is not None else None
+        self.max_value = str(max_value) if max_value is not None else None
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

https://docs.slack.dev/reference/block-kit/block-elements/number-input-element/

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
is_decimal_allowed : required
+
Decimal numbers are allowed if is_decimal_allowed= true, set the value to +false otherwise.
+
initial_value
+
The initial value in the number input when it is loaded.
+
min_value
+
The minimum value, cannot be greater than max_value.
+
max_value
+
The maximum value, cannot be less than min_value.
+
dispatch_action_config
+
A dispatch configuration object that determines when +during text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown +in the plain-text input. Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "is_decimal_allowed",
+            "min_value",
+            "max_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class OverflowMenuElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option],
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class OverflowMenuElement(InteractiveElement):
+    type = "overflow"
+    options_min_length = 1
+    options_max_length = 5
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"confirm", "options"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Sequence[Option],
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        **others: dict,
+    ):
+        """
+        This is like a cross between a button and a select menu - when a user clicks
+        on this overflow button, they will be presented with a list of options to
+        choose from. Unlike the select menu, there is no typeahead field, and the
+        button always appears with an ellipsis ("…") rather than customisable text.
+
+        As such, it is usually used if you want a more compact layout than a select
+        menu, or to supply a list of less visually important actions after a row of
+        buttons. You can also specify simple URL links as overflow menu options,
+        instead of actions.
+
+        https://docs.slack.dev/reference/block-kit/block-elements/overflow-menu-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects to display in the menu.
+                Maximum number of options is 5, minimum is 1.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after a menu item is selected.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+
+    @JsonValidator(f"options attribute must have between {options_min_length} " f"and {options_max_length} items")
+    def _validate_options_length(self) -> bool:
+        return self.options_min_length <= len(self.options) <= self.options_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is like a cross between a button and a select menu - when a user clicks +on this overflow button, they will be presented with a list of options to +choose from. Unlike the select menu, there is no typeahead field, and the +button always appears with an ellipsis ("…") rather than customisable text.

+

As such, it is usually used if you want a more compact layout than a select +menu, or to supply a list of less visually important actions after a row of +buttons. You can also specify simple URL links as overflow menu options, +instead of actions.

+

https://docs.slack.dev/reference/block-kit/block-elements/overflow-menu-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects to display in the menu. +Maximum number of options is 5, minimum is 1.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after a menu item is selected.
+
+

Ancestors

+ +

Class variables

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var options_min_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class PlainTextInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
multiline:Β boolΒ |Β NoneΒ =Β None,
min_length:Β intΒ |Β NoneΒ =Β None,
max_length:Β intΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class PlainTextInputElement(InputInteractiveElement):
+    type = "plain_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "multiline",
+                "min_length",
+                "max_length",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_value: Optional[str] = None,
+        multiline: Optional[bool] = None,
+        min_length: Optional[int] = None,
+        max_length: Optional[int] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        A plain-text input, similar to the HTML <input> tag, creates a field
+        where a user can enter freeform data. It can appear as a single-line
+        field or a larger textarea using the multiline flag. Plain-text input
+        elements can be used inside of SectionBlocks and ActionsBlocks.
+        https://docs.slack.dev/reference/block-kit/block-elements/plain-text-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown
+                in the plain-text input. Maximum length for the text in this field is 150 characters.
+            initial_value: The initial value in the plain-text input when it is loaded.
+            multiline: Indicates whether the input will be a single line (false) or a larger textarea (true).
+                Defaults to false.
+            min_length: The minimum length of input that the user must provide. If the user provides less,
+                they will receive an error. Maximum value is 3000.
+            max_length: The maximum length of input that the user can provide. If the user provides more,
+                they will receive an error.
+            dispatch_action_config: A dispatch configuration object that determines when
+                during text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.multiline = multiline
+        self.min_length = min_length
+        self.max_length = max_length
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A plain-text input, similar to the HTML tag, creates a field +where a user can enter freeform data. It can appear as a single-line +field or a larger textarea using the multiline flag. Plain-text input +elements can be used inside of SectionBlocks and ActionsBlocks. +https://docs.slack.dev/reference/block-kit/block-elements/plain-text-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown +in the plain-text input. Maximum length for the text in this field is 150 characters.
+
initial_value
+
The initial value in the plain-text input when it is loaded.
+
multiline
+
Indicates whether the input will be a single line (false) or a larger textarea (true). +Defaults to false.
+
min_length
+
The minimum length of input that the user must provide. If the user provides less, +they will receive an error. Maximum value is 3000.
+
max_length
+
The maximum length of input that the user can provide. If the user provides more, +they will receive an error.
+
dispatch_action_config
+
A dispatch configuration object that determines when +during text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "multiline",
+            "min_length",
+            "max_length",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RadioButtonsElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
initial_option:Β dictΒ |Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RadioButtonsElement(InputInteractiveElement):
+    type = "radio_buttons"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        initial_option: Optional[Union[dict, Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A radio button group that allows a user to choose one item from a list of possible options.
+        https://docs.slack.dev/reference/block-kit/block-elements/radio-button-group-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when the radio button group is changed.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects. A maximum of 10 options are allowed.
+            initial_option: An option object that exactly matches one of the options.
+                This option will be selected when the radio button group initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after clicking one of the radio buttons in this element.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.initial_option = initial_option
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A radio button group that allows a user to choose one item from a list of possible options. +https://docs.slack.dev/reference/block-kit/block-elements/radio-button-group-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when the radio button group is changed. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects. A maximum of 10 options are allowed.
+
initial_option
+
An option object that exactly matches one of the options. +This option will be selected when the radio button group initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after clicking one of the radio buttons in this element.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextElement +(*, type:Β strΒ |Β NoneΒ =Β None, subtype:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class RichTextElement(BlockElement):
+    pass
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Subclasses

+ +

Inherited members

+ +
+
+class RichTextElementParts +
+
+
+ +Expand source code + +
class RichTextElementParts:
+    class TextStyle:
+        def __init__(
+            self,
+            *,
+            bold: Optional[bool] = None,
+            italic: Optional[bool] = None,
+            strike: Optional[bool] = None,
+            code: Optional[bool] = None,
+            underline: Optional[bool] = None,
+        ):
+            self.bold = bold
+            self.italic = italic
+            self.strike = strike
+            self.code = code
+            self.underline = underline
+
+        def to_dict(self, *args) -> dict:
+            result = {
+                "bold": self.bold,
+                "italic": self.italic,
+                "strike": self.strike,
+                "code": self.code,
+                "underline": self.underline,
+            }
+            return {k: v for k, v in result.items() if v is not None}
+
+    class Text(RichTextElement):
+        type = "text"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"text", "style"})
+
+        def __init__(
+            self,
+            *,
+            text: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.text = text
+            self.style = style
+
+    class Channel(RichTextElement):
+        type = "channel"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"channel_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            channel_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.channel_id = channel_id
+            self.style = style
+
+    class User(RichTextElement):
+        type = "user"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"user_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            user_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.user_id = user_id
+            self.style = style
+
+    class Emoji(RichTextElement):
+        type = "emoji"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"name", "skin_tone", "unicode", "style"})
+
+        def __init__(
+            self,
+            *,
+            name: str,
+            skin_tone: Optional[int] = None,
+            unicode: Optional[str] = None,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.name = name
+            self.skin_tone = skin_tone
+            self.unicode = unicode
+            self.style = style
+
+    class Link(RichTextElement):
+        type = "link"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"url", "text", "style"})
+
+        def __init__(
+            self,
+            *,
+            url: str,
+            text: Optional[str] = None,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.url = url
+            self.text = text
+            self.style = style
+
+    class Team(RichTextElement):
+        type = "team"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"team_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            team_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.team_id = team_id
+            self.style = style
+
+    class UserGroup(RichTextElement):
+        type = "usergroup"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"usergroup_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            usergroup_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.usergroup_id = usergroup_id
+            self.style = style
+
+    class Date(RichTextElement):
+        type = "date"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"timestamp", "format", "url", "fallback"})
+
+        def __init__(
+            self,
+            *,
+            timestamp: int,
+            format: str,
+            url: Optional[str] = None,
+            fallback: Optional[str] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.timestamp = timestamp
+            self.format = format
+            self.url = url
+            self.fallback = fallback
+
+    class Broadcast(RichTextElement):
+        type = "broadcast"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"range"})
+
+        def __init__(
+            self,
+            *,
+            range: str,  # channel, here, ..
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.range = range
+
+    class Color(RichTextElement):
+        type = "color"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"value"})
+
+        def __init__(
+            self,
+            *,
+            value: str,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.value = value
+
+
+

Class variables

+
+
var Broadcast
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Channel
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Color
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Date
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Emoji
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+ +
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Team
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Text
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var TextStyle
+
+

The type of the None singleton.

+
+
var User
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var UserGroup
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
+
+
+class RichTextInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_value:Β Dict[str,Β Any]Β |Β ForwardRef('RichTextBlock')Β |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextInputElement(InputInteractiveElement):
+    type = "rich_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        # To avoid circular imports, the RichTextBlock type here is intentionally a string
+        initial_value: Optional[Union[Dict[str, Any], "RichTextBlock"]] = None,  # type: ignore[name-defined] # noqa: F821
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

InteractiveElement that is usable in input blocks

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextListElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
style:Β strΒ |Β NoneΒ =Β None,
indent:Β intΒ |Β NoneΒ =Β None,
offset:Β intΒ |Β NoneΒ =Β None,
border:Β intΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextListElement(RichTextElement):
+    type = "rich_text_list"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements", "style", "indent", "offset", "border"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        style: Optional[str] = None,  # bullet, ordered
+        indent: Optional[int] = None,
+        offset: Optional[int] = None,
+        border: Optional[int] = None,
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+        self.style = style
+        self.indent = indent
+        self.offset = offset
+        self.border = border
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements", "style", "indent", "offset", "border"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextPreformattedElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
border:Β intΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextPreformattedElement(RichTextElement):
+    type = "rich_text_preformatted"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements", "border"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        border: Optional[int] = None,
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+        self.border = border
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements", "border"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextQuoteElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextQuoteElement(RichTextElement):
+    type = "rich_text_quote"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextSectionElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextSectionElement(RichTextElement):
+    type = "rich_text_section"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class SelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[OptionGroup]Β |Β NoneΒ =Β None,
initial_option:Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class SelectElement(InputInteractiveElement):
+    type = "static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[str] = None,
+        options: Optional[Sequence[Option]] = None,
+        option_groups: Optional[Sequence[OptionGroup]] = None,
+        initial_option: Optional[Option] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_option: A single option that exactly matches one of the options or option_groups.
+                This option will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.option_groups = option_groups
+        self.initial_option = initial_option
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return not (self.options is not None and self.option_groups is not None)
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_option
+
A single option that exactly matches one of the options or option_groups. +This option will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class StaticMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[OptionGroup]Β |Β NoneΒ =Β None,
initial_options:Β Sequence[Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class StaticMultiSelectElement(InputInteractiveElement):
+    type = "multi_static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Option]] = None,
+        option_groups: Optional[Sequence[OptionGroup]] = None,
+        initial_options: Optional[Sequence[Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#static_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_options: An array of option objects that exactly match one or more of the options
+                within options or option_groups. These options will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = Option.parse_all(options)
+        self.option_groups = OptionGroup.parse_all(option_groups)
+        self.initial_options = Option.parse_all(initial_options)
+        self.max_selected_items = max_selected_items
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return self.options is None or self.option_groups is None
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#static_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_options
+
An array of option objects that exactly match one or more of the options +within options or option_groups. These options will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class StaticSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[dictΒ |Β OptionGroup]Β |Β NoneΒ =Β None,
initial_option:Β dictΒ |Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class StaticSelectElement(InputInteractiveElement):
+    type = "static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        option_groups: Optional[Sequence[Union[dict, OptionGroup]]] = None,
+        initial_option: Optional[Union[dict, Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_option: A single option that exactly matches one of the options or option_groups.
+                This option will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.option_groups = option_groups
+        self.initial_option = initial_option
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return not (self.options is not None and self.option_groups is not None)
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_option
+
A single option that exactly matches one of the options or option_groups. +This option will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class TimePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_time:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
timezone:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class TimePickerElement(InputInteractiveElement):
+    type = "timepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_time", "timezone"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_time: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        timezone: Optional[str] = None,
+        **others: dict,
+    ):
+        """
+        An element which allows selection of a time of day.
+        On desktop clients, this time picker will take the form of a dropdown list
+        with free-text entry for precise choices.
+        On mobile clients, the time picker will use native time picker UIs.
+        https://docs.slack.dev/reference/block-kit/block-elements/time-picker-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a time is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown on the timepicker.
+                Maximum length for the text in this field is 150 characters.
+            initial_time: The initial time that is selected when the element is loaded.
+                This should be in the format HH:mm, where HH is the 24-hour format of an hour (00 to 23)
+                and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a time is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            timezone: The timezone to consider for this input value.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_time = initial_time
+        self.timezone = timezone
+
+    @JsonValidator("initial_time attribute must be in format 'HH:mm'")
+    def _validate_initial_time_valid(self) -> bool:
+        return self.initial_time is None or re.match(r"([0-1][0-9]|2[0-3]):([0-5][0-9])", self.initial_time) is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element which allows selection of a time of day. +On desktop clients, this time picker will take the form of a dropdown list +with free-text entry for precise choices. +On mobile clients, the time picker will use native time picker UIs. +https://docs.slack.dev/reference/block-kit/block-elements/time-picker-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a time is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown on the timepicker. +Maximum length for the text in this field is 150 characters.
+
initial_time
+
The initial time that is selected when the element is loaded. +This should be in the format HH:mm, where HH is the 24-hour format of an hour (00 to 23) +and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a time is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
timezone
+
The timezone to consider for this input value.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_time", "timezone"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UrlInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UrlInputElement(InputInteractiveElement):
+    type = "url_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_value: Optional[str] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        A URL input element, similar to the Plain-text input element,
+        creates a single line field where a user can enter URL-encoded data.
+        https://docs.slack.dev/reference/block-kit/block-elements/url-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_value: The initial value in the URL input when it is loaded.
+            dispatch_action_config: A dispatch configuration object that determines when during text input
+                the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown in the URL input.
+                Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A URL input element, similar to the Plain-text input element, +creates a single line field where a user can enter URL-encoded data. +https://docs.slack.dev/reference/block-kit/block-elements/url-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_value
+
The initial value in the URL input when it is loaded.
+
dispatch_action_config
+
A dispatch configuration object that determines when during text input +the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown in the URL input. +Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UserMultiSelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_users:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UserMultiSelectElement(InputInteractiveElement):
+    type = "multi_users_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_users", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_users: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of Slack users visible to
+        the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#users_multi_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            initial_users: An array of user IDs of any valid users to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_users = initial_users
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of Slack users visible to +the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#users_multi_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
initial_users
+
An array of user IDs of any valid users to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_users", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UserSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_user:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UserSelectElement(InputInteractiveElement):
+    type = "users_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_user"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_user: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of Slack users visible to
+        the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#users_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_user: The user ID of any valid user to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_user = initial_user
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of Slack users visible to +the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#users_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_user
+
The user ID of any valid user to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_user"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class WorkflowButtonElement +(*,
text:Β strΒ |Β dictΒ |Β TextObject,
action_id:Β strΒ |Β NoneΒ =Β None,
workflow:Β dictΒ |Β WorkflowΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class WorkflowButtonElement(InteractiveElement):
+    type = "workflow_button"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text", "workflow", "style", "accessibility_label"})
+
+    def __init__(
+        self,
+        *,
+        text: Union[str, dict, TextObject],
+        action_id: Optional[str] = None,
+        workflow: Optional[Union[dict, Workflow]] = None,
+        style: Optional[str] = None,  # primary, danger
+        accessibility_label: Optional[str] = None,
+        **others: dict,
+    ):
+        """Allows users to run a link trigger with customizable inputs
+        Interactive component - but interactions with workflow button elements will not send block_actions events,
+        since these are used to start new workflow runs.
+        https://docs.slack.dev/reference/block-kit/block-elements/workflow-button-element
+
+        Args:
+            text (required): A text object that defines the button's text.
+                Can only be of type: plain_text. text may truncate with ~30 characters.
+                Maximum length for the text in this field is 75 characters.
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            workflow: A workflow object that contains details about the workflow
+                that will run when the button is clicked.
+            style: Decorates buttons with alternative visual color schemes. Use this option with restraint.
+                "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions.
+                "primary" should only be used for one button within a set.
+                "danger" gives buttons a red outline and text, and should be used when the action is destructive.
+                Use "danger" even more sparingly than "primary".
+                If you don't include this field, the default button style will be used.
+            accessibility_label: A label for longer descriptive text about a button element.
+                This label will be read out by screen readers instead of the button text object.
+                Maximum length for this field is 75 characters.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        # NOTE: default_type=PlainTextObject.type here is only for backward-compatibility with version 2.5.0
+        self.text = TextObject.parse(text, default_type=PlainTextObject.type)
+        self.workflow = workflow
+        self.style = style
+        self.accessibility_label = accessibility_label
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Allows users to run a link trigger with customizable inputs +Interactive component - but interactions with workflow button elements will not send block_actions events, +since these are used to start new workflow runs. +https://docs.slack.dev/reference/block-kit/block-elements/workflow-button-element

+

Args

+
+
text : required
+
A text object that defines the button's text. +Can only be of type: plain_text. text may truncate with ~30 characters. +Maximum length for the text in this field is 75 characters.
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
workflow
+
A workflow object that contains details about the workflow +that will run when the button is clicked.
+
style
+
Decorates buttons with alternative visual color schemes. Use this option with restraint. +"primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. +"primary" should only be used for one button within a set. +"danger" gives buttons a red outline and text, and should be used when the action is destructive. +Use "danger" even more sparingly than "primary". +If you don't include this field, the default button style will be used.
+
accessibility_label
+
A label for longer descriptive text about a button element. +This label will be read out by screen readers instead of the button text object. +Maximum length for this field is 75 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/blocks/blocks.html b/docs/reference/models/blocks/blocks.html new file mode 100644 index 000000000..722d12164 --- /dev/null +++ b/docs/reference/models/blocks/blocks.html @@ -0,0 +1,2051 @@ + + + + + + +slack_sdk.models.blocks.blocks API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.blocks.blocks

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class ActionsBlock +(*,
elements:Β Sequence[dictΒ |Β InteractiveElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ActionsBlock(Block):
+    type = "actions"
+    elements_max_length = 25
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, InteractiveElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A block that is used to hold interactive elements.
+        https://docs.slack.dev/reference/block-kit/blocks/actions-block
+
+        Args:
+            elements (required): An array of interactive element objects - buttons, select menus, overflow menus,
+                or date pickers. There is a maximum of 25 elements in each action block.
+            block_id: A string acting as a unique identifier for a block.
+                If not specified, a block_id will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that is used to hold interactive elements. +https://docs.slack.dev/reference/block-kit/blocks/actions-block

+

Args

+
+
elements : required
+
An array of interactive element objects - buttons, select menus, overflow menus, +or date pickers. There is a maximum of 25 elements in each action block.
+
block_id
+
A string acting as a unique identifier for a block. +If not specified, a block_id will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class Block +(*,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Block(JsonObject):
+    """Blocks are a series of components that can be combined
+    to create visually rich and compellingly interactive messages.
+    https://docs.slack.dev/reference/block-kit/blocks
+    """
+
+    attributes = {"block_id", "type"}
+    block_id_max_length = 255
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,  # deprecated
+        block_id: Optional[str] = None,
+    ):
+        if subtype:
+            self._subtype_warning()
+        self.type = type if type else subtype
+        self.block_id = block_id
+        self.color = None
+
+    @JsonValidator(f"block_id cannot exceed {block_id_max_length} characters")
+    def _validate_block_id_length(self):
+        return self.block_id is None or len(self.block_id) <= self.block_id_max_length
+
+    @classmethod
+    def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]:
+        if block is None:
+            return None
+        elif isinstance(block, Block):
+            return block
+        else:
+            if "type" in block:
+                type = block["type"]
+                if type == SectionBlock.type:
+                    return SectionBlock(**block)
+                elif type == DividerBlock.type:
+                    return DividerBlock(**block)
+                elif type == ImageBlock.type:
+                    return ImageBlock(**block)
+                elif type == ActionsBlock.type:
+                    return ActionsBlock(**block)
+                elif type == ContextBlock.type:
+                    return ContextBlock(**block)
+                elif type == ContextActionsBlock.type:
+                    return ContextActionsBlock(**block)
+                elif type == InputBlock.type:
+                    return InputBlock(**block)
+                elif type == FileBlock.type:
+                    return FileBlock(**block)
+                elif type == CallBlock.type:
+                    return CallBlock(**block)
+                elif type == HeaderBlock.type:
+                    return HeaderBlock(**block)
+                elif type == MarkdownBlock.type:
+                    return MarkdownBlock(**block)
+                elif type == VideoBlock.type:
+                    return VideoBlock(**block)
+                elif type == RichTextBlock.type:
+                    return RichTextBlock(**block)
+                elif type == TableBlock.type:
+                    return TableBlock(**block)
+                else:
+                    cls.logger.warning(f"Unknown block detected and skipped ({block})")
+                    return None
+            else:
+                cls.logger.warning(f"Unknown block detected and skipped ({block})")
+                return None
+
+    @classmethod
+    def parse_all(cls, blocks: Optional[Sequence[Union[dict, "Block"]]]) -> List["Block"]:
+        return [cls.parse(b) for b in blocks or []]  # type: ignore[misc]
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var block_id_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(block:Β dictΒ |Β ForwardRef('Block')) ‑>Β BlockΒ |Β None +
+
+
+
+
+def parse_all(blocks:Β Sequence[dictΒ |Β ForwardRef('Block')]Β |Β None) ‑>Β List[Block] +
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class CallBlock +(*,
call_id:Β str,
api_decoration_available:Β boolΒ |Β NoneΒ =Β None,
call:Β Dict[str,Β Dict[str,Β Any]]Β |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class CallBlock(Block):
+    type = "call"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"call_id", "api_decoration_available", "call"})
+
+    def __init__(
+        self,
+        *,
+        call_id: str,
+        api_decoration_available: Optional[bool] = None,
+        call: Optional[Dict[str, Dict[str, Any]]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays a call information
+        https://docs.slack.dev/reference/block-kit/blocks#call
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.call_id = call_id
+        self.api_decoration_available = api_decoration_available
+        self.call = call
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays a call information +https://docs.slack.dev/reference/block-kit/blocks#call

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"call_id", "api_decoration_available", "call"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ContextActionsBlock +(*,
elements:Β Sequence[dictΒ |Β FeedbackButtonsElementΒ |Β IconButtonElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ContextActionsBlock(Block):
+    type = "context_actions"
+    elements_max_length = 5
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, FeedbackButtonsElement, IconButtonElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays actions as contextual info, which can include both feedback buttons and icon buttons.
+        https://docs.slack.dev/reference/block-kit/blocks/context-actions-block
+
+        Args:
+            elements (required): An array of feedback_buttons or icon_button block elements. Maximum number of items is 5.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator("elements attribute must be specified")
+    def _validate_elements(self):
+        return self.elements is None or len(self.elements) > 0
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays actions as contextual info, which can include both feedback buttons and icon buttons. +https://docs.slack.dev/reference/block-kit/blocks/context-actions-block

+

Args

+
+
elements : required
+
An array of feedback_buttons or icon_button block elements. Maximum number of items is 5.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ContextBlock +(*,
elements:Β Sequence[dictΒ |Β ImageElementΒ |Β TextObject],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ContextBlock(Block):
+    type = "context"
+    elements_max_length = 10
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, ImageElement, TextObject]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays message context, which can include both images and text.
+        https://docs.slack.dev/reference/block-kit/blocks/context-block
+
+        Args:
+            elements (required): An array of image elements and text objects. Maximum number of items is 10.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays message context, which can include both images and text. +https://docs.slack.dev/reference/block-kit/blocks/context-block

+

Args

+
+
elements : required
+
An array of image elements and text objects. Maximum number of items is 10.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DividerBlock +(*, block_id:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class DividerBlock(Block):
+    type = "divider"
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A content divider, like an <hr>, to split up different blocks inside of a message.
+        https://docs.slack.dev/reference/block-kit/blocks/divider-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A content divider, like an


, to split up different blocks inside of a message. +https://docs.slack.dev/reference/block-kit/blocks/divider-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FileBlock +(*,
external_id:Β str,
source:Β strΒ =Β 'remote',
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class FileBlock(Block):
+    type = "file"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"external_id", "source"})
+
+    def __init__(
+        self,
+        *,
+        external_id: str,
+        source: str = "remote",
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays a remote file.
+        https://docs.slack.dev/reference/block-kit/blocks/file-block
+
+        Args:
+            external_id (required): The external unique ID for this file.
+            source (required): At the moment, source will always be remote for a remote file.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.external_id = external_id
+        self.source = source
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays a remote file. +https://docs.slack.dev/reference/block-kit/blocks/file-block

+

Args

+
+
external_id : required
+
The external unique ID for this file.
+
source : required
+
At the moment, source will always be remote for a remote file.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"external_id", "source"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class HeaderBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class HeaderBlock(Block):
+    type = "header"
+    text_max_length = 150
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text"})
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        text: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """A header is a plain-text block that displays in a larger, bold font.
+        https://docs.slack.dev/reference/block-kit/blocks/header-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (required): The text for the block, in the form of a plain_text text object.
+                Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = TextObject.parse(text, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+
+    @JsonValidator("text attribute must be specified")
+    def _validate_text(self):
+        return self.text is not None
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return self.text is None or len(self.text.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A header is a plain-text block that displays in a larger, bold font. +https://docs.slack.dev/reference/block-kit/blocks/header-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : required
+
The text for the block, in the form of a plain_text text object. +Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ImageBlock +(*,
alt_text:Β str,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β SlackFileΒ |Β NoneΒ =Β None,
title:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ImageBlock(Block):
+    type = "image"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "image_url", "title", "slack_file"})
+
+    image_url_max_length = 3000
+    alt_text_max_length = 2000
+    title_max_length = 2000
+
+    def __init__(
+        self,
+        *,
+        alt_text: str,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None,
+        title: Optional[Union[str, dict, PlainTextObject]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A simple image block, designed to make those cat photos really pop.
+        https://docs.slack.dev/reference/block-kit/blocks/image-block
+
+        Args:
+            alt_text (required): A plain-text summary of the image. This should not contain any markup.
+                Maximum length for this field is 2000 characters.
+            image_url: The URL of the image to be displayed.
+                Maximum length for this field is 3000 characters.
+            slack_file: A Slack image file object that defines the source of the image.
+            title: An optional title for the image in the form of a text object that can only be of type: plain_text.
+                Maximum length for the text in this field is 2000 characters.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.image_url = image_url
+        self.alt_text = alt_text
+        parsed_title = None
+        if title is not None:
+            if isinstance(title, str):
+                parsed_title = PlainTextObject(text=title)
+            elif isinstance(title, dict):
+                if title.get("type") != PlainTextObject.type:
+                    raise SlackObjectFormationError(f"Unsupported type for title in an image block: {title.get('type')}")
+                parsed_title = PlainTextObject(text=title.get("text"), emoji=title.get("emoji"))  # type: ignore[arg-type]
+            elif isinstance(title, PlainTextObject):
+                parsed_title = title
+            else:
+                raise SlackObjectFormationError(f"Unsupported type for title in an image block: {type(title)}")
+        if slack_file is not None:
+            self.slack_file = (
+                slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file)
+            )
+        self.title = parsed_title
+
+    @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters")
+    def _validate_image_url_length(self):
+        return self.image_url is None or len(self.image_url) <= self.image_url_max_length
+
+    @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return len(self.alt_text) <= self.alt_text_max_length
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def _validate_title_length(self):
+        return self.title is None or self.title.text is None or len(self.title.text) <= self.title_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A simple image block, designed to make those cat photos really pop. +https://docs.slack.dev/reference/block-kit/blocks/image-block

+

Args

+
+
alt_text : required
+
A plain-text summary of the image. This should not contain any markup. +Maximum length for this field is 2000 characters.
+
image_url
+
The URL of the image to be displayed. +Maximum length for this field is 3000 characters.
+
slack_file
+
A Slack image file object that defines the source of the image.
+
title
+
An optional title for the image in the form of a text object that can only be of type: plain_text. +Maximum length for the text in this field is 2000 characters.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var alt_text_max_length
+
+

The type of the None singleton.

+
+
var image_url_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "image_url", "title", "slack_file"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class InputBlock +(*,
label:Β strΒ |Β dictΒ |Β PlainTextObject,
element:Β strΒ |Β dictΒ |Β InputInteractiveElement,
block_id:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
dispatch_action:Β boolΒ |Β NoneΒ =Β None,
optional:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InputBlock(Block):
+    type = "input"
+    label_max_length = 2000
+    hint_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"})
+
+    def __init__(
+        self,
+        *,
+        label: Union[str, dict, PlainTextObject],
+        element: Union[str, dict, InputInteractiveElement],
+        block_id: Optional[str] = None,
+        hint: Optional[Union[str, dict, PlainTextObject]] = None,
+        dispatch_action: Optional[bool] = None,
+        optional: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A block that collects information from users - it can hold a plain-text input element,
+        a select menu element, a multi-select menu element, or a datepicker.
+        https://docs.slack.dev/reference/block-kit/blocks/input-block
+
+        Args:
+            label (required): A label that appears above an input element in the form of a text object
+                that must have type of plain_text. Maximum length for the text in this field is 2000 characters.
+            element (required): An plain-text input element, a checkbox element, a radio button element,
+                a select menu element, a multi-select menu element, or a datepicker.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message or view and each iteration of a message or view.
+                If a message or view is updated, use a new block_id.
+            hint: An optional hint that appears below an input element in a lighter grey.
+                It must be a text object with a type of plain_text.
+                Maximum length for the text in this field is 2000 characters.
+            dispatch_action: A boolean that indicates whether or not the use of elements in this block
+                should dispatch a block_actions payload. Defaults to false.
+            optional: A boolean that indicates whether the input element may be empty when a user submits the modal.
+                Defaults to false.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.label = TextObject.parse(label, default_type=PlainTextObject.type)
+        self.element = BlockElement.parse(element)  # type: ignore[arg-type]
+        self.hint = TextObject.parse(hint, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.dispatch_action = dispatch_action
+        self.optional = optional
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self):
+        return self.label is None or self.label.text is None or len(self.label.text) <= self.label_max_length
+
+    @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+    def _validate_hint_length(self):
+        return self.hint is None or self.hint.text is None or len(self.hint.text) <= self.label_max_length
+
+    @JsonValidator(
+        (
+            "element attribute must be a string, select element, multi-select element, "
+            "or a datepicker. (Sub-classes of InputInteractiveElement)"
+        )
+    )
+    def _validate_element_type(self):
+        return self.element is None or isinstance(self.element, (str, InputInteractiveElement))
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that collects information from users - it can hold a plain-text input element, +a select menu element, a multi-select menu element, or a datepicker. +https://docs.slack.dev/reference/block-kit/blocks/input-block

+

Args

+
+
label : required
+
A label that appears above an input element in the form of a text object +that must have type of plain_text. Maximum length for the text in this field is 2000 characters.
+
element : required
+
An plain-text input element, a checkbox element, a radio button element, +a select menu element, a multi-select menu element, or a datepicker.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message or view and each iteration of a message or view. +If a message or view is updated, use a new block_id.
+
hint
+
An optional hint that appears below an input element in a lighter grey. +It must be a text object with a type of plain_text. +Maximum length for the text in this field is 2000 characters.
+
dispatch_action
+
A boolean that indicates whether or not the use of elements in this block +should dispatch a block_actions payload. Defaults to false.
+
optional
+
A boolean that indicates whether the input element may be empty when a user submits the modal. +Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var hint_max_length
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class MarkdownBlock +(*, text:Β str, block_id:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class MarkdownBlock(Block):
+    type = "markdown"
+    text_max_length = 12000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text"})
+
+    def __init__(
+        self,
+        *,
+        text: str,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays formatted markdown.
+        https://docs.slack.dev/reference/block-kit/blocks/markdown-block/
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (required): The standard markdown-formatted text. Limit 12,000 characters max.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = text
+
+    @JsonValidator("text attribute must be specified")
+    def _validate_text(self):
+        return self.text != ""
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return len(self.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays formatted markdown. +https://docs.slack.dev/reference/block-kit/blocks/markdown-block/

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : required
+
The standard markdown-formatted text. Limit 12,000 characters max.
+
+

Ancestors

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextBlock +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextBlock(Block):
+    type = "rich_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A block that is used to hold interactive elements.
+        https://docs.slack.dev/reference/block-kit/blocks/rich-text-block
+
+        Args:
+            elements (required): An array of rich text objects -
+                rich_text_section, rich_text_list, rich_text_quote, rich_text_preformatted
+            block_id: A unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message or view and each iteration of a message or view.
+                If a message or view is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that is used to hold interactive elements. +https://docs.slack.dev/reference/block-kit/blocks/rich-text-block

+

Args

+
+
elements : required
+
An array of rich text objects - +rich_text_section, rich_text_list, rich_text_quote, rich_text_preformatted
+
block_id
+
A unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message or view and each iteration of a message or view. +If a message or view is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class SectionBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
fields:Β Sequence[strΒ |Β dictΒ |Β TextObject]Β |Β NoneΒ =Β None,
accessory:Β dictΒ |Β BlockElementΒ |Β NoneΒ =Β None,
expand:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class SectionBlock(Block):
+    type = "section"
+    fields_max_length = 10
+    text_max_length = 3000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text", "fields", "accessory", "expand"})
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        text: Optional[Union[str, dict, TextObject]] = None,
+        fields: Optional[Sequence[Union[str, dict, TextObject]]] = None,
+        accessory: Optional[Union[dict, BlockElement]] = None,
+        expand: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A section is one of the most flexible blocks available.
+        https://docs.slack.dev/reference/block-kit/blocks/section-block
+
+        Args:
+            block_id (required): A string acting as a unique identifier for a block.
+                If not specified, one will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (preferred): The text for the block, in the form of a text object.
+                Maximum length for the text in this field is 3000 characters.
+                This field is not required if a valid array of fields objects is provided instead.
+            fields (required if no text is provided): Required if no text is provided.
+                An array of text objects. Any text objects included with fields will be rendered
+                in a compact format that allows for 2 columns of side-by-side text.
+                Maximum number of items is 10. Maximum length for the text in each item is 2000 characters.
+            accessory: One of the available element objects.
+            expand: Whether or not this section block's text should always expand when rendered.
+                If false or not provided, it may be rendered with a 'see more' option to expand and show the full text.
+                For AI Assistant apps, this allows the app to post long messages without users needing
+                to click 'see more' to expand the message.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = TextObject.parse(text)  # type: ignore[arg-type]
+        field_objects = []
+        for f in fields or []:
+            if isinstance(f, str):
+                field_objects.append(MarkdownTextObject.from_str(f))
+            elif isinstance(f, TextObject):
+                field_objects.append(f)  # type: ignore[arg-type]
+            elif isinstance(f, dict) and "type" in f:
+                d = copy.copy(f)
+                t = d.pop("type")
+                if t == MarkdownTextObject.type:
+                    field_objects.append(MarkdownTextObject(**d))
+                else:
+                    field_objects.append(PlainTextObject(**d))  # type: ignore[arg-type]
+            else:
+                self.logger.warning(f"Unsupported filed detected and skipped {f}")
+        self.fields = field_objects
+        self.accessory = BlockElement.parse(accessory)  # type: ignore[arg-type]
+        self.expand = expand
+
+    @JsonValidator("text or fields attribute must be specified")
+    def _validate_text_or_fields_populated(self):
+        return self.text is not None or self.fields
+
+    @JsonValidator(f"fields attribute cannot exceed {fields_max_length} items")
+    def _validate_fields_length(self):
+        return self.fields is None or len(self.fields) <= self.fields_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return self.text is None or len(self.text.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A section is one of the most flexible blocks available. +https://docs.slack.dev/reference/block-kit/blocks/section-block

+

Args

+
+
block_id : required
+
A string acting as a unique identifier for a block. +If not specified, one will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : preferred
+
The text for the block, in the form of a text object. +Maximum length for the text in this field is 3000 characters. +This field is not required if a valid array of fields objects is provided instead.
+
fields : required if no text is provided
+
Required if no text is provided. +An array of text objects. Any text objects included with fields will be rendered +in a compact format that allows for 2 columns of side-by-side text. +Maximum number of items is 10. Maximum length for the text in each item is 2000 characters.
+
accessory
+
One of the available element objects.
+
expand
+
Whether or not this section block's text should always expand when rendered. +If false or not provided, it may be rendered with a 'see more' option to expand and show the full text. +For AI Assistant apps, this allows the app to post long messages without users needing +to click 'see more' to expand the message.
+
+

Ancestors

+ +

Class variables

+
+
var fields_max_length
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text", "fields", "accessory", "expand"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class TableBlock +(*,
rows:Β Sequence[Sequence[Dict[str,Β Any]]],
column_settings:Β Sequence[Dict[str,Β Any]Β |Β None]Β |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class TableBlock(Block):
+    type = "table"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"rows", "column_settings"})
+
+    def __init__(
+        self,
+        *,
+        rows: Sequence[Sequence[Dict[str, Any]]],
+        column_settings: Optional[Sequence[Optional[Dict[str, Any]]]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays structured information in a table.
+        https://docs.slack.dev/reference/block-kit/blocks/table-block
+
+        Args:
+            rows (required): An array consisting of table rows. Maximum 100 rows.
+                Each row object is an array with a max of 20 table cells.
+                Table cells can have a type of raw_text or rich_text.
+            column_settings: An array describing column behavior. If there are fewer items in the column_settings array
+                than there are columns in the table, then the items in the the column_settings array will describe
+                the same number of columns in the table as there are in the array itself.
+                Any additional columns will have the default behavior. Maximum 20 items.
+                See below for column settings schema.
+            block_id: A unique identifier for a block. If not specified, a block_id will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.rows = rows
+        self.column_settings = column_settings
+
+    @JsonValidator("rows attribute must be specified")
+    def _validate_rows(self):
+        return self.rows is not None and len(self.rows) > 0
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays structured information in a table. +https://docs.slack.dev/reference/block-kit/blocks/table-block

+

Args

+
+
rows : required
+
An array consisting of table rows. Maximum 100 rows. +Each row object is an array with a max of 20 table cells. +Table cells can have a type of raw_text or rich_text.
+
column_settings
+
An array describing column behavior. If there are fewer items in the column_settings array +than there are columns in the table, then the items in the the column_settings array will describe +the same number of columns in the table as there are in the array itself. +Any additional columns will have the default behavior. Maximum 20 items. +See below for column settings schema.
+
block_id
+
A unique identifier for a block. If not specified, a block_id will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"rows", "column_settings"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class VideoBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
alt_text:Β strΒ |Β NoneΒ =Β None,
video_url:Β strΒ |Β NoneΒ =Β None,
thumbnail_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
title_url:Β strΒ |Β NoneΒ =Β None,
description:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
provider_icon_url:Β strΒ |Β NoneΒ =Β None,
provider_name:Β strΒ |Β NoneΒ =Β None,
author_name:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class VideoBlock(Block):
+    type = "video"
+    title_max_length = 200
+    author_name_max_length = 50
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "alt_text",
+                "video_url",
+                "thumbnail_url",
+                "title",
+                "title_url",
+                "description",
+                "provider_icon_url",
+                "provider_name",
+                "author_name",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        alt_text: Optional[str] = None,
+        video_url: Optional[str] = None,
+        thumbnail_url: Optional[str] = None,
+        title: Optional[Union[str, dict, PlainTextObject]] = None,
+        title_url: Optional[str] = None,
+        description: Optional[Union[str, dict, PlainTextObject]] = None,
+        provider_icon_url: Optional[str] = None,
+        provider_name: Optional[str] = None,
+        author_name: Optional[str] = None,
+        **others: dict,
+    ):
+        """A video block is designed to embed videos in all app surfaces
+        (e.g. link unfurls, messages, modals, App Home) β€”
+        anywhere you can put blocks! To use the video block within your app,
+        you must have the links.embed:write scope.
+        https://docs.slack.dev/reference/block-kit/blocks/video-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            alt_text (required): A tooltip for the video. Required for accessibility
+            video_url (required): The URL to be embedded. Must match any existing unfurl domains within the app
+                and point to a HTTPS URL.
+            thumbnail_url (required): The thumbnail image URL
+            title (required): Video title in plain text format. Must be less than 200 characters.
+            title_url: Hyperlink for the title text. Must correspond to the non-embeddable URL for the video.
+                Must go to an HTTPS URL.
+            description: Description for video in plain text format.
+            provider_icon_url: Icon for the video provider - ex. Youtube icon
+            provider_name: The originating application or domain of the video ex. Youtube
+            author_name: Author name to be displayed. Must be less than 50 characters.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.alt_text = alt_text
+        self.video_url = video_url
+        self.thumbnail_url = thumbnail_url
+        self.title = TextObject.parse(title, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.title_url = title_url
+        self.description = TextObject.parse(description, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.provider_icon_url = provider_icon_url
+        self.provider_name = provider_name
+        self.author_name = author_name
+
+    @JsonValidator("alt_text attribute must be specified")
+    def _validate_alt_text(self):
+        return self.alt_text is not None
+
+    @JsonValidator("video_url attribute must be specified")
+    def _validate_video_url(self):
+        return self.video_url is not None
+
+    @JsonValidator("thumbnail_url attribute must be specified")
+    def _validate_thumbnail_url(self):
+        return self.thumbnail_url is not None
+
+    @JsonValidator("title attribute must be specified")
+    def _validate_title(self):
+        return self.title is not None
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def _validate_title_length(self):
+        return self.title is None or len(self.title.text) < self.title_max_length
+
+    @JsonValidator(f"author_name attribute cannot exceed {author_name_max_length} characters")
+    def _validate_author_name_length(self):
+        return self.author_name is None or len(self.author_name) < self.author_name_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A video block is designed to embed videos in all app surfaces +(e.g. link unfurls, messages, modals, App Home) β€” +anywhere you can put blocks! To use the video block within your app, +you must have the links.embed:write scope. +https://docs.slack.dev/reference/block-kit/blocks/video-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
alt_text : required
+
A tooltip for the video. Required for accessibility
+
video_url : required
+
The URL to be embedded. Must match any existing unfurl domains within the app +and point to a HTTPS URL.
+
thumbnail_url : required
+
The thumbnail image URL
+
title : required
+
Video title in plain text format. Must be less than 200 characters.
+
title_url
+
Hyperlink for the title text. Must correspond to the non-embeddable URL for the video. +Must go to an HTTPS URL.
+
description
+
Description for video in plain text format.
+
provider_icon_url
+
Icon for the video provider - ex. Youtube icon
+
provider_name
+
The originating application or domain of the video ex. Youtube
+
author_name
+
Author name to be displayed. Must be less than 50 characters.
+
+

Ancestors

+ +

Class variables

+
+
var author_name_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "alt_text",
+            "video_url",
+            "thumbnail_url",
+            "title",
+            "title_url",
+            "description",
+            "provider_icon_url",
+            "provider_name",
+            "author_name",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/blocks/index.html b/docs/reference/models/blocks/index.html new file mode 100644 index 000000000..0d2047c12 --- /dev/null +++ b/docs/reference/models/blocks/index.html @@ -0,0 +1,8566 @@ + + + + + + +slack_sdk.models.blocks API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.blocks

+
+
+

Block Kit data model objects

+

To learn more about Block Kit, please check the following resources and tools:

+ +
+
+

Sub-modules

+
+
slack_sdk.models.blocks.basic_components
+
+
+
+
slack_sdk.models.blocks.block_elements
+
+
+
+
slack_sdk.models.blocks.blocks
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class ActionsBlock +(*,
elements:Β Sequence[dictΒ |Β InteractiveElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ActionsBlock(Block):
+    type = "actions"
+    elements_max_length = 25
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, InteractiveElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A block that is used to hold interactive elements.
+        https://docs.slack.dev/reference/block-kit/blocks/actions-block
+
+        Args:
+            elements (required): An array of interactive element objects - buttons, select menus, overflow menus,
+                or date pickers. There is a maximum of 25 elements in each action block.
+            block_id: A string acting as a unique identifier for a block.
+                If not specified, a block_id will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that is used to hold interactive elements. +https://docs.slack.dev/reference/block-kit/blocks/actions-block

+

Args

+
+
elements : required
+
An array of interactive element objects - buttons, select menus, overflow menus, +or date pickers. There is a maximum of 25 elements in each action block.
+
block_id
+
A string acting as a unique identifier for a block. +If not specified, a block_id will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class Block +(*,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Block(JsonObject):
+    """Blocks are a series of components that can be combined
+    to create visually rich and compellingly interactive messages.
+    https://docs.slack.dev/reference/block-kit/blocks
+    """
+
+    attributes = {"block_id", "type"}
+    block_id_max_length = 255
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,  # deprecated
+        block_id: Optional[str] = None,
+    ):
+        if subtype:
+            self._subtype_warning()
+        self.type = type if type else subtype
+        self.block_id = block_id
+        self.color = None
+
+    @JsonValidator(f"block_id cannot exceed {block_id_max_length} characters")
+    def _validate_block_id_length(self):
+        return self.block_id is None or len(self.block_id) <= self.block_id_max_length
+
+    @classmethod
+    def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]:
+        if block is None:
+            return None
+        elif isinstance(block, Block):
+            return block
+        else:
+            if "type" in block:
+                type = block["type"]
+                if type == SectionBlock.type:
+                    return SectionBlock(**block)
+                elif type == DividerBlock.type:
+                    return DividerBlock(**block)
+                elif type == ImageBlock.type:
+                    return ImageBlock(**block)
+                elif type == ActionsBlock.type:
+                    return ActionsBlock(**block)
+                elif type == ContextBlock.type:
+                    return ContextBlock(**block)
+                elif type == ContextActionsBlock.type:
+                    return ContextActionsBlock(**block)
+                elif type == InputBlock.type:
+                    return InputBlock(**block)
+                elif type == FileBlock.type:
+                    return FileBlock(**block)
+                elif type == CallBlock.type:
+                    return CallBlock(**block)
+                elif type == HeaderBlock.type:
+                    return HeaderBlock(**block)
+                elif type == MarkdownBlock.type:
+                    return MarkdownBlock(**block)
+                elif type == VideoBlock.type:
+                    return VideoBlock(**block)
+                elif type == RichTextBlock.type:
+                    return RichTextBlock(**block)
+                elif type == TableBlock.type:
+                    return TableBlock(**block)
+                else:
+                    cls.logger.warning(f"Unknown block detected and skipped ({block})")
+                    return None
+            else:
+                cls.logger.warning(f"Unknown block detected and skipped ({block})")
+                return None
+
+    @classmethod
+    def parse_all(cls, blocks: Optional[Sequence[Union[dict, "Block"]]]) -> List["Block"]:
+        return [cls.parse(b) for b in blocks or []]  # type: ignore[misc]
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var block_id_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(block:Β dictΒ |Β ForwardRef('Block')) ‑>Β BlockΒ |Β None +
+
+
+
+
+def parse_all(blocks:Β Sequence[dictΒ |Β ForwardRef('Block')]Β |Β None) ‑>Β List[Block] +
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class BlockElement +(*, type:Β strΒ |Β NoneΒ =Β None, subtype:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class BlockElement(JsonObject, metaclass=ABCMeta):
+    """Block Elements are things that exists inside of your Blocks.
+    https://docs.slack.dev/reference/block-kit/block-elements/
+    """
+
+    attributes = {"type"}
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        **others: dict,
+    ):
+        if subtype:
+            self._subtype_warning()
+        self.type = type if type else subtype
+        show_unknown_key_warning(self, others)
+
+    @classmethod
+    def parse(cls, block_element: Union[dict, "BlockElement"]) -> Optional[Union["BlockElement", TextObject]]:
+        if block_element is None:
+            return None
+        elif isinstance(block_element, dict):
+            if "type" in block_element:
+                d = copy.copy(block_element)
+                t = d.pop("type")
+                for subclass in cls._get_sub_block_elements():
+                    if t == subclass.type:
+                        return subclass(**d)
+                if t == PlainTextObject.type:
+                    return PlainTextObject(**d)
+                elif t == MarkdownTextObject.type:
+                    return MarkdownTextObject(**d)
+        elif isinstance(block_element, (TextObject, BlockElement)):
+            return block_element
+        cls.logger.warning(f"Unknown element detected and skipped ({block_element})")
+        return None
+
+    @classmethod
+    def parse_all(
+        cls, block_elements: Sequence[Union[dict, "BlockElement", TextObject]]
+    ) -> List[Union["BlockElement", TextObject]]:
+        return [cls.parse(e) for e in block_elements or []]  # type: ignore[arg-type, misc]
+
+    @classmethod
+    def _get_sub_block_elements(cls: Type["BlockElement"]) -> Iterator[Type["BlockElement"]]:
+        for subclass in cls.__subclasses__():
+            if hasattr(subclass, "type"):
+                yield subclass
+            yield from subclass._get_sub_block_elements()
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(block_element:Β dictΒ |Β ForwardRef('BlockElement')) ‑>Β BlockElementΒ |Β TextObjectΒ |Β None +
+
+
+
+
+def parse_all(block_elements:Β Sequence[dictΒ |Β ForwardRef('BlockElement')Β |Β TextObject]) ‑>Β List[BlockElementΒ |Β TextObject] +
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class ButtonElement +(*,
text:Β strΒ |Β dictΒ |Β TextObject,
action_id:Β strΒ |Β NoneΒ =Β None,
url:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ButtonElement(InteractiveElement):
+    type = "button"
+    text_max_length = 75
+    url_max_length = 3000
+    value_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text", "url", "value", "style", "confirm", "accessibility_label"})
+
+    def __init__(
+        self,
+        *,
+        text: Union[str, dict, TextObject],
+        action_id: Optional[str] = None,
+        url: Optional[str] = None,
+        value: Optional[str] = None,
+        style: Optional[str] = None,  # primary, danger
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        accessibility_label: Optional[str] = None,
+        **others: dict,
+    ):
+        """An interactive element that inserts a button. The button can be a trigger for
+        anything from opening a simple link to starting a complex workflow.
+        https://docs.slack.dev/reference/block-kit/block-elements/button-element/
+
+        Args:
+            text (required): A text object that defines the button's text.
+                Can only be of type: plain_text.
+                Maximum length for the text in this field is 75 characters.
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            url: A URL to load in the user's browser when the button is clicked.
+                Maximum length for this field is 3000 characters.
+                If you're using url, you'll still receive an interaction payload
+                and will need to send an acknowledgement response.
+            value: The value to send along with the interaction payload.
+                Maximum length for this field is 2000 characters.
+            style: Decorates buttons with alternative visual color schemes. Use this option with restraint.
+                "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions.
+                "primary" should only be used for one button within a set.
+                "danger" gives buttons a red outline and text, and should be used when the action is destructive.
+                Use "danger" even more sparingly than "primary".
+                If you don't include this field, the default button style will be used.
+            confirm: A confirm object that defines an optional confirmation dialog after the button is clicked.
+            accessibility_label: A label for longer descriptive text about a button element.
+                This label will be read out by screen readers instead of the button text object.
+                Maximum length for this field is 75 characters.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        # NOTE: default_type=PlainTextObject.type here is only for backward-compatibility with version 2.5.0
+        self.text = TextObject.parse(text, default_type=PlainTextObject.type)
+        self.url = url
+        self.value = value
+        self.style = style
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+        self.accessibility_label = accessibility_label
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_text_length(self) -> bool:
+        return self.text is None or self.text.text is None or len(self.text.text) <= self.text_max_length
+
+    @JsonValidator(f"url attribute cannot exceed {url_max_length} characters")
+    def _validate_url_length(self) -> bool:
+        return self.url is None or len(self.url) <= self.url_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def _validate_value_length(self) -> bool:
+        return self.value is None or len(self.value) <= self.value_max_length
+
+    @EnumValidator("style", ButtonStyles)
+    def _validate_style_valid(self):
+        return self.style is None or self.style in ButtonStyles
+
+    @JsonValidator(f"accessibility_label attribute cannot exceed {text_max_length} characters")
+    def _validate_accessibility_label_length(self) -> bool:
+        return self.accessibility_label is None or len(self.accessibility_label) <= self.text_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An interactive element that inserts a button. The button can be a trigger for +anything from opening a simple link to starting a complex workflow. +https://docs.slack.dev/reference/block-kit/block-elements/button-element/

+

Args

+
+
text : required
+
A text object that defines the button's text. +Can only be of type: plain_text. +Maximum length for the text in this field is 75 characters.
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
url
+
A URL to load in the user's browser when the button is clicked. +Maximum length for this field is 3000 characters. +If you're using url, you'll still receive an interaction payload +and will need to send an acknowledgement response.
+
value
+
The value to send along with the interaction payload. +Maximum length for this field is 2000 characters.
+
style
+
Decorates buttons with alternative visual color schemes. Use this option with restraint. +"primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. +"primary" should only be used for one button within a set. +"danger" gives buttons a red outline and text, and should be used when the action is destructive. +Use "danger" even more sparingly than "primary". +If you don't include this field, the default button style will be used.
+
confirm
+
A confirm object that defines an optional confirmation dialog after the button is clicked.
+
accessibility_label
+
A label for longer descriptive text about a button element. +This label will be read out by screen readers instead of the button text object. +Maximum length for this field is 75 characters.
+
+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
var url_max_length
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class CallBlock +(*,
call_id:Β str,
api_decoration_available:Β boolΒ |Β NoneΒ =Β None,
call:Β Dict[str,Β Dict[str,Β Any]]Β |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class CallBlock(Block):
+    type = "call"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"call_id", "api_decoration_available", "call"})
+
+    def __init__(
+        self,
+        *,
+        call_id: str,
+        api_decoration_available: Optional[bool] = None,
+        call: Optional[Dict[str, Dict[str, Any]]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays a call information
+        https://docs.slack.dev/reference/block-kit/blocks#call
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.call_id = call_id
+        self.api_decoration_available = api_decoration_available
+        self.call = call
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays a call information +https://docs.slack.dev/reference/block-kit/blocks#call

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"call_id", "api_decoration_available", "call"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ChannelMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_channels:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ChannelMultiSelectElement(InputInteractiveElement):
+    type = "multi_channels_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_channels", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_channels: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This multi-select menu will populate its options with a list of public channels visible
+        to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#channel_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_channels: An array of one or more IDs of any valid public channel
+                to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_channels = initial_channels
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This multi-select menu will populate its options with a list of public channels visible +to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#channel_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_channels
+
An array of one or more IDs of any valid public channel +to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_channels", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ChannelSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_channel:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
response_url_enabled:Β boolΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ChannelSelectElement(InputInteractiveElement):
+    type = "channels_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_channel", "response_url_enabled"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_channel: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        response_url_enabled: Optional[bool] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of public channels
+        visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#channels_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_channel: The ID of any valid public channel to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after a menu item is selected.
+            response_url_enabled: This field only works with menus in input blocks in modals.
+                When set to true, the view_submission payload from the menu's parent view will contain a response_url.
+                This response_url can be used for message responses.
+                The target channel for the message will be determined by the value of this select menu
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_channel = initial_channel
+        self.response_url_enabled = response_url_enabled
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of public channels +visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#channels_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_channel
+
The ID of any valid public channel to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after a menu item is selected.
+
response_url_enabled
+
This field only works with menus in input blocks in modals. +When set to true, the view_submission payload from the menu's parent view will contain a response_url. +This response_url can be used for message responses. +The target channel for the message will be determined by the value of this select menu
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_channel", "response_url_enabled"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class CheckboxesElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
initial_options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class CheckboxesElement(InputInteractiveElement):
+    type = "checkboxes"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "initial_options"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        initial_options: Optional[Sequence[Union[dict, Option]]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A checkbox group that allows a user to choose multiple items from a list of possible options.
+        https://docs.slack.dev/reference/block-kit/block-elements/checkboxes-element/
+
+        Args:
+            action_id (required): An identifier for the action triggered when the checkbox group is changed.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects. A maximum of 10 options are allowed.
+            initial_options: An array of option objects that exactly matches one or more of the options.
+                These options will be selected when the checkbox group initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after clicking one of the checkboxes in this element.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = Option.parse_all(options)
+        self.initial_options = Option.parse_all(initial_options)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A checkbox group that allows a user to choose multiple items from a list of possible options. +https://docs.slack.dev/reference/block-kit/block-elements/checkboxes-element/

+

Args

+
+
action_id : required
+
An identifier for the action triggered when the checkbox group is changed. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects. A maximum of 10 options are allowed.
+
initial_options
+
An array of option objects that exactly matches one or more of the options. +These options will be selected when the checkbox group initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after clicking one of the checkboxes in this element.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "initial_options"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ConfirmObject +(*,
title:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObject,
text:Β strΒ |Β Dict[str,Β Any]Β |Β TextObject,
confirm:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObjectΒ =Β 'Yes',
deny:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObjectΒ =Β 'No',
style:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ConfirmObject(JsonObject):
+    attributes: Set[str] = set()
+
+    title_max_length = 100
+    text_max_length = 300
+    confirm_max_length = 30
+    deny_max_length = 30
+
+    @classmethod
+    def parse(cls, confirm: Union["ConfirmObject", Dict[str, Any]]):
+        if confirm:
+            if isinstance(confirm, ConfirmObject):
+                return confirm
+            elif isinstance(confirm, dict):
+                return ConfirmObject(**confirm)
+            else:
+                # Not yet implemented: show some warning here
+                return None
+        return None
+
+    def __init__(
+        self,
+        *,
+        title: Union[str, Dict[str, Any], PlainTextObject],
+        text: Union[str, Dict[str, Any], TextObject],
+        confirm: Union[str, Dict[str, Any], PlainTextObject] = "Yes",
+        deny: Union[str, Dict[str, Any], PlainTextObject] = "No",
+        style: Optional[str] = None,
+    ):
+        """
+        An object that defines a dialog that provides a confirmation step to any
+        interactive element. This dialog will ask the user to confirm their action by
+        offering a confirm and deny button.
+        https://docs.slack.dev/reference/block-kit/composition-objects/confirmation-dialog-object/
+        """
+        self._title = TextObject.parse(title, default_type=PlainTextObject.type)
+        self._text = TextObject.parse(text, default_type=MarkdownTextObject.type)
+        self._confirm = TextObject.parse(confirm, default_type=PlainTextObject.type)
+        self._deny = TextObject.parse(deny, default_type=PlainTextObject.type)
+        self._style = style
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        self.title = self._title.text if self._title else None
+        self.text = self._text.text if self._text else None
+        self.confirm = self._confirm.text if self._confirm else None
+        self.deny = self._deny.text if self._deny else None
+        self.style = self._style
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def title_length(self) -> bool:
+        return self._title is None or len(self._title.text) <= self.title_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def text_length(self) -> bool:
+        return self._text is None or len(self._text.text) <= self.text_max_length
+
+    @JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters")
+    def confirm_length(self) -> bool:
+        return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length
+
+    @JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters")
+    def deny_length(self) -> bool:
+        return self._deny is None or len(self._deny.text) <= self.deny_max_length
+
+    @JsonValidator('style for confirm must be either "primary" or "danger"')
+    def _validate_confirm_style(self) -> bool:
+        return self._style is None or self._style in ["primary", "danger"]
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        if option_type == "action":
+            # deliberately skipping JSON validators here - can't find documentation
+            # on actual limits here
+            json: Dict[str, Union[str, dict]] = {
+                "ok_text": self._confirm.text if self._confirm and self._confirm.text != "Yes" else "Okay",
+                "dismiss_text": self._deny.text if self._deny and self._deny.text != "No" else "Cancel",
+            }
+            if self._title:
+                json["title"] = self._title.text
+            if self._text:
+                json["text"] = self._text.text
+            return json
+
+        else:
+            self.validate_json()
+            json = {}
+            if self._title:
+                json["title"] = self._title.to_dict()
+            if self._text:
+                json["text"] = self._text.to_dict()
+            if self._confirm:
+                json["confirm"] = self._confirm.to_dict()
+            if self._deny:
+                json["deny"] = self._deny.to_dict()
+            if self._style:
+                json["style"] = self._style
+            return json
+
+

The base class for JSON serializable class objects

+

An object that defines a dialog that provides a confirmation step to any +interactive element. This dialog will ask the user to confirm their action by +offering a confirm and deny button. +https://docs.slack.dev/reference/block-kit/composition-objects/confirmation-dialog-object/

+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var confirm_max_length
+
+

The type of the None singleton.

+
+
var deny_max_length
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(confirm:Β ForwardRef('ConfirmObject')Β |Β Dict[str,Β Any]) +
+
+
+
+
+

Methods

+
+
+def confirm_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters")
+def confirm_length(self) -> bool:
+    return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length
+
+
+
+
+def deny_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters")
+def deny_length(self) -> bool:
+    return self._deny is None or len(self._deny.text) <= self.deny_max_length
+
+
+
+
+def text_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+def text_length(self) -> bool:
+    return self._text is None or len(self._text.text) <= self.text_max_length
+
+
+
+
+def title_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+def title_length(self) -> bool:
+    return self._title is None or len(self._title.text) <= self.title_max_length
+
+
+
+
+

Inherited members

+ +
+
+class ContextActionsBlock +(*,
elements:Β Sequence[dictΒ |Β FeedbackButtonsElementΒ |Β IconButtonElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ContextActionsBlock(Block):
+    type = "context_actions"
+    elements_max_length = 5
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, FeedbackButtonsElement, IconButtonElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays actions as contextual info, which can include both feedback buttons and icon buttons.
+        https://docs.slack.dev/reference/block-kit/blocks/context-actions-block
+
+        Args:
+            elements (required): An array of feedback_buttons or icon_button block elements. Maximum number of items is 5.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator("elements attribute must be specified")
+    def _validate_elements(self):
+        return self.elements is None or len(self.elements) > 0
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays actions as contextual info, which can include both feedback buttons and icon buttons. +https://docs.slack.dev/reference/block-kit/blocks/context-actions-block

+

Args

+
+
elements : required
+
An array of feedback_buttons or icon_button block elements. Maximum number of items is 5.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ContextBlock +(*,
elements:Β Sequence[dictΒ |Β ImageElementΒ |Β TextObject],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ContextBlock(Block):
+    type = "context"
+    elements_max_length = 10
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, ImageElement, TextObject]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays message context, which can include both images and text.
+        https://docs.slack.dev/reference/block-kit/blocks/context-block
+
+        Args:
+            elements (required): An array of image elements and text objects. Maximum number of items is 10.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+    @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements")
+    def _validate_elements_length(self):
+        return self.elements is None or len(self.elements) <= self.elements_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays message context, which can include both images and text. +https://docs.slack.dev/reference/block-kit/blocks/context-block

+

Args

+
+
elements : required
+
An array of image elements and text objects. Maximum number of items is 10.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ConversationFilter +(*,
include:Β Sequence[str]Β |Β NoneΒ =Β None,
exclude_bot_users:Β boolΒ |Β NoneΒ =Β None,
exclude_external_shared_channels:Β boolΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ConversationFilter(JsonObject):
+    attributes = {"include", "exclude_bot_users", "exclude_external_shared_channels"}
+    logger = logging.getLogger(__name__)
+
+    def __init__(
+        self,
+        *,
+        include: Optional[Sequence[str]] = None,
+        exclude_bot_users: Optional[bool] = None,
+        exclude_external_shared_channels: Optional[bool] = None,
+    ):
+        """Provides a way to filter the list of options in a conversations select menu
+        or conversations multi-select menu.
+        https://docs.slack.dev/reference/block-kit/composition-objects/conversation-filter-object
+
+        Args:
+            include: Indicates which type of conversations should be included in the list.
+                When this field is provided, any conversations that do not match will be excluded.
+                You should provide an array of strings from the following options:
+                "im", "mpim", "private", and "public". The array cannot be empty.
+            exclude_bot_users: Indicates whether to exclude bot users from conversation lists. Defaults to false.
+            exclude_external_shared_channels: Indicates whether to exclude external shared channels
+                from conversation lists. Defaults to false.
+        """
+        self.include = include
+        self.exclude_bot_users = exclude_bot_users
+        self.exclude_external_shared_channels = exclude_external_shared_channels
+
+    @classmethod
+    def parse(cls, filter: Union[dict, "ConversationFilter"]):
+        if filter is None:
+            return None
+        elif isinstance(filter, ConversationFilter):
+            return filter
+        elif isinstance(filter, dict):
+            d = copy.copy(filter)
+            return ConversationFilter(**d)
+        else:
+            cls.logger.warning(f"Unknown conversation filter object detected and skipped ({filter})")
+            return None
+
+

The base class for JSON serializable class objects

+

Provides a way to filter the list of options in a conversations select menu +or conversations multi-select menu. +https://docs.slack.dev/reference/block-kit/composition-objects/conversation-filter-object

+

Args

+
+
include
+
Indicates which type of conversations should be included in the list. +When this field is provided, any conversations that do not match will be excluded. +You should provide an array of strings from the following options: +"im", "mpim", "private", and "public". The array cannot be empty.
+
exclude_bot_users
+
Indicates whether to exclude bot users from conversation lists. Defaults to false.
+
exclude_external_shared_channels
+
Indicates whether to exclude external shared channels +from conversation lists. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(filter:Β dictΒ |Β ForwardRef('ConversationFilter')) +
+
+
+
+
+

Inherited members

+ +
+
+class ConversationMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_conversations:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
default_to_current_conversation:Β boolΒ |Β NoneΒ =Β None,
filter:Β dictΒ |Β ConversationFilterΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ConversationMultiSelectElement(InputInteractiveElement):
+    type = "multi_conversations_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_conversations",
+                "max_selected_items",
+                "default_to_current_conversation",
+                "filter",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_conversations: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        default_to_current_conversation: Optional[bool] = None,
+        filter: Optional[Union[dict, ConversationFilter]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This multi-select menu will populate its options with a list of public and private channels,
+        DMs, and MPIMs visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element/#conversation_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_conversations: An array of one or more IDs of any valid conversations to be pre-selected
+                when the menu loads. If default_to_current_conversation is also supplied,
+                initial_conversations will be ignored.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            default_to_current_conversation: Pre-populates the select menu with the conversation that
+                the user was viewing when they opened the modal, if available. Default is false.
+            filter: A filter object that reduces the list of available conversations using the specified criteria.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_conversations = initial_conversations
+        self.max_selected_items = max_selected_items
+        self.default_to_current_conversation = default_to_current_conversation
+        self.filter = ConversationFilter.parse(filter)  # type: ignore[arg-type]
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This multi-select menu will populate its options with a list of public and private channels, +DMs, and MPIMs visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element/#conversation_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_conversations
+
An array of one or more IDs of any valid conversations to be pre-selected +when the menu loads. If default_to_current_conversation is also supplied, +initial_conversations will be ignored.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
default_to_current_conversation
+
Pre-populates the select menu with the conversation that +the user was viewing when they opened the modal, if available. Default is false.
+
filter
+
A filter object that reduces the list of available conversations using the specified criteria.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_conversations",
+            "max_selected_items",
+            "default_to_current_conversation",
+            "filter",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ConversationSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_conversation:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
response_url_enabled:Β boolΒ |Β NoneΒ =Β None,
default_to_current_conversation:Β boolΒ |Β NoneΒ =Β None,
filter:Β ConversationFilterΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ConversationSelectElement(InputInteractiveElement):
+    type = "conversations_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_conversation",
+                "response_url_enabled",
+                "filter",
+                "default_to_current_conversation",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_conversation: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        response_url_enabled: Optional[bool] = None,
+        default_to_current_conversation: Optional[bool] = None,
+        filter: Optional[ConversationFilter] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of public and private
+        channels, DMs, and MPIMs visible to the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#conversations_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_conversation: The ID of any valid conversation to be pre-selected when the menu loads.
+                If default_to_current_conversation is also supplied, initial_conversation will take precedence.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            response_url_enabled: This field only works with menus in input blocks in modals.
+                When set to true, the view_submission payload from the menu's parent view will contain a response_url.
+                This response_url can be used for message responses. The target conversation for the message
+                will be determined by the value of this select menu.
+            default_to_current_conversation: Pre-populates the select menu with the conversation
+                that the user was viewing when they opened the modal, if available. Default is false.
+            filter: A filter object that reduces the list of available conversations using the specified criteria.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_conversation = initial_conversation
+        self.response_url_enabled = response_url_enabled
+        self.default_to_current_conversation = default_to_current_conversation
+        self.filter = filter
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of public and private +channels, DMs, and MPIMs visible to the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#conversations_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_conversation
+
The ID of any valid conversation to be pre-selected when the menu loads. +If default_to_current_conversation is also supplied, initial_conversation will take precedence.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
response_url_enabled
+
This field only works with menus in input blocks in modals. +When set to true, the view_submission payload from the menu's parent view will contain a response_url. +This response_url can be used for message responses. The target conversation for the message +will be determined by the value of this select menu.
+
default_to_current_conversation
+
Pre-populates the select menu with the conversation +that the user was viewing when they opened the modal, if available. Default is false.
+
filter
+
A filter object that reduces the list of available conversations using the specified criteria.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_conversation",
+            "response_url_enabled",
+            "filter",
+            "default_to_current_conversation",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DatePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_date:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class DatePickerElement(InputInteractiveElement):
+    type = "datepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_date"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_date: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        An element which lets users easily select a date from a calendar style UI.
+        Date picker elements can be used inside of SectionBlocks and ActionsBlocks.
+        https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown on the datepicker.
+                Maximum length for the text in this field is 150 characters.
+            initial_date: The initial date that is selected when the element is loaded.
+                This should be in the format YYYY-MM-DD.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a date is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_date = initial_date
+
+    @JsonValidator("initial_date attribute must be in format 'YYYY-MM-DD'")
+    def _validate_initial_date_valid(self) -> bool:
+        return (
+            self.initial_date is None
+            or re.match(r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date) is not None
+        )
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element which lets users easily select a date from a calendar style UI. +Date picker elements can be used inside of SectionBlocks and ActionsBlocks. +https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown on the datepicker. +Maximum length for the text in this field is 150 characters.
+
initial_date
+
The initial date that is selected when the element is loaded. +This should be in the format YYYY-MM-DD.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a date is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_date"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DateTimePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_date_time:Β intΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class DateTimePickerElement(InputInteractiveElement):
+    type = "datetimepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_date_time"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_date_time: Optional[int] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        An element that allows the selection of a time of day formatted as a UNIX timestamp.
+        On desktop clients, this time picker will take the form of a dropdown list and the
+        date picker will take the form of a dropdown calendar. Both options will have free-text
+        entry for precise choices. On mobile clients, the time picker and date
+        picker will use native UIs.
+        https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element/
+
+        Args:
+            action_id (required): An identifier for the action triggered when a time is selected. You can use this
+                when you receive an interaction payload to identify the source of the action. Should be unique among
+                all other action_ids in the containing block. Maximum length for this field is 255 characters.
+            initial_date_time: The initial date and time that is selected when the element is loaded, represented as
+                a UNIX timestamp in seconds. This should be in the format of 10 digits, for example 1628633820
+                represents the date and time August 10th, 2021 at 03:17pm PST.
+                and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a time is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_date_time = initial_date_time
+
+    @JsonValidator("initial_date_time attribute must be between 0 and 99999999 seconds")
+    def _validate_initial_date_time_valid(self) -> bool:
+        return self.initial_date_time is None or (0 <= self.initial_date_time <= 9999999999)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element that allows the selection of a time of day formatted as a UNIX timestamp. +On desktop clients, this time picker will take the form of a dropdown list and the +date picker will take the form of a dropdown calendar. Both options will have free-text +entry for precise choices. On mobile clients, the time picker and date +picker will use native UIs. +https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element/

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a time is selected. You can use this +when you receive an interaction payload to identify the source of the action. Should be unique among +all other action_ids in the containing block. Maximum length for this field is 255 characters.
+
initial_date_time
+
The initial date and time that is selected when the element is loaded, represented as +a UNIX timestamp in seconds. This should be in the format of 10 digits, for example 1628633820 +represents the date and time August 10th, 2021 at 03:17pm PST. +and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a time is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_date_time"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DividerBlock +(*, block_id:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class DividerBlock(Block):
+    type = "divider"
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A content divider, like an <hr>, to split up different blocks inside of a message.
+        https://docs.slack.dev/reference/block-kit/blocks/divider-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A content divider, like an


, to split up different blocks inside of a message. +https://docs.slack.dev/reference/block-kit/blocks/divider-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EmailInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class EmailInputElement(InputInteractiveElement):
+    type = "email_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_value: Optional[str] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        https://docs.slack.dev/reference/block-kit/block-elements/email-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_value: The initial value in the email input when it is loaded.
+            dispatch_action_config:  dispatch configuration object that determines when during
+                text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown in the
+                email input. Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

https://docs.slack.dev/reference/block-kit/block-elements/email-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_value
+
The initial value in the email input when it is loaded.
+
dispatch_action_config
+
dispatch configuration object that determines when during +text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown in the +email input. Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ExternalDataMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
initial_options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ExternalDataMultiSelectElement(InputInteractiveElement):
+    type = "multi_external_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        min_query_length: Optional[int] = None,
+        initial_options: Optional[Sequence[Union[dict, Option]]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will load its options from an external data source, allowing
+        for a dynamic list of options.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            min_query_length: When the typeahead field is used, a request will be sent on every character change.
+                If you prefer fewer requests or more fully ideated queries,
+                use the min_query_length attribute to tell Slack
+                the fewest number of typed characters required before dispatch.
+                The default value is 3
+            initial_options: An array of option objects that exactly match one or more of the options
+                within options or option_groups. These options will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.min_query_length = min_query_length
+        self.initial_options = Option.parse_all(initial_options)
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will load its options from an external data source, allowing +for a dynamic list of options. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
min_query_length
+
When the typeahead field is used, a request will be sent on every character change. +If you prefer fewer requests or more fully ideated queries, +use the min_query_length attribute to tell Slack +the fewest number of typed characters required before dispatch. +The default value is 3
+
initial_options
+
An array of option objects that exactly match one or more of the options +within options or option_groups. These options will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ExternalDataSelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_option:Β OptionΒ |Β OptionGroupΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ExternalDataSelectElement(InputInteractiveElement):
+    type = "external_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, TextObject]] = None,
+        initial_option: Union[Optional[Option], Optional[OptionGroup]] = None,
+        min_query_length: Optional[int] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will load its options from an external data source, allowing
+        for a dynamic list of options.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#external_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            initial_option: A single option that exactly matches one of the options
+                within the options or option_groups loaded from the external data source.
+                This option will be selected when the menu initially loads.
+            min_query_length: When the typeahead field is used, a request will be sent on every character change.
+                If you prefer fewer requests or more fully ideated queries,
+                use the min_query_length attribute to tell Slack
+                the fewest number of typed characters required before dispatch.
+                The default value is 3.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.min_query_length = min_query_length
+        self.initial_option = initial_option
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will load its options from an external data source, allowing +for a dynamic list of options. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#external_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
initial_option
+
A single option that exactly matches one of the options +within the options or option_groups loaded from the external data source. +This option will be selected when the menu initially loads.
+
min_query_length
+
When the typeahead field is used, a request will be sent on every character change. +If you prefer fewer requests or more fully ideated queries, +use the min_query_length attribute to tell Slack +the fewest number of typed characters required before dispatch. +The default value is 3.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class FeedbackButtonObject +(*,
text:Β strΒ |Β Dict[str,Β Any]Β |Β PlainTextObject,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
value:Β str,
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class FeedbackButtonObject(JsonObject):
+    attributes: Set[str] = set()
+
+    text_max_length = 75
+    value_max_length = 2000
+
+    @classmethod
+    def parse(cls, feedback_button: Union["FeedbackButtonObject", Dict[str, Any]]):
+        if feedback_button:
+            if isinstance(feedback_button, FeedbackButtonObject):
+                return feedback_button
+            elif isinstance(feedback_button, dict):
+                return FeedbackButtonObject(**feedback_button)
+            else:
+                # Not yet implemented: show some warning here
+                return None
+        return None
+
+    def __init__(
+        self,
+        *,
+        text: Union[str, Dict[str, Any], PlainTextObject],
+        accessibility_label: Optional[str] = None,
+        value: str,
+        **others: Dict[str, Any],
+    ):
+        """
+        A feedback button element object for either positive or negative feedback.
+        https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element#button-object-fields
+
+        Args:
+            text (required): An object containing some text. Maximum length for this field is 75 characters.
+            accessibility_label: A label for longer descriptive text about a button element. This label will be read out by
+                screen readers instead of the button `text` object.
+            value (required): The button value. Maximum length for this field is 2000 characters.
+        """
+        self._text: Optional[TextObject] = PlainTextObject.parse(text, default_type=PlainTextObject.type)
+        self._accessibility_label: Optional[str] = accessibility_label
+        self._value: Optional[str] = value
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def text_length(self) -> bool:
+        return self._text is None or len(self._text.text) <= self.text_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def value_length(self) -> bool:
+        return self._value is None or len(self._value) <= self.value_max_length
+
+    def to_dict(self) -> Dict[str, Any]:
+        self.validate_json()
+        json: Dict[str, Union[str, dict]] = {}
+        if self._text:
+            json["text"] = self._text.to_dict()
+        if self._accessibility_label:
+            json["accessibility_label"] = self._accessibility_label
+        if self._value:
+            json["value"] = self._value
+        return json
+
+

The base class for JSON serializable class objects

+

A feedback button element object for either positive or negative feedback. +https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element#button-object-fields

+

Args

+
+
text : required
+
An object containing some text. Maximum length for this field is 75 characters.
+
accessibility_label
+
A label for longer descriptive text about a button element. This label will be read out by +screen readers instead of the button text object.
+
value : required
+
The button value. Maximum length for this field is 2000 characters.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(feedback_button:Β ForwardRef('FeedbackButtonObject')Β |Β Dict[str,Β Any]) +
+
+
+
+
+

Methods

+
+
+def text_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+def text_length(self) -> bool:
+    return self._text is None or len(self._text.text) <= self.text_max_length
+
+
+
+
+def value_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+def value_length(self) -> bool:
+    return self._value is None or len(self._value) <= self.value_max_length
+
+
+
+
+

Inherited members

+ +
+
+class FeedbackButtonsElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
positive_button:Β dictΒ |Β FeedbackButtonObject,
negative_button:Β dictΒ |Β FeedbackButtonObject,
**others:Β dict)
+
+
+
+ +Expand source code + +
class FeedbackButtonsElement(InteractiveElement):
+    type = "feedback_buttons"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"positive_button", "negative_button"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        positive_button: Union[dict, FeedbackButtonObject],
+        negative_button: Union[dict, FeedbackButtonObject],
+        **others: dict,
+    ):
+        """Buttons to indicate positive or negative feedback.
+        https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element
+
+        Args:
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            positive_button (required): A button to indicate positive feedback.
+            negative_button (required): A button to indicate negative feedback.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.positive_button = FeedbackButtonObject.parse(positive_button)
+        self.negative_button = FeedbackButtonObject.parse(negative_button)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Buttons to indicate positive or negative feedback. +https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element

+

Args

+
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
positive_button : required
+
A button to indicate positive feedback.
+
negative_button : required
+
A button to indicate negative feedback.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FileBlock +(*,
external_id:Β str,
source:Β strΒ =Β 'remote',
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class FileBlock(Block):
+    type = "file"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"external_id", "source"})
+
+    def __init__(
+        self,
+        *,
+        external_id: str,
+        source: str = "remote",
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays a remote file.
+        https://docs.slack.dev/reference/block-kit/blocks/file-block
+
+        Args:
+            external_id (required): The external unique ID for this file.
+            source (required): At the moment, source will always be remote for a remote file.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.external_id = external_id
+        self.source = source
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays a remote file. +https://docs.slack.dev/reference/block-kit/blocks/file-block

+

Args

+
+
external_id : required
+
The external unique ID for this file.
+
source : required
+
At the moment, source will always be remote for a remote file.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"external_id", "source"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class HeaderBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class HeaderBlock(Block):
+    type = "header"
+    text_max_length = 150
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text"})
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        text: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """A header is a plain-text block that displays in a larger, bold font.
+        https://docs.slack.dev/reference/block-kit/blocks/header-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (required): The text for the block, in the form of a plain_text text object.
+                Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = TextObject.parse(text, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+
+    @JsonValidator("text attribute must be specified")
+    def _validate_text(self):
+        return self.text is not None
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return self.text is None or len(self.text.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A header is a plain-text block that displays in a larger, bold font. +https://docs.slack.dev/reference/block-kit/blocks/header-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : required
+
The text for the block, in the form of a plain_text text object. +Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class IconButtonElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
icon:Β str,
text:Β strΒ |Β dictΒ |Β TextObject,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
visible_to_user_ids:Β List[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class IconButtonElement(InteractiveElement):
+    type = "icon_button"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"icon", "text", "accessibility_label", "value", "visible_to_user_ids", "confirm"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        icon: str,
+        text: Union[str, dict, TextObject],
+        accessibility_label: Optional[str] = None,
+        value: Optional[str] = None,
+        visible_to_user_ids: Optional[List[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        **others: dict,
+    ):
+        """An icon button to perform actions.
+        https://docs.slack.dev/reference/block-kit/block-elements/icon-button-element
+
+        Args:
+            action_id: An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            icon (required): The icon to show (e.g., 'trash').
+            text (required): Defines an object containing some text.
+            accessibility_label: A label for longer descriptive text about a button element.
+                This label will be read out by screen readers instead of the button text object.
+                Maximum length for this field is 75 characters.
+            value: The button value.
+                Maximum length for this field is 2000 characters.
+            visible_to_user_ids: User IDs for which the icon appears.
+                Maximum length for this field is 10 user IDs.
+            confirm: A confirm object that defines an optional confirmation dialog after the button is clicked.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.icon = icon
+        self.text = TextObject.parse(text, PlainTextObject.type)
+        self.accessibility_label = accessibility_label
+        self.value = value
+        self.visible_to_user_ids = visible_to_user_ids
+        self.confirm = ConfirmObject.parse(confirm) if confirm else None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An icon button to perform actions. +https://docs.slack.dev/reference/block-kit/block-elements/icon-button-element

+

Args

+
+
action_id
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
icon : required
+
The icon to show (e.g., 'trash').
+
text : required
+
Defines an object containing some text.
+
accessibility_label
+
A label for longer descriptive text about a button element. +This label will be read out by screen readers instead of the button text object. +Maximum length for this field is 75 characters.
+
value
+
The button value. +Maximum length for this field is 2000 characters.
+
visible_to_user_ids
+
User IDs for which the icon appears. +Maximum length for this field is 10 user IDs.
+
confirm
+
A confirm object that defines an optional confirmation dialog after the button is clicked.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ImageBlock +(*,
alt_text:Β str,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β SlackFileΒ |Β NoneΒ =Β None,
title:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ImageBlock(Block):
+    type = "image"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "image_url", "title", "slack_file"})
+
+    image_url_max_length = 3000
+    alt_text_max_length = 2000
+    title_max_length = 2000
+
+    def __init__(
+        self,
+        *,
+        alt_text: str,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None,
+        title: Optional[Union[str, dict, PlainTextObject]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A simple image block, designed to make those cat photos really pop.
+        https://docs.slack.dev/reference/block-kit/blocks/image-block
+
+        Args:
+            alt_text (required): A plain-text summary of the image. This should not contain any markup.
+                Maximum length for this field is 2000 characters.
+            image_url: The URL of the image to be displayed.
+                Maximum length for this field is 3000 characters.
+            slack_file: A Slack image file object that defines the source of the image.
+            title: An optional title for the image in the form of a text object that can only be of type: plain_text.
+                Maximum length for the text in this field is 2000 characters.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.image_url = image_url
+        self.alt_text = alt_text
+        parsed_title = None
+        if title is not None:
+            if isinstance(title, str):
+                parsed_title = PlainTextObject(text=title)
+            elif isinstance(title, dict):
+                if title.get("type") != PlainTextObject.type:
+                    raise SlackObjectFormationError(f"Unsupported type for title in an image block: {title.get('type')}")
+                parsed_title = PlainTextObject(text=title.get("text"), emoji=title.get("emoji"))  # type: ignore[arg-type]
+            elif isinstance(title, PlainTextObject):
+                parsed_title = title
+            else:
+                raise SlackObjectFormationError(f"Unsupported type for title in an image block: {type(title)}")
+        if slack_file is not None:
+            self.slack_file = (
+                slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file)
+            )
+        self.title = parsed_title
+
+    @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters")
+    def _validate_image_url_length(self):
+        return self.image_url is None or len(self.image_url) <= self.image_url_max_length
+
+    @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return len(self.alt_text) <= self.alt_text_max_length
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def _validate_title_length(self):
+        return self.title is None or self.title.text is None or len(self.title.text) <= self.title_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A simple image block, designed to make those cat photos really pop. +https://docs.slack.dev/reference/block-kit/blocks/image-block

+

Args

+
+
alt_text : required
+
A plain-text summary of the image. This should not contain any markup. +Maximum length for this field is 2000 characters.
+
image_url
+
The URL of the image to be displayed. +Maximum length for this field is 3000 characters.
+
slack_file
+
A Slack image file object that defines the source of the image.
+
title
+
An optional title for the image in the form of a text object that can only be of type: plain_text. +Maximum length for the text in this field is 2000 characters.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var alt_text_max_length
+
+

The type of the None singleton.

+
+
var image_url_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "image_url", "title", "slack_file"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class ImageElement +(*,
alt_text:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β SlackFileΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class ImageElement(BlockElement):
+    type = "image"
+    image_url_max_length = 3000
+    alt_text_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "image_url", "slack_file"})
+
+    def __init__(
+        self,
+        *,
+        alt_text: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None,
+        **others: dict,
+    ):
+        """An element to insert an image - this element can be used in section and
+        context blocks only. If you want a block with only an image in it,
+        you're looking for the image block.
+        https://docs.slack.dev/reference/block-kit/block-elements/image-element
+
+        Args:
+            alt_text (required): A plain-text summary of the image. This should not contain any markup.
+            image_url: The URL of the image to be displayed.
+            slack_file: A Slack image file object that defines the source of the image.
+        """
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.image_url = image_url
+        self.alt_text = alt_text
+        self.slack_file = slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file)
+
+    @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters")
+    def _validate_image_url_length(self) -> bool:
+        return self.image_url is None or len(self.image_url) <= self.image_url_max_length
+
+    @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters")
+    def _validate_alt_text_length(self) -> bool:
+        return len(self.alt_text) <= self.alt_text_max_length  # type: ignore[arg-type]
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element to insert an image - this element can be used in section and +context blocks only. If you want a block with only an image in it, +you're looking for the image block. +https://docs.slack.dev/reference/block-kit/block-elements/image-element

+

Args

+
+
alt_text : required
+
A plain-text summary of the image. This should not contain any markup.
+
image_url
+
The URL of the image to be displayed.
+
slack_file
+
A Slack image file object that defines the source of the image.
+
+

Ancestors

+ +

Class variables

+
+
var alt_text_max_length
+
+

The type of the None singleton.

+
+
var image_url_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "image_url", "slack_file"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class InputBlock +(*,
label:Β strΒ |Β dictΒ |Β PlainTextObject,
element:Β strΒ |Β dictΒ |Β InputInteractiveElement,
block_id:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
dispatch_action:Β boolΒ |Β NoneΒ =Β None,
optional:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InputBlock(Block):
+    type = "input"
+    label_max_length = 2000
+    hint_max_length = 2000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"})
+
+    def __init__(
+        self,
+        *,
+        label: Union[str, dict, PlainTextObject],
+        element: Union[str, dict, InputInteractiveElement],
+        block_id: Optional[str] = None,
+        hint: Optional[Union[str, dict, PlainTextObject]] = None,
+        dispatch_action: Optional[bool] = None,
+        optional: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A block that collects information from users - it can hold a plain-text input element,
+        a select menu element, a multi-select menu element, or a datepicker.
+        https://docs.slack.dev/reference/block-kit/blocks/input-block
+
+        Args:
+            label (required): A label that appears above an input element in the form of a text object
+                that must have type of plain_text. Maximum length for the text in this field is 2000 characters.
+            element (required): An plain-text input element, a checkbox element, a radio button element,
+                a select menu element, a multi-select menu element, or a datepicker.
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message or view and each iteration of a message or view.
+                If a message or view is updated, use a new block_id.
+            hint: An optional hint that appears below an input element in a lighter grey.
+                It must be a text object with a type of plain_text.
+                Maximum length for the text in this field is 2000 characters.
+            dispatch_action: A boolean that indicates whether or not the use of elements in this block
+                should dispatch a block_actions payload. Defaults to false.
+            optional: A boolean that indicates whether the input element may be empty when a user submits the modal.
+                Defaults to false.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.label = TextObject.parse(label, default_type=PlainTextObject.type)
+        self.element = BlockElement.parse(element)  # type: ignore[arg-type]
+        self.hint = TextObject.parse(hint, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.dispatch_action = dispatch_action
+        self.optional = optional
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self):
+        return self.label is None or self.label.text is None or len(self.label.text) <= self.label_max_length
+
+    @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+    def _validate_hint_length(self):
+        return self.hint is None or self.hint.text is None or len(self.hint.text) <= self.label_max_length
+
+    @JsonValidator(
+        (
+            "element attribute must be a string, select element, multi-select element, "
+            "or a datepicker. (Sub-classes of InputInteractiveElement)"
+        )
+    )
+    def _validate_element_type(self):
+        return self.element is None or isinstance(self.element, (str, InputInteractiveElement))
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that collects information from users - it can hold a plain-text input element, +a select menu element, a multi-select menu element, or a datepicker. +https://docs.slack.dev/reference/block-kit/blocks/input-block

+

Args

+
+
label : required
+
A label that appears above an input element in the form of a text object +that must have type of plain_text. Maximum length for the text in this field is 2000 characters.
+
element : required
+
An plain-text input element, a checkbox element, a radio button element, +a select menu element, a multi-select menu element, or a datepicker.
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message or view and each iteration of a message or view. +If a message or view is updated, use a new block_id.
+
hint
+
An optional hint that appears below an input element in a lighter grey. +It must be a text object with a type of plain_text. +Maximum length for the text in this field is 2000 characters.
+
dispatch_action
+
A boolean that indicates whether or not the use of elements in this block +should dispatch a block_actions payload. Defaults to false.
+
optional
+
A boolean that indicates whether the input element may be empty when a user submits the modal. +Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var hint_max_length
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class InputInteractiveElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β TextObjectΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InputInteractiveElement(InteractiveElement, metaclass=ABCMeta):
+    placeholder_max_length = 150
+
+    attributes = {"type", "action_id", "placeholder", "confirm", "focus_on_load"}
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, TextObject]] = None,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """InteractiveElement that is usable in input blocks
+
+        We generally recommend using the concrete subclasses for better supports of available properties.
+        """
+        if subtype:
+            self._subtype_warning()
+        super().__init__(action_id=action_id, type=type or subtype)
+
+        # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here.
+        # It's fine to pass any kwargs to the held dict here although the class does not do any validation.
+        # show_unknown_key_warning(self, others)
+
+        self.placeholder = TextObject.parse(placeholder)  # type: ignore[arg-type]
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+        self.focus_on_load = focus_on_load
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def _validate_placeholder_length(self) -> bool:
+        return (
+            self.placeholder is None
+            or self.placeholder.text is None
+            or len(self.placeholder.text) <= self.placeholder_max_length
+        )
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

InteractiveElement that is usable in input blocks

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class InteractiveElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class InteractiveElement(BlockElement):
+    action_id_max_length = 255
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"alt_text", "action_id"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        **others: dict,
+    ):
+        """An interactive block element.
+
+        We generally recommend using the concrete subclasses for better supports of available properties.
+        """
+        if subtype:
+            self._subtype_warning()
+        super().__init__(type=type or subtype)
+
+        # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here.
+        # It's fine to pass any kwargs to the held dict here although the class does not do any validation.
+        # show_unknown_key_warning(self, others)
+
+        self.action_id = action_id
+
+    @JsonValidator(f"action_id attribute cannot exceed {action_id_max_length} characters")
+    def _validate_action_id_length(self) -> bool:
+        return self.action_id is None or len(self.action_id) <= self.action_id_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An interactive block element.

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var action_id_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"alt_text", "action_id"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class LinkButtonElement +(*,
text:Β strΒ |Β dictΒ |Β PlainTextObject,
url:Β str,
action_id:Β strΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class LinkButtonElement(ButtonElement):
+    def __init__(
+        self,
+        *,
+        text: Union[str, dict, PlainTextObject],
+        url: str,
+        action_id: Optional[str] = None,
+        style: Optional[str] = None,
+        **others: dict,
+    ):
+        """A simple button that simply opens a given URL. You will still receive an
+        interaction payload and will need to send an acknowledgement response.
+        This is a helper class that makes creating links simpler.
+        https://docs.slack.dev/reference/block-kit/block-elements/button-element/
+
+        Args:
+            text (required): A text object that defines the button's text.
+                Can only be of type: plain_text.
+                Maximum length for the text in this field is 75 characters.
+            url (required): A URL to load in the user's browser when the button is clicked.
+                Maximum length for this field is 3000 characters.
+                If you're using url, you'll still receive an interaction payload
+                and will need to send an acknowledgement response.
+            action_id (required): An identifier for this action.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            style: Decorates buttons with alternative visual color schemes. Use this option with restraint.
+                "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions.
+                "primary" should only be used for one button within a set.
+                "danger" gives buttons a red outline and text, and should be used when the action is destructive.
+                Use "danger" even more sparingly than "primary".
+                If you don't include this field, the default button style will be used.
+        """
+        super().__init__(
+            # NOTE: value must be always absent
+            text=text,
+            url=url,
+            action_id=action_id,
+            value=None,
+            style=style,
+        )
+        show_unknown_key_warning(self, others)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A simple button that simply opens a given URL. You will still receive an +interaction payload and will need to send an acknowledgement response. +This is a helper class that makes creating links simpler. +https://docs.slack.dev/reference/block-kit/block-elements/button-element/

+

Args

+
+
text : required
+
A text object that defines the button's text. +Can only be of type: plain_text. +Maximum length for the text in this field is 75 characters.
+
url : required
+
A URL to load in the user's browser when the button is clicked. +Maximum length for this field is 3000 characters. +If you're using url, you'll still receive an interaction payload +and will need to send an acknowledgement response.
+
action_id : required
+
An identifier for this action. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
style
+
Decorates buttons with alternative visual color schemes. Use this option with restraint. +"primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. +"primary" should only be used for one button within a set. +"danger" gives buttons a red outline and text, and should be used when the action is destructive. +Use "danger" even more sparingly than "primary". +If you don't include this field, the default button style will be used.
+
+

Ancestors

+ +

Inherited members

+ +
+
+class MarkdownBlock +(*, text:Β str, block_id:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class MarkdownBlock(Block):
+    type = "markdown"
+    text_max_length = 12000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text"})
+
+    def __init__(
+        self,
+        *,
+        text: str,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays formatted markdown.
+        https://docs.slack.dev/reference/block-kit/blocks/markdown-block/
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (required): The standard markdown-formatted text. Limit 12,000 characters max.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = text
+
+    @JsonValidator("text attribute must be specified")
+    def _validate_text(self):
+        return self.text != ""
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return len(self.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays formatted markdown. +https://docs.slack.dev/reference/block-kit/blocks/markdown-block/

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : required
+
The standard markdown-formatted text. Limit 12,000 characters max.
+
+

Ancestors

+ +

Class variables

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class MarkdownTextObject +(*, text:Β str, verbatim:Β boolΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class MarkdownTextObject(TextObject):
+    """mrkdwn typed text object"""
+
+    type = "mrkdwn"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"verbatim"})
+
+    def __init__(self, *, text: str, verbatim: Optional[bool] = None):
+        """A Markdown text object, meaning markdown characters will be parsed as
+        formatting information.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object
+
+        Args:
+            text (required): The text for the block. This field accepts any of the standard text formatting markup
+                when type is mrkdwn.
+            verbatim: When set to false (as is default) URLs will be auto-converted into links,
+                conversation names will be link-ified, and certain mentions will be automatically parsed.
+                Using a value of true will skip any preprocessing of this nature,
+                although you can still include manual parsing strings. This field is only usable when type is mrkdwn.
+        """
+        super().__init__(text=text, type=self.type)
+        self.verbatim = verbatim
+
+    @staticmethod
+    def from_str(text: str) -> "MarkdownTextObject":
+        """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+        return MarkdownTextObject(text=text)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+        return MarkdownTextObject.from_str(text).to_dict()
+
+    @staticmethod
+    def from_link(link: Link, title: str = "") -> "MarkdownTextObject":
+        """
+        Transform a Link object directly into the required object shape
+        to act as a MarkdownTextObject
+        """
+        if title:
+            title = f": {title}"
+        return MarkdownTextObject(text=f"{link}{title}")
+
+    @staticmethod
+    def direct_from_link(link: Link, title: str = "") -> Dict[str, Any]:
+        """
+        Transform a Link object directly into the required object shape
+        to act as a MarkdownTextObject
+        """
+        return MarkdownTextObject.from_link(link, title).to_dict()
+
+

mrkdwn typed text object

+

A Markdown text object, meaning markdown characters will be parsed as +formatting information. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object

+

Args

+
+
text : required
+
The text for the block. This field accepts any of the standard text formatting markup +when type is mrkdwn.
+
verbatim
+
When set to false (as is default) URLs will be auto-converted into links, +conversation names will be link-ified, and certain mentions will be automatically parsed. +Using a value of true will skip any preprocessing of this nature, +although you can still include manual parsing strings. This field is only usable when type is mrkdwn.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+ +
+
+ +Expand source code + +
@staticmethod
+def direct_from_link(link: Link, title: str = "") -> Dict[str, Any]:
+    """
+    Transform a Link object directly into the required object shape
+    to act as a MarkdownTextObject
+    """
+    return MarkdownTextObject.from_link(link, title).to_dict()
+
+

Transform a Link object directly into the required object shape +to act as a MarkdownTextObject

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+    return MarkdownTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a MarkdownTextObject

+
+ +
+
+ +Expand source code + +
@staticmethod
+def from_link(link: Link, title: str = "") -> "MarkdownTextObject":
+    """
+    Transform a Link object directly into the required object shape
+    to act as a MarkdownTextObject
+    """
+    if title:
+        title = f": {title}"
+    return MarkdownTextObject(text=f"{link}{title}")
+
+

Transform a Link object directly into the required object shape +to act as a MarkdownTextObject

+
+
+def from_str(text:Β str) ‑>Β MarkdownTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "MarkdownTextObject":
+    """Transforms a string into the required object shape to act as a MarkdownTextObject"""
+    return MarkdownTextObject(text=text)
+
+

Transforms a string into the required object shape to act as a MarkdownTextObject

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"verbatim"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class NumberInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
is_decimal_allowed:Β boolΒ |Β NoneΒ =Β False,
initial_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
min_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
max_value:Β intΒ |Β floatΒ |Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class NumberInputElement(InputInteractiveElement):
+    type = "number_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "is_decimal_allowed",
+                "min_value",
+                "max_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        is_decimal_allowed: Optional[bool] = False,
+        initial_value: Optional[Union[int, float, str]] = None,
+        min_value: Optional[Union[int, float, str]] = None,
+        max_value: Optional[Union[int, float, str]] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        https://docs.slack.dev/reference/block-kit/block-elements/number-input-element/
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            is_decimal_allowed (required): Decimal numbers are allowed if is_decimal_allowed= true, set the value to
+                false otherwise.
+            initial_value: The initial value in the number input when it is loaded.
+            min_value: The minimum value, cannot be greater than max_value.
+            max_value: The maximum value, cannot be less than min_value.
+            dispatch_action_config: A dispatch configuration object that determines when
+                during text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown
+                in the plain-text input. Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = str(initial_value) if initial_value is not None else None
+        self.is_decimal_allowed = is_decimal_allowed
+        self.min_value = str(min_value) if min_value is not None else None
+        self.max_value = str(max_value) if max_value is not None else None
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

https://docs.slack.dev/reference/block-kit/block-elements/number-input-element/

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
is_decimal_allowed : required
+
Decimal numbers are allowed if is_decimal_allowed= true, set the value to +false otherwise.
+
initial_value
+
The initial value in the number input when it is loaded.
+
min_value
+
The minimum value, cannot be greater than max_value.
+
max_value
+
The maximum value, cannot be less than min_value.
+
dispatch_action_config
+
A dispatch configuration object that determines when +during text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown +in the plain-text input. Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "is_decimal_allowed",
+            "min_value",
+            "max_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class Option +(*,
value:Β str,
label:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
description:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
url:Β strΒ |Β NoneΒ =Β None,
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class Option(JsonObject):
+    """Option object used in dialogs, legacy message actions (interactivity in attachments),
+    and blocks. JSON must be retrieved with an explicit option_type - the Slack API has
+    different required formats in different situations
+    """
+
+    attributes: Set[str] = set()
+    logger = logging.getLogger(__name__)
+
+    label_max_length = 75
+    value_max_length = 150
+
+    def __init__(
+        self,
+        *,
+        value: str,
+        label: Optional[str] = None,
+        text: Optional[Union[str, Dict[str, Any], TextObject]] = None,  # Block Kit
+        description: Optional[Union[str, Dict[str, Any], TextObject]] = None,
+        url: Optional[str] = None,
+        **others: Dict[str, Any],
+    ):
+        """
+        An object that represents a single selectable item in a block element (
+        SelectElement, OverflowMenuElement) or dialog element
+        (StaticDialogSelectElement)
+
+        Blocks:
+        https://docs.slack.dev/reference/block-kit/composition-objects/option-object
+
+        Dialogs:
+        https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+
+        Legacy interactive attachments:
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_fields
+
+        Args:
+            label: A short, user-facing string to label this option to users.
+                Cannot exceed 75 characters.
+            value: A short string that identifies this particular option to your
+                application. It will be part of the payload when this option is selected
+                . Cannot exceed 150 characters.
+            description: A user-facing string that provides more details about
+                this option. Only supported in legacy message actions, not in blocks or
+                dialogs.
+        """
+        if text:
+            # For better compatibility with Block Kit ("mrkdwn" does not work for it),
+            # we've changed the default text object type to plain_text since version 3.10.0
+            self._text: Optional[TextObject] = TextObject.parse(
+                text=text,  # "text" here can be either a str or a TextObject
+                default_type=PlainTextObject.type,
+            )
+            self._label: Optional[str] = None
+        else:
+            self._text = None
+            self._label = label
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        self.text: Optional[str] = self._text.text if self._text else None
+        self.label: Optional[str] = self._label
+
+        self.value: str = value
+
+        # for backward-compatibility with version 2.0-2.5, the following fields return str values
+        if isinstance(description, str):
+            self.description = description
+            self._block_description = PlainTextObject.from_str(description)
+        elif isinstance(description, dict):
+            self.description = description["text"]
+            self._block_description = TextObject.parse(description)  # type: ignore[assignment]
+        elif isinstance(description, TextObject):
+            self.description = description.text
+            self._block_description = description  # type: ignore[assignment]
+        else:
+            self.description = None  # type: ignore[assignment]
+            self._block_description = None  # type: ignore[assignment]
+
+        # A URL to load in the user's browser when the option is clicked.
+        # The url attribute is only available in overflow menus.
+        # Maximum length for this field is 3000 characters.
+        # If you're using url, you'll still receive an interaction payload
+        # and will need to send an acknowledgement response.
+        self.url: Optional[str] = url
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self) -> bool:
+        return self._label is None or len(self._label) <= self.label_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {label_max_length} characters")
+    def _validate_text_length(self) -> bool:
+        return self._text is None or self._text.text is None or len(self._text.text) <= self.label_max_length
+
+    @JsonValidator(f"value attribute cannot exceed {value_max_length} characters")
+    def _validate_value_length(self) -> bool:
+        return len(self.value) <= self.value_max_length
+
+    @classmethod
+    def parse_all(cls, options: Optional[Sequence[Union[Dict[str, Any], "Option"]]]) -> Optional[List["Option"]]:
+        if options is None:
+            return None
+        option_objects: List[Option] = []
+        for o in options:
+            if isinstance(o, dict):
+                d = copy.copy(o)
+                option_objects.append(Option(**d))
+            elif isinstance(o, Option):
+                option_objects.append(o)
+            else:
+                cls.logger.warning(f"Unknown option object detected and skipped ({o})")
+        return option_objects
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        """
+        Different parent classes must call this with a valid value from OptionTypes -
+        either "dialog", "action", or "block", so that JSON is returned in the
+        correct shape.
+        """
+        self.validate_json()
+        if option_type == "dialog":
+            return {"label": self.label, "value": self.value}
+        elif option_type == "action" or option_type == "attachment":
+            # "action" can be confusing but it means a legacy message action in attachments
+            # we don't remove the type name for backward compatibility though
+            json: Dict[str, Any] = {"text": self.label, "value": self.value}
+            if self.description is not None:
+                json["description"] = self.description
+            return json
+        else:  # if option_type == "block"; this should be the most common case
+            text: TextObject = self._text or PlainTextObject.from_str(self.label)  # type: ignore[arg-type]
+            json = {
+                "text": text.to_dict(),
+                "value": self.value,
+            }
+            if self._block_description:
+                json["description"] = self._block_description.to_dict()
+            if self.url:
+                json["url"] = self.url
+            return json
+
+    @staticmethod
+    def from_single_value(value_and_label: str):
+        """Creates a simple Option instance with the same value and label"""
+        return Option(value=value_and_label, label=value_and_label)
+
+

Option object used in dialogs, legacy message actions (interactivity in attachments), +and blocks. JSON must be retrieved with an explicit option_type - the Slack API has +different required formats in different situations

+

An object that represents a single selectable item in a block element ( +SelectElement, OverflowMenuElement) or dialog element +(StaticDialogSelectElement)

+

Blocks: +https://docs.slack.dev/reference/block-kit/composition-objects/option-object

+

Dialogs: +https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Legacy interactive attachments: +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_fields

+

Args

+
+
label
+
A short, user-facing string to label this option to users. +Cannot exceed 75 characters.
+
value
+
A short string that identifies this particular option to your +application. It will be part of the payload when this option is selected +. Cannot exceed 150 characters.
+
description
+
A user-facing string that provides more details about +this option. Only supported in legacy message actions, not in blocks or +dialogs.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
var value_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_single_value(value_and_label:Β str) +
+
+
+ +Expand source code + +
@staticmethod
+def from_single_value(value_and_label: str):
+    """Creates a simple Option instance with the same value and label"""
+    return Option(value=value_and_label, label=value_and_label)
+
+

Creates a simple Option instance with the same value and label

+
+
+def parse_all(options:Β Sequence[Dict[str,Β Any]Β |Β ForwardRef('Option')]Β |Β None) ‑>Β List[Option]Β |Β None +
+
+
+
+
+

Methods

+
+
+def to_dict(self, option_type:Β strΒ =Β 'block') ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+    """
+    Different parent classes must call this with a valid value from OptionTypes -
+    either "dialog", "action", or "block", so that JSON is returned in the
+    correct shape.
+    """
+    self.validate_json()
+    if option_type == "dialog":
+        return {"label": self.label, "value": self.value}
+    elif option_type == "action" or option_type == "attachment":
+        # "action" can be confusing but it means a legacy message action in attachments
+        # we don't remove the type name for backward compatibility though
+        json: Dict[str, Any] = {"text": self.label, "value": self.value}
+        if self.description is not None:
+            json["description"] = self.description
+        return json
+    else:  # if option_type == "block"; this should be the most common case
+        text: TextObject = self._text or PlainTextObject.from_str(self.label)  # type: ignore[arg-type]
+        json = {
+            "text": text.to_dict(),
+            "value": self.value,
+        }
+        if self._block_description:
+            json["description"] = self._block_description.to_dict()
+        if self.url:
+            json["url"] = self.url
+        return json
+
+

Different parent classes must call this with a valid value from OptionTypes - +either "dialog", "action", or "block", so that JSON is returned in the +correct shape.

+
+
+

Inherited members

+ +
+
+class OptionGroup +(*,
label:Β strΒ |Β Dict[str,Β Any]Β |Β TextObjectΒ |Β NoneΒ =Β None,
options:Β Sequence[Dict[str,Β Any]Β |Β Option],
**others:Β Dict[str,Β Any])
+
+
+
+ +Expand source code + +
class OptionGroup(JsonObject):
+    """
+    JSON must be retrieved with an explicit option_type - the Slack API has
+    different required formats in different situations
+    """
+
+    attributes: Set[str] = set()
+    label_max_length = 75
+    options_max_length = 100
+    logger = logging.getLogger(__name__)
+
+    def __init__(
+        self,
+        *,
+        label: Optional[Union[str, Dict[str, Any], TextObject]] = None,
+        options: Sequence[Union[Dict[str, Any], Option]],
+        **others: Dict[str, Any],
+    ):
+        """
+        Create a group of Option objects - pass in a label (that will be part of the
+        UI) and a list of Option objects.
+
+        Blocks:
+        https://docs.slack.dev/reference/block-kit/composition-objects/option-group-object
+
+        Dialogs:
+        https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+
+        Legacy interactive attachments:
+        https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_groups
+
+        Args:
+            label: Text to display at the top of this group of options.
+            options: A list of no more than 100 Option objects.
+        """  # noqa prevent flake8 blowing up on the long URL
+        # default_type=PlainTextObject.type is for backward-compatibility
+        self._label: Optional[TextObject] = TextObject.parse(label, default_type=PlainTextObject.type)  # type: ignore[arg-type] # noqa: E501
+        self.label: Optional[str] = self._label.text if self._label else None
+        self.options = Option.parse_all(options)  # compatible with version 2.5
+        show_unknown_key_warning(self, others)
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def _validate_label_length(self):
+        return self.label is None or len(self.label) <= self.label_max_length
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self):
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @classmethod
+    def parse_all(
+        cls, option_groups: Optional[Sequence[Union[Dict[str, Any], "OptionGroup"]]]
+    ) -> Optional[List["OptionGroup"]]:
+        if option_groups is None:
+            return None
+        option_group_objects = []
+        for o in option_groups:
+            if isinstance(o, dict):
+                d = copy.copy(o)
+                option_group_objects.append(OptionGroup(**d))
+            elif isinstance(o, OptionGroup):
+                option_group_objects.append(o)
+            else:
+                cls.logger.warning(f"Unknown option group object detected and skipped ({o})")
+        return option_group_objects
+
+    def to_dict(self, option_type: str = "block") -> Dict[str, Any]:
+        self.validate_json()
+        dict_options = [o.to_dict(option_type) for o in self.options]  # type: ignore[union-attr]
+        if option_type == "dialog":
+            return {
+                "label": self.label,
+                "options": dict_options,
+            }
+        elif option_type == "action":
+            return {
+                "text": self.label,
+                "options": dict_options,
+            }
+        else:  # if option_type == "block"; this should be the most common case
+            dict_label: Dict[str, Any] = self._label.to_dict()  # type: ignore[union-attr]
+            return {
+                "label": dict_label,
+                "options": dict_options,
+            }
+
+

JSON must be retrieved with an explicit option_type - the Slack API has +different required formats in different situations

+

Create a group of Option objects - pass in a label (that will be part of the +UI) and a list of Option objects.

+

Blocks: +https://docs.slack.dev/reference/block-kit/composition-objects/option-group-object

+

Dialogs: +https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Legacy interactive attachments: +https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_groups

+

Args

+
+
label
+
Text to display at the top of this group of options.
+
options
+
A list of no more than 100 Option objects.
+
+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse_all(option_groups:Β Sequence[Dict[str,Β Any]Β |Β ForwardRef('OptionGroup')]Β |Β None) ‑>Β List[OptionGroup]Β |Β None +
+
+
+
+
+

Inherited members

+ +
+
+class OverflowMenuElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option],
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class OverflowMenuElement(InteractiveElement):
+    type = "overflow"
+    options_min_length = 1
+    options_max_length = 5
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"confirm", "options"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Sequence[Option],
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        **others: dict,
+    ):
+        """
+        This is like a cross between a button and a select menu - when a user clicks
+        on this overflow button, they will be presented with a list of options to
+        choose from. Unlike the select menu, there is no typeahead field, and the
+        button always appears with an ellipsis ("…") rather than customisable text.
+
+        As such, it is usually used if you want a more compact layout than a select
+        menu, or to supply a list of less visually important actions after a row of
+        buttons. You can also specify simple URL links as overflow menu options,
+        instead of actions.
+
+        https://docs.slack.dev/reference/block-kit/block-elements/overflow-menu-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects to display in the menu.
+                Maximum number of options is 5, minimum is 1.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after a menu item is selected.
+        """
+        super().__init__(action_id=action_id, type=self.type)
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.confirm = ConfirmObject.parse(confirm)  # type: ignore[arg-type]
+
+    @JsonValidator(f"options attribute must have between {options_min_length} " f"and {options_max_length} items")
+    def _validate_options_length(self) -> bool:
+        return self.options_min_length <= len(self.options) <= self.options_max_length
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is like a cross between a button and a select menu - when a user clicks +on this overflow button, they will be presented with a list of options to +choose from. Unlike the select menu, there is no typeahead field, and the +button always appears with an ellipsis ("…") rather than customisable text.

+

As such, it is usually used if you want a more compact layout than a select +menu, or to supply a list of less visually important actions after a row of +buttons. You can also specify simple URL links as overflow menu options, +instead of actions.

+

https://docs.slack.dev/reference/block-kit/block-elements/overflow-menu-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects to display in the menu. +Maximum number of options is 5, minimum is 1.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after a menu item is selected.
+
+

Ancestors

+ +

Class variables

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var options_min_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class PlainTextInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
multiline:Β boolΒ |Β NoneΒ =Β None,
min_length:Β intΒ |Β NoneΒ =Β None,
max_length:Β intΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class PlainTextInputElement(InputInteractiveElement):
+    type = "plain_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "multiline",
+                "min_length",
+                "max_length",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_value: Optional[str] = None,
+        multiline: Optional[bool] = None,
+        min_length: Optional[int] = None,
+        max_length: Optional[int] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        A plain-text input, similar to the HTML <input> tag, creates a field
+        where a user can enter freeform data. It can appear as a single-line
+        field or a larger textarea using the multiline flag. Plain-text input
+        elements can be used inside of SectionBlocks and ActionsBlocks.
+        https://docs.slack.dev/reference/block-kit/block-elements/plain-text-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown
+                in the plain-text input. Maximum length for the text in this field is 150 characters.
+            initial_value: The initial value in the plain-text input when it is loaded.
+            multiline: Indicates whether the input will be a single line (false) or a larger textarea (true).
+                Defaults to false.
+            min_length: The minimum length of input that the user must provide. If the user provides less,
+                they will receive an error. Maximum value is 3000.
+            max_length: The maximum length of input that the user can provide. If the user provides more,
+                they will receive an error.
+            dispatch_action_config: A dispatch configuration object that determines when
+                during text input the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.multiline = multiline
+        self.min_length = min_length
+        self.max_length = max_length
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A plain-text input, similar to the HTML tag, creates a field +where a user can enter freeform data. It can appear as a single-line +field or a larger textarea using the multiline flag. Plain-text input +elements can be used inside of SectionBlocks and ActionsBlocks. +https://docs.slack.dev/reference/block-kit/block-elements/plain-text-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown +in the plain-text input. Maximum length for the text in this field is 150 characters.
+
initial_value
+
The initial value in the plain-text input when it is loaded.
+
multiline
+
Indicates whether the input will be a single line (false) or a larger textarea (true). +Defaults to false.
+
min_length
+
The minimum length of input that the user must provide. If the user provides less, +they will receive an error. Maximum value is 3000.
+
max_length
+
The maximum length of input that the user can provide. If the user provides more, +they will receive an error.
+
dispatch_action_config
+
A dispatch configuration object that determines when +during text input the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "multiline",
+            "min_length",
+            "max_length",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class PlainTextObject +(*, text:Β str, emoji:Β boolΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
class PlainTextObject(TextObject):
+    """plain_text typed text object"""
+
+    type = "plain_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"emoji"})
+
+    def __init__(self, *, text: str, emoji: Optional[bool] = None):
+        """A plain text object, meaning markdown characters will not be parsed as
+        formatting information.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object
+
+        Args:
+            text (required): The text for the block. This field accepts any of the standard text formatting markup
+                when type is mrkdwn.
+            emoji: Indicates whether emojis in a text field should be escaped into the colon emoji format.
+                This field is only usable when type is plain_text.
+        """
+        super().__init__(text=text, type=self.type)
+        self.emoji = emoji
+
+    @staticmethod
+    def from_str(text: str) -> "PlainTextObject":
+        return PlainTextObject(text=text, emoji=True)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a PlainTextObject"""
+        return PlainTextObject.from_str(text).to_dict()
+
+

plain_text typed text object

+

A plain text object, meaning markdown characters will not be parsed as +formatting information. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object

+

Args

+
+
text : required
+
The text for the block. This field accepts any of the standard text formatting markup +when type is mrkdwn.
+
emoji
+
Indicates whether emojis in a text field should be escaped into the colon emoji format. +This field is only usable when type is plain_text.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a PlainTextObject"""
+    return PlainTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a PlainTextObject

+
+
+def from_str(text:Β str) ‑>Β PlainTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "PlainTextObject":
+    return PlainTextObject(text=text, emoji=True)
+
+
+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"emoji"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RadioButtonsElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
initial_option:Β dictΒ |Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RadioButtonsElement(InputInteractiveElement):
+    type = "radio_buttons"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        initial_option: Optional[Union[dict, Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A radio button group that allows a user to choose one item from a list of possible options.
+        https://docs.slack.dev/reference/block-kit/block-elements/radio-button-group-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when the radio button group is changed.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (required): An array of option objects. A maximum of 10 options are allowed.
+            initial_option: An option object that exactly matches one of the options.
+                This option will be selected when the radio button group initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                after clicking one of the radio buttons in this element.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.initial_option = initial_option
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A radio button group that allows a user to choose one item from a list of possible options. +https://docs.slack.dev/reference/block-kit/block-elements/radio-button-group-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when the radio button group is changed. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : required
+
An array of option objects. A maximum of 10 options are allowed.
+
initial_option
+
An option object that exactly matches one of the options. +This option will be selected when the radio button group initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +after clicking one of the radio buttons in this element.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RawTextObject +(*, text:Β str) +
+
+
+ +Expand source code + +
class RawTextObject(TextObject):
+    """raw_text typed text object"""
+
+    type = "raw_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return {"text", "type"}
+
+    def __init__(self, *, text: str):
+        """A raw text object used in table block cells.
+        https://docs.slack.dev/reference/block-kit/composition-objects/text-object/
+        https://docs.slack.dev/reference/block-kit/blocks/table-block
+
+        Args:
+            text (required): The text content for the table block cell.
+        """
+        super().__init__(text=text, type=self.type)
+
+    @staticmethod
+    def from_str(text: str) -> "RawTextObject":
+        """Transforms a string into a RawTextObject"""
+        return RawTextObject(text=text)
+
+    @staticmethod
+    def direct_from_string(text: str) -> Dict[str, Any]:
+        """Transforms a string into the required object shape to act as a RawTextObject"""
+        return RawTextObject.from_str(text).to_dict()
+
+    @JsonValidator("text attribute must have at least 1 character")
+    def _validate_text_min_length(self):
+        return len(self.text) >= 1
+
+

raw_text typed text object

+

A raw text object used in table block cells. +https://docs.slack.dev/reference/block-kit/composition-objects/text-object/ +https://docs.slack.dev/reference/block-kit/blocks/table-block

+

Args

+
+
text : required
+
The text content for the table block cell.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def direct_from_string(text:Β str) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
@staticmethod
+def direct_from_string(text: str) -> Dict[str, Any]:
+    """Transforms a string into the required object shape to act as a RawTextObject"""
+    return RawTextObject.from_str(text).to_dict()
+
+

Transforms a string into the required object shape to act as a RawTextObject

+
+
+def from_str(text:Β str) ‑>Β RawTextObject +
+
+
+ +Expand source code + +
@staticmethod
+def from_str(text: str) -> "RawTextObject":
+    """Transforms a string into a RawTextObject"""
+    return RawTextObject(text=text)
+
+

Transforms a string into a RawTextObject

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return {"text", "type"}
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextBlock +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextBlock(Block):
+    type = "rich_text"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """A block that is used to hold interactive elements.
+        https://docs.slack.dev/reference/block-kit/blocks/rich-text-block
+
+        Args:
+            elements (required): An array of rich text objects -
+                rich_text_section, rich_text_list, rich_text_quote, rich_text_preformatted
+            block_id: A unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message or view and each iteration of a message or view.
+                If a message or view is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.elements = BlockElement.parse_all(elements)
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A block that is used to hold interactive elements. +https://docs.slack.dev/reference/block-kit/blocks/rich-text-block

+

Args

+
+
elements : required
+
An array of rich text objects - +rich_text_section, rich_text_list, rich_text_quote, rich_text_preformatted
+
block_id
+
A unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message or view and each iteration of a message or view. +If a message or view is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextElement +(*, type:Β strΒ |Β NoneΒ =Β None, subtype:Β strΒ |Β NoneΒ =Β None, **others:Β dict) +
+
+
+ +Expand source code + +
class RichTextElement(BlockElement):
+    pass
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Subclasses

+ +

Inherited members

+ +
+
+class RichTextElementParts +
+
+
+ +Expand source code + +
class RichTextElementParts:
+    class TextStyle:
+        def __init__(
+            self,
+            *,
+            bold: Optional[bool] = None,
+            italic: Optional[bool] = None,
+            strike: Optional[bool] = None,
+            code: Optional[bool] = None,
+            underline: Optional[bool] = None,
+        ):
+            self.bold = bold
+            self.italic = italic
+            self.strike = strike
+            self.code = code
+            self.underline = underline
+
+        def to_dict(self, *args) -> dict:
+            result = {
+                "bold": self.bold,
+                "italic": self.italic,
+                "strike": self.strike,
+                "code": self.code,
+                "underline": self.underline,
+            }
+            return {k: v for k, v in result.items() if v is not None}
+
+    class Text(RichTextElement):
+        type = "text"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"text", "style"})
+
+        def __init__(
+            self,
+            *,
+            text: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.text = text
+            self.style = style
+
+    class Channel(RichTextElement):
+        type = "channel"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"channel_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            channel_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.channel_id = channel_id
+            self.style = style
+
+    class User(RichTextElement):
+        type = "user"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"user_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            user_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.user_id = user_id
+            self.style = style
+
+    class Emoji(RichTextElement):
+        type = "emoji"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"name", "skin_tone", "unicode", "style"})
+
+        def __init__(
+            self,
+            *,
+            name: str,
+            skin_tone: Optional[int] = None,
+            unicode: Optional[str] = None,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.name = name
+            self.skin_tone = skin_tone
+            self.unicode = unicode
+            self.style = style
+
+    class Link(RichTextElement):
+        type = "link"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"url", "text", "style"})
+
+        def __init__(
+            self,
+            *,
+            url: str,
+            text: Optional[str] = None,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.url = url
+            self.text = text
+            self.style = style
+
+    class Team(RichTextElement):
+        type = "team"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"team_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            team_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.team_id = team_id
+            self.style = style
+
+    class UserGroup(RichTextElement):
+        type = "usergroup"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"usergroup_id", "style"})
+
+        def __init__(
+            self,
+            *,
+            usergroup_id: str,
+            style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.usergroup_id = usergroup_id
+            self.style = style
+
+    class Date(RichTextElement):
+        type = "date"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"timestamp", "format", "url", "fallback"})
+
+        def __init__(
+            self,
+            *,
+            timestamp: int,
+            format: str,
+            url: Optional[str] = None,
+            fallback: Optional[str] = None,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.timestamp = timestamp
+            self.format = format
+            self.url = url
+            self.fallback = fallback
+
+    class Broadcast(RichTextElement):
+        type = "broadcast"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"range"})
+
+        def __init__(
+            self,
+            *,
+            range: str,  # channel, here, ..
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.range = range
+
+    class Color(RichTextElement):
+        type = "color"
+
+        @property
+        def attributes(self) -> Set[str]:  # type: ignore[override]
+            return super().attributes.union({"value"})
+
+        def __init__(
+            self,
+            *,
+            value: str,
+            **others: dict,
+        ):
+            super().__init__(type=self.type)
+            show_unknown_key_warning(self, others)
+            self.value = value
+
+
+

Class variables

+
+
var Broadcast
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Channel
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Color
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Date
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Emoji
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+ +
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Team
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var Text
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var TextStyle
+
+

The type of the None singleton.

+
+
var User
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
var UserGroup
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+
+
+
+
+class RichTextInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_value:Β Dict[str,Β Any]Β |Β ForwardRef('RichTextBlock')Β |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextInputElement(InputInteractiveElement):
+    type = "rich_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        # To avoid circular imports, the RichTextBlock type here is intentionally a string
+        initial_value: Optional[Union[Dict[str, Any], "RichTextBlock"]] = None,  # type: ignore[name-defined] # noqa: F821
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

InteractiveElement that is usable in input blocks

+

We generally recommend using the concrete subclasses for better supports of available properties.

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextListElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
style:Β strΒ |Β NoneΒ =Β None,
indent:Β intΒ |Β NoneΒ =Β None,
offset:Β intΒ |Β NoneΒ =Β None,
border:Β intΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextListElement(RichTextElement):
+    type = "rich_text_list"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements", "style", "indent", "offset", "border"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        style: Optional[str] = None,  # bullet, ordered
+        indent: Optional[int] = None,
+        offset: Optional[int] = None,
+        border: Optional[int] = None,
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+        self.style = style
+        self.indent = indent
+        self.offset = offset
+        self.border = border
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements", "style", "indent", "offset", "border"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextPreformattedElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
border:Β intΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextPreformattedElement(RichTextElement):
+    type = "rich_text_preformatted"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements", "border"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        border: Optional[int] = None,
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+        self.border = border
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements", "border"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextQuoteElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextQuoteElement(RichTextElement):
+    type = "rich_text_quote"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class RichTextSectionElement +(*,
elements:Β Sequence[dictΒ |Β RichTextElement],
**others:Β dict)
+
+
+
+ +Expand source code + +
class RichTextSectionElement(RichTextElement):
+    type = "rich_text_section"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"elements"})
+
+    def __init__(
+        self,
+        *,
+        elements: Sequence[Union[dict, RichTextElement]],
+        **others: dict,
+    ):
+        super().__init__(type=self.type)
+        show_unknown_key_warning(self, others)
+        self.elements = BlockElement.parse_all(elements)
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"elements"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class SectionBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
text:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
fields:Β Sequence[strΒ |Β dictΒ |Β TextObject]Β |Β NoneΒ =Β None,
accessory:Β dictΒ |Β BlockElementΒ |Β NoneΒ =Β None,
expand:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class SectionBlock(Block):
+    type = "section"
+    fields_max_length = 10
+    text_max_length = 3000
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"text", "fields", "accessory", "expand"})
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        text: Optional[Union[str, dict, TextObject]] = None,
+        fields: Optional[Sequence[Union[str, dict, TextObject]]] = None,
+        accessory: Optional[Union[dict, BlockElement]] = None,
+        expand: Optional[bool] = None,
+        **others: dict,
+    ):
+        """A section is one of the most flexible blocks available.
+        https://docs.slack.dev/reference/block-kit/blocks/section-block
+
+        Args:
+            block_id (required): A string acting as a unique identifier for a block.
+                If not specified, one will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            text (preferred): The text for the block, in the form of a text object.
+                Maximum length for the text in this field is 3000 characters.
+                This field is not required if a valid array of fields objects is provided instead.
+            fields (required if no text is provided): Required if no text is provided.
+                An array of text objects. Any text objects included with fields will be rendered
+                in a compact format that allows for 2 columns of side-by-side text.
+                Maximum number of items is 10. Maximum length for the text in each item is 2000 characters.
+            accessory: One of the available element objects.
+            expand: Whether or not this section block's text should always expand when rendered.
+                If false or not provided, it may be rendered with a 'see more' option to expand and show the full text.
+                For AI Assistant apps, this allows the app to post long messages without users needing
+                to click 'see more' to expand the message.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.text = TextObject.parse(text)  # type: ignore[arg-type]
+        field_objects = []
+        for f in fields or []:
+            if isinstance(f, str):
+                field_objects.append(MarkdownTextObject.from_str(f))
+            elif isinstance(f, TextObject):
+                field_objects.append(f)  # type: ignore[arg-type]
+            elif isinstance(f, dict) and "type" in f:
+                d = copy.copy(f)
+                t = d.pop("type")
+                if t == MarkdownTextObject.type:
+                    field_objects.append(MarkdownTextObject(**d))
+                else:
+                    field_objects.append(PlainTextObject(**d))  # type: ignore[arg-type]
+            else:
+                self.logger.warning(f"Unsupported filed detected and skipped {f}")
+        self.fields = field_objects
+        self.accessory = BlockElement.parse(accessory)  # type: ignore[arg-type]
+        self.expand = expand
+
+    @JsonValidator("text or fields attribute must be specified")
+    def _validate_text_or_fields_populated(self):
+        return self.text is not None or self.fields
+
+    @JsonValidator(f"fields attribute cannot exceed {fields_max_length} items")
+    def _validate_fields_length(self):
+        return self.fields is None or len(self.fields) <= self.fields_max_length
+
+    @JsonValidator(f"text attribute cannot exceed {text_max_length} characters")
+    def _validate_alt_text_length(self):
+        return self.text is None or len(self.text.text) <= self.text_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A section is one of the most flexible blocks available. +https://docs.slack.dev/reference/block-kit/blocks/section-block

+

Args

+
+
block_id : required
+
A string acting as a unique identifier for a block. +If not specified, one will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
text : preferred
+
The text for the block, in the form of a text object. +Maximum length for the text in this field is 3000 characters. +This field is not required if a valid array of fields objects is provided instead.
+
fields : required if no text is provided
+
Required if no text is provided. +An array of text objects. Any text objects included with fields will be rendered +in a compact format that allows for 2 columns of side-by-side text. +Maximum number of items is 10. Maximum length for the text in each item is 2000 characters.
+
accessory
+
One of the available element objects.
+
expand
+
Whether or not this section block's text should always expand when rendered. +If false or not provided, it may be rendered with a 'see more' option to expand and show the full text. +For AI Assistant apps, this allows the app to post long messages without users needing +to click 'see more' to expand the message.
+
+

Ancestors

+ +

Class variables

+
+
var fields_max_length
+
+

The type of the None singleton.

+
+
var text_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"text", "fields", "accessory", "expand"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class SelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[OptionGroup]Β |Β NoneΒ =Β None,
initial_option:Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class SelectElement(InputInteractiveElement):
+    type = "static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[str] = None,
+        options: Optional[Sequence[Option]] = None,
+        option_groups: Optional[Sequence[OptionGroup]] = None,
+        initial_option: Optional[Option] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_option: A single option that exactly matches one of the options or option_groups.
+                This option will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.option_groups = option_groups
+        self.initial_option = initial_option
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return not (self.options is not None and self.option_groups is not None)
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_option
+
A single option that exactly matches one of the options or option_groups. +This option will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class StaticMultiSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[OptionGroup]Β |Β NoneΒ =Β None,
initial_options:Β Sequence[Option]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class StaticMultiSelectElement(InputInteractiveElement):
+    type = "multi_static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Option]] = None,
+        option_groups: Optional[Sequence[OptionGroup]] = None,
+        initial_options: Optional[Sequence[Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#static_multi_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_options: An array of option objects that exactly match one or more of the options
+                within options or option_groups. These options will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = Option.parse_all(options)
+        self.option_groups = OptionGroup.parse_all(option_groups)
+        self.initial_options = Option.parse_all(initial_options)
+        self.max_selected_items = max_selected_items
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return self.options is None or self.option_groups is None
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#static_multi_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_options
+
An array of option objects that exactly match one or more of the options +within options or option_groups. These options will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class StaticSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None,
option_groups:Β Sequence[dictΒ |Β OptionGroup]Β |Β NoneΒ =Β None,
initial_option:Β dictΒ |Β OptionΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class StaticSelectElement(InputInteractiveElement):
+    type = "static_select"
+    options_max_length = 100
+    option_groups_max_length = 100
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"options", "option_groups", "initial_option"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        options: Optional[Sequence[Union[dict, Option]]] = None,
+        option_groups: Optional[Sequence[Union[dict, OptionGroup]]] = None,
+        initial_option: Optional[Union[dict, Option]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """This is the simplest form of select menu, with a static list of options passed in when defining the element.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            options (either options or option_groups is required): An array of option objects.
+                Maximum number of options is 100.
+                If option_groups is specified, this field should not be.
+            option_groups (either options or option_groups is required): An array of option group objects.
+                Maximum number of option groups is 100.
+                If options is specified, this field should not be.
+            initial_option: A single option that exactly matches one of the options or option_groups.
+                This option will be selected when the menu initially loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.options = options
+        self.option_groups = option_groups
+        self.initial_option = initial_option
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} elements")
+    def _validate_options_length(self) -> bool:
+        return self.options is None or len(self.options) <= self.options_max_length
+
+    @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements")
+    def _validate_option_groups_length(self) -> bool:
+        return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length
+
+    @JsonValidator("options and option_groups cannot both be specified")
+    def _validate_options_and_option_groups_both_specified(self) -> bool:
+        return not (self.options is not None and self.option_groups is not None)
+
+    @JsonValidator("options or option_groups must be specified")
+    def _validate_neither_options_or_option_groups_is_specified(self) -> bool:
+        return self.options is not None or self.option_groups is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This is the simplest form of select menu, with a static list of options passed in when defining the element. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
options : either options or option_groups is required
+
An array of option objects. +Maximum number of options is 100. +If option_groups is specified, this field should not be.
+
option_groups : either options or option_groups is required
+
An array of option group objects. +Maximum number of option groups is 100. +If options is specified, this field should not be.
+
initial_option
+
A single option that exactly matches one of the options or option_groups. +This option will be selected when the menu initially loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var option_groups_max_length
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"options", "option_groups", "initial_option"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class TableBlock +(*,
rows:Β Sequence[Sequence[Dict[str,Β Any]]],
column_settings:Β Sequence[Dict[str,Β Any]Β |Β None]Β |Β NoneΒ =Β None,
block_id:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class TableBlock(Block):
+    type = "table"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"rows", "column_settings"})
+
+    def __init__(
+        self,
+        *,
+        rows: Sequence[Sequence[Dict[str, Any]]],
+        column_settings: Optional[Sequence[Optional[Dict[str, Any]]]] = None,
+        block_id: Optional[str] = None,
+        **others: dict,
+    ):
+        """Displays structured information in a table.
+        https://docs.slack.dev/reference/block-kit/blocks/table-block
+
+        Args:
+            rows (required): An array consisting of table rows. Maximum 100 rows.
+                Each row object is an array with a max of 20 table cells.
+                Table cells can have a type of raw_text or rich_text.
+            column_settings: An array describing column behavior. If there are fewer items in the column_settings array
+                than there are columns in the table, then the items in the the column_settings array will describe
+                the same number of columns in the table as there are in the array itself.
+                Any additional columns will have the default behavior. Maximum 20 items.
+                See below for column settings schema.
+            block_id: A unique identifier for a block. If not specified, a block_id will be generated.
+                You can use this block_id when you receive an interaction payload to identify the source of the action.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.rows = rows
+        self.column_settings = column_settings
+
+    @JsonValidator("rows attribute must be specified")
+    def _validate_rows(self):
+        return self.rows is not None and len(self.rows) > 0
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

Displays structured information in a table. +https://docs.slack.dev/reference/block-kit/blocks/table-block

+

Args

+
+
rows : required
+
An array consisting of table rows. Maximum 100 rows. +Each row object is an array with a max of 20 table cells. +Table cells can have a type of raw_text or rich_text.
+
column_settings
+
An array describing column behavior. If there are fewer items in the column_settings array +than there are columns in the table, then the items in the the column_settings array will describe +the same number of columns in the table as there are in the array itself. +Any additional columns will have the default behavior. Maximum 20 items. +See below for column settings schema.
+
block_id
+
A unique identifier for a block. If not specified, a block_id will be generated. +You can use this block_id when you receive an interaction payload to identify the source of the action. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"rows", "column_settings"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class TextObject +(text:Β str,
type:Β strΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None,
emoji:Β boolΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class TextObject(JsonObject):
+    """The interface for text objects (types: plain_text, mrkdwn)"""
+
+    attributes = {"text", "type", "emoji"}
+    logger = logging.getLogger(__name__)
+
+    def _subtype_warning(self):
+        warnings.warn(
+            "subtype is deprecated since slackclient 2.6.0, use type instead",
+            DeprecationWarning,
+        )
+
+    @property
+    def subtype(self) -> Optional[str]:
+        return self.type
+
+    @classmethod
+    def parse(
+        cls,
+        text: Union[str, Dict[str, Any], "TextObject"],
+        default_type: str = "mrkdwn",
+    ) -> Optional["TextObject"]:
+        if not text:
+            return None
+        elif isinstance(text, str):
+            if default_type == PlainTextObject.type:
+                return PlainTextObject.from_str(text)
+            else:
+                return MarkdownTextObject.from_str(text)
+        elif isinstance(text, dict):
+            d = copy.copy(text)
+            t = d.pop("type")
+            if t == PlainTextObject.type:
+                return PlainTextObject(**d)
+            else:
+                return MarkdownTextObject(**d)
+        elif isinstance(text, TextObject):
+            return text
+        else:
+            cls.logger.warning(f"Unknown type ({type(text)}) detected when parsing a TextObject")
+            return None
+
+    def __init__(
+        self,
+        text: str,
+        type: Optional[str] = None,
+        subtype: Optional[str] = None,
+        emoji: Optional[bool] = None,
+        **kwargs,
+    ):
+        """Super class for new text "objects" used in Block kit"""
+        if subtype:
+            self._subtype_warning()
+
+        self.text = text
+        self.type = type if type else subtype
+        self.emoji = emoji
+
+

The interface for text objects (types: plain_text, mrkdwn)

+

Super class for new text "objects" used in Block kit

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def parse(text:Β strΒ |Β Dict[str,Β Any]Β |Β ForwardRef('TextObject'),
default_type:Β strΒ =Β 'mrkdwn') ‑>Β TextObjectΒ |Β None
+
+
+
+
+
+

Instance variables

+
+
prop subtype :Β strΒ |Β None
+
+
+ +Expand source code + +
@property
+def subtype(self) -> Optional[str]:
+    return self.type
+
+
+
+
+

Inherited members

+ +
+
+class TimePickerElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_time:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
timezone:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class TimePickerElement(InputInteractiveElement):
+    type = "timepicker"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_time", "timezone"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_time: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        timezone: Optional[str] = None,
+        **others: dict,
+    ):
+        """
+        An element which allows selection of a time of day.
+        On desktop clients, this time picker will take the form of a dropdown list
+        with free-text entry for precise choices.
+        On mobile clients, the time picker will use native time picker UIs.
+        https://docs.slack.dev/reference/block-kit/block-elements/time-picker-element
+
+        Args:
+            action_id (required): An identifier for the action triggered when a time is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder: A plain_text only text object that defines the placeholder text shown on the timepicker.
+                Maximum length for the text in this field is 150 characters.
+            initial_time: The initial time that is selected when the element is loaded.
+                This should be in the format HH:mm, where HH is the 24-hour format of an hour (00 to 23)
+                and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a time is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            timezone: The timezone to consider for this input value.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_time = initial_time
+        self.timezone = timezone
+
+    @JsonValidator("initial_time attribute must be in format 'HH:mm'")
+    def _validate_initial_time_valid(self) -> bool:
+        return self.initial_time is None or re.match(r"([0-1][0-9]|2[0-3]):([0-5][0-9])", self.initial_time) is not None
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

An element which allows selection of a time of day. +On desktop clients, this time picker will take the form of a dropdown list +with free-text entry for precise choices. +On mobile clients, the time picker will use native time picker UIs. +https://docs.slack.dev/reference/block-kit/block-elements/time-picker-element

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a time is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown on the timepicker. +Maximum length for the text in this field is 150 characters.
+
initial_time
+
The initial time that is selected when the element is loaded. +This should be in the format HH:mm, where HH is the 24-hour format of an hour (00 to 23) +and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a time is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
timezone
+
The timezone to consider for this input value.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_time", "timezone"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UrlInputElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_value:Β strΒ |Β NoneΒ =Β None,
dispatch_action_config:Β dictΒ |Β DispatchActionConfigΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UrlInputElement(InputInteractiveElement):
+    type = "url_text_input"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "initial_value",
+                "dispatch_action_config",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        initial_value: Optional[str] = None,
+        dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None,
+        focus_on_load: Optional[bool] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        **others: dict,
+    ):
+        """
+        A URL input element, similar to the Plain-text input element,
+        creates a single line field where a user can enter URL-encoded data.
+        https://docs.slack.dev/reference/block-kit/block-elements/url-input-element
+
+        Args:
+            action_id (required): An identifier for the input value when the parent modal is submitted.
+                You can use this when you receive a view_submission payload to identify the value of the input element.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_value: The initial value in the URL input when it is loaded.
+            dispatch_action_config: A dispatch configuration object that determines when during text input
+                the element returns a block_actions payload.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+            placeholder: A plain_text only text object that defines the placeholder text shown in the URL input.
+                Maximum length for the text in this field is 150 characters.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_value = initial_value
+        self.dispatch_action_config = dispatch_action_config
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

A URL input element, similar to the Plain-text input element, +creates a single line field where a user can enter URL-encoded data. +https://docs.slack.dev/reference/block-kit/block-elements/url-input-element

+

Args

+
+
action_id : required
+
An identifier for the input value when the parent modal is submitted. +You can use this when you receive a view_submission payload to identify the value of the input element. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_value
+
The initial value in the URL input when it is loaded.
+
dispatch_action_config
+
A dispatch configuration object that determines when during text input +the element returns a block_actions payload.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
placeholder
+
A plain_text only text object that defines the placeholder text shown in the URL input. +Maximum length for the text in this field is 150 characters.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "initial_value",
+            "dispatch_action_config",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UserMultiSelectElement +(*,
action_id:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
initial_users:Β Sequence[str]Β |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
max_selected_items:Β intΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UserMultiSelectElement(InputInteractiveElement):
+    type = "multi_users_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_users", "max_selected_items"})
+
+    def __init__(
+        self,
+        *,
+        action_id: Optional[str] = None,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        initial_users: Optional[Sequence[str]] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        max_selected_items: Optional[int] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of Slack users visible to
+        the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#users_multi_select
+
+        Args:
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            initial_users: An array of user IDs of any valid users to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog that appears
+                before the multi-select choices are submitted.
+            max_selected_items: Specifies the maximum number of items that can be selected in the menu.
+                Minimum number is 1.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_users = initial_users
+        self.max_selected_items = max_selected_items
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of Slack users visible to +the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#users_multi_select

+

Args

+
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
initial_users
+
An array of user IDs of any valid users to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog that appears +before the multi-select choices are submitted.
+
max_selected_items
+
Specifies the maximum number of items that can be selected in the menu. +Minimum number is 1.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_users", "max_selected_items"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class UserSelectElement +(*,
placeholder:Β strΒ |Β dictΒ |Β TextObjectΒ |Β NoneΒ =Β None,
action_id:Β strΒ |Β NoneΒ =Β None,
initial_user:Β strΒ |Β NoneΒ =Β None,
confirm:Β dictΒ |Β ConfirmObjectΒ |Β NoneΒ =Β None,
focus_on_load:Β boolΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class UserSelectElement(InputInteractiveElement):
+    type = "users_select"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"initial_user"})
+
+    def __init__(
+        self,
+        *,
+        placeholder: Optional[Union[str, dict, TextObject]] = None,
+        action_id: Optional[str] = None,
+        initial_user: Optional[str] = None,
+        confirm: Optional[Union[dict, ConfirmObject]] = None,
+        focus_on_load: Optional[bool] = None,
+        **others: dict,
+    ):
+        """
+        This select menu will populate its options with a list of Slack users visible to
+        the current user in the active workspace.
+        https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#users_select
+
+        Args:
+            placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu.
+                Maximum length for the text in this field is 150 characters.
+            action_id (required): An identifier for the action triggered when a menu option is selected.
+                You can use this when you receive an interaction payload to identify the source of the action.
+                Should be unique among all other action_ids in the containing block.
+                Maximum length for this field is 255 characters.
+            initial_user: The user ID of any valid user to be pre-selected when the menu loads.
+            confirm: A confirm object that defines an optional confirmation dialog
+                that appears after a menu item is selected.
+            focus_on_load: Indicates whether the element will be set to auto focus within the view object.
+                Only one element can be set to true. Defaults to false.
+        """
+        super().__init__(
+            type=self.type,
+            action_id=action_id,
+            placeholder=TextObject.parse(placeholder, PlainTextObject.type),  # type: ignore[arg-type]
+            confirm=ConfirmObject.parse(confirm),  # type: ignore[arg-type]
+            focus_on_load=focus_on_load,
+        )
+        show_unknown_key_warning(self, others)
+
+        self.initial_user = initial_user
+
+

Block Elements are things that exists inside of your Blocks. +https://docs.slack.dev/reference/block-kit/block-elements/

+

This select menu will populate its options with a list of Slack users visible to +the current user in the active workspace. +https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#users_select

+

Args

+
+
placeholder : required
+
A plain_text only text object that defines the placeholder text shown on the menu. +Maximum length for the text in this field is 150 characters.
+
action_id : required
+
An identifier for the action triggered when a menu option is selected. +You can use this when you receive an interaction payload to identify the source of the action. +Should be unique among all other action_ids in the containing block. +Maximum length for this field is 255 characters.
+
initial_user
+
The user ID of any valid user to be pre-selected when the menu loads.
+
confirm
+
A confirm object that defines an optional confirmation dialog +that appears after a menu item is selected.
+
focus_on_load
+
Indicates whether the element will be set to auto focus within the view object. +Only one element can be set to true. Defaults to false.
+
+

Ancestors

+ +

Class variables

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"initial_user"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class VideoBlock +(*,
block_id:Β strΒ |Β NoneΒ =Β None,
alt_text:Β strΒ |Β NoneΒ =Β None,
video_url:Β strΒ |Β NoneΒ =Β None,
thumbnail_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
title_url:Β strΒ |Β NoneΒ =Β None,
description:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
provider_icon_url:Β strΒ |Β NoneΒ =Β None,
provider_name:Β strΒ |Β NoneΒ =Β None,
author_name:Β strΒ |Β NoneΒ =Β None,
**others:Β dict)
+
+
+
+ +Expand source code + +
class VideoBlock(Block):
+    type = "video"
+    title_max_length = 200
+    author_name_max_length = 50
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union(
+            {
+                "alt_text",
+                "video_url",
+                "thumbnail_url",
+                "title",
+                "title_url",
+                "description",
+                "provider_icon_url",
+                "provider_name",
+                "author_name",
+            }
+        )
+
+    def __init__(
+        self,
+        *,
+        block_id: Optional[str] = None,
+        alt_text: Optional[str] = None,
+        video_url: Optional[str] = None,
+        thumbnail_url: Optional[str] = None,
+        title: Optional[Union[str, dict, PlainTextObject]] = None,
+        title_url: Optional[str] = None,
+        description: Optional[Union[str, dict, PlainTextObject]] = None,
+        provider_icon_url: Optional[str] = None,
+        provider_name: Optional[str] = None,
+        author_name: Optional[str] = None,
+        **others: dict,
+    ):
+        """A video block is designed to embed videos in all app surfaces
+        (e.g. link unfurls, messages, modals, App Home) β€”
+        anywhere you can put blocks! To use the video block within your app,
+        you must have the links.embed:write scope.
+        https://docs.slack.dev/reference/block-kit/blocks/video-block
+
+        Args:
+            block_id: A string acting as a unique identifier for a block. If not specified, one will be generated.
+                Maximum length for this field is 255 characters.
+                block_id should be unique for each message and each iteration of a message.
+                If a message is updated, use a new block_id.
+            alt_text (required): A tooltip for the video. Required for accessibility
+            video_url (required): The URL to be embedded. Must match any existing unfurl domains within the app
+                and point to a HTTPS URL.
+            thumbnail_url (required): The thumbnail image URL
+            title (required): Video title in plain text format. Must be less than 200 characters.
+            title_url: Hyperlink for the title text. Must correspond to the non-embeddable URL for the video.
+                Must go to an HTTPS URL.
+            description: Description for video in plain text format.
+            provider_icon_url: Icon for the video provider - ex. Youtube icon
+            provider_name: The originating application or domain of the video ex. Youtube
+            author_name: Author name to be displayed. Must be less than 50 characters.
+        """
+        super().__init__(type=self.type, block_id=block_id)
+        show_unknown_key_warning(self, others)
+
+        self.alt_text = alt_text
+        self.video_url = video_url
+        self.thumbnail_url = thumbnail_url
+        self.title = TextObject.parse(title, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.title_url = title_url
+        self.description = TextObject.parse(description, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.provider_icon_url = provider_icon_url
+        self.provider_name = provider_name
+        self.author_name = author_name
+
+    @JsonValidator("alt_text attribute must be specified")
+    def _validate_alt_text(self):
+        return self.alt_text is not None
+
+    @JsonValidator("video_url attribute must be specified")
+    def _validate_video_url(self):
+        return self.video_url is not None
+
+    @JsonValidator("thumbnail_url attribute must be specified")
+    def _validate_thumbnail_url(self):
+        return self.thumbnail_url is not None
+
+    @JsonValidator("title attribute must be specified")
+    def _validate_title(self):
+        return self.title is not None
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def _validate_title_length(self):
+        return self.title is None or len(self.title.text) < self.title_max_length
+
+    @JsonValidator(f"author_name attribute cannot exceed {author_name_max_length} characters")
+    def _validate_author_name_length(self):
+        return self.author_name is None or len(self.author_name) < self.author_name_max_length
+
+

Blocks are a series of components that can be combined +to create visually rich and compellingly interactive messages. +https://docs.slack.dev/reference/block-kit/blocks

+

A video block is designed to embed videos in all app surfaces +(e.g. link unfurls, messages, modals, App Home) β€” +anywhere you can put blocks! To use the video block within your app, +you must have the links.embed:write scope. +https://docs.slack.dev/reference/block-kit/blocks/video-block

+

Args

+
+
block_id
+
A string acting as a unique identifier for a block. If not specified, one will be generated. +Maximum length for this field is 255 characters. +block_id should be unique for each message and each iteration of a message. +If a message is updated, use a new block_id.
+
alt_text : required
+
A tooltip for the video. Required for accessibility
+
video_url : required
+
The URL to be embedded. Must match any existing unfurl domains within the app +and point to a HTTPS URL.
+
thumbnail_url : required
+
The thumbnail image URL
+
title : required
+
Video title in plain text format. Must be less than 200 characters.
+
title_url
+
Hyperlink for the title text. Must correspond to the non-embeddable URL for the video. +Must go to an HTTPS URL.
+
description
+
Description for video in plain text format.
+
provider_icon_url
+
Icon for the video provider - ex. Youtube icon
+
provider_name
+
The originating application or domain of the video ex. Youtube
+
author_name
+
Author name to be displayed. Must be less than 50 characters.
+
+

Ancestors

+ +

Class variables

+
+
var author_name_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union(
+        {
+            "alt_text",
+            "video_url",
+            "thumbnail_url",
+            "title",
+            "title_url",
+            "description",
+            "provider_icon_url",
+            "provider_name",
+            "author_name",
+        }
+    )
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/dialoags.html b/docs/reference/models/dialoags.html new file mode 100644 index 000000000..cc2ff46a2 --- /dev/null +++ b/docs/reference/models/dialoags.html @@ -0,0 +1,2653 @@ + + + + + + +slack_sdk.models.dialoags API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.dialoags

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AbstractDialogSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AbstractDialogSelector(JsonObject, metaclass=ABCMeta):
+    DataSourceTypes = DynamicSelectElementTypes.union({"external", "static"})
+
+    attributes = {"data_source", "label", "name", "optional", "placeholder", "type"}
+
+    name_max_length = 300
+    label_max_length = 48
+    placeholder_max_length = 150
+
+    @property
+    @abstractmethod
+    def data_source(self) -> str:
+        pass
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[Union[Option, str]] = None,
+        placeholder: Optional[str] = None,
+    ):
+        self.name = name
+        self.label = label
+        self.optional = optional
+        self.value = value
+        self.placeholder = placeholder
+        self.type = "select"
+
+    @JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+    def name_length(self) -> bool:
+        return len(self.name) < self.name_max_length
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def label_length(self) -> bool:
+        return len(self.label) < self.label_max_length
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def placeholder_length(self) -> bool:
+        return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+    @EnumValidator("data_source", DataSourceTypes)
+    def data_source_valid(self) -> bool:
+        return self.data_source in self.DataSourceTypes
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if self.data_source == "external":
+            if isinstance(self.value, Option):
+                json["selected_options"] = extract_json([self.value], "dialog")
+            elif self.value is not None:
+                json["selected_options"] = Option.from_single_value(self.value)
+        else:
+            if isinstance(self.value, Option):
+                json["value"] = self.value.value
+            elif self.value is not None:
+                json["value"] = self.value
+        return json
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var DataSourceTypes
+
+

The type of the None singleton.

+
+
var attributes
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var name_max_length
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop data_source :Β str
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def data_source(self) -> str:
+    pass
+
+
+
+
+

Methods

+
+
+def data_source_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@EnumValidator("data_source", DataSourceTypes)
+def data_source_valid(self) -> bool:
+    return self.data_source in self.DataSourceTypes
+
+
+
+
+def label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+def label_length(self) -> bool:
+    return len(self.label) < self.label_max_length
+
+
+
+
+def name_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+def name_length(self) -> bool:
+    return len(self.name) < self.name_max_length
+
+
+
+
+def placeholder_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+def placeholder_length(self) -> bool:
+    return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogBuilder +
+
+
+ +Expand source code + +
class DialogBuilder(JsonObject):
+    attributes: Set[str] = set()
+
+    _callback_id: Optional[str]
+    _elements: List[Union[DialogTextComponent, AbstractDialogSelector]]
+    _submit_label: Optional[str]
+    _notify_on_cancel: bool
+    _state: Optional[str]
+
+    title_max_length = 24
+    submit_label_max_length = 24
+    elements_max_length = 10
+    state_max_length = 3000
+
+    def __init__(self):
+        """
+        Create a DialogBuilder to more easily construct the JSON required to submit a
+        dialog to Slack
+        """
+        self._title = None
+        self._callback_id = None
+        self._elements = []
+        self._submit_label = None
+        self._notify_on_cancel = False
+        self._state = None
+
+    def title(self, title: str) -> "DialogBuilder":
+        """
+        Specify a title for this dialog
+
+        Args:
+          title: must not exceed 24 characters
+        """
+        self._title = title
+        return self
+
+    def state(self, state: Union[dict, str]) -> "DialogBuilder":
+        """
+        Pass state into this dialog - dictionaries will be automatically formatted to
+        JSON
+
+        Args:
+            state: Extra state information that you need to pass from this dialog
+                back to your application on submission
+        """
+        if isinstance(state, dict):
+            self._state = dumps(state)
+        else:
+            self._state = state
+        return self
+
+    def callback_id(self, callback_id: str) -> "DialogBuilder":
+        """
+        Specify a callback ID for this dialog, which your application will then
+        receive upon dialog submission
+
+        Args:
+          callback_id: a string identifying this particular dialog
+        """
+        self._callback_id = callback_id
+        return self
+
+    def submit_label(self, label: str) -> "DialogBuilder":
+        """
+        The label to use on the 'Submit' button on the dialog. Defaults to 'Submit'
+        if not specified.
+
+        Args:
+            label: must not exceed 24 characters, and must be a single word (no
+                spaces)
+        """
+        self._submit_label = label
+        return self
+
+    def notify_on_cancel(self, notify: bool) -> "DialogBuilder":
+        """
+        Whether this dialog should send a request to your application even if the
+        user cancels their interaction. Defaults to False.
+
+        Args:
+            notify: Set to True to indicate that your application should receive a
+                request even if the user cancels interaction with the dialog.
+        """
+        self._notify_on_cancel = notify
+        return self
+
+    def text_field(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: int = 150,
+        subtype: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Text elements are single-line plain text fields.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. 48 character maximum.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+            hint: Helpful text provided to assist users in answering a question.
+                Up to 150 characters.
+            value: A default value for this field. Up to 150 characters.
+            min_length: Minimum input length allowed for element. Up to 150
+                characters. Defaults to 0.
+            max_length: Maximum input length allowed for element. Up to 150
+                characters. Defaults to 150.
+            subtype: A subtype for this text input. Accepts email, number, tel,
+                    or url. In some form factors, optimized input is provided for this
+                    subtype.
+        """
+        self._elements.append(
+            DialogTextField(
+                name=name,
+                label=label,
+                optional=optional,
+                placeholder=placeholder,
+                hint=hint,
+                value=value,
+                min_length=min_length,
+                max_length=max_length,
+                subtype=subtype,
+            )
+        )
+        return self
+
+    def text_area(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: int = 3000,
+        subtype: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        A textarea is a multi-line plain text editing control. You've likely
+        encountered these on the world wide web. Use this element if you want a
+        relatively long answer from users. The element UI provides a remaining
+        character count to the max_length you have set or the default,
+        3000.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. 48 character maximum.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+            hint: Helpful text provided to assist users in answering a question.
+                Up to 150 characters.
+            value: A default value for this field. Up to 3000 characters.
+            min_length: Minimum input length allowed for element. 1-3000
+                characters. Defaults to 0.
+            max_length: Maximum input length allowed for element. 0-3000
+                characters. Defaults to 3000.
+            subtype: A subtype for this text input. Accepts email, number, tel,
+                or url. In some form factors, optimized input is provided for this
+                subtype.
+        """
+        self._elements.append(
+            DialogTextArea(
+                name=name,
+                label=label,
+                optional=optional,
+                placeholder=placeholder,
+                hint=hint,
+                value=value,
+                min_length=min_length,
+                max_length=max_length,
+                subtype=subtype,
+            )
+        )
+        return self
+
+    def static_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        options: Union[Sequence[Option], Sequence[OptionGroup]],
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A select element may contain up to 100 selections, provided as a list of
+        Option or OptionGroup objects
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            options: A list of up to 100 Option or OptionGroup objects. Object
+                types cannot be mixed.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogStaticSelector(
+                name=name,
+                label=label,
+                options=options,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def external_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[Option] = None,
+        placeholder: Optional[str] = None,
+        min_query_length: Optional[int] = None,
+    ) -> "DialogBuilder":
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A list of options can be loaded from an external URL and used in your dialog
+        menus.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            min_query_length: Specify the number of characters that must be
+                typed by a user into a dynamic select menu before dispatching to your
+                application.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value. This should be a single
+                Option or OptionGroup that exactly matches one that will be returned
+                from your external endpoint.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogExternalSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+                min_query_length=min_query_length,
+            )
+        )
+        return self
+
+    def user_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Now you can easily populate a select menu with a list of users. For example,
+        when you are creating a bug tracking app, you want to include a field for an
+        assignee. Slack pre-populates the user list in client-side, so your app
+        doesn't need access to a related OAuth scope.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogUserSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def channel_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        You can also provide a select menu with a list of channels. Specify your
+        data_source as channels to limit only to public channels
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogChannelSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def conversation_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        You can also provide a select menu with a list of conversations - including
+        private channels, direct messages, MPIMs, and whatever else we consider a
+        conversation-like thing.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogConversationSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    @JsonValidator("title attribute is required")
+    def title_present(self) -> bool:
+        return self._title is not None
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def title_length(self) -> bool:
+        return self._title is not None and len(self._title) <= self.title_max_length
+
+    @JsonValidator("callback_id attribute is required")
+    def callback_id_present(self) -> bool:
+        return self._callback_id is not None
+
+    @JsonValidator(f"dialogs must contain between 1 and {elements_max_length} elements")
+    def elements_length(self) -> bool:
+        return 0 < len(self._elements) <= self.elements_max_length
+
+    @JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters")
+    def submit_label_length(self) -> bool:
+        return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length
+
+    @JsonValidator("submit_label can only be one word")
+    def submit_label_valid(self) -> bool:
+        return self._submit_label is None or " " not in self._submit_label
+
+    @JsonValidator(f"state cannot exceed {state_max_length} characters")
+    def state_length(self) -> bool:
+        return not self._state or len(self._state) <= self.state_max_length
+
+    def to_dict(self) -> dict:
+        self.validate_json()
+        json = {
+            "title": self._title,
+            "callback_id": self._callback_id,
+            "elements": extract_json(self._elements),
+            "notify_on_cancel": self._notify_on_cancel,
+        }
+        if self._submit_label is not None:
+            json["submit_label"] = self._submit_label
+        if self._state is not None:
+            json["state"] = self._state
+        return json
+
+

The base class for JSON serializable class objects

+

Create a DialogBuilder to more easily construct the JSON required to submit a +dialog to Slack

+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var state_max_length
+
+

The type of the None singleton.

+
+
var submit_label_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def callback_id(self, callback_id:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def callback_id(self, callback_id: str) -> "DialogBuilder":
+    """
+    Specify a callback ID for this dialog, which your application will then
+    receive upon dialog submission
+
+    Args:
+      callback_id: a string identifying this particular dialog
+    """
+    self._callback_id = callback_id
+    return self
+
+

Specify a callback ID for this dialog, which your application will then +receive upon dialog submission

+

Args

+
+
callback_id
+
a string identifying this particular dialog
+
+
+
+def callback_id_present(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("callback_id attribute is required")
+def callback_id_present(self) -> bool:
+    return self._callback_id is not None
+
+
+
+
+def channel_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def channel_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    You can also provide a select menu with a list of channels. Specify your
+    data_source as channels to limit only to public channels
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogChannelSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

You can also provide a select menu with a list of channels. Specify your +data_source as channels to limit only to public channels

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def conversation_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def conversation_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    You can also provide a select menu with a list of conversations - including
+    private channels, direct messages, MPIMs, and whatever else we consider a
+    conversation-like thing.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogConversationSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

You can also provide a select menu with a list of conversations - including +private channels, direct messages, MPIMs, and whatever else we consider a +conversation-like thing.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def elements_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"dialogs must contain between 1 and {elements_max_length} elements")
+def elements_length(self) -> bool:
+    return 0 < len(self._elements) <= self.elements_max_length
+
+
+
+
+def external_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def external_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[Option] = None,
+    placeholder: Optional[str] = None,
+    min_query_length: Optional[int] = None,
+) -> "DialogBuilder":
+    """
+    Use the select element for multiple choice selections allowing users to pick
+    a single item from a list. True to web roots, this selection is displayed as
+    a dropdown menu.
+
+    A list of options can be loaded from an external URL and used in your dialog
+    menus.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        min_query_length: Specify the number of characters that must be
+            typed by a user into a dynamic select menu before dispatching to your
+            application.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value. This should be a single
+            Option or OptionGroup that exactly matches one that will be returned
+            from your external endpoint.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogExternalSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+            min_query_length=min_query_length,
+        )
+    )
+    return self
+
+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A list of options can be loaded from an external URL and used in your dialog +menus.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
min_query_length
+
Specify the number of characters that must be +typed by a user into a dynamic select menu before dispatching to your +application.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value. This should be a single +Option or OptionGroup that exactly matches one that will be returned +from your external endpoint.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def notify_on_cancel(self, notify:Β bool) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def notify_on_cancel(self, notify: bool) -> "DialogBuilder":
+    """
+    Whether this dialog should send a request to your application even if the
+    user cancels their interaction. Defaults to False.
+
+    Args:
+        notify: Set to True to indicate that your application should receive a
+            request even if the user cancels interaction with the dialog.
+    """
+    self._notify_on_cancel = notify
+    return self
+
+

Whether this dialog should send a request to your application even if the +user cancels their interaction. Defaults to False.

+

Args

+
+
notify
+
Set to True to indicate that your application should receive a +request even if the user cancels interaction with the dialog.
+
+
+
+def state(self, state:Β dictΒ |Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def state(self, state: Union[dict, str]) -> "DialogBuilder":
+    """
+    Pass state into this dialog - dictionaries will be automatically formatted to
+    JSON
+
+    Args:
+        state: Extra state information that you need to pass from this dialog
+            back to your application on submission
+    """
+    if isinstance(state, dict):
+        self._state = dumps(state)
+    else:
+        self._state = state
+    return self
+
+

Pass state into this dialog - dictionaries will be automatically formatted to +JSON

+

Args

+
+
state
+
Extra state information that you need to pass from this dialog +back to your application on submission
+
+
+
+def state_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"state cannot exceed {state_max_length} characters")
+def state_length(self) -> bool:
+    return not self._state or len(self._state) <= self.state_max_length
+
+
+
+
+def static_selector(self,
*,
name:Β str,
label:Β str,
options:Β Sequence[Option]Β |Β Sequence[OptionGroup],
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def static_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    options: Union[Sequence[Option], Sequence[OptionGroup]],
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Use the select element for multiple choice selections allowing users to pick
+    a single item from a list. True to web roots, this selection is displayed as
+    a dropdown menu.
+
+    A select element may contain up to 100 selections, provided as a list of
+    Option or OptionGroup objects
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        options: A list of up to 100 Option or OptionGroup objects. Object
+            types cannot be mixed.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogStaticSelector(
+            name=name,
+            label=label,
+            options=options,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A select element may contain up to 100 selections, provided as a list of +Option or OptionGroup objects

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
options
+
A list of up to 100 Option or OptionGroup objects. Object +types cannot be mixed.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def submit_label(self, label:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def submit_label(self, label: str) -> "DialogBuilder":
+    """
+    The label to use on the 'Submit' button on the dialog. Defaults to 'Submit'
+    if not specified.
+
+    Args:
+        label: must not exceed 24 characters, and must be a single word (no
+            spaces)
+    """
+    self._submit_label = label
+    return self
+
+

The label to use on the 'Submit' button on the dialog. Defaults to 'Submit' +if not specified.

+

Args

+
+
label
+
must not exceed 24 characters, and must be a single word (no +spaces)
+
+
+
+def submit_label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters")
+def submit_label_length(self) -> bool:
+    return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length
+
+
+
+
+def submit_label_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("submit_label can only be one word")
+def submit_label_valid(self) -> bool:
+    return self._submit_label is None or " " not in self._submit_label
+
+
+
+
+def text_area(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ =Β 3000,
subtype:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def text_area(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    placeholder: Optional[str] = None,
+    hint: Optional[str] = None,
+    value: Optional[str] = None,
+    min_length: int = 0,
+    max_length: int = 3000,
+    subtype: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    A textarea is a multi-line plain text editing control. You've likely
+    encountered these on the world wide web. Use this element if you want a
+    relatively long answer from users. The element UI provides a remaining
+    character count to the max_length you have set or the default,
+    3000.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. 48 character maximum.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+        hint: Helpful text provided to assist users in answering a question.
+            Up to 150 characters.
+        value: A default value for this field. Up to 3000 characters.
+        min_length: Minimum input length allowed for element. 1-3000
+            characters. Defaults to 0.
+        max_length: Maximum input length allowed for element. 0-3000
+            characters. Defaults to 3000.
+        subtype: A subtype for this text input. Accepts email, number, tel,
+            or url. In some form factors, optimized input is provided for this
+            subtype.
+    """
+    self._elements.append(
+        DialogTextArea(
+            name=name,
+            label=label,
+            optional=optional,
+            placeholder=placeholder,
+            hint=hint,
+            value=value,
+            min_length=min_length,
+            max_length=max_length,
+            subtype=subtype,
+        )
+    )
+    return self
+
+

A textarea is a multi-line plain text editing control. You've likely +encountered these on the world wide web. Use this element if you want a +relatively long answer from users. The element UI provides a remaining +character count to the max_length you have set or the default, +3000.

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. 48 character maximum.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
hint
+
Helpful text provided to assist users in answering a question. +Up to 150 characters.
+
value
+
A default value for this field. Up to 3000 characters.
+
min_length
+
Minimum input length allowed for element. 1-3000 +characters. Defaults to 0.
+
max_length
+
Maximum input length allowed for element. 0-3000 +characters. Defaults to 3000.
+
subtype
+
A subtype for this text input. Accepts email, number, tel, +or url. In some form factors, optimized input is provided for this +subtype.
+
+
+
+def text_field(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ =Β 150,
subtype:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def text_field(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    placeholder: Optional[str] = None,
+    hint: Optional[str] = None,
+    value: Optional[str] = None,
+    min_length: int = 0,
+    max_length: int = 150,
+    subtype: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Text elements are single-line plain text fields.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. 48 character maximum.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+        hint: Helpful text provided to assist users in answering a question.
+            Up to 150 characters.
+        value: A default value for this field. Up to 150 characters.
+        min_length: Minimum input length allowed for element. Up to 150
+            characters. Defaults to 0.
+        max_length: Maximum input length allowed for element. Up to 150
+            characters. Defaults to 150.
+        subtype: A subtype for this text input. Accepts email, number, tel,
+                or url. In some form factors, optimized input is provided for this
+                subtype.
+    """
+    self._elements.append(
+        DialogTextField(
+            name=name,
+            label=label,
+            optional=optional,
+            placeholder=placeholder,
+            hint=hint,
+            value=value,
+            min_length=min_length,
+            max_length=max_length,
+            subtype=subtype,
+        )
+    )
+    return self
+
+

Text elements are single-line plain text fields.

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. 48 character maximum.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
hint
+
Helpful text provided to assist users in answering a question. +Up to 150 characters.
+
value
+
A default value for this field. Up to 150 characters.
+
min_length
+
Minimum input length allowed for element. Up to 150 +characters. Defaults to 0.
+
max_length
+
Maximum input length allowed for element. Up to 150 +characters. Defaults to 150.
+
subtype
+
A subtype for this text input. Accepts email, number, tel, +or url. In some form factors, optimized input is provided for this +subtype.
+
+
+
+def title(self, title:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def title(self, title: str) -> "DialogBuilder":
+    """
+    Specify a title for this dialog
+
+    Args:
+      title: must not exceed 24 characters
+    """
+    self._title = title
+    return self
+
+

Specify a title for this dialog

+

Args

+
+
title
+
must not exceed 24 characters
+
+
+
+def title_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+def title_length(self) -> bool:
+    return self._title is not None and len(self._title) <= self.title_max_length
+
+
+
+
+def title_present(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("title attribute is required")
+def title_present(self) -> bool:
+    return self._title is not None
+
+
+
+
+def user_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def user_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Now you can easily populate a select menu with a list of users. For example,
+    when you are creating a bug tracking app, you want to include a field for an
+    assignee. Slack pre-populates the user list in client-side, so your app
+    doesn't need access to a related OAuth scope.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogUserSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

Now you can easily populate a select menu with a list of users. For example, +when you are creating a bug tracking app, you want to include a field for an +assignee. Slack pre-populates the user list in client-side, so your app +doesn't need access to a related OAuth scope.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+

Inherited members

+ +
+
+class DialogChannelSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogChannelSelector(AbstractDialogSelector):
+    data_source = "channels"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        You can also provide a select menu with a list of channels. Specify your
+        data_source as channels to limit only to public channels
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

You can also provide a select menu with a list of channels. Specify your +data_source as channels to limit only to public channels

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogConversationSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogConversationSelector(AbstractDialogSelector):
+    data_source = "conversations"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        You can also provide a select menu with a list of conversations - including
+        private channels, direct messages, MPIMs, and whatever else we consider a
+        conversation-like thing.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

You can also provide a select menu with a list of conversations - including +private channels, direct messages, MPIMs, and whatever else we consider a +conversation-like thing.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogExternalSelector +(*,
name:Β str,
label:Β str,
value:Β OptionΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
optional:Β boolΒ |Β NoneΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogExternalSelector(AbstractDialogSelector):
+    data_source = "external"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length"})
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        value: Optional[Option] = None,
+        min_query_length: Optional[int] = None,
+        optional: Optional[bool] = False,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A list of options can be loaded from an external URL and used in your dialog
+        menus.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            min_query_length: Specify the number of characters that must be typed
+                by a user into a dynamic select menu before dispatching to the app.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value. This should be a single
+                Option or OptionGroup that exactly matches one that will be returned
+                from your external endpoint.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            value=value,
+            optional=optional,  # type: ignore[arg-type]
+            placeholder=placeholder,
+        )
+        self.min_query_length = min_query_length
+
+

The base class for JSON serializable class objects

+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A list of options can be loaded from an external URL and used in your dialog +menus.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
min_query_length
+
Specify the number of characters that must be typed +by a user into a dynamic select menu before dispatching to the app.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value. This should be a single +Option or OptionGroup that exactly matches one that will be returned +from your external endpoint.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DialogStaticSelector +(*,
name:Β str,
label:Β str,
options:Β Sequence[Option]Β |Β Sequence[OptionGroup],
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogStaticSelector(AbstractDialogSelector):
+    """
+    Use the select element for multiple choice selections allowing users to pick a
+    single item from a list. True to web roots, this selection is displayed as a
+    dropdown menu.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+    """
+
+    data_source = "static"
+
+    options_max_length = 100
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        options: Union[Sequence[Option], Sequence[OptionGroup]],
+        optional: bool = False,
+        value: Optional[Union[Option, str]] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A select element may contain up to 100 selections, provided as a list of
+        Option or OptionGroup objects
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            options: A list of up to 100 Option or OptionGroup objects. Object
+                types cannot be mixed.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+        self.options = options
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} items")
+    def options_length(self) -> bool:
+        return len(self.options) < self.options_max_length
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if isinstance(self.options[0], OptionGroup):
+            json["option_groups"] = extract_json(self.options, "dialog")
+        else:
+            json["options"] = extract_json(self.options, "dialog")
+        return json
+
+

Use the select element for multiple choice selections allowing users to pick a +single item from a list. True to web roots, this selection is displayed as a +dropdown menu.

+

https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A select element may contain up to 100 selections, provided as a list of +Option or OptionGroup objects

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
options
+
A list of up to 100 Option or OptionGroup objects. Object +types cannot be mixed.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def options_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"options attribute cannot exceed {options_max_length} items")
+def options_length(self) -> bool:
+    return len(self.options) < self.options_max_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogTextArea +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextArea(DialogTextComponent):
+    """
+    A textarea is a multi-line plain text editing control. You've likely encountered
+    these on the world wide web. Use this element if you want a relatively long
+    answer from users. The element UI provides a remaining character count to the
+    max_length you have set or the default, 3000.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#textarea_elements
+    """
+
+    type = "textarea"
+    max_value_length = 3000
+
+

A textarea is a multi-line plain text editing control. You've likely encountered +these on the world wide web. Use this element if you want a relatively long +answer from users. The element UI provides a remaining character count to the +max_length you have set or the default, 3000.

+

https://docs.slack.dev/legacy/legacy-dialogs/#textarea_elements

+

Ancestors

+ +

Class variables

+
+
var max_value_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogTextComponent +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextComponent(JsonObject, metaclass=ABCMeta):
+    attributes = {
+        "hint",
+        "label",
+        "max_length",
+        "min_length",
+        "name",
+        "optional",
+        "placeholder",
+        "subtype",
+        "type",
+        "value",
+    }
+
+    name_max_length = 300
+    label_max_length = 48
+    placeholder_max_length = 150
+    hint_max_length = 150
+
+    @property
+    @abstractmethod
+    def type(self):
+        pass
+
+    @property
+    @abstractmethod
+    def max_value_length(self):
+        pass
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: Optional[int] = None,
+        subtype: Optional[str] = None,
+    ):
+        self.name = name
+        self.label = label
+        self.optional = optional
+        self.placeholder = placeholder
+        self.hint = hint
+        self.value = value
+        self.min_length = min_length
+        self.max_length = max_length or self.max_value_length
+        self.subtype = subtype
+
+    @JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+    def name_length(self) -> bool:
+        return len(self.name) < self.name_max_length
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def label_length(self) -> bool:
+        return len(self.label) < self.label_max_length
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def placeholder_length(self) -> bool:
+        return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+    @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+    def hint_length(self) -> bool:
+        return self.hint is None or len(self.hint) < self.hint_max_length
+
+    @JsonValidator("value attribute exceeded bounds")
+    def value_length(self) -> bool:
+        return self.value is None or len(self.value) < self.max_value_length
+
+    @JsonValidator("min_length attribute must be greater than or equal to 0")
+    def min_length_above_zero(self) -> bool:
+        return self.min_length is None or self.min_length >= 0
+
+    @JsonValidator("min_length attribute exceed bounds")
+    def min_length_length(self) -> bool:
+        return self.min_length is None or self.min_length <= self.max_value_length
+
+    @JsonValidator("min_length attribute must be less than max value attribute")
+    def min_length_below_max_length(self) -> bool:
+        return self.min_length is None or self.min_length < self.max_length
+
+    @JsonValidator("max_length attribute must be greater than or equal to 0")
+    def max_length_above_zero(self) -> bool:
+        return self.max_length is None or self.max_length > 0
+
+    @JsonValidator("max_length attribute exceeded bounds")
+    def max_length_length(self) -> bool:
+        return self.max_length is None or self.max_length <= self.max_value_length
+
+    @EnumValidator("subtype", TextElementSubtypes)
+    def subtype_valid(self) -> bool:
+        return self.subtype is None or self.subtype in TextElementSubtypes
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var hint_max_length
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var name_max_length
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop max_value_length
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def max_value_length(self):
+    pass
+
+
+
+
prop type
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def type(self):
+    pass
+
+
+
+
+

Methods

+
+
+def hint_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+def hint_length(self) -> bool:
+    return self.hint is None or len(self.hint) < self.hint_max_length
+
+
+
+
+def label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+def label_length(self) -> bool:
+    return len(self.label) < self.label_max_length
+
+
+
+
+def max_length_above_zero(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("max_length attribute must be greater than or equal to 0")
+def max_length_above_zero(self) -> bool:
+    return self.max_length is None or self.max_length > 0
+
+
+
+
+def max_length_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("max_length attribute exceeded bounds")
+def max_length_length(self) -> bool:
+    return self.max_length is None or self.max_length <= self.max_value_length
+
+
+
+
+def min_length_above_zero(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute must be greater than or equal to 0")
+def min_length_above_zero(self) -> bool:
+    return self.min_length is None or self.min_length >= 0
+
+
+
+
+def min_length_below_max_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute must be less than max value attribute")
+def min_length_below_max_length(self) -> bool:
+    return self.min_length is None or self.min_length < self.max_length
+
+
+
+
+def min_length_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute exceed bounds")
+def min_length_length(self) -> bool:
+    return self.min_length is None or self.min_length <= self.max_value_length
+
+
+
+
+def name_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+def name_length(self) -> bool:
+    return len(self.name) < self.name_max_length
+
+
+
+
+def placeholder_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+def placeholder_length(self) -> bool:
+    return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+
+
+
+def subtype_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@EnumValidator("subtype", TextElementSubtypes)
+def subtype_valid(self) -> bool:
+    return self.subtype is None or self.subtype in TextElementSubtypes
+
+
+
+
+def value_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("value attribute exceeded bounds")
+def value_length(self) -> bool:
+    return self.value is None or len(self.value) < self.max_value_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogTextField +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextField(DialogTextComponent):
+    """
+    Text elements are single-line plain text fields.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#text_elements
+    """
+
+    type = "text"
+    max_value_length = 150
+
+

Text elements are single-line plain text fields.

+

https://docs.slack.dev/legacy/legacy-dialogs/#text_elements

+

Ancestors

+ +

Class variables

+
+
var max_value_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogUserSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogUserSelector(AbstractDialogSelector):
+    data_source = "users"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Now you can easily populate a select menu with a list of users. For example,
+        when you are creating a bug tracking app, you want to include a field for an
+        assignee. Slack pre-populates the user list in client-side, so your app
+        doesn't need access to a related OAuth scope.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

Now you can easily populate a select menu with a list of users. For example, +when you are creating a bug tracking app, you want to include a field for an +assignee. Slack pre-populates the user list in client-side, so your app +doesn't need access to a related OAuth scope.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/dialogs/index.html b/docs/reference/models/dialogs/index.html new file mode 100644 index 000000000..e0c6fe457 --- /dev/null +++ b/docs/reference/models/dialogs/index.html @@ -0,0 +1,2653 @@ + + + + + + +slack_sdk.models.dialogs API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.dialogs

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AbstractDialogSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AbstractDialogSelector(JsonObject, metaclass=ABCMeta):
+    DataSourceTypes = DynamicSelectElementTypes.union({"external", "static"})
+
+    attributes = {"data_source", "label", "name", "optional", "placeholder", "type"}
+
+    name_max_length = 300
+    label_max_length = 48
+    placeholder_max_length = 150
+
+    @property
+    @abstractmethod
+    def data_source(self) -> str:
+        pass
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[Union[Option, str]] = None,
+        placeholder: Optional[str] = None,
+    ):
+        self.name = name
+        self.label = label
+        self.optional = optional
+        self.value = value
+        self.placeholder = placeholder
+        self.type = "select"
+
+    @JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+    def name_length(self) -> bool:
+        return len(self.name) < self.name_max_length
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def label_length(self) -> bool:
+        return len(self.label) < self.label_max_length
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def placeholder_length(self) -> bool:
+        return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+    @EnumValidator("data_source", DataSourceTypes)
+    def data_source_valid(self) -> bool:
+        return self.data_source in self.DataSourceTypes
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if self.data_source == "external":
+            if isinstance(self.value, Option):
+                json["selected_options"] = extract_json([self.value], "dialog")
+            elif self.value is not None:
+                json["selected_options"] = Option.from_single_value(self.value)
+        else:
+            if isinstance(self.value, Option):
+                json["value"] = self.value.value
+            elif self.value is not None:
+                json["value"] = self.value
+        return json
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var DataSourceTypes
+
+

The type of the None singleton.

+
+
var attributes
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var name_max_length
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop data_source :Β str
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def data_source(self) -> str:
+    pass
+
+
+
+
+

Methods

+
+
+def data_source_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@EnumValidator("data_source", DataSourceTypes)
+def data_source_valid(self) -> bool:
+    return self.data_source in self.DataSourceTypes
+
+
+
+
+def label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+def label_length(self) -> bool:
+    return len(self.label) < self.label_max_length
+
+
+
+
+def name_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+def name_length(self) -> bool:
+    return len(self.name) < self.name_max_length
+
+
+
+
+def placeholder_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+def placeholder_length(self) -> bool:
+    return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogBuilder +
+
+
+ +Expand source code + +
class DialogBuilder(JsonObject):
+    attributes: Set[str] = set()
+
+    _callback_id: Optional[str]
+    _elements: List[Union[DialogTextComponent, AbstractDialogSelector]]
+    _submit_label: Optional[str]
+    _notify_on_cancel: bool
+    _state: Optional[str]
+
+    title_max_length = 24
+    submit_label_max_length = 24
+    elements_max_length = 10
+    state_max_length = 3000
+
+    def __init__(self):
+        """
+        Create a DialogBuilder to more easily construct the JSON required to submit a
+        dialog to Slack
+        """
+        self._title = None
+        self._callback_id = None
+        self._elements = []
+        self._submit_label = None
+        self._notify_on_cancel = False
+        self._state = None
+
+    def title(self, title: str) -> "DialogBuilder":
+        """
+        Specify a title for this dialog
+
+        Args:
+          title: must not exceed 24 characters
+        """
+        self._title = title
+        return self
+
+    def state(self, state: Union[dict, str]) -> "DialogBuilder":
+        """
+        Pass state into this dialog - dictionaries will be automatically formatted to
+        JSON
+
+        Args:
+            state: Extra state information that you need to pass from this dialog
+                back to your application on submission
+        """
+        if isinstance(state, dict):
+            self._state = dumps(state)
+        else:
+            self._state = state
+        return self
+
+    def callback_id(self, callback_id: str) -> "DialogBuilder":
+        """
+        Specify a callback ID for this dialog, which your application will then
+        receive upon dialog submission
+
+        Args:
+          callback_id: a string identifying this particular dialog
+        """
+        self._callback_id = callback_id
+        return self
+
+    def submit_label(self, label: str) -> "DialogBuilder":
+        """
+        The label to use on the 'Submit' button on the dialog. Defaults to 'Submit'
+        if not specified.
+
+        Args:
+            label: must not exceed 24 characters, and must be a single word (no
+                spaces)
+        """
+        self._submit_label = label
+        return self
+
+    def notify_on_cancel(self, notify: bool) -> "DialogBuilder":
+        """
+        Whether this dialog should send a request to your application even if the
+        user cancels their interaction. Defaults to False.
+
+        Args:
+            notify: Set to True to indicate that your application should receive a
+                request even if the user cancels interaction with the dialog.
+        """
+        self._notify_on_cancel = notify
+        return self
+
+    def text_field(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: int = 150,
+        subtype: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Text elements are single-line plain text fields.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. 48 character maximum.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+            hint: Helpful text provided to assist users in answering a question.
+                Up to 150 characters.
+            value: A default value for this field. Up to 150 characters.
+            min_length: Minimum input length allowed for element. Up to 150
+                characters. Defaults to 0.
+            max_length: Maximum input length allowed for element. Up to 150
+                characters. Defaults to 150.
+            subtype: A subtype for this text input. Accepts email, number, tel,
+                    or url. In some form factors, optimized input is provided for this
+                    subtype.
+        """
+        self._elements.append(
+            DialogTextField(
+                name=name,
+                label=label,
+                optional=optional,
+                placeholder=placeholder,
+                hint=hint,
+                value=value,
+                min_length=min_length,
+                max_length=max_length,
+                subtype=subtype,
+            )
+        )
+        return self
+
+    def text_area(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: int = 3000,
+        subtype: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        A textarea is a multi-line plain text editing control. You've likely
+        encountered these on the world wide web. Use this element if you want a
+        relatively long answer from users. The element UI provides a remaining
+        character count to the max_length you have set or the default,
+        3000.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. 48 character maximum.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+            hint: Helpful text provided to assist users in answering a question.
+                Up to 150 characters.
+            value: A default value for this field. Up to 3000 characters.
+            min_length: Minimum input length allowed for element. 1-3000
+                characters. Defaults to 0.
+            max_length: Maximum input length allowed for element. 0-3000
+                characters. Defaults to 3000.
+            subtype: A subtype for this text input. Accepts email, number, tel,
+                or url. In some form factors, optimized input is provided for this
+                subtype.
+        """
+        self._elements.append(
+            DialogTextArea(
+                name=name,
+                label=label,
+                optional=optional,
+                placeholder=placeholder,
+                hint=hint,
+                value=value,
+                min_length=min_length,
+                max_length=max_length,
+                subtype=subtype,
+            )
+        )
+        return self
+
+    def static_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        options: Union[Sequence[Option], Sequence[OptionGroup]],
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A select element may contain up to 100 selections, provided as a list of
+        Option or OptionGroup objects
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            options: A list of up to 100 Option or OptionGroup objects. Object
+                types cannot be mixed.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogStaticSelector(
+                name=name,
+                label=label,
+                options=options,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def external_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[Option] = None,
+        placeholder: Optional[str] = None,
+        min_query_length: Optional[int] = None,
+    ) -> "DialogBuilder":
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A list of options can be loaded from an external URL and used in your dialog
+        menus.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            min_query_length: Specify the number of characters that must be
+                typed by a user into a dynamic select menu before dispatching to your
+                application.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value. This should be a single
+                Option or OptionGroup that exactly matches one that will be returned
+                from your external endpoint.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogExternalSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+                min_query_length=min_query_length,
+            )
+        )
+        return self
+
+    def user_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        Now you can easily populate a select menu with a list of users. For example,
+        when you are creating a bug tracking app, you want to include a field for an
+        assignee. Slack pre-populates the user list in client-side, so your app
+        doesn't need access to a related OAuth scope.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogUserSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def channel_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        You can also provide a select menu with a list of channels. Specify your
+        data_source as channels to limit only to public channels
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogChannelSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    def conversation_selector(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ) -> "DialogBuilder":
+        """
+        You can also provide a select menu with a list of conversations - including
+        private channels, direct messages, MPIMs, and whatever else we consider a
+        conversation-like thing.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        self._elements.append(
+            DialogConversationSelector(
+                name=name,
+                label=label,
+                optional=optional,
+                value=value,
+                placeholder=placeholder,
+            )
+        )
+        return self
+
+    @JsonValidator("title attribute is required")
+    def title_present(self) -> bool:
+        return self._title is not None
+
+    @JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+    def title_length(self) -> bool:
+        return self._title is not None and len(self._title) <= self.title_max_length
+
+    @JsonValidator("callback_id attribute is required")
+    def callback_id_present(self) -> bool:
+        return self._callback_id is not None
+
+    @JsonValidator(f"dialogs must contain between 1 and {elements_max_length} elements")
+    def elements_length(self) -> bool:
+        return 0 < len(self._elements) <= self.elements_max_length
+
+    @JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters")
+    def submit_label_length(self) -> bool:
+        return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length
+
+    @JsonValidator("submit_label can only be one word")
+    def submit_label_valid(self) -> bool:
+        return self._submit_label is None or " " not in self._submit_label
+
+    @JsonValidator(f"state cannot exceed {state_max_length} characters")
+    def state_length(self) -> bool:
+        return not self._state or len(self._state) <= self.state_max_length
+
+    def to_dict(self) -> dict:
+        self.validate_json()
+        json = {
+            "title": self._title,
+            "callback_id": self._callback_id,
+            "elements": extract_json(self._elements),
+            "notify_on_cancel": self._notify_on_cancel,
+        }
+        if self._submit_label is not None:
+            json["submit_label"] = self._submit_label
+        if self._state is not None:
+            json["state"] = self._state
+        return json
+
+

The base class for JSON serializable class objects

+

Create a DialogBuilder to more easily construct the JSON required to submit a +dialog to Slack

+

Ancestors

+ +

Class variables

+
+
var attributes :Β Set[str]
+
+

The type of the None singleton.

+
+
var elements_max_length
+
+

The type of the None singleton.

+
+
var state_max_length
+
+

The type of the None singleton.

+
+
var submit_label_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def callback_id(self, callback_id:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def callback_id(self, callback_id: str) -> "DialogBuilder":
+    """
+    Specify a callback ID for this dialog, which your application will then
+    receive upon dialog submission
+
+    Args:
+      callback_id: a string identifying this particular dialog
+    """
+    self._callback_id = callback_id
+    return self
+
+

Specify a callback ID for this dialog, which your application will then +receive upon dialog submission

+

Args

+
+
callback_id
+
a string identifying this particular dialog
+
+
+
+def callback_id_present(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("callback_id attribute is required")
+def callback_id_present(self) -> bool:
+    return self._callback_id is not None
+
+
+
+
+def channel_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def channel_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    You can also provide a select menu with a list of channels. Specify your
+    data_source as channels to limit only to public channels
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogChannelSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

You can also provide a select menu with a list of channels. Specify your +data_source as channels to limit only to public channels

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def conversation_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def conversation_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    You can also provide a select menu with a list of conversations - including
+    private channels, direct messages, MPIMs, and whatever else we consider a
+    conversation-like thing.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogConversationSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

You can also provide a select menu with a list of conversations - including +private channels, direct messages, MPIMs, and whatever else we consider a +conversation-like thing.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def elements_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"dialogs must contain between 1 and {elements_max_length} elements")
+def elements_length(self) -> bool:
+    return 0 < len(self._elements) <= self.elements_max_length
+
+
+
+
+def external_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def external_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[Option] = None,
+    placeholder: Optional[str] = None,
+    min_query_length: Optional[int] = None,
+) -> "DialogBuilder":
+    """
+    Use the select element for multiple choice selections allowing users to pick
+    a single item from a list. True to web roots, this selection is displayed as
+    a dropdown menu.
+
+    A list of options can be loaded from an external URL and used in your dialog
+    menus.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        min_query_length: Specify the number of characters that must be
+            typed by a user into a dynamic select menu before dispatching to your
+            application.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value. This should be a single
+            Option or OptionGroup that exactly matches one that will be returned
+            from your external endpoint.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogExternalSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+            min_query_length=min_query_length,
+        )
+    )
+    return self
+
+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A list of options can be loaded from an external URL and used in your dialog +menus.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
min_query_length
+
Specify the number of characters that must be +typed by a user into a dynamic select menu before dispatching to your +application.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value. This should be a single +Option or OptionGroup that exactly matches one that will be returned +from your external endpoint.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def notify_on_cancel(self, notify:Β bool) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def notify_on_cancel(self, notify: bool) -> "DialogBuilder":
+    """
+    Whether this dialog should send a request to your application even if the
+    user cancels their interaction. Defaults to False.
+
+    Args:
+        notify: Set to True to indicate that your application should receive a
+            request even if the user cancels interaction with the dialog.
+    """
+    self._notify_on_cancel = notify
+    return self
+
+

Whether this dialog should send a request to your application even if the +user cancels their interaction. Defaults to False.

+

Args

+
+
notify
+
Set to True to indicate that your application should receive a +request even if the user cancels interaction with the dialog.
+
+
+
+def state(self, state:Β dictΒ |Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def state(self, state: Union[dict, str]) -> "DialogBuilder":
+    """
+    Pass state into this dialog - dictionaries will be automatically formatted to
+    JSON
+
+    Args:
+        state: Extra state information that you need to pass from this dialog
+            back to your application on submission
+    """
+    if isinstance(state, dict):
+        self._state = dumps(state)
+    else:
+        self._state = state
+    return self
+
+

Pass state into this dialog - dictionaries will be automatically formatted to +JSON

+

Args

+
+
state
+
Extra state information that you need to pass from this dialog +back to your application on submission
+
+
+
+def state_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"state cannot exceed {state_max_length} characters")
+def state_length(self) -> bool:
+    return not self._state or len(self._state) <= self.state_max_length
+
+
+
+
+def static_selector(self,
*,
name:Β str,
label:Β str,
options:Β Sequence[Option]Β |Β Sequence[OptionGroup],
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def static_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    options: Union[Sequence[Option], Sequence[OptionGroup]],
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Use the select element for multiple choice selections allowing users to pick
+    a single item from a list. True to web roots, this selection is displayed as
+    a dropdown menu.
+
+    A select element may contain up to 100 selections, provided as a list of
+    Option or OptionGroup objects
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        options: A list of up to 100 Option or OptionGroup objects. Object
+            types cannot be mixed.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogStaticSelector(
+            name=name,
+            label=label,
+            options=options,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A select element may contain up to 100 selections, provided as a list of +Option or OptionGroup objects

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
options
+
A list of up to 100 Option or OptionGroup objects. Object +types cannot be mixed.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+def submit_label(self, label:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def submit_label(self, label: str) -> "DialogBuilder":
+    """
+    The label to use on the 'Submit' button on the dialog. Defaults to 'Submit'
+    if not specified.
+
+    Args:
+        label: must not exceed 24 characters, and must be a single word (no
+            spaces)
+    """
+    self._submit_label = label
+    return self
+
+

The label to use on the 'Submit' button on the dialog. Defaults to 'Submit' +if not specified.

+

Args

+
+
label
+
must not exceed 24 characters, and must be a single word (no +spaces)
+
+
+
+def submit_label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters")
+def submit_label_length(self) -> bool:
+    return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length
+
+
+
+
+def submit_label_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("submit_label can only be one word")
+def submit_label_valid(self) -> bool:
+    return self._submit_label is None or " " not in self._submit_label
+
+
+
+
+def text_area(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ =Β 3000,
subtype:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def text_area(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    placeholder: Optional[str] = None,
+    hint: Optional[str] = None,
+    value: Optional[str] = None,
+    min_length: int = 0,
+    max_length: int = 3000,
+    subtype: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    A textarea is a multi-line plain text editing control. You've likely
+    encountered these on the world wide web. Use this element if you want a
+    relatively long answer from users. The element UI provides a remaining
+    character count to the max_length you have set or the default,
+    3000.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. 48 character maximum.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+        hint: Helpful text provided to assist users in answering a question.
+            Up to 150 characters.
+        value: A default value for this field. Up to 3000 characters.
+        min_length: Minimum input length allowed for element. 1-3000
+            characters. Defaults to 0.
+        max_length: Maximum input length allowed for element. 0-3000
+            characters. Defaults to 3000.
+        subtype: A subtype for this text input. Accepts email, number, tel,
+            or url. In some form factors, optimized input is provided for this
+            subtype.
+    """
+    self._elements.append(
+        DialogTextArea(
+            name=name,
+            label=label,
+            optional=optional,
+            placeholder=placeholder,
+            hint=hint,
+            value=value,
+            min_length=min_length,
+            max_length=max_length,
+            subtype=subtype,
+        )
+    )
+    return self
+
+

A textarea is a multi-line plain text editing control. You've likely +encountered these on the world wide web. Use this element if you want a +relatively long answer from users. The element UI provides a remaining +character count to the max_length you have set or the default, +3000.

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. 48 character maximum.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
hint
+
Helpful text provided to assist users in answering a question. +Up to 150 characters.
+
value
+
A default value for this field. Up to 3000 characters.
+
min_length
+
Minimum input length allowed for element. 1-3000 +characters. Defaults to 0.
+
max_length
+
Maximum input length allowed for element. 0-3000 +characters. Defaults to 3000.
+
subtype
+
A subtype for this text input. Accepts email, number, tel, +or url. In some form factors, optimized input is provided for this +subtype.
+
+
+
+def text_field(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ =Β 150,
subtype:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def text_field(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    placeholder: Optional[str] = None,
+    hint: Optional[str] = None,
+    value: Optional[str] = None,
+    min_length: int = 0,
+    max_length: int = 150,
+    subtype: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Text elements are single-line plain text fields.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. 48 character maximum.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+        hint: Helpful text provided to assist users in answering a question.
+            Up to 150 characters.
+        value: A default value for this field. Up to 150 characters.
+        min_length: Minimum input length allowed for element. Up to 150
+            characters. Defaults to 0.
+        max_length: Maximum input length allowed for element. Up to 150
+            characters. Defaults to 150.
+        subtype: A subtype for this text input. Accepts email, number, tel,
+                or url. In some form factors, optimized input is provided for this
+                subtype.
+    """
+    self._elements.append(
+        DialogTextField(
+            name=name,
+            label=label,
+            optional=optional,
+            placeholder=placeholder,
+            hint=hint,
+            value=value,
+            min_length=min_length,
+            max_length=max_length,
+            subtype=subtype,
+        )
+    )
+    return self
+
+

Text elements are single-line plain text fields.

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. 48 character maximum.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
hint
+
Helpful text provided to assist users in answering a question. +Up to 150 characters.
+
value
+
A default value for this field. Up to 150 characters.
+
min_length
+
Minimum input length allowed for element. Up to 150 +characters. Defaults to 0.
+
max_length
+
Maximum input length allowed for element. Up to 150 +characters. Defaults to 150.
+
subtype
+
A subtype for this text input. Accepts email, number, tel, +or url. In some form factors, optimized input is provided for this +subtype.
+
+
+
+def title(self, title:Β str) ‑>Β DialogBuilder +
+
+
+ +Expand source code + +
def title(self, title: str) -> "DialogBuilder":
+    """
+    Specify a title for this dialog
+
+    Args:
+      title: must not exceed 24 characters
+    """
+    self._title = title
+    return self
+
+

Specify a title for this dialog

+

Args

+
+
title
+
must not exceed 24 characters
+
+
+
+def title_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"title attribute cannot exceed {title_max_length} characters")
+def title_length(self) -> bool:
+    return self._title is not None and len(self._title) <= self.title_max_length
+
+
+
+
+def title_present(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("title attribute is required")
+def title_present(self) -> bool:
+    return self._title is not None
+
+
+
+
+def user_selector(self,
*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None) ‑>Β DialogBuilder
+
+
+
+ +Expand source code + +
def user_selector(
+    self,
+    *,
+    name: str,
+    label: str,
+    optional: bool = False,
+    value: Optional[str] = None,
+    placeholder: Optional[str] = None,
+) -> "DialogBuilder":
+    """
+    Now you can easily populate a select menu with a list of users. For example,
+    when you are creating a bug tracking app, you want to include a field for an
+    assignee. Slack pre-populates the user list in client-side, so your app
+    doesn't need access to a related OAuth scope.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+    Args:
+        name: Name of form element. Required. No more than 300 characters.
+        label: Label displayed to user. Required. No more than 48 characters.
+        optional: Provide true when the form element is not required. By
+            default, form elements are required.
+        value: Provide a default selected value.
+        placeholder: A string displayed as needed to help guide users in
+            completing the element. 150 character maximum.
+    """
+    self._elements.append(
+        DialogUserSelector(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+    )
+    return self
+
+

Now you can easily populate a select menu with a list of users. For example, +when you are creating a bug tracking app, you want to include a field for an +assignee. Slack pre-populates the user list in client-side, so your app +doesn't need access to a related OAuth scope.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+
+
+

Inherited members

+ +
+
+class DialogChannelSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogChannelSelector(AbstractDialogSelector):
+    data_source = "channels"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        You can also provide a select menu with a list of channels. Specify your
+        data_source as channels to limit only to public channels
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

You can also provide a select menu with a list of channels. Specify your +data_source as channels to limit only to public channels

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogConversationSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogConversationSelector(AbstractDialogSelector):
+    data_source = "conversations"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        You can also provide a select menu with a list of conversations - including
+        private channels, direct messages, MPIMs, and whatever else we consider a
+        conversation-like thing.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

You can also provide a select menu with a list of conversations - including +private channels, direct messages, MPIMs, and whatever else we consider a +conversation-like thing.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogExternalSelector +(*,
name:Β str,
label:Β str,
value:Β OptionΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
optional:Β boolΒ |Β NoneΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogExternalSelector(AbstractDialogSelector):
+    data_source = "external"
+
+    @property
+    def attributes(self) -> Set[str]:  # type: ignore[override]
+        return super().attributes.union({"min_query_length"})
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        value: Optional[Option] = None,
+        min_query_length: Optional[int] = None,
+        optional: Optional[bool] = False,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A list of options can be loaded from an external URL and used in your dialog
+        menus.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            min_query_length: Specify the number of characters that must be typed
+                by a user into a dynamic select menu before dispatching to the app.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value. This should be a single
+                Option or OptionGroup that exactly matches one that will be returned
+                from your external endpoint.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            value=value,
+            optional=optional,  # type: ignore[arg-type]
+            placeholder=placeholder,
+        )
+        self.min_query_length = min_query_length
+
+

The base class for JSON serializable class objects

+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A list of options can be loaded from an external URL and used in your dialog +menus.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
min_query_length
+
Specify the number of characters that must be typed +by a user into a dynamic select menu before dispatching to the app.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value. This should be a single +Option or OptionGroup that exactly matches one that will be returned +from your external endpoint.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+def attributes(self) -> Set[str]:  # type: ignore[override]
+    return super().attributes.union({"min_query_length"})
+
+

Build an unordered collection of unique elements.

+
+
+

Inherited members

+ +
+
+class DialogStaticSelector +(*,
name:Β str,
label:Β str,
options:Β Sequence[Option]Β |Β Sequence[OptionGroup],
optional:Β boolΒ =Β False,
value:Β OptionΒ |Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogStaticSelector(AbstractDialogSelector):
+    """
+    Use the select element for multiple choice selections allowing users to pick a
+    single item from a list. True to web roots, this selection is displayed as a
+    dropdown menu.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#select_elements
+    """
+
+    data_source = "static"
+
+    options_max_length = 100
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        options: Union[Sequence[Option], Sequence[OptionGroup]],
+        optional: bool = False,
+        value: Optional[Union[Option, str]] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Use the select element for multiple choice selections allowing users to pick
+        a single item from a list. True to web roots, this selection is displayed as
+        a dropdown menu.
+
+        A select element may contain up to 100 selections, provided as a list of
+        Option or OptionGroup objects
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            options: A list of up to 100 Option or OptionGroup objects. Object
+                types cannot be mixed.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+        self.options = options
+
+    @JsonValidator(f"options attribute cannot exceed {options_max_length} items")
+    def options_length(self) -> bool:
+        return len(self.options) < self.options_max_length
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if isinstance(self.options[0], OptionGroup):
+            json["option_groups"] = extract_json(self.options, "dialog")
+        else:
+            json["options"] = extract_json(self.options, "dialog")
+        return json
+
+

Use the select element for multiple choice selections allowing users to pick a +single item from a list. True to web roots, this selection is displayed as a +dropdown menu.

+

https://docs.slack.dev/legacy/legacy-dialogs/#select_elements

+

Use the select element for multiple choice selections allowing users to pick +a single item from a list. True to web roots, this selection is displayed as +a dropdown menu.

+

A select element may contain up to 100 selections, provided as a list of +Option or OptionGroup objects

+

https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
options
+
A list of up to 100 Option or OptionGroup objects. Object +types cannot be mixed.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
var options_max_length
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def options_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"options attribute cannot exceed {options_max_length} items")
+def options_length(self) -> bool:
+    return len(self.options) < self.options_max_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogTextArea +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextArea(DialogTextComponent):
+    """
+    A textarea is a multi-line plain text editing control. You've likely encountered
+    these on the world wide web. Use this element if you want a relatively long
+    answer from users. The element UI provides a remaining character count to the
+    max_length you have set or the default, 3000.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#textarea_elements
+    """
+
+    type = "textarea"
+    max_value_length = 3000
+
+

A textarea is a multi-line plain text editing control. You've likely encountered +these on the world wide web. Use this element if you want a relatively long +answer from users. The element UI provides a remaining character count to the +max_length you have set or the default, 3000.

+

https://docs.slack.dev/legacy/legacy-dialogs/#textarea_elements

+

Ancestors

+ +

Class variables

+
+
var max_value_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogTextComponent +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextComponent(JsonObject, metaclass=ABCMeta):
+    attributes = {
+        "hint",
+        "label",
+        "max_length",
+        "min_length",
+        "name",
+        "optional",
+        "placeholder",
+        "subtype",
+        "type",
+        "value",
+    }
+
+    name_max_length = 300
+    label_max_length = 48
+    placeholder_max_length = 150
+    hint_max_length = 150
+
+    @property
+    @abstractmethod
+    def type(self):
+        pass
+
+    @property
+    @abstractmethod
+    def max_value_length(self):
+        pass
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        placeholder: Optional[str] = None,
+        hint: Optional[str] = None,
+        value: Optional[str] = None,
+        min_length: int = 0,
+        max_length: Optional[int] = None,
+        subtype: Optional[str] = None,
+    ):
+        self.name = name
+        self.label = label
+        self.optional = optional
+        self.placeholder = placeholder
+        self.hint = hint
+        self.value = value
+        self.min_length = min_length
+        self.max_length = max_length or self.max_value_length
+        self.subtype = subtype
+
+    @JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+    def name_length(self) -> bool:
+        return len(self.name) < self.name_max_length
+
+    @JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+    def label_length(self) -> bool:
+        return len(self.label) < self.label_max_length
+
+    @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+    def placeholder_length(self) -> bool:
+        return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+    @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+    def hint_length(self) -> bool:
+        return self.hint is None or len(self.hint) < self.hint_max_length
+
+    @JsonValidator("value attribute exceeded bounds")
+    def value_length(self) -> bool:
+        return self.value is None or len(self.value) < self.max_value_length
+
+    @JsonValidator("min_length attribute must be greater than or equal to 0")
+    def min_length_above_zero(self) -> bool:
+        return self.min_length is None or self.min_length >= 0
+
+    @JsonValidator("min_length attribute exceed bounds")
+    def min_length_length(self) -> bool:
+        return self.min_length is None or self.min_length <= self.max_value_length
+
+    @JsonValidator("min_length attribute must be less than max value attribute")
+    def min_length_below_max_length(self) -> bool:
+        return self.min_length is None or self.min_length < self.max_length
+
+    @JsonValidator("max_length attribute must be greater than or equal to 0")
+    def max_length_above_zero(self) -> bool:
+        return self.max_length is None or self.max_length > 0
+
+    @JsonValidator("max_length attribute exceeded bounds")
+    def max_length_length(self) -> bool:
+        return self.max_length is None or self.max_length <= self.max_value_length
+
+    @EnumValidator("subtype", TextElementSubtypes)
+    def subtype_valid(self) -> bool:
+        return self.subtype is None or self.subtype in TextElementSubtypes
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var hint_max_length
+
+

The type of the None singleton.

+
+
var label_max_length
+
+

The type of the None singleton.

+
+
var name_max_length
+
+

The type of the None singleton.

+
+
var placeholder_max_length
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop max_value_length
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def max_value_length(self):
+    pass
+
+
+
+
prop type
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def type(self):
+    pass
+
+
+
+
+

Methods

+
+
+def hint_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters")
+def hint_length(self) -> bool:
+    return self.hint is None or len(self.hint) < self.hint_max_length
+
+
+
+
+def label_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"label attribute cannot exceed {label_max_length} characters")
+def label_length(self) -> bool:
+    return len(self.label) < self.label_max_length
+
+
+
+
+def max_length_above_zero(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("max_length attribute must be greater than or equal to 0")
+def max_length_above_zero(self) -> bool:
+    return self.max_length is None or self.max_length > 0
+
+
+
+
+def max_length_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("max_length attribute exceeded bounds")
+def max_length_length(self) -> bool:
+    return self.max_length is None or self.max_length <= self.max_value_length
+
+
+
+
+def min_length_above_zero(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute must be greater than or equal to 0")
+def min_length_above_zero(self) -> bool:
+    return self.min_length is None or self.min_length >= 0
+
+
+
+
+def min_length_below_max_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute must be less than max value attribute")
+def min_length_below_max_length(self) -> bool:
+    return self.min_length is None or self.min_length < self.max_length
+
+
+
+
+def min_length_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("min_length attribute exceed bounds")
+def min_length_length(self) -> bool:
+    return self.min_length is None or self.min_length <= self.max_value_length
+
+
+
+
+def name_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"name attribute cannot exceed {name_max_length} characters")
+def name_length(self) -> bool:
+    return len(self.name) < self.name_max_length
+
+
+
+
+def placeholder_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters")
+def placeholder_length(self) -> bool:
+    return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length
+
+
+
+
+def subtype_valid(self) ‑>Β bool +
+
+
+ +Expand source code + +
@EnumValidator("subtype", TextElementSubtypes)
+def subtype_valid(self) -> bool:
+    return self.subtype is None or self.subtype in TextElementSubtypes
+
+
+
+
+def value_length(self) ‑>Β bool +
+
+
+ +Expand source code + +
@JsonValidator("value attribute exceeded bounds")
+def value_length(self) -> bool:
+    return self.value is None or len(self.value) < self.max_value_length
+
+
+
+
+

Inherited members

+ +
+
+class DialogTextField +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
placeholder:Β strΒ |Β NoneΒ =Β None,
hint:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
min_length:Β intΒ =Β 0,
max_length:Β intΒ |Β NoneΒ =Β None,
subtype:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogTextField(DialogTextComponent):
+    """
+    Text elements are single-line plain text fields.
+
+    https://docs.slack.dev/legacy/legacy-dialogs/#text_elements
+    """
+
+    type = "text"
+    max_value_length = 150
+
+

Text elements are single-line plain text fields.

+

https://docs.slack.dev/legacy/legacy-dialogs/#text_elements

+

Ancestors

+ +

Class variables

+
+
var max_value_length
+
+

The type of the None singleton.

+
+
var type
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class DialogUserSelector +(*,
name:Β str,
label:Β str,
optional:Β boolΒ =Β False,
value:Β strΒ |Β NoneΒ =Β None,
placeholder:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class DialogUserSelector(AbstractDialogSelector):
+    data_source = "users"
+
+    def __init__(
+        self,
+        *,
+        name: str,
+        label: str,
+        optional: bool = False,
+        value: Optional[str] = None,
+        placeholder: Optional[str] = None,
+    ):
+        """
+        Now you can easily populate a select menu with a list of users. For example,
+        when you are creating a bug tracking app, you want to include a field for an
+        assignee. Slack pre-populates the user list in client-side, so your app
+        doesn't need access to a related OAuth scope.
+
+        https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users
+
+        Args:
+            name: Name of form element. Required. No more than 300 characters.
+            label: Label displayed to user. Required. No more than 48 characters.
+            optional: Provide true when the form element is not required. By
+                default, form elements are required.
+            value: Provide a default selected value.
+            placeholder: A string displayed as needed to help guide users in
+                completing the element. 150 character maximum.
+        """
+        super().__init__(
+            name=name,
+            label=label,
+            optional=optional,
+            value=value,
+            placeholder=placeholder,
+        )
+
+

The base class for JSON serializable class objects

+

Now you can easily populate a select menu with a list of users. For example, +when you are creating a bug tracking app, you want to include a field for an +assignee. Slack pre-populates the user list in client-side, so your app +doesn't need access to a related OAuth scope.

+

https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users

+

Args

+
+
name
+
Name of form element. Required. No more than 300 characters.
+
label
+
Label displayed to user. Required. No more than 48 characters.
+
optional
+
Provide true when the form element is not required. By +default, form elements are required.
+
value
+
Provide a default selected value.
+
placeholder
+
A string displayed as needed to help guide users in +completing the element. 150 character maximum.
+
+

Ancestors

+ +

Class variables

+
+
var data_source
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/index.html b/docs/reference/models/index.html new file mode 100644 index 000000000..d3670bfde --- /dev/null +++ b/docs/reference/models/index.html @@ -0,0 +1,596 @@ + + + + + + +slack_sdk.models API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models

+
+
+

Classes for constructing Slack-specific data structure

+
+
+

Sub-modules

+
+
slack_sdk.models.attachments
+
+
+
+
slack_sdk.models.basic_objects
+
+
+
+
slack_sdk.models.blocks
+
+

Block Kit data model objects …

+
+
slack_sdk.models.dialoags
+
+
+
+
slack_sdk.models.dialogs
+
+
+
+
slack_sdk.models.messages
+
+
+
+
slack_sdk.models.metadata
+
+
+
+
slack_sdk.models.views
+
+
+
+
+
+
+
+
+

Functions

+
+
+def extract_json(item_or_items:Β JsonObjectΒ |Β Sequence[JsonObject],
*format_args) ‑>Β Dict[Any,Β Any]Β |Β List[Dict[Any,Β Any]]Β |Β Sequence[JsonObject]
+
+
+
+ +Expand source code + +
def extract_json(
+    item_or_items: Union[JsonObject, Sequence[JsonObject]], *format_args
+) -> Union[Dict[Any, Any], List[Dict[Any, Any]], Sequence[JsonObject]]:
+    """
+    Given a sequence (or single item), attempt to call the to_dict() method on each
+    item and return a plain list. If item is not the expected type, return it
+    unmodified, in case it's already a plain dict or some other user created class.
+
+    Args:
+      item_or_items: item(s) to go through
+      format_args: Any formatting specifiers to pass into the object's to_dict
+            method
+    """
+    try:
+        return [
+            elem.to_dict(*format_args) if isinstance(elem, JsonObject) else elem
+            for elem in item_or_items  # type: ignore[union-attr]
+        ]
+    except TypeError:  # not iterable, so try returning it as a single item
+        return item_or_items.to_dict(*format_args) if isinstance(item_or_items, JsonObject) else item_or_items
+
+

Given a sequence (or single item), attempt to call the to_dict() method on each +item and return a plain list. If item is not the expected type, return it +unmodified, in case it's already a plain dict or some other user created class.

+

Args

+
+
item_or_items
+
item(s) to go through
+
format_args
+
Any formatting specifiers to pass into the object's to_dict +method
+
+
+
+def show_unknown_key_warning(name:Β strΒ |Β object, others:Β dict) +
+
+
+ +Expand source code + +
def show_unknown_key_warning(name: Union[str, object], others: dict):
+    if "type" in others:
+        others.pop("type")
+    if len(others) > 0:
+        keys = ", ".join(others.keys())
+        logger = logging.getLogger(__name__)
+        if isinstance(name, object):
+            name = name.__class__.__name__
+        logger.debug(
+            f"!!! {name}'s constructor args ({keys}) were ignored."
+            f"If they should be supported by this library, report this issue to the project :bow: "
+            f"https://github.com/slackapi/python-slack-sdk/issues"
+        )
+
+
+
+
+
+
+

Classes

+
+
+class BaseObject +
+
+
+ +Expand source code + +
class BaseObject:
+    """The base class for all model objects in this module"""
+
+    def __str__(self):
+        return f"<slack_sdk.{self.__class__.__name__}>"
+
+

The base class for all model objects in this module

+

Subclasses

+ +
+
+class EnumValidator +(attribute:Β str, enum:Β Iterable[str]) +
+
+
+ +Expand source code + +
class EnumValidator(JsonValidator):
+    def __init__(self, attribute: str, enum: Iterable[str]):
+        super().__init__(f"{attribute} attribute must be one of the following values: " f"{', '.join(enum)}")
+
+

Decorate a method on a class to mark it as a JSON validator. Validation +functions should return true if valid, false if not.

+

Args

+
+
message
+
Message to be attached to the thrown SlackObjectFormationError
+
+

Ancestors

+ +
+
+class JsonObject +
+
+
+ +Expand source code + +
class JsonObject(BaseObject, metaclass=ABCMeta):
+    """The base class for JSON serializable class objects"""
+
+    @property
+    @abstractmethod
+    def attributes(self) -> Set[str]:
+        """Provide a set of attributes of this object that will make up its JSON structure"""
+        return set()
+
+    def validate_json(self) -> None:
+        """
+        Raises:
+          SlackObjectFormationError if the object was not valid
+        """
+        for attribute in (func for func in dir(self) if not func.startswith("__")):
+            method = getattr(self, attribute, None)
+            if callable(method) and hasattr(method, "validator"):
+                method()
+
+    def get_object_attribute(self, key: str):
+        return getattr(self, key, None)
+
+    def get_non_null_attributes(self) -> dict:
+        """
+        Construct a dictionary out of non-null keys (from attributes property)
+        present on this object
+        """
+
+        def to_dict_compatible(value: Union[dict, list, object, tuple]) -> Union[dict, list, Any]:
+            if isinstance(value, (list, tuple)):
+                return [to_dict_compatible(v) for v in value]
+            else:
+                to_dict = getattr(value, "to_dict", None)
+                if to_dict and callable(to_dict):
+                    return {k: to_dict_compatible(v) for k, v in value.to_dict().items()}  # type: ignore[attr-defined]
+                else:
+                    return value
+
+        def is_not_empty(self, key: str) -> bool:
+            value = self.get_object_attribute(key)
+            if value is None:
+                return False
+
+            # Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions.
+            # The following code deals with these exceptions:
+            type_value = getattr(self, "type", None)
+            for empty_allowed in EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST:
+                if type_value == empty_allowed["type"] and key == empty_allowed["property"]:
+                    return True
+
+            has_len = getattr(value, "__len__", None) is not None
+            if has_len:
+                return len(value) > 0
+            else:
+                return value is not None
+
+        return {
+            key: to_dict_compatible(value=self.get_object_attribute(key))
+            for key in sorted(self.attributes)
+            if is_not_empty(self, key)
+        }
+
+    def to_dict(self, *args) -> dict:
+        """
+        Extract this object as a JSON-compatible, Slack-API-valid dictionary
+
+        Args:
+          *args: Any specific formatting args (rare; generally not required)
+
+        Raises:
+          SlackObjectFormationError if the object was not valid
+        """
+        self.validate_json()
+        return self.get_non_null_attributes()
+
+    def __repr__(self):
+        dict_value = self.get_non_null_attributes()
+        if dict_value:
+            return f"<slack_sdk.{self.__class__.__name__}: {dict_value}>"
+        else:
+            return self.__str__()
+
+    def __eq__(self, other: Any) -> bool:
+        if not isinstance(other, JsonObject):
+            return False
+        return self.to_dict() == other.to_dict()
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Subclasses

+ +

Instance variables

+
+
prop attributes :Β Set[str]
+
+
+ +Expand source code + +
@property
+@abstractmethod
+def attributes(self) -> Set[str]:
+    """Provide a set of attributes of this object that will make up its JSON structure"""
+    return set()
+
+

Provide a set of attributes of this object that will make up its JSON structure

+
+
+

Methods

+
+
+def get_non_null_attributes(self) ‑>Β dict +
+
+
+ +Expand source code + +
def get_non_null_attributes(self) -> dict:
+    """
+    Construct a dictionary out of non-null keys (from attributes property)
+    present on this object
+    """
+
+    def to_dict_compatible(value: Union[dict, list, object, tuple]) -> Union[dict, list, Any]:
+        if isinstance(value, (list, tuple)):
+            return [to_dict_compatible(v) for v in value]
+        else:
+            to_dict = getattr(value, "to_dict", None)
+            if to_dict and callable(to_dict):
+                return {k: to_dict_compatible(v) for k, v in value.to_dict().items()}  # type: ignore[attr-defined]
+            else:
+                return value
+
+    def is_not_empty(self, key: str) -> bool:
+        value = self.get_object_attribute(key)
+        if value is None:
+            return False
+
+        # Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions.
+        # The following code deals with these exceptions:
+        type_value = getattr(self, "type", None)
+        for empty_allowed in EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST:
+            if type_value == empty_allowed["type"] and key == empty_allowed["property"]:
+                return True
+
+        has_len = getattr(value, "__len__", None) is not None
+        if has_len:
+            return len(value) > 0
+        else:
+            return value is not None
+
+    return {
+        key: to_dict_compatible(value=self.get_object_attribute(key))
+        for key in sorted(self.attributes)
+        if is_not_empty(self, key)
+    }
+
+

Construct a dictionary out of non-null keys (from attributes property) +present on this object

+
+
+def get_object_attribute(self, key:Β str) +
+
+
+ +Expand source code + +
def get_object_attribute(self, key: str):
+    return getattr(self, key, None)
+
+
+
+
+def to_dict(self, *args) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self, *args) -> dict:
+    """
+    Extract this object as a JSON-compatible, Slack-API-valid dictionary
+
+    Args:
+      *args: Any specific formatting args (rare; generally not required)
+
+    Raises:
+      SlackObjectFormationError if the object was not valid
+    """
+    self.validate_json()
+    return self.get_non_null_attributes()
+
+

Extract this object as a JSON-compatible, Slack-API-valid dictionary

+

Args

+
+
*args
+
Any specific formatting args (rare; generally not required)
+
+

Raises

+

SlackObjectFormationError if the object was not valid

+
+
+def validate_json(self) ‑>Β None +
+
+
+ +Expand source code + +
def validate_json(self) -> None:
+    """
+    Raises:
+      SlackObjectFormationError if the object was not valid
+    """
+    for attribute in (func for func in dir(self) if not func.startswith("__")):
+        method = getattr(self, attribute, None)
+        if callable(method) and hasattr(method, "validator"):
+            method()
+
+

Raises

+

SlackObjectFormationError if the object was not valid

+
+
+
+
+class JsonValidator +(message:Β str) +
+
+
+ +Expand source code + +
class JsonValidator:
+    def __init__(self, message: str):
+        """
+        Decorate a method on a class to mark it as a JSON validator. Validation
+            functions should return true if valid, false if not.
+
+        Args:
+            message: Message to be attached to the thrown SlackObjectFormationError
+        """
+        self.message = message
+
+    def __call__(self, func: Callable) -> Callable[..., None]:
+        @wraps(func)
+        def wrapped_f(*args, **kwargs):
+            if not func(*args, **kwargs):
+                raise SlackObjectFormationError(self.message)
+
+        wrapped_f.validator = True  # type: ignore[attr-defined]
+        return wrapped_f
+
+

Decorate a method on a class to mark it as a JSON validator. Validation +functions should return true if valid, false if not.

+

Args

+
+
message
+
Message to be attached to the thrown SlackObjectFormationError
+
+

Subclasses

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/messages/index.html b/docs/reference/models/messages/index.html new file mode 100644 index 000000000..5d10ced1c --- /dev/null +++ b/docs/reference/models/messages/index.html @@ -0,0 +1,300 @@ + + + + + + +slack_sdk.models.messages API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.messages

+
+
+
+
+

Sub-modules

+
+
slack_sdk.models.messages.message
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+ +
+
+ +Expand source code + +
class ChannelLink(Link):
+    def __init__(self):
+        """Represents an @channel link, which notifies everyone present in this channel.
+        https://docs.slack.dev/messaging/formatting-message-text/
+        """
+        super().__init__(url="!channel", text="channel")
+
+

The base class for all model objects in this module

+

Represents an @channel link, which notifies everyone present in this channel. +https://docs.slack.dev/messaging/formatting-message-text/

+

Ancestors

+ +
+ +
+
+ +Expand source code + +
class DateLink(Link):
+    def __init__(
+        self,
+        *,
+        date: Union[datetime, int],
+        date_format: str,
+        fallback: str,
+        link: Optional[str] = None,
+    ):
+        """Text containing a date or time should display that date in the local timezone of the person seeing the text.
+        https://docs.slack.dev/messaging/formatting-message-text/#date-formatting
+        """
+        if isinstance(date, datetime):
+            epoch = int(date.timestamp())
+        else:
+            epoch = date
+        if link is not None:
+            link = f"^{link}"
+        else:
+            link = ""
+        super().__init__(url=f"!date^{epoch}^{date_format}{link}", text=fallback)
+
+

The base class for all model objects in this module

+

Text containing a date or time should display that date in the local timezone of the person seeing the text. +https://docs.slack.dev/messaging/formatting-message-text/#date-formatting

+

Ancestors

+ +
+ +
+
+ +Expand source code + +
class EveryoneLink(Link):
+    def __init__(self):
+        """Represents an @everyone link, which notifies all users of this workspace.
+        https://docs.slack.dev/messaging/formatting-message-text/
+        """
+        super().__init__(url="!everyone", text="everyone")
+
+

The base class for all model objects in this module

+

Represents an @everyone link, which notifies all users of this workspace. +https://docs.slack.dev/messaging/formatting-message-text/

+

Ancestors

+ +
+ +
+
+ +Expand source code + +
class HereLink(Link):
+    def __init__(self):
+        """Represents an @here link, which notifies all online users of this channel.
+        https://docs.slack.dev/messaging/formatting-message-text/
+        """
+        super().__init__(url="!here", text="here")
+
+

The base class for all model objects in this module

+

Represents an @here link, which notifies all online users of this channel. +https://docs.slack.dev/messaging/formatting-message-text/

+

Ancestors

+ +
+ +
+
+ +Expand source code + +
class Link(BaseObject):
+    def __init__(self, *, url: str, text: str):
+        """Base class used to generate links in Slack's not-quite Markdown, not quite HTML syntax
+        https://docs.slack.dev/messaging/formatting-message-text/#linking_to_urls
+        """
+        self.url = url
+        self.text = text
+
+    def __str__(self):
+        if self.text:
+            separator = "|"
+        else:
+            separator = ""
+        return f"<{self.url}{separator}{self.text}>"
+
+

The base class for all model objects in this module

+

Base class used to generate links in Slack's not-quite Markdown, not quite HTML syntax +https://docs.slack.dev/messaging/formatting-message-text/#linking_to_urls

+

Ancestors

+ +

Subclasses

+ +
+ +
+
+ +Expand source code + +
class ObjectLink(Link):
+    prefix_mapping = {
+        "C": "#",  # channel
+        "G": "#",  # group message
+        "U": "@",  # user
+        "W": "@",  # workspace user (enterprise)
+        "B": "@",  # bot user
+        "S": "!subteam^",  # user groups, originally known as subteams
+    }
+
+    def __init__(self, *, object_id: str, text: str = ""):
+        """Convenience class to create links to specific object types
+        https://docs.slack.dev/messaging/formatting-message-text/#linking-channels
+        """
+        prefix = self.prefix_mapping.get(object_id[0].upper(), "@")
+        super().__init__(url=f"{prefix}{object_id}", text=text)
+
+

The base class for all model objects in this module

+

Convenience class to create links to specific object types +https://docs.slack.dev/messaging/formatting-message-text/#linking-channels

+

Ancestors

+ +

Class variables

+
+
var prefix_mapping
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/models/messages/message.html b/docs/reference/models/messages/message.html new file mode 100644 index 000000000..6a7e7a85a --- /dev/null +++ b/docs/reference/models/messages/message.html @@ -0,0 +1,210 @@ + + + + + + +slack_sdk.models.messages.message API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.messages.message

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Message +(*,
text:Β str,
attachments:Β Sequence[Attachment]Β |Β NoneΒ =Β None,
blocks:Β Sequence[Block]Β |Β NoneΒ =Β None,
markdown:Β boolΒ =Β True)
+
+
+
+ +Expand source code + +
class Message(JsonObject):
+    attributes = {"text"}
+
+    attachments_max_length = 100
+
+    def __init__(
+        self,
+        *,
+        text: str,
+        attachments: Optional[Sequence[Attachment]] = None,
+        blocks: Optional[Sequence[Block]] = None,
+        markdown: bool = True,
+    ):
+        """
+        Create a message.
+
+        https://docs.slack.dev/messaging/#message-structure
+
+        Args:
+            text: Plain or Slack Markdown-like text to display in the message.
+            attachments: A list of Attachment objects to display after the rest of
+                the message's content. More than 20 is not recommended, but the actual
+                limit is 100
+            blocks: A list of Block objects to attach to this message. If
+                specified, the 'text' property is ignored (more specifically, it's used
+                as a fallback on clients that can't render blocks)
+            markdown: Whether to parse markdown into formatting such as
+                bold/italics, or leave text completely unmodified.
+        """
+        self.text = text
+        self.attachments = attachments or []
+        self.blocks = blocks or []
+        self.markdown = markdown
+
+    @JsonValidator(f"attachments attribute cannot exceed {attachments_max_length} items")
+    def attachments_length(self):
+        return self.attachments is None or len(self.attachments) <= self.attachments_max_length
+
+    def to_dict(self) -> dict:
+        json = super().to_dict()
+        if len(self.text) > 40000:
+            LOGGER.error("Messages over 40,000 characters are automatically truncated by Slack")
+        # The following limitation used to be true in the past.
+        # As of Feb 2021, having both is recommended
+        # -----------------
+        # if self.text and self.blocks:
+        #     #  Slack doesn't render the text property if there are blocks, so:
+        #     LOGGER.info(q
+        #         "text attribute is treated as fallback text if blocks are attached to "
+        #         "a message - insert text as a new SectionBlock if you want it to be "
+        #         "displayed "
+        #     )
+        json["attachments"] = extract_json(self.attachments)
+        json["blocks"] = extract_json(self.blocks)
+        json["mrkdwn"] = self.markdown
+        return json
+
+

The base class for JSON serializable class objects

+

Create a message.

+

https://docs.slack.dev/messaging/#message-structure

+

Args

+
+
text
+
Plain or Slack Markdown-like text to display in the message.
+
attachments
+
A list of Attachment objects to display after the rest of +the message's content. More than 20 is not recommended, but the actual +limit is 100
+
blocks
+
A list of Block objects to attach to this message. If +specified, the 'text' property is ignored (more specifically, it's used +as a fallback on clients that can't render blocks)
+
markdown
+
Whether to parse markdown into formatting such as +bold/italics, or leave text completely unmodified.
+
+

Ancestors

+ +

Class variables

+
+
var attachments_max_length
+
+

The type of the None singleton.

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def attachments_length(self) +
+
+
+ +Expand source code + +
@JsonValidator(f"attachments attribute cannot exceed {attachments_max_length} items")
+def attachments_length(self):
+    return self.attachments is None or len(self.attachments) <= self.attachments_max_length
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/metadata/index.html b/docs/reference/models/metadata/index.html new file mode 100644 index 000000000..1c4d7a69c --- /dev/null +++ b/docs/reference/models/metadata/index.html @@ -0,0 +1,2680 @@ + + + + + + +slack_sdk.models.metadata API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.metadata

+
+
+
+
+
+
+

Global variables

+
+
var EntityType
+
+

Custom field types

+
+
+
+
+
+
+

Classes

+
+
+class ContentItemEntityFields +(preview:Β Dict[str,Β Any]Β |Β EntityImageFieldΒ |Β NoneΒ =Β None,
description:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
created_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
date_created:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
date_updated:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
last_modified_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class ContentItemEntityFields(JsonObject):
+    """Fields specific to content item entities"""
+
+    attributes = {
+        "preview",
+        "description",
+        "created_by",
+        "date_created",
+        "date_updated",
+        "last_modified_by",
+    }
+
+    def __init__(
+        self,
+        preview: Optional[Union[Dict[str, Any], EntityImageField]] = None,
+        description: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        last_modified_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        **kwargs,
+    ):
+        self.preview = preview
+        self.description = description
+        self.created_by = created_by
+        self.date_created = date_created
+        self.date_updated = date_updated
+        self.last_modified_by = last_modified_by
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Fields specific to content item entities

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityActionButton +(text:Β str,
action_id:Β str,
value:Β strΒ |Β NoneΒ =Β None,
style:Β strΒ |Β NoneΒ =Β None,
url:Β strΒ |Β NoneΒ =Β None,
accessibility_label:Β strΒ |Β NoneΒ =Β None,
processing_state:Β Dict[str,Β Any]Β |Β EntityActionProcessingStateΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityActionButton(JsonObject):
+    """Action button for entity"""
+
+    attributes = {
+        "text",
+        "action_id",
+        "value",
+        "style",
+        "url",
+        "accessibility_label",
+        "processing_state",
+    }
+
+    def __init__(
+        self,
+        text: str,
+        action_id: str,
+        value: Optional[str] = None,
+        style: Optional[str] = None,
+        url: Optional[str] = None,
+        accessibility_label: Optional[str] = None,
+        processing_state: Optional[Union[Dict[str, Any], EntityActionProcessingState]] = None,
+        **kwargs,
+    ):
+        self.text = text
+        self.action_id = action_id
+        self.value = value
+        self.style = style
+        self.url = url
+        self.accessibility_label = accessibility_label
+        self.processing_state = processing_state
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Action button for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityActionProcessingState +(enabled:Β bool, interstitial_text:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class EntityActionProcessingState(JsonObject):
+    """Processing state configuration for entity action button"""
+
+    attributes = {
+        "enabled",
+        "interstitial_text",
+    }
+
+    def __init__(
+        self,
+        enabled: bool,
+        interstitial_text: Optional[str] = None,
+        **kwargs,
+    ):
+        self.enabled = enabled
+        self.interstitial_text = interstitial_text
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Processing state configuration for entity action button

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityActions +(primary_actions:Β List[Dict[str,Β Any]Β |Β EntityActionButton]Β |Β NoneΒ =Β None,
overflow_actions:Β List[Dict[str,Β Any]Β |Β EntityActionButton]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityActions(JsonObject):
+    """Actions configuration for entity"""
+
+    attributes = {
+        "primary_actions",
+        "overflow_actions",
+    }
+
+    def __init__(
+        self,
+        primary_actions: Optional[List[Union[Dict[str, Any], EntityActionButton]]] = None,
+        overflow_actions: Optional[List[Union[Dict[str, Any], EntityActionButton]]] = None,
+        **kwargs,
+    ):
+        self.primary_actions = primary_actions
+        self.overflow_actions = overflow_actions
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Actions configuration for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityArrayItemField +(type:Β strΒ |Β NoneΒ =Β None,
label:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β intΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
long:Β boolΒ |Β NoneΒ =Β None,
format:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
alt_text:Β strΒ |Β NoneΒ =Β None,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
tag_color:Β strΒ |Β NoneΒ =Β None,
user:Β Dict[str,Β Any]Β |Β EntityUserIDFieldΒ |Β EntityUserFieldΒ |Β NoneΒ =Β None,
entity_ref:Β Dict[str,Β Any]Β |Β EntityRefFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityArrayItemField(JsonObject):
+    """Array item field for entity (similar to EntityTypedField but with optional type)"""
+
+    attributes = {
+        "type",
+        "label",
+        "value",
+        "link",
+        "icon",
+        "long",
+        "format",
+        "image_url",
+        "slack_file",
+        "alt_text",
+        "edit",
+        "tag_color",
+        "user",
+        "entity_ref",
+    }
+
+    def __init__(
+        self,
+        type: Optional[str] = None,
+        label: Optional[str] = None,
+        value: Optional[Union[str, int]] = None,
+        link: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        long: Optional[bool] = None,
+        format: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Dict[str, Any]] = None,
+        alt_text: Optional[str] = None,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        tag_color: Optional[str] = None,
+        user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None,
+        entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None,
+        **kwargs,
+    ):
+        self.type = type
+        self.label = label
+        self.value = value
+        self.link = link
+        self.icon = icon
+        self.long = long
+        self.format = format
+        self.image_url = image_url
+        self.slack_file = slack_file
+        self.alt_text = alt_text
+        self.edit = edit
+        self.tag_color = tag_color
+        self.user = user
+        self.entity_ref = entity_ref
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Array item field for entity (similar to EntityTypedField but with optional type)

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityAttributes +(title:Β Dict[str,Β Any]Β |Β EntityTitle,
display_type:Β strΒ |Β NoneΒ =Β None,
display_id:Β strΒ |Β NoneΒ =Β None,
product_icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
product_name:Β strΒ |Β NoneΒ =Β None,
locale:Β strΒ |Β NoneΒ =Β None,
full_size_preview:Β Dict[str,Β Any]Β |Β EntityFullSizePreviewΒ |Β NoneΒ =Β None,
metadata_last_modified:Β intΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityAttributes(JsonObject):
+    """Attributes for an entity"""
+
+    attributes = {
+        "title",
+        "display_type",
+        "display_id",
+        "product_icon",
+        "product_name",
+        "locale",
+        "full_size_preview",
+        "metadata_last_modified",
+    }
+
+    def __init__(
+        self,
+        title: Union[Dict[str, Any], EntityTitle],
+        display_type: Optional[str] = None,
+        display_id: Optional[str] = None,
+        product_icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        product_name: Optional[str] = None,
+        locale: Optional[str] = None,
+        full_size_preview: Optional[Union[Dict[str, Any], EntityFullSizePreview]] = None,
+        metadata_last_modified: Optional[int] = None,
+        **kwargs,
+    ):
+        self.title = title
+        self.display_type = display_type
+        self.display_id = display_id
+        self.product_icon = product_icon
+        self.product_name = product_name
+        self.locale = locale
+        self.full_size_preview = full_size_preview
+        self.metadata_last_modified = metadata_last_modified
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Attributes for an entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityBooleanCheckboxField +(type:Β str, text:Β str, description:Β strΒ |Β None, **kwargs) +
+
+
+ +Expand source code + +
class EntityBooleanCheckboxField(JsonObject):
+    """Boolean checkbox properties"""
+
+    attributes = {"type", "text", "description"}
+
+    def __init__(
+        self,
+        type: str,
+        text: str,
+        description: Optional[str],
+        **kwargs,
+    ):
+        self.type = type
+        self.text = text
+        self.description = description
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Boolean checkbox properties

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityBooleanTextField +(type:Β str,
true_text:Β str,
false_text:Β str,
true_description:Β strΒ |Β None,
false_description:Β strΒ |Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityBooleanTextField(JsonObject):
+    """Boolean text properties"""
+
+    attributes = {"type", "true_text", "false_text", "true_description", "false_description"}
+
+    def __init__(
+        self,
+        type: str,
+        true_text: str,
+        false_text: str,
+        true_description: Optional[str],
+        false_description: Optional[str],
+        **kwargs,
+    ):
+        self.type = type
+        self.true_text = (true_text,)
+        self.false_text = (false_text,)
+        self.true_description = (true_description,)
+        self.false_description = (false_description,)
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Boolean text properties

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityCustomField +(label:Β str,
key:Β str,
type:Β str,
value:Β strΒ |Β intΒ |Β List[Dict[str,Β Any]Β |Β EntityArrayItemField]Β |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
long:Β boolΒ |Β NoneΒ =Β None,
format:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
alt_text:Β strΒ |Β NoneΒ =Β None,
tag_color:Β strΒ |Β NoneΒ =Β None,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
item_type:Β strΒ |Β NoneΒ =Β None,
user:Β Dict[str,Β Any]Β |Β EntityUserIDFieldΒ |Β EntityUserFieldΒ |Β NoneΒ =Β None,
entity_ref:Β Dict[str,Β Any]Β |Β EntityRefFieldΒ |Β NoneΒ =Β None,
boolean:Β Dict[str,Β Any]Β |Β EntityBooleanCheckboxFieldΒ |Β EntityBooleanTextFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityCustomField(JsonObject):
+    """Custom field for entity with flexible types"""
+
+    attributes = {
+        "label",
+        "key",
+        "type",
+        "value",
+        "link",
+        "icon",
+        "long",
+        "format",
+        "image_url",
+        "slack_file",
+        "alt_text",
+        "tag_color",
+        "edit",
+        "item_type",
+        "user",
+        "entity_ref",
+        "boolean",
+    }
+
+    def __init__(
+        self,
+        label: str,
+        key: str,
+        type: str,
+        value: Optional[Union[str, int, List[Union[Dict[str, Any], EntityArrayItemField]]]] = None,
+        link: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        long: Optional[bool] = None,
+        format: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Dict[str, Any]] = None,
+        alt_text: Optional[str] = None,
+        tag_color: Optional[str] = None,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        item_type: Optional[str] = None,
+        user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None,
+        entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None,
+        boolean: Optional[Union[Dict[str, Any], EntityBooleanCheckboxField, EntityBooleanTextField]] = None,
+        **kwargs,
+    ):
+        self.label = label
+        self.key = key
+        self.type = type
+        self.value = value
+        self.link = link
+        self.icon = icon
+        self.long = long
+        self.format = format
+        self.image_url = image_url
+        self.slack_file = slack_file
+        self.alt_text = alt_text
+        self.tag_color = tag_color
+        self.edit = edit
+        self.item_type = item_type
+        self.user = user
+        self.entity_ref = entity_ref
+        self.boolean = boolean
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+    @EnumValidator("type", CustomFieldType)
+    def type_valid(self):
+        return self.type is None or self.type in CustomFieldType
+
+

Custom field for entity with flexible types

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def type_valid(self) +
+
+
+ +Expand source code + +
@EnumValidator("type", CustomFieldType)
+def type_valid(self):
+    return self.type is None or self.type in CustomFieldType
+
+
+
+
+

Inherited members

+ +
+
+class EntityEditNumberConfig +(is_decimal_allowed:Β boolΒ |Β NoneΒ =Β None,
min_value:Β intΒ |Β floatΒ |Β NoneΒ =Β None,
max_value:Β intΒ |Β floatΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityEditNumberConfig(JsonObject):
+    """Number configuration for entity edit support"""
+
+    attributes = {
+        "is_decimal_allowed",
+        "min_value",
+        "max_value",
+    }
+
+    def __init__(
+        self,
+        is_decimal_allowed: Optional[bool] = None,
+        min_value: Optional[Union[int, float]] = None,
+        max_value: Optional[Union[int, float]] = None,
+        **kwargs,
+    ):
+        self.is_decimal_allowed = is_decimal_allowed
+        self.min_value = min_value
+        self.max_value = max_value
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Number configuration for entity edit support

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityEditSelectConfig +(current_value:Β strΒ |Β NoneΒ =Β None,
current_values:Β List[str]Β |Β NoneΒ =Β None,
static_options:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
fetch_options_dynamically:Β boolΒ |Β NoneΒ =Β None,
min_query_length:Β intΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityEditSelectConfig(JsonObject):
+    """Select configuration for entity edit support"""
+
+    attributes = {
+        "current_value",
+        "current_values",
+        "static_options",
+        "fetch_options_dynamically",
+        "min_query_length",
+    }
+
+    def __init__(
+        self,
+        current_value: Optional[str] = None,
+        current_values: Optional[List[str]] = None,
+        static_options: Optional[List[Dict[str, Any]]] = None,  # Option[]
+        fetch_options_dynamically: Optional[bool] = None,
+        min_query_length: Optional[int] = None,
+        **kwargs,
+    ):
+        self.current_value = current_value
+        self.current_values = current_values
+        self.static_options = static_options
+        self.fetch_options_dynamically = fetch_options_dynamically
+        self.min_query_length = min_query_length
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Select configuration for entity edit support

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityEditSupport +(enabled:Β bool,
placeholder:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
hint:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
optional:Β boolΒ |Β NoneΒ =Β None,
select:Β Dict[str,Β Any]Β |Β EntityEditSelectConfigΒ |Β NoneΒ =Β None,
number:Β Dict[str,Β Any]Β |Β EntityEditNumberConfigΒ |Β NoneΒ =Β None,
text:Β Dict[str,Β Any]Β |Β EntityEditTextConfigΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityEditSupport(JsonObject):
+    """Edit support configuration for entity fields"""
+
+    attributes = {
+        "enabled",
+        "placeholder",
+        "hint",
+        "optional",
+        "select",
+        "number",
+        "text",
+    }
+
+    def __init__(
+        self,
+        enabled: bool,
+        placeholder: Optional[Dict[str, Any]] = None,  # PlainTextElement
+        hint: Optional[Dict[str, Any]] = None,  # PlainTextElement
+        optional: Optional[bool] = None,
+        select: Optional[Union[Dict[str, Any], EntityEditSelectConfig]] = None,
+        number: Optional[Union[Dict[str, Any], EntityEditNumberConfig]] = None,
+        text: Optional[Union[Dict[str, Any], EntityEditTextConfig]] = None,
+        **kwargs,
+    ):
+        self.enabled = enabled
+        self.placeholder = placeholder
+        self.hint = hint
+        self.optional = optional
+        self.select = select
+        self.number = number
+        self.text = text
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Edit support configuration for entity fields

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityEditTextConfig +(min_length:Β intΒ |Β NoneΒ =Β None, max_length:Β intΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class EntityEditTextConfig(JsonObject):
+    """Text configuration for entity edit support"""
+
+    attributes = {
+        "min_length",
+        "max_length",
+    }
+
+    def __init__(
+        self,
+        min_length: Optional[int] = None,
+        max_length: Optional[int] = None,
+        **kwargs,
+    ):
+        self.min_length = min_length
+        self.max_length = max_length
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Text configuration for entity edit support

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityFullSizePreview +(is_supported:Β bool,
preview_url:Β strΒ |Β NoneΒ =Β None,
mime_type:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β EntityFullSizePreviewErrorΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityFullSizePreview(JsonObject):
+    """Full-size preview configuration for entity"""
+
+    attributes = {
+        "is_supported",
+        "preview_url",
+        "mime_type",
+        "error",
+    }
+
+    def __init__(
+        self,
+        is_supported: bool,
+        preview_url: Optional[str] = None,
+        mime_type: Optional[str] = None,
+        error: Optional[Union[Dict[str, Any], EntityFullSizePreviewError]] = None,
+        **kwargs,
+    ):
+        self.is_supported = is_supported
+        self.preview_url = preview_url
+        self.mime_type = mime_type
+        self.error = error
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Full-size preview configuration for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityFullSizePreviewError +(code:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class EntityFullSizePreviewError(JsonObject):
+    """Error information for full-size preview"""
+
+    attributes = {
+        "code",
+        "message",
+    }
+
+    def __init__(
+        self,
+        code: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ):
+        self.code = code
+        self.message = message
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Error information for full-size preview

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityIconField +(alt_text:Β str,
url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β EntityIconSlackFileΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityIconField(JsonObject):
+    """Icon field for entity attributes"""
+
+    attributes = {
+        "alt_text",
+        "url",
+        "slack_file",
+    }
+
+    def __init__(
+        self,
+        alt_text: str,
+        url: Optional[str] = None,
+        slack_file: Optional[Union[Dict[str, Any], EntityIconSlackFile]] = None,
+        **kwargs,
+    ):
+        self.alt_text = alt_text
+        self.url = url
+        self.slack_file = slack_file
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Icon field for entity attributes

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityIconSlackFile +(id:Β strΒ |Β NoneΒ =Β None, url:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class EntityIconSlackFile(JsonObject):
+    """Slack file reference for entity icon"""
+
+    attributes = {
+        "id",
+        "url",
+    }
+
+    def __init__(
+        self,
+        id: Optional[str] = None,
+        url: Optional[str] = None,
+        **kwargs,
+    ):
+        self.id = id
+        self.url = url
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Slack file reference for entity icon

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityImageField +(alt_text:Β str,
label:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityImageField(JsonObject):
+    """Image field for entity"""
+
+    attributes = {
+        "alt_text",
+        "label",
+        "image_url",
+        "slack_file",
+        "title",
+        "type",
+    }
+
+    def __init__(
+        self,
+        alt_text: str,
+        label: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Dict[str, Any]] = None,
+        title: Optional[str] = None,
+        type: Optional[str] = None,
+        **kwargs,
+    ):
+        self.alt_text = alt_text
+        self.label = label
+        self.image_url = image_url
+        self.slack_file = slack_file
+        self.title = title
+        self.type = type
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Image field for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityMetadata +(entity_type:Β str,
entity_payload:Β Dict[str,Β Any]Β |Β EntityPayload,
external_ref:Β Dict[str,Β Any]Β |Β ExternalRef,
url:Β str,
app_unfurl_url:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityMetadata(JsonObject):
+    """Work object entity metadata
+
+    https://docs.slack.dev/messaging/work-objects/
+    """
+
+    attributes = {
+        "entity_type",
+        "entity_payload",
+        "external_ref",
+        "url",
+        "app_unfurl_url",
+    }
+
+    def __init__(
+        self,
+        entity_type: str,
+        entity_payload: Union[Dict[str, Any], EntityPayload],
+        external_ref: Union[Dict[str, Any], ExternalRef],
+        url: str,
+        app_unfurl_url: Optional[str] = None,
+        **kwargs,
+    ):
+        self.entity_type = entity_type
+        self.entity_payload = entity_payload
+        self.external_ref = external_ref
+        self.url = url
+        self.app_unfurl_url = app_unfurl_url
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+    @EnumValidator("entity_type", EntityType)
+    def entity_type_valid(self):
+        return self.entity_type is None or self.entity_type in EntityType
+
+ +

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def entity_type_valid(self) +
+
+
+ +Expand source code + +
@EnumValidator("entity_type", EntityType)
+def entity_type_valid(self):
+    return self.entity_type is None or self.entity_type in EntityType
+
+
+
+
+

Inherited members

+ +
+
+class EntityPayload +(attributes:Β Dict[str,Β Any]Β |Β EntityAttributes,
fields:Β Dict[str,Β Any]Β |Β ContentItemEntityFieldsΒ |Β FileEntityFieldsΒ |Β IncidentEntityFieldsΒ |Β TaskEntityFieldsΒ |Β NoneΒ =Β None,
custom_fields:Β List[Dict[str,Β Any]Β |Β EntityCustomField]Β |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β FileEntitySlackFileΒ |Β NoneΒ =Β None,
display_order:Β List[str]Β |Β NoneΒ =Β None,
actions:Β Dict[str,Β Any]Β |Β EntityActionsΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityPayload(JsonObject):
+    """Payload schema for an entity"""
+
+    attributes = {
+        "attributes",
+        "fields",
+        "custom_fields",
+        "slack_file",
+        "display_order",
+        "actions",
+    }
+
+    def __init__(
+        self,
+        attributes: Union[Dict[str, Any], EntityAttributes],
+        fields: Optional[
+            Union[Dict[str, Any], ContentItemEntityFields, FileEntityFields, IncidentEntityFields, TaskEntityFields]
+        ] = None,
+        custom_fields: Optional[List[Union[Dict[str, Any], EntityCustomField]]] = None,
+        slack_file: Optional[Union[Dict[str, Any], FileEntitySlackFile]] = None,
+        display_order: Optional[List[str]] = None,
+        actions: Optional[Union[Dict[str, Any], EntityActions]] = None,
+        **kwargs,
+    ):
+        # Store entity attributes data with a different internal name to avoid
+        # shadowing the class-level 'attributes' set used for JSON serialization
+        self._entity_attributes = attributes
+        self.fields = fields
+        self.custom_fields = custom_fields
+        self.slack_file = slack_file
+        self.display_order = display_order
+        self.actions = actions
+        self.additional_attributes = kwargs
+
+    @property
+    def entity_attributes(self) -> Union[Dict[str, Any], EntityAttributes]:
+        """Get the entity attributes data.
+
+        Note: Use this property to access the attributes data. The class-level
+        'attributes' is reserved for the JSON serialization schema.
+        """
+        return self._entity_attributes
+
+    @entity_attributes.setter
+    def entity_attributes(self, value: Union[Dict[str, Any], EntityAttributes]):
+        """Set the entity attributes data."""
+        self._entity_attributes = value
+
+    def get_object_attribute(self, key: str):
+        if key == "attributes":
+            return self._entity_attributes
+        else:
+            return getattr(self, key, None)
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Payload schema for an entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop entity_attributes :Β Dict[str,Β Any]Β |Β EntityAttributes
+
+
+ +Expand source code + +
@property
+def entity_attributes(self) -> Union[Dict[str, Any], EntityAttributes]:
+    """Get the entity attributes data.
+
+    Note: Use this property to access the attributes data. The class-level
+    'attributes' is reserved for the JSON serialization schema.
+    """
+    return self._entity_attributes
+
+

Get the entity attributes data.

+

Note: Use this property to access the attributes data. The class-level +'attributes' is reserved for the JSON serialization schema.

+
+
+

Methods

+
+
+def get_object_attribute(self, key:Β str) +
+
+
+ +Expand source code + +
def get_object_attribute(self, key: str):
+    if key == "attributes":
+        return self._entity_attributes
+    else:
+        return getattr(self, key, None)
+
+
+
+
+

Inherited members

+ +
+
+class EntityRefField +(entity_url:Β str,
external_ref:Β Dict[str,Β Any]Β |Β ExternalRef,
title:Β str,
display_type:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityRefField(JsonObject):
+    """Entity reference field"""
+
+    attributes = {
+        "entity_url",
+        "external_ref",
+        "title",
+        "display_type",
+        "icon",
+    }
+
+    def __init__(
+        self,
+        entity_url: str,
+        external_ref: Union[Dict[str, Any], ExternalRef],
+        title: str,
+        display_type: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        **kwargs,
+    ):
+        self.entity_url = entity_url
+        self.external_ref = external_ref
+        self.title = title
+        self.display_type = display_type
+        self.icon = icon
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Entity reference field

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityStringField +(value:Β str,
label:Β strΒ |Β NoneΒ =Β None,
format:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
long:Β boolΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
tag_color:Β strΒ |Β NoneΒ =Β None,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityStringField(JsonObject):
+    """String field for entity"""
+
+    attributes = {
+        "value",
+        "label",
+        "format",
+        "link",
+        "icon",
+        "long",
+        "type",
+        "tag_color",
+        "edit",
+    }
+
+    def __init__(
+        self,
+        value: str,
+        label: Optional[str] = None,
+        format: Optional[str] = None,
+        link: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        long: Optional[bool] = None,
+        type: Optional[str] = None,
+        tag_color: Optional[str] = None,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        **kwargs,
+    ):
+        self.value = value
+        self.label = label
+        self.format = format
+        self.link = link
+        self.icon = icon
+        self.long = long
+        self.type = type
+        self.tag_color = tag_color
+        self.edit = edit
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

String field for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityTimestampField +(value:Β int,
label:Β strΒ |Β NoneΒ =Β None,
type:Β strΒ |Β NoneΒ =Β None,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityTimestampField(JsonObject):
+    """Timestamp field for entity"""
+
+    attributes = {
+        "value",
+        "label",
+        "type",
+        "edit",
+    }
+
+    def __init__(
+        self,
+        value: int,
+        label: Optional[str] = None,
+        type: Optional[str] = None,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        **kwargs,
+    ):
+        self.value = value
+        self.label = label
+        self.type = type
+        self.edit = edit
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Timestamp field for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityTitle +(text:Β str,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityTitle(JsonObject):
+    """Title for entity attributes"""
+
+    attributes = {
+        "text",
+        "edit",
+    }
+
+    def __init__(
+        self,
+        text: str,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        **kwargs,
+    ):
+        self.text = text
+        self.edit = edit
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Title for entity attributes

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityTypedField +(type:Β str,
label:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β intΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
long:Β boolΒ |Β NoneΒ =Β None,
format:Β strΒ |Β NoneΒ =Β None,
image_url:Β strΒ |Β NoneΒ =Β None,
slack_file:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
alt_text:Β strΒ |Β NoneΒ =Β None,
edit:Β Dict[str,Β Any]Β |Β EntityEditSupportΒ |Β NoneΒ =Β None,
tag_color:Β strΒ |Β NoneΒ =Β None,
user:Β Dict[str,Β Any]Β |Β EntityUserIDFieldΒ |Β EntityUserFieldΒ |Β NoneΒ =Β None,
entity_ref:Β Dict[str,Β Any]Β |Β EntityRefFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityTypedField(JsonObject):
+    """Typed field for entity with various display options"""
+
+    attributes = {
+        "type",
+        "label",
+        "value",
+        "link",
+        "icon",
+        "long",
+        "format",
+        "image_url",
+        "slack_file",
+        "alt_text",
+        "edit",
+        "tag_color",
+        "user",
+        "entity_ref",
+    }
+
+    def __init__(
+        self,
+        type: str,
+        label: Optional[str] = None,
+        value: Optional[Union[str, int]] = None,
+        link: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        long: Optional[bool] = None,
+        format: Optional[str] = None,
+        image_url: Optional[str] = None,
+        slack_file: Optional[Dict[str, Any]] = None,
+        alt_text: Optional[str] = None,
+        edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None,
+        tag_color: Optional[str] = None,
+        user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None,
+        entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None,
+        **kwargs,
+    ):
+        self.type = type
+        self.label = label
+        self.value = value
+        self.link = link
+        self.icon = icon
+        self.long = long
+        self.format = format
+        self.image_url = image_url
+        self.slack_file = slack_file
+        self.alt_text = alt_text
+        self.edit = edit
+        self.tag_color = tag_color
+        self.user = user
+        self.entity_ref = entity_ref
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Typed field for entity with various display options

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityUserField +(text:Β str,
url:Β strΒ |Β NoneΒ =Β None,
email:Β strΒ |Β NoneΒ =Β None,
icon:Β Dict[str,Β Any]Β |Β EntityIconFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EntityUserField(JsonObject):
+    """User field for entity"""
+
+    attributes = {
+        "text",
+        "url",
+        "email",
+        "icon",
+    }
+
+    def __init__(
+        self,
+        text: str,
+        url: Optional[str] = None,
+        email: Optional[str] = None,
+        icon: Optional[Union[Dict[str, Any], EntityIconField]] = None,
+        **kwargs,
+    ):
+        self.text = text
+        self.url = url
+        self.email = email
+        self.icon = icon
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

User field for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EntityUserIDField +(user_id:Β str, **kwargs) +
+
+
+ +Expand source code + +
class EntityUserIDField(JsonObject):
+    """User ID field for entity"""
+
+    attributes = {
+        "user_id",
+    }
+
+    def __init__(
+        self,
+        user_id: str,
+        **kwargs,
+    ):
+        self.user_id = user_id
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

User ID field for entity

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class EventAndEntityMetadata +(event_type:Β strΒ |Β NoneΒ =Β None,
event_payload:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
entities:Β List[Dict[str,Β Any]Β |Β EntityMetadata]Β |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class EventAndEntityMetadata(JsonObject):
+    """Message metadata with entities
+
+    https://docs.slack.dev/messaging/message-metadata/
+    https://docs.slack.dev/messaging/work-objects/
+    """
+
+    attributes = {"event_type", "event_payload", "entities"}
+
+    def __init__(
+        self,
+        event_type: Optional[str] = None,
+        event_payload: Optional[Dict[str, Any]] = None,
+        entities: Optional[List[Union[Dict[str, Any], EntityMetadata]]] = None,
+        **kwargs,
+    ):
+        self.event_type = event_type
+        self.event_payload = event_payload
+        self.entities = entities
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+ +

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ExternalRef +(id:Β str, type:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class ExternalRef(JsonObject):
+    """Reference (and optional type) used to identify an entity within the developer's system"""
+
+    attributes = {
+        "id",
+        "type",
+    }
+
+    def __init__(
+        self,
+        id: str,
+        type: Optional[str] = None,
+        **kwargs,
+    ):
+        self.id = id
+        self.type = type
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Reference (and optional type) used to identify an entity within the developer's system

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FileEntityFields +(preview:Β Dict[str,Β Any]Β |Β EntityImageFieldΒ |Β NoneΒ =Β None,
created_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
date_created:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
date_updated:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
last_modified_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
file_size:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
mime_type:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
full_size_preview:Β Dict[str,Β Any]Β |Β EntityFullSizePreviewΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class FileEntityFields(JsonObject):
+    """Fields specific to file entities"""
+
+    attributes = {
+        "preview",
+        "created_by",
+        "date_created",
+        "date_updated",
+        "last_modified_by",
+        "file_size",
+        "mime_type",
+        "full_size_preview",
+    }
+
+    def __init__(
+        self,
+        preview: Optional[Union[Dict[str, Any], EntityImageField]] = None,
+        created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        last_modified_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        file_size: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        mime_type: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        full_size_preview: Optional[Union[Dict[str, Any], EntityFullSizePreview]] = None,
+        **kwargs,
+    ):
+        self.preview = preview
+        self.created_by = created_by
+        self.date_created = date_created
+        self.date_updated = date_updated
+        self.last_modified_by = last_modified_by
+        self.file_size = file_size
+        self.mime_type = mime_type
+        self.full_size_preview = full_size_preview
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Fields specific to file entities

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class FileEntitySlackFile +(id:Β str, type:Β strΒ |Β NoneΒ =Β None, **kwargs) +
+
+
+ +Expand source code + +
class FileEntitySlackFile(JsonObject):
+    """Slack file reference for file entities"""
+
+    attributes = {
+        "id",
+        "type",
+    }
+
+    def __init__(
+        self,
+        id: str,
+        type: Optional[str] = None,
+        **kwargs,
+    ):
+        self.id = id
+        self.type = type
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Slack file reference for file entities

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class IncidentEntityFields +(status:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
priority:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
urgency:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
created_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
assigned_to:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
date_created:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
date_updated:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
description:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
service:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class IncidentEntityFields(JsonObject):
+    """Fields specific to incident entities"""
+
+    attributes = {
+        "status",
+        "priority",
+        "urgency",
+        "created_by",
+        "assigned_to",
+        "date_created",
+        "date_updated",
+        "description",
+        "service",
+    }
+
+    def __init__(
+        self,
+        status: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        priority: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        urgency: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        assigned_to: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        description: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        service: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        **kwargs,
+    ):
+        self.status = status
+        self.priority = priority
+        self.urgency = urgency
+        self.created_by = created_by
+        self.assigned_to = assigned_to
+        self.date_created = date_created
+        self.date_updated = date_updated
+        self.description = description
+        self.service = service
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Fields specific to incident entities

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class Metadata +(event_type:Β str, event_payload:Β Dict[str,Β Any], **kwargs) +
+
+
+ +Expand source code + +
class Metadata(JsonObject):
+    """Message metadata
+
+    https://docs.slack.dev/messaging/message-metadata/
+    """
+
+    attributes = {
+        "event_type",
+        "event_payload",
+    }
+
+    def __init__(
+        self,
+        event_type: str,
+        event_payload: Dict[str, Any],
+        **kwargs,
+    ):
+        self.event_type = event_type
+        self.event_payload = event_payload
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+ +

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class TaskEntityFields +(description:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
created_by:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
date_created:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
date_updated:Β Dict[str,Β Any]Β |Β EntityTimestampFieldΒ |Β NoneΒ =Β None,
assignee:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
status:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
due_date:Β Dict[str,Β Any]Β |Β EntityTypedFieldΒ |Β NoneΒ =Β None,
priority:Β Dict[str,Β Any]Β |Β EntityStringFieldΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class TaskEntityFields(JsonObject):
+    """Fields specific to task entities"""
+
+    attributes = {
+        "description",
+        "created_by",
+        "date_created",
+        "date_updated",
+        "assignee",
+        "status",
+        "due_date",
+        "priority",
+    }
+
+    def __init__(
+        self,
+        description: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None,
+        assignee: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        status: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        due_date: Optional[Union[Dict[str, Any], EntityTypedField]] = None,
+        priority: Optional[Union[Dict[str, Any], EntityStringField]] = None,
+        **kwargs,
+    ):
+        self.description = description
+        self.created_by = created_by
+        self.date_created = date_created
+        self.date_updated = date_updated
+        self.assignee = assignee
+        self.status = status
+        self.due_date = due_date
+        self.priority = priority
+        self.additional_attributes = kwargs
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

Fields specific to task entities

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/models/views/index.html b/docs/reference/models/views/index.html new file mode 100644 index 000000000..d9e60359b --- /dev/null +++ b/docs/reference/models/views/index.html @@ -0,0 +1,454 @@ + + + + + + +slack_sdk.models.views API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.models.views

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class View +(type:Β str,
id:Β strΒ |Β NoneΒ =Β None,
callback_id:Β strΒ |Β NoneΒ =Β None,
external_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
bot_id:Β strΒ |Β NoneΒ =Β None,
app_id:Β strΒ |Β NoneΒ =Β None,
root_view_id:Β strΒ |Β NoneΒ =Β None,
previous_view_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
submit:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
close:Β strΒ |Β dictΒ |Β PlainTextObjectΒ |Β NoneΒ =Β None,
blocks:Β Sequence[dictΒ |Β Block]Β |Β NoneΒ =Β None,
private_metadata:Β strΒ |Β NoneΒ =Β None,
state:Β dictΒ |Β ForwardRef('ViewState')Β |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
clear_on_close:Β boolΒ |Β NoneΒ =Β None,
notify_on_close:Β boolΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class View(JsonObject):
+    """View object for modals and Home tabs.
+
+    https://docs.slack.dev/reference/views/
+    """
+
+    types = ["modal", "home", "workflow_step"]
+
+    attributes = {
+        "type",
+        "id",
+        "callback_id",
+        "external_id",
+        "team_id",
+        "bot_id",
+        "app_id",
+        "root_view_id",
+        "previous_view_id",
+        "title",
+        "submit",
+        "close",
+        "blocks",
+        "private_metadata",
+        "state",
+        "hash",
+        "clear_on_close",
+        "notify_on_close",
+    }
+
+    def __init__(
+        self,
+        # "modal", "home", and "workflow_step"
+        type: str,
+        id: Optional[str] = None,
+        callback_id: Optional[str] = None,
+        external_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        bot_id: Optional[str] = None,
+        app_id: Optional[str] = None,
+        root_view_id: Optional[str] = None,
+        previous_view_id: Optional[str] = None,
+        title: Optional[Union[str, dict, PlainTextObject]] = None,
+        submit: Optional[Union[str, dict, PlainTextObject]] = None,
+        close: Optional[Union[str, dict, PlainTextObject]] = None,
+        blocks: Optional[Sequence[Union[dict, Block]]] = None,
+        private_metadata: Optional[str] = None,
+        state: Optional[Union[dict, "ViewState"]] = None,
+        hash: Optional[str] = None,
+        clear_on_close: Optional[bool] = None,
+        notify_on_close: Optional[bool] = None,
+        **kwargs,
+    ):
+        self.type = type
+        self.id = id
+        self.callback_id = callback_id
+        self.external_id = external_id
+        self.team_id = team_id
+        self.bot_id = bot_id
+        self.app_id = app_id
+        self.root_view_id = root_view_id
+        self.previous_view_id = previous_view_id
+        self.title = TextObject.parse(title, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.submit = TextObject.parse(submit, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.close = TextObject.parse(close, default_type=PlainTextObject.type)  # type: ignore[arg-type]
+        self.blocks = Block.parse_all(blocks)
+        self.private_metadata = private_metadata
+        self.state = state
+        if self.state is not None and isinstance(self.state, dict):
+            self.state = ViewState(**self.state)
+        self.hash = hash
+        self.clear_on_close = clear_on_close
+        self.notify_on_close = notify_on_close
+        self.additional_attributes = kwargs
+
+    title_max_length = 24
+    blocks_max_length = 100
+    close_max_length = 24
+    submit_max_length = 24
+    private_metadata_max_length = 3000
+    callback_id_max_length: int = 255
+
+    @JsonValidator('type must be either "modal", "home" or "workflow_step"')
+    def _validate_type(self):
+        return self.type is not None and self.type in self.types
+
+    @JsonValidator(f"title must be between 1 and {title_max_length} characters")
+    def _validate_title_length(self):
+        return self.title is None or 1 <= len(self.title.text) <= self.title_max_length
+
+    @JsonValidator(f"views must contain between 1 and {blocks_max_length} blocks")
+    def _validate_blocks_length(self):
+        return self.blocks is None or 0 < len(self.blocks) <= self.blocks_max_length
+
+    @JsonValidator("home view cannot have submit and close")
+    def _validate_home_tab_structure(self):
+        return self.type != "home" or (self.type == "home" and self.close is None and self.submit is None)
+
+    @JsonValidator(f"close cannot exceed {close_max_length} characters")
+    def _validate_close_length(self):
+        return self.close is None or len(self.close.text) <= self.close_max_length
+
+    @JsonValidator(f"submit cannot exceed {submit_max_length} characters")
+    def _validate_submit_length(self):
+        return self.submit is None or len(self.submit.text) <= int(self.submit_max_length)
+
+    @JsonValidator(f"private_metadata cannot exceed {private_metadata_max_length} characters")
+    def _validate_private_metadata_max_length(self):
+        return self.private_metadata is None or len(self.private_metadata) <= self.private_metadata_max_length
+
+    @JsonValidator(f"callback_id cannot exceed {callback_id_max_length} characters")
+    def _validate_callback_id_max_length(self):
+        return self.callback_id is None or len(self.callback_id) <= self.callback_id_max_length
+
+    def __str__(self):
+        return str(self.get_non_null_attributes())
+
+    def __repr__(self):
+        return self.__str__()
+
+

View object for modals and Home tabs.

+

https://docs.slack.dev/reference/views/

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var blocks_max_length
+
+

The type of the None singleton.

+
+
var callback_id_max_length :Β int
+
+

The type of the None singleton.

+
+
var close_max_length
+
+

The type of the None singleton.

+
+
var private_metadata_max_length
+
+

The type of the None singleton.

+
+
var submit_max_length
+
+

The type of the None singleton.

+
+
var title_max_length
+
+

The type of the None singleton.

+
+
var types
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ViewState +(*,
values:Β Dict[str,Β Dict[str,Β dictΒ |Β ForwardRef('ViewStateValue')]])
+
+
+
+ +Expand source code + +
class ViewState(JsonObject):
+    attributes = {"values"}
+    logger = logging.getLogger(__name__)
+
+    @classmethod
+    def _show_warning_about_unknown(cls, value):
+        c = value.__class__
+        name = ".".join([c.__module__, c.__name__])
+        cls.logger.warning(f"Unknown type for view.state.values detected ({name}) and ViewState skipped to add it")
+
+    def __init__(
+        self,
+        *,
+        values: Dict[str, Dict[str, Union[dict, "ViewStateValue"]]],
+    ):
+        value_objects: Dict[str, Dict[str, ViewStateValue]] = {}
+        new_state_values = copy.copy(values)
+        if isinstance(new_state_values, dict):  # just in case
+            for block_id, actions in new_state_values.items():
+                if actions is None:
+                    continue
+                elif isinstance(actions, dict):
+                    new_actions: Dict[str, Union[ViewStateValue, dict]] = copy.copy(actions)
+                    for action_id, v in actions.items():
+                        if isinstance(v, dict):
+                            d = copy.copy(v)
+                            value_object = ViewStateValue(**d)
+                        elif isinstance(v, ViewStateValue):
+                            value_object = v
+                        else:
+                            self._show_warning_about_unknown(v)
+                            continue
+                        new_actions[action_id] = value_object
+                    value_objects[block_id] = new_actions  # type: ignore[assignment]
+                else:
+                    self._show_warning_about_unknown(v)
+        self.values = value_objects
+
+    def to_dict(self, *args) -> Dict[str, Dict[str, Dict[str, dict]]]:
+        self.validate_json()
+        if self.values is not None:
+            dict_values: Dict[str, Dict[str, dict]] = {}
+            for block_id, actions in self.values.items():
+                if actions:
+                    dict_value: Dict[str, dict] = {action_id: value.to_dict() for action_id, value in actions.items()}
+                    dict_values[block_id] = dict_value
+            return {"values": dict_values}
+        else:
+            return {}
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
var logger
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+class ViewStateValue +(*,
type:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
selected_date:Β strΒ |Β NoneΒ =Β None,
selected_time:Β strΒ |Β NoneΒ =Β None,
selected_conversation:Β strΒ |Β NoneΒ =Β None,
selected_channel:Β strΒ |Β NoneΒ =Β None,
selected_user:Β strΒ |Β NoneΒ =Β None,
selected_option:Β dictΒ |Β OptionΒ |Β NoneΒ =Β None,
selected_conversations:Β Sequence[str]Β |Β NoneΒ =Β None,
selected_channels:Β Sequence[str]Β |Β NoneΒ =Β None,
selected_users:Β Sequence[str]Β |Β NoneΒ =Β None,
selected_options:Β Sequence[dictΒ |Β Option]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class ViewStateValue(JsonObject):
+    attributes = {
+        "type",
+        "value",
+        "selected_date",
+        "selected_time",
+        "selected_conversation",
+        "selected_channel",
+        "selected_user",
+        "selected_option",
+        "selected_conversations",
+        "selected_channels",
+        "selected_users",
+        "selected_options",
+    }
+
+    def __init__(
+        self,
+        *,
+        type: Optional[str] = None,
+        value: Optional[str] = None,
+        selected_date: Optional[str] = None,
+        selected_time: Optional[str] = None,
+        selected_conversation: Optional[str] = None,
+        selected_channel: Optional[str] = None,
+        selected_user: Optional[str] = None,
+        selected_option: Optional[Union[dict, Option]] = None,
+        selected_conversations: Optional[Sequence[str]] = None,
+        selected_channels: Optional[Sequence[str]] = None,
+        selected_users: Optional[Sequence[str]] = None,
+        selected_options: Optional[Sequence[Union[dict, Option]]] = None,
+    ):
+        self.type = type
+        self.value = value
+        self.selected_date = selected_date
+        self.selected_time = selected_time
+        self.selected_conversation = selected_conversation
+        self.selected_channel = selected_channel
+        self.selected_user = selected_user
+        self.selected_option = selected_option
+        self.selected_conversations = selected_conversations
+        self.selected_channels = selected_channels
+        self.selected_users = selected_users
+
+        if isinstance(selected_options, list):
+            self.selected_options = []
+            for option in selected_options:
+                if isinstance(option, Option):
+                    self.selected_options.append(option)
+                elif isinstance(option, dict):
+                    self.selected_options.append(Option(**option))
+        else:
+            self.selected_options = selected_options  # type: ignore[assignment]
+
+

The base class for JSON serializable class objects

+

Ancestors

+ +

Class variables

+
+
var attributes
+
+

The type of the None singleton.

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/authorize_url_generator/index.html b/docs/reference/oauth/authorize_url_generator/index.html new file mode 100644 index 000000000..97e893156 --- /dev/null +++ b/docs/reference/oauth/authorize_url_generator/index.html @@ -0,0 +1,229 @@ + + + + + + +slack_sdk.oauth.authorize_url_generator API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.authorize_url_generator

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AuthorizeUrlGenerator +(*,
client_id:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
user_scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
authorization_url:Β strΒ =Β 'https://slack.com/oauth/v2/authorize')
+
+
+
+ +Expand source code + +
class AuthorizeUrlGenerator:
+    def __init__(
+        self,
+        *,
+        client_id: str,
+        redirect_uri: Optional[str] = None,
+        scopes: Optional[Sequence[str]] = None,
+        user_scopes: Optional[Sequence[str]] = None,
+        authorization_url: str = "https://slack.com/oauth/v2/authorize",
+    ):
+        self.client_id = client_id
+        self.redirect_uri = redirect_uri
+        self.scopes = scopes
+        self.user_scopes = user_scopes
+        self.authorization_url = authorization_url
+
+    def generate(self, state: str, team: Optional[str] = None) -> str:
+        scopes = ",".join(self.scopes) if self.scopes else ""
+        user_scopes = ",".join(self.user_scopes) if self.user_scopes else ""
+        url = (
+            f"{self.authorization_url}?"
+            f"state={state}&"
+            f"client_id={self.client_id}&"
+            f"scope={scopes}&"
+            f"user_scope={user_scopes}"
+        )
+        if self.redirect_uri is not None:
+            url += f"&redirect_uri={self.redirect_uri}"
+        if team is not None:
+            url += f"&team={team}"
+        return url
+
+
+

Methods

+
+
+def generate(self, state:Β str, team:Β strΒ |Β NoneΒ =Β None) ‑>Β str +
+
+
+ +Expand source code + +
def generate(self, state: str, team: Optional[str] = None) -> str:
+    scopes = ",".join(self.scopes) if self.scopes else ""
+    user_scopes = ",".join(self.user_scopes) if self.user_scopes else ""
+    url = (
+        f"{self.authorization_url}?"
+        f"state={state}&"
+        f"client_id={self.client_id}&"
+        f"scope={scopes}&"
+        f"user_scope={user_scopes}"
+    )
+    if self.redirect_uri is not None:
+        url += f"&redirect_uri={self.redirect_uri}"
+    if team is not None:
+        url += f"&team={team}"
+    return url
+
+
+
+
+
+
+class OpenIDConnectAuthorizeUrlGenerator +(*,
client_id:Β str,
redirect_uri:Β str,
scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
authorization_url:Β strΒ =Β 'https://slack.com/openid/connect/authorize')
+
+
+
+ +Expand source code + +
class OpenIDConnectAuthorizeUrlGenerator:
+    """Refer to https://openid.net/specs/openid-connect-core-1_0.html"""
+
+    def __init__(
+        self,
+        *,
+        client_id: str,
+        redirect_uri: str,
+        scopes: Optional[Sequence[str]] = None,
+        authorization_url: str = "https://slack.com/openid/connect/authorize",
+    ):
+        self.client_id = client_id
+        self.redirect_uri = redirect_uri
+        self.scopes = scopes
+        self.authorization_url = authorization_url
+
+    def generate(self, state: str, nonce: Optional[str] = None, team: Optional[str] = None) -> str:
+        scopes = ",".join(self.scopes) if self.scopes else ""
+        url = (
+            f"{self.authorization_url}?"
+            "response_type=code&"
+            f"state={state}&"
+            f"client_id={self.client_id}&"
+            f"scope={scopes}&"
+            f"redirect_uri={self.redirect_uri}"
+        )
+        if team is not None:
+            url += f"&team={team}"
+        if nonce is not None:
+            url += f"&nonce={nonce}"
+        return url
+
+ +

Methods

+
+
+def generate(self, state:Β str, nonce:Β strΒ |Β NoneΒ =Β None, team:Β strΒ |Β NoneΒ =Β None) ‑>Β str +
+
+
+ +Expand source code + +
def generate(self, state: str, nonce: Optional[str] = None, team: Optional[str] = None) -> str:
+    scopes = ",".join(self.scopes) if self.scopes else ""
+    url = (
+        f"{self.authorization_url}?"
+        "response_type=code&"
+        f"state={state}&"
+        f"client_id={self.client_id}&"
+        f"scope={scopes}&"
+        f"redirect_uri={self.redirect_uri}"
+    )
+    if team is not None:
+        url += f"&team={team}"
+    if nonce is not None:
+        url += f"&nonce={nonce}"
+    return url
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/index.html b/docs/reference/oauth/index.html new file mode 100644 index 000000000..8fe69e5d0 --- /dev/null +++ b/docs/reference/oauth/index.html @@ -0,0 +1,936 @@ + + + + + + +slack_sdk.oauth API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth

+
+
+

Modules for implementing the Slack OAuth flow

+

https://docs.slack.dev/tools/python-slack-sdk/oauth

+
+
+

Sub-modules

+
+
slack_sdk.oauth.authorize_url_generator
+
+
+
+
slack_sdk.oauth.installation_store
+
+
+
+
slack_sdk.oauth.redirect_uri_page_renderer
+
+
+
+
slack_sdk.oauth.state_store
+
+

OAuth state parameter data store …

+
+
slack_sdk.oauth.state_utils
+
+
+
+
slack_sdk.oauth.token_rotation
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AuthorizeUrlGenerator +(*,
client_id:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
user_scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
authorization_url:Β strΒ =Β 'https://slack.com/oauth/v2/authorize')
+
+
+
+ +Expand source code + +
class AuthorizeUrlGenerator:
+    def __init__(
+        self,
+        *,
+        client_id: str,
+        redirect_uri: Optional[str] = None,
+        scopes: Optional[Sequence[str]] = None,
+        user_scopes: Optional[Sequence[str]] = None,
+        authorization_url: str = "https://slack.com/oauth/v2/authorize",
+    ):
+        self.client_id = client_id
+        self.redirect_uri = redirect_uri
+        self.scopes = scopes
+        self.user_scopes = user_scopes
+        self.authorization_url = authorization_url
+
+    def generate(self, state: str, team: Optional[str] = None) -> str:
+        scopes = ",".join(self.scopes) if self.scopes else ""
+        user_scopes = ",".join(self.user_scopes) if self.user_scopes else ""
+        url = (
+            f"{self.authorization_url}?"
+            f"state={state}&"
+            f"client_id={self.client_id}&"
+            f"scope={scopes}&"
+            f"user_scope={user_scopes}"
+        )
+        if self.redirect_uri is not None:
+            url += f"&redirect_uri={self.redirect_uri}"
+        if team is not None:
+            url += f"&team={team}"
+        return url
+
+
+

Methods

+
+
+def generate(self, state:Β str, team:Β strΒ |Β NoneΒ =Β None) ‑>Β str +
+
+
+ +Expand source code + +
def generate(self, state: str, team: Optional[str] = None) -> str:
+    scopes = ",".join(self.scopes) if self.scopes else ""
+    user_scopes = ",".join(self.user_scopes) if self.user_scopes else ""
+    url = (
+        f"{self.authorization_url}?"
+        f"state={state}&"
+        f"client_id={self.client_id}&"
+        f"scope={scopes}&"
+        f"user_scope={user_scopes}"
+    )
+    if self.redirect_uri is not None:
+        url += f"&redirect_uri={self.redirect_uri}"
+    if team is not None:
+        url += f"&team={team}"
+    return url
+
+
+
+
+
+
+class InstallationStore +
+
+
+ +Expand source code + +
class InstallationStore:
+    """The installation store interface.
+
+    The minimum required methods are:
+
+    * save(installation)
+    * find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
+
+    If you would like to properly handle app uninstallations and token revocations,
+    the following methods should be implemented.
+
+    * delete_installation(enterprise_id, team_id, user_id)
+    * delete_all(enterprise_id, team_id)
+
+    If your app needs only bot scope installations, the simpler way to implement would be:
+
+    * save(installation)
+    * find_bot(enterprise_id, team_id, is_enterprise_install)
+    * delete_bot(enterprise_id, team_id)
+    * delete_all(enterprise_id, team_id)
+    """
+
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def save(self, installation: Installation):
+        """Saves an installation data"""
+        raise NotImplementedError()
+
+    def save_bot(self, bot: Bot):
+        """Saves a bot installation data"""
+        raise NotImplementedError()
+
+    def find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        """Finds a bot scope installation per workspace / org"""
+        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]:
+        """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()
+
+    def delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        """Deletes a bot scope installation per workspace / org"""
+        raise NotImplementedError()
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        """Deletes an installation that matches the given IDs"""
+        raise NotImplementedError()
+
+    def delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        """Deletes all installation data for the given workspace / org"""
+        self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+        self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def delete_all(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) +
+
+
+ +Expand source code + +
def delete_all(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+):
+    """Deletes all installation data for the given workspace / org"""
+    self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+    self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

Deletes all installation data for the given workspace / org

+
+
+def delete_bot(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+) -> None:
+    """Deletes a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Deletes a bot scope installation per workspace / org

+
+
+def delete_installation(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None, user_id:Β strΒ |Β NoneΒ =Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_installation(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    user_id: Optional[str] = None,
+) -> None:
+    """Deletes an installation that matches the given IDs"""
+    raise NotImplementedError()
+
+

Deletes an installation that matches the given IDs

+
+
+def find_bot(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
def find_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    is_enterprise_install: Optional[bool] = False,
+) -> Optional[Bot]:
+    """Finds a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Finds a bot scope installation per workspace / org

+
+
+def find_installation(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
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]:
+    """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()
+
+

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.

+
+
+def save(self,
installation:Β Installation)
+
+
+
+ +Expand source code + +
def save(self, installation: Installation):
+    """Saves an installation data"""
+    raise NotImplementedError()
+
+

Saves an installation data

+
+
+def save_bot(self,
bot:Β Bot)
+
+
+
+ +Expand source code + +
def save_bot(self, bot: Bot):
+    """Saves a bot installation data"""
+    raise NotImplementedError()
+
+

Saves a bot installation data

+
+
+
+
+class OAuthStateStore +
+
+
+ +Expand source code + +
class OAuthStateStore:
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def issue(self, *args, **kwargs) -> str:
+        raise NotImplementedError()
+
+    def consume(self, state: str) -> bool:
+        raise NotImplementedError()
+
+
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    raise NotImplementedError()
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    raise NotImplementedError()
+
+
+
+
+
+
+class OAuthStateUtils +(*, cookie_name:Β strΒ =Β 'slack-app-oauth-state', expiration_seconds:Β intΒ =Β 600) +
+
+
+ +Expand source code + +
class OAuthStateUtils:
+    cookie_name: str
+    expiration_seconds: int
+
+    default_cookie_name: str = "slack-app-oauth-state"
+    default_expiration_seconds: int = 60 * 10  # 10 minutes
+
+    def __init__(
+        self,
+        *,
+        cookie_name: str = default_cookie_name,
+        expiration_seconds: int = default_expiration_seconds,
+    ):
+        self.cookie_name = cookie_name
+        self.expiration_seconds = expiration_seconds
+
+    def build_set_cookie_for_new_state(self, state: str) -> str:
+        return f"{self.cookie_name}={state}; " "Secure; " "HttpOnly; " "Path=/; " f"Max-Age={self.expiration_seconds}"
+
+    def build_set_cookie_for_deletion(self) -> str:
+        return f"{self.cookie_name}=deleted; " "Secure; " "HttpOnly; " "Path=/; " "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
+
+    def is_valid_browser(
+        self,
+        state: Optional[str],
+        request_headers: Dict[str, Union[str, Sequence[str]]],
+    ) -> bool:
+        if state is None or request_headers is None or request_headers.get("cookie", None) is None:
+            return False
+        cookies = request_headers["cookie"]
+        if isinstance(cookies, str):
+            cookies = [cookies]
+        for cookie in cookies:
+            values = cookie.split(";")
+            for value in values:
+                # handle quoted cookie values (e.g. due to base64 encoding)
+                if value.strip().replace('"', "").replace("'", "") == f"{self.cookie_name}={state}":
+                    return True
+        return False
+
+
+

Class variables

+
+
var cookie_name :Β str
+
+

The type of the None singleton.

+
+ +
+

The type of the None singleton.

+
+
var default_expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
var expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
+

Methods

+
+ +
+
+ +Expand source code + +
def build_set_cookie_for_deletion(self) -> str:
+    return f"{self.cookie_name}=deleted; " "Secure; " "HttpOnly; " "Path=/; " "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
+
+
+
+ +
+
+ +Expand source code + +
def build_set_cookie_for_new_state(self, state: str) -> str:
+    return f"{self.cookie_name}={state}; " "Secure; " "HttpOnly; " "Path=/; " f"Max-Age={self.expiration_seconds}"
+
+
+
+
+def is_valid_browser(self, state:Β strΒ |Β None, request_headers:Β Dict[str,Β strΒ |Β Sequence[str]]) ‑>Β bool +
+
+
+ +Expand source code + +
def is_valid_browser(
+    self,
+    state: Optional[str],
+    request_headers: Dict[str, Union[str, Sequence[str]]],
+) -> bool:
+    if state is None or request_headers is None or request_headers.get("cookie", None) is None:
+        return False
+    cookies = request_headers["cookie"]
+    if isinstance(cookies, str):
+        cookies = [cookies]
+    for cookie in cookies:
+        values = cookie.split(";")
+        for value in values:
+            # handle quoted cookie values (e.g. due to base64 encoding)
+            if value.strip().replace('"', "").replace("'", "") == f"{self.cookie_name}={state}":
+                return True
+    return False
+
+
+
+
+
+
+class OpenIDConnectAuthorizeUrlGenerator +(*,
client_id:Β str,
redirect_uri:Β str,
scopes:Β Sequence[str]Β |Β NoneΒ =Β None,
authorization_url:Β strΒ =Β 'https://slack.com/openid/connect/authorize')
+
+
+
+ +Expand source code + +
class OpenIDConnectAuthorizeUrlGenerator:
+    """Refer to https://openid.net/specs/openid-connect-core-1_0.html"""
+
+    def __init__(
+        self,
+        *,
+        client_id: str,
+        redirect_uri: str,
+        scopes: Optional[Sequence[str]] = None,
+        authorization_url: str = "https://slack.com/openid/connect/authorize",
+    ):
+        self.client_id = client_id
+        self.redirect_uri = redirect_uri
+        self.scopes = scopes
+        self.authorization_url = authorization_url
+
+    def generate(self, state: str, nonce: Optional[str] = None, team: Optional[str] = None) -> str:
+        scopes = ",".join(self.scopes) if self.scopes else ""
+        url = (
+            f"{self.authorization_url}?"
+            "response_type=code&"
+            f"state={state}&"
+            f"client_id={self.client_id}&"
+            f"scope={scopes}&"
+            f"redirect_uri={self.redirect_uri}"
+        )
+        if team is not None:
+            url += f"&team={team}"
+        if nonce is not None:
+            url += f"&nonce={nonce}"
+        return url
+
+ +

Methods

+
+
+def generate(self, state:Β str, nonce:Β strΒ |Β NoneΒ =Β None, team:Β strΒ |Β NoneΒ =Β None) ‑>Β str +
+
+
+ +Expand source code + +
def generate(self, state: str, nonce: Optional[str] = None, team: Optional[str] = None) -> str:
+    scopes = ",".join(self.scopes) if self.scopes else ""
+    url = (
+        f"{self.authorization_url}?"
+        "response_type=code&"
+        f"state={state}&"
+        f"client_id={self.client_id}&"
+        f"scope={scopes}&"
+        f"redirect_uri={self.redirect_uri}"
+    )
+    if team is not None:
+        url += f"&team={team}"
+    if nonce is not None:
+        url += f"&nonce={nonce}"
+    return url
+
+
+
+
+
+
+class RedirectUriPageRenderer +(*,
install_path:Β str,
redirect_uri_path:Β str,
success_url:Β strΒ |Β NoneΒ =Β None,
failure_url:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class RedirectUriPageRenderer:
+    def __init__(
+        self,
+        *,
+        install_path: str,
+        redirect_uri_path: str,
+        success_url: Optional[str] = None,
+        failure_url: Optional[str] = None,
+    ):
+        self.install_path = install_path
+        self.redirect_uri_path = redirect_uri_path
+        self.success_url = success_url
+        self.failure_url = failure_url
+
+    def render_success_page(
+        self,
+        app_id: str,
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = None,
+        enterprise_url: Optional[str] = None,
+    ) -> str:
+        url = self.success_url
+        if url is None:
+            if is_enterprise_install is True and enterprise_url is not None and app_id is not None:
+                url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add"
+            elif team_id is None or app_id is None:
+                url = "slack://open"
+            else:
+                url = f"slack://app?team={team_id}&id={app_id}"
+        browser_url = f"https://app.slack.com/client/{team_id}"
+
+        return f"""
+<html>
+<head>
+<meta http-equiv="refresh" content="0; URL={html.escape(url)}">
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Thank you!</h2>
+<p>Redirecting to the Slack App... click <a href="{html.escape(url)}">here</a>. If you use the browser version of Slack, click <a href="{html.escape(browser_url)}" target="_blank">this link</a> instead.</p>
+</body>
+</html>
+"""  # noqa: E501
+
+    def render_failure_page(self, reason: str) -> str:
+        return f"""
+<html>
+<head>
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Oops, Something Went Wrong!</h2>
+<p>Please try again from <a href="{html.escape(self.install_path)}">here</a> or contact the app owner (reason: {html.escape(reason)})</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+

Methods

+
+
+def render_failure_page(self, reason:Β str) ‑>Β str +
+
+
+ +Expand source code + +
    def render_failure_page(self, reason: str) -> str:
+        return f"""
+<html>
+<head>
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Oops, Something Went Wrong!</h2>
+<p>Please try again from <a href="{html.escape(self.install_path)}">here</a> or contact the app owner (reason: {html.escape(reason)})</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+
+
+def render_success_page(self,
app_id:Β str,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β None,
enterprise_url:Β strΒ |Β NoneΒ =Β None) ‑>Β str
+
+
+
+ +Expand source code + +
    def render_success_page(
+        self,
+        app_id: str,
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = None,
+        enterprise_url: Optional[str] = None,
+    ) -> str:
+        url = self.success_url
+        if url is None:
+            if is_enterprise_install is True and enterprise_url is not None and app_id is not None:
+                url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add"
+            elif team_id is None or app_id is None:
+                url = "slack://open"
+            else:
+                url = f"slack://app?team={team_id}&id={app_id}"
+        browser_url = f"https://app.slack.com/client/{team_id}"
+
+        return f"""
+<html>
+<head>
+<meta http-equiv="refresh" content="0; URL={html.escape(url)}">
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Thank you!</h2>
+<p>Redirecting to the Slack App... click <a href="{html.escape(url)}">here</a>. If you use the browser version of Slack, click <a href="{html.escape(browser_url)}" target="_blank">this link</a> instead.</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/amazon_s3/index.html b/docs/reference/oauth/installation_store/amazon_s3/index.html new file mode 100644 index 000000000..0b3afe30a --- /dev/null +++ b/docs/reference/oauth/installation_store/amazon_s3/index.html @@ -0,0 +1,527 @@ + + + + + + +slack_sdk.oauth.installation_store.amazon_s3 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.amazon_s3

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AmazonS3InstallationStore +(*,
s3_client:Β botocore.client.BaseClient,
bucket_name:Β str,
client_id:Β str,
historical_data_enabled:Β boolΒ =Β True,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.amazon_s3 (WARNING)>)
+
+
+
+ +Expand source code + +
class AmazonS3InstallationStore(InstallationStore, AsyncInstallationStore):
+    def __init__(
+        self,
+        *,
+        s3_client: BaseClient,
+        bucket_name: str,
+        client_id: str,
+        historical_data_enabled: bool = True,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.s3_client = s3_client
+        self.bucket_name = bucket_name
+        self.historical_data_enabled = historical_data_enabled
+        self.client_id = client_id
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_save(self, installation: Installation):
+        return self.save(installation)
+
+    async def async_save_bot(self, bot: Bot):
+        return self.save_bot(bot)
+
+    def save(self, installation: Installation):
+        none = "none"
+        e_id = installation.enterprise_id or none
+        t_id = installation.team_id or none
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+
+        self.save_bot(installation.to_bot())
+
+        if self.historical_data_enabled:
+            history_version: str = str(installation.installed_at)
+
+            # per workspace
+            entity: str = json.dumps(installation.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-{history_version}",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+            # per workspace per user
+            u_id = installation.user_id or none
+            entity = json.dumps(installation.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-{u_id}-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-{u_id}-{history_version}",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+        else:
+            # per workspace
+            entity = json.dumps(installation.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+            # per workspace per user
+            u_id = installation.user_id or none
+            entity = json.dumps(installation.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/installer-{u_id}-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+    def save_bot(self, bot: Bot):
+        if bot.bot_token is None:
+            self.logger.debug("Skipped saving a new row because of the absense of bot token in it")
+            return
+
+        none = "none"
+        e_id = bot.enterprise_id or none
+        t_id = bot.team_id or none
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+
+        if self.historical_data_enabled:
+            history_version: str = str(bot.installed_at)
+            entity: str = json.dumps(bot.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/bot-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/bot-{history_version}",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+        else:
+            entity = json.dumps(bot.__dict__)
+            response = self.s3_client.put_object(
+                Bucket=self.bucket_name,
+                Body=entity,
+                Key=f"{workspace_path}/bot-latest",
+            )
+            self.logger.debug(f"S3 put_object response: {response}")
+
+    async def async_find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        return self.find_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+        try:
+            fetch_response = self.s3_client.get_object(
+                Bucket=self.bucket_name,
+                Key=f"{workspace_path}/bot-latest",
+            )
+            self.logger.debug(f"S3 get_object response: {fetch_response}")
+            body = fetch_response["Body"].read().decode("utf-8")
+            data = json.loads(body)
+            return Bot(**data)
+        except Exception as e:
+            message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.warning(message)
+            return None
+
+    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]:
+        return self.find_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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]:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        if is_enterprise_install:
+            t_id = none
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+        try:
+            key = f"{workspace_path}/installer-{user_id}-latest" if user_id else f"{workspace_path}/installer-latest"
+            fetch_response = self.s3_client.get_object(
+                Bucket=self.bucket_name,
+                Key=key,
+            )
+            self.logger.debug(f"S3 get_object response: {fetch_response}")
+            body = fetch_response["Body"].read().decode("utf-8")
+            data = json.loads(body)
+            installation = Installation(**data)
+
+            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 = self.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.bot_token != latest_bot_installation.bot_token:
+                    # NOTE: this logic is based on the assumption that every single installation has bot scopes
+                    # If you need to installation patterns without bot scopes in the same S3 bucket,
+                    # please fork this code and implement your own logic.
+                    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
+
+        except Exception as e:
+            message = f"Failed to find an installation data for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.warning(message)
+            return None
+
+    async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        return self.delete_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+        )
+
+    def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+        objects = self.s3_client.list_objects(
+            Bucket=self.bucket_name,
+            Prefix=f"{workspace_path}/bot-",
+        )
+        for content in objects.get("Contents", []):
+            key = content.get("Key")
+            if key is not None:
+                self.logger.info(f"Going to delete bot installation ({key})")
+                try:
+                    self.s3_client.delete_object(
+                        Bucket=self.bucket_name,
+                        Key=content.get("Key"),
+                    )
+                except Exception as e:
+                    message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                    raise SlackClientConfigurationError(message)
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        return self.delete_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+        )
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        workspace_path = f"{self.client_id}/{e_id}-{t_id}"
+        objects = self.s3_client.list_objects(
+            Bucket=self.bucket_name,
+            Prefix=f"{workspace_path}/installer-{user_id or ''}",
+        )
+        deleted_keys = []
+        for content in objects.get("Contents", []):
+            key = content.get("Key")
+            if key is not None:
+                self.logger.info(f"Going to delete installation ({key})")
+                try:
+                    self.s3_client.delete_object(
+                        Bucket=self.bucket_name,
+                        Key=key,
+                    )
+                    deleted_keys.append(key)
+                except Exception as e:
+                    message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                    raise SlackClientConfigurationError(message)
+
+                try:
+                    no_user_id_key = key.replace(f"-{user_id}", "")
+                    if not no_user_id_key.endswith("installer-latest"):
+                        self.s3_client.delete_object(
+                            Bucket=self.bucket_name,
+                            Key=no_user_id_key,
+                        )
+                        deleted_keys.append(no_user_id_key)
+                except Exception as e:
+                    message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                    raise SlackClientConfigurationError(message)
+
+        # Check the remaining installation data
+        objects = self.s3_client.list_objects(
+            Bucket=self.bucket_name,
+            Prefix=f"{workspace_path}/installer-",
+            MaxKeys=10,  # the small number would be enough for this purpose
+        )
+        keys = [c.get("Key") for c in objects.get("Contents", []) if c.get("Key") not in deleted_keys]
+        # If only installer-latest remains, we should delete the one as well
+        if len(keys) == 1 and keys[0].endswith("installer-latest"):
+            content = objects.get("Contents", [])[0]
+            try:
+                self.s3_client.delete_object(
+                    Bucket=self.bucket_name,
+                    Key=content.get("Key"),
+                )
+            except Exception as e:
+                message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                raise SlackClientConfigurationError(message)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/async_cacheable_installation_store.html b/docs/reference/oauth/installation_store/async_cacheable_installation_store.html new file mode 100644 index 000000000..a38205174 --- /dev/null +++ b/docs/reference/oauth/installation_store/async_cacheable_installation_store.html @@ -0,0 +1,293 @@ + + + + + + +slack_sdk.oauth.installation_store.async_cacheable_installation_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.async_cacheable_installation_store

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncCacheableInstallationStore +(installation_store:Β AsyncInstallationStore) +
+
+
+ +Expand source code + +
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
+
+    async def async_delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        await self.underlying.async_delete_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+        )
+        key = f"{enterprise_id or ''}-{team_id or ''}"
+        self.cached_bots.pop(key)
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        await self.underlying.async_delete_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+        )
+        key_prefix = f"{enterprise_id or ''}-{team_id or ''}"
+        for key in list(self.cached_installations.keys()):
+            if key.startswith(key_prefix):
+                self.cached_installations.pop(key)
+
+    async def async_delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        await self.underlying.async_delete_all(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+        )
+        key_prefix = f"{enterprise_id or ''}-{team_id or ''}"
+        for key in list(self.cached_bots.keys()):
+            if key.startswith(key_prefix):
+                self.cached_bots.pop(key)
+        for key in list(self.cached_installations.keys()):
+            if key.startswith(key_prefix):
+                self.cached_installations.pop(key)
+
+

The installation store interface for asyncio-based apps.

+

The minimum required methods are:

+
    +
  • async_save(installation)
  • +
  • async_find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • async_delete_installation(enterprise_id, team_id, user_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • async_save(installation)
  • +
  • async_find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • async_delete_bot(enterprise_id, team_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

A simple memory cache wrapper for any installation stores.

+

Args

+
+
installation_store
+
The installation store to wrap
+
+

Ancestors

+ +

Class variables

+
+
var cached_bots :Β Dict[str,Β Bot]
+
+

The type of the None singleton.

+
+
var cached_installations :Β Dict[str,Β Installation]
+
+

The type of the None singleton.

+
+
var underlying :Β AsyncInstallationStore
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    return self.underlying.logger
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/async_installation_store.html b/docs/reference/oauth/installation_store/async_installation_store.html new file mode 100644 index 000000000..e6e6583e4 --- /dev/null +++ b/docs/reference/oauth/installation_store/async_installation_store.html @@ -0,0 +1,357 @@ + + + + + + +slack_sdk.oauth.installation_store.async_installation_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.async_installation_store

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncInstallationStore +
+
+
+ +Expand source code + +
class AsyncInstallationStore:
+    """The installation store interface for asyncio-based apps.
+
+    The minimum required methods are:
+
+    * async_save(installation)
+    * async_find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
+
+    If you would like to properly handle app uninstallations and token revocations,
+    the following methods should be implemented.
+
+    * async_delete_installation(enterprise_id, team_id, user_id)
+    * async_delete_all(enterprise_id, team_id)
+
+    If your app needs only bot scope installations, the simpler way to implement would be:
+
+    * async_save(installation)
+    * async_find_bot(enterprise_id, team_id, is_enterprise_install)
+    * async_delete_bot(enterprise_id, team_id)
+    * async_delete_all(enterprise_id, team_id)
+    """
+
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    async def async_save(self, installation: Installation):
+        """Saves an installation data"""
+        raise NotImplementedError()
+
+    async def async_save_bot(self, bot: Bot):
+        """Saves a bot installation data"""
+        raise NotImplementedError()
+
+    async def async_find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        """Finds a bot scope installation per workspace / org"""
+        raise NotImplementedError()
+
+    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()
+
+    async def async_delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        """Deletes a bot scope installation per workspace / org"""
+        raise NotImplementedError()
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        """Deletes an installation that matches the given IDs"""
+        raise NotImplementedError()
+
+    async def async_delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        """Deletes all installation data for the given workspace / org"""
+        await self.async_delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+        await self.async_delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

The installation store interface for asyncio-based apps.

+

The minimum required methods are:

+
    +
  • async_save(installation)
  • +
  • async_find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • async_delete_installation(enterprise_id, team_id, user_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • async_save(installation)
  • +
  • async_find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • async_delete_bot(enterprise_id, team_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+async def async_delete_all(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) +
+
+
+ +Expand source code + +
async def async_delete_all(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+):
+    """Deletes all installation data for the given workspace / org"""
+    await self.async_delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+    await self.async_delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

Deletes all installation data for the given workspace / org

+
+
+async def async_delete_bot(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) ‑>Β None +
+
+
+ +Expand source code + +
async def async_delete_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+) -> None:
+    """Deletes a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Deletes a bot scope installation per workspace / org

+
+
+async def async_delete_installation(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None, user_id:Β strΒ |Β NoneΒ =Β None) ‑>Β None +
+
+
+ +Expand source code + +
async def async_delete_installation(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    user_id: Optional[str] = None,
+) -> None:
+    """Deletes an installation that matches the given IDs"""
+    raise NotImplementedError()
+
+

Deletes an installation that matches the given IDs

+
+
+async def async_find_bot(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
async def async_find_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    is_enterprise_install: Optional[bool] = False,
+) -> Optional[Bot]:
+    """Finds a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Finds a bot scope installation per workspace / org

+
+
+async def async_find_installation(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
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()
+
+

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.

+
+
+async def async_save(self,
installation:Β Installation)
+
+
+
+ +Expand source code + +
async def async_save(self, installation: Installation):
+    """Saves an installation data"""
+    raise NotImplementedError()
+
+

Saves an installation data

+
+
+async def async_save_bot(self,
bot:Β Bot)
+
+
+
+ +Expand source code + +
async def async_save_bot(self, bot: Bot):
+    """Saves a bot installation data"""
+    raise NotImplementedError()
+
+

Saves a bot installation data

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/cacheable_installation_store.html b/docs/reference/oauth/installation_store/cacheable_installation_store.html new file mode 100644 index 000000000..54bb7662d --- /dev/null +++ b/docs/reference/oauth/installation_store/cacheable_installation_store.html @@ -0,0 +1,295 @@ + + + + + + +slack_sdk.oauth.installation_store.cacheable_installation_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.cacheable_installation_store

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class CacheableInstallationStore +(installation_store:Β InstallationStore) +
+
+
+ +Expand source code + +
class CacheableInstallationStore(InstallationStore):
+    underlying: InstallationStore
+    cached_bots: Dict[str, Bot]
+    cached_installations: Dict[str, Installation]
+
+    def __init__(self, installation_store: InstallationStore):
+        """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
+
+    def 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 self.underlying.save(installation)
+
+    def 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 self.underlying.save_bot(bot)
+
+    def 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 = self.underlying.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
+
+    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 = ""
+        key = f"{enterprise_id or ''}-{team_id or ''}-{user_id or ''}"
+        if key in self.cached_installations:
+            return self.cached_installations[key]
+        installation = self.underlying.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
+
+    def delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        self.underlying.delete_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+        )
+        key = f"{enterprise_id or ''}-{team_id or ''}"
+        if key in self.cached_bots:
+            self.cached_bots.pop(key)
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        self.underlying.delete_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+        )
+        key_prefix = f"{enterprise_id or ''}-{team_id or ''}"
+        for key in list(self.cached_installations.keys()):
+            if key.startswith(key_prefix):
+                self.cached_installations.pop(key)
+
+    def delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        self.underlying.delete_all(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+        )
+        key_prefix = f"{enterprise_id or ''}-{team_id or ''}"
+        for key in list(self.cached_bots.keys()):
+            if key.startswith(key_prefix):
+                self.cached_bots.pop(key)
+        for key in list(self.cached_installations.keys()):
+            if key.startswith(key_prefix):
+                self.cached_installations.pop(key)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

A simple memory cache wrapper for any installation stores.

+

Args

+
+
installation_store
+
The installation store to wrap
+
+

Ancestors

+ +

Class variables

+
+
var cached_bots :Β Dict[str,Β Bot]
+
+

The type of the None singleton.

+
+
var cached_installations :Β Dict[str,Β Installation]
+
+

The type of the None singleton.

+
+
var underlying :Β InstallationStore
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    return self.underlying.logger
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/file/index.html b/docs/reference/oauth/installation_store/file/index.html new file mode 100644 index 000000000..db77a087c --- /dev/null +++ b/docs/reference/oauth/installation_store/file/index.html @@ -0,0 +1,428 @@ + + + + + + +slack_sdk.oauth.installation_store.file API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.file

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class FileInstallationStore +(*,
base_dir:Β strΒ =Β '$HOME/.bolt-app-installation',
historical_data_enabled:Β boolΒ =Β True,
client_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.file (WARNING)>)
+
+
+
+ +Expand source code + +
class FileInstallationStore(InstallationStore, AsyncInstallationStore):
+    def __init__(
+        self,
+        *,
+        base_dir: str = str(Path.home()) + "/.bolt-app-installation",
+        historical_data_enabled: bool = True,
+        client_id: Optional[str] = None,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.base_dir = base_dir
+        self.historical_data_enabled = historical_data_enabled
+        self.client_id = client_id
+        if self.client_id is not None:
+            self.base_dir = f"{self.base_dir}/{self.client_id}"
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_save(self, installation: Installation):
+        return self.save(installation)
+
+    async def async_save_bot(self, bot: Bot):
+        return self.save_bot(bot)
+
+    def save(self, installation: Installation):
+        none = "none"
+        e_id = installation.enterprise_id or none
+        t_id = installation.team_id or none
+        team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}"
+        self._mkdir(team_installation_dir)
+
+        self.save_bot(installation.to_bot())
+
+        if self.historical_data_enabled:
+            history_version: str = str(installation.installed_at)
+
+            # per workspace
+            entity: str = json.dumps(installation.__dict__)
+            with open(f"{team_installation_dir}/installer-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/installer-{history_version}", "w") as f:
+                f.write(entity)
+
+            # per workspace per user
+            u_id = installation.user_id or none
+            entity = json.dumps(installation.__dict__)
+            with open(f"{team_installation_dir}/installer-{u_id}-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/installer-{u_id}-{history_version}", "w") as f:
+                f.write(entity)
+
+        else:
+            u_id = installation.user_id or none
+            installer_filepath = f"{team_installation_dir}/installer-{u_id}-latest"
+            with open(installer_filepath, "w") as f:
+                entity = json.dumps(installation.__dict__)
+                f.write(entity)
+
+    def save_bot(self, bot: Bot):
+        if bot.bot_token is None:
+            self.logger.debug("Skipped saving a new row because of the absense of bot token in it")
+            return
+
+        none = "none"
+        e_id = bot.enterprise_id or none
+        t_id = bot.team_id or none
+        team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}"
+        self._mkdir(team_installation_dir)
+
+        if self.historical_data_enabled:
+            history_version: str = str(bot.installed_at)
+
+            entity: str = json.dumps(bot.__dict__)
+            with open(f"{team_installation_dir}/bot-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/bot-{history_version}", "w") as f:
+                f.write(entity)
+        else:
+            with open(f"{team_installation_dir}/bot-latest", "w") as f:
+                entity = json.dumps(bot.__dict__)
+                f.write(entity)
+
+    async def async_find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        return self.find_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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:
+            message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.debug(message)
+            return None
+
+    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]:
+        return self.find_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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]:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        if is_enterprise_install:
+            t_id = none
+        installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-latest"
+        if user_id is not None:
+            installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest"
+
+        try:
+            installation: Optional[Installation] = None
+            with open(installation_filepath) as f:
+                data = json.loads(f.read())
+                installation = Installation(**data)
+
+            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 = self.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.bot_token != latest_bot_installation.bot_token:
+                    # NOTE: this logic is based on the assumption that every single installation has bot scopes
+                    # If you need to installation patterns without bot scopes in the same S3 bucket,
+                    # please fork this code and implement your own logic.
+                    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
+
+        except FileNotFoundError as e:
+            message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.debug(message)
+            return None
+
+    async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        return self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+
+    def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/bot-*"
+        self._delete_by_glob(e_id, t_id, filepath_glob)
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        return self.delete_installation(enterprise_id=enterprise_id, team_id=team_id, user_id=user_id)
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        if user_id is not None:
+            filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-*"
+        else:
+            filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-*"
+        self._delete_by_glob(e_id, t_id, filepath_glob)
+
+    def _delete_by_glob(self, e_id: str, t_id: str, filepath_glob: str):
+        for filepath in glob.glob(filepath_glob):
+            try:
+                os.remove(filepath)
+            except FileNotFoundError as e:
+                message = f"Failed to delete installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                self.logger.warning(message)
+
+    @staticmethod
+    def _mkdir(path: Union[str, Path]):
+        if isinstance(path, str):
+            path = Path(path)
+        path.mkdir(parents=True, exist_ok=True)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/index.html b/docs/reference/oauth/installation_store/index.html new file mode 100644 index 000000000..4f90fb1c5 --- /dev/null +++ b/docs/reference/oauth/installation_store/index.html @@ -0,0 +1,1455 @@ + + + + + + +slack_sdk.oauth.installation_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store

+
+
+
+
+

Sub-modules

+
+
slack_sdk.oauth.installation_store.amazon_s3
+
+
+
+
slack_sdk.oauth.installation_store.async_cacheable_installation_store
+
+
+
+
slack_sdk.oauth.installation_store.async_installation_store
+
+
+
+
slack_sdk.oauth.installation_store.cacheable_installation_store
+
+
+
+
slack_sdk.oauth.installation_store.file
+
+
+
+
slack_sdk.oauth.installation_store.installation_store
+
+

Slack installation data store …

+
+
slack_sdk.oauth.installation_store.internals
+
+
+
+
slack_sdk.oauth.installation_store.models
+
+
+
+
slack_sdk.oauth.installation_store.sqlalchemy
+
+
+
+
slack_sdk.oauth.installation_store.sqlite3
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Bot +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β str,
bot_id:Β str,
bot_user_id:Β str,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β str,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Bot:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: str
+    bot_id: str
+    bot_user_id: str
+    bot_scopes: Sequence[str]
+    # only when token rotation is enabled
+    bot_refresh_token: Optional[str]
+    # only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    is_enterprise_install: bool
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        enterprise_id: Optional[str] = None,
+        enterprise_name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        team_name: Optional[str] = None,
+        # bot
+        bot_token: str,
+        bot_id: str,
+        bot_user_id: str,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        # only when token rotation is enabled
+        bot_refresh_token: Optional[str] = None,
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        is_enterprise_install: Optional[bool] = False,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we support only ISO datetime format.
+        installed_at: Union[float, datetime, str],
+        # custom values
+        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
+        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:
+            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.is_enterprise_install = is_enterprise_install or False
+
+        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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "is_enterprise_install": self.is_enterprise_install,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β str
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]
+
+

The type of the None singleton.

+
+
var bot_token :Β str
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β str
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+class FileInstallationStore +(*,
base_dir:Β strΒ =Β '$HOME/.bolt-app-installation',
historical_data_enabled:Β boolΒ =Β True,
client_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.file (WARNING)>)
+
+
+
+ +Expand source code + +
class FileInstallationStore(InstallationStore, AsyncInstallationStore):
+    def __init__(
+        self,
+        *,
+        base_dir: str = str(Path.home()) + "/.bolt-app-installation",
+        historical_data_enabled: bool = True,
+        client_id: Optional[str] = None,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.base_dir = base_dir
+        self.historical_data_enabled = historical_data_enabled
+        self.client_id = client_id
+        if self.client_id is not None:
+            self.base_dir = f"{self.base_dir}/{self.client_id}"
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_save(self, installation: Installation):
+        return self.save(installation)
+
+    async def async_save_bot(self, bot: Bot):
+        return self.save_bot(bot)
+
+    def save(self, installation: Installation):
+        none = "none"
+        e_id = installation.enterprise_id or none
+        t_id = installation.team_id or none
+        team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}"
+        self._mkdir(team_installation_dir)
+
+        self.save_bot(installation.to_bot())
+
+        if self.historical_data_enabled:
+            history_version: str = str(installation.installed_at)
+
+            # per workspace
+            entity: str = json.dumps(installation.__dict__)
+            with open(f"{team_installation_dir}/installer-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/installer-{history_version}", "w") as f:
+                f.write(entity)
+
+            # per workspace per user
+            u_id = installation.user_id or none
+            entity = json.dumps(installation.__dict__)
+            with open(f"{team_installation_dir}/installer-{u_id}-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/installer-{u_id}-{history_version}", "w") as f:
+                f.write(entity)
+
+        else:
+            u_id = installation.user_id or none
+            installer_filepath = f"{team_installation_dir}/installer-{u_id}-latest"
+            with open(installer_filepath, "w") as f:
+                entity = json.dumps(installation.__dict__)
+                f.write(entity)
+
+    def save_bot(self, bot: Bot):
+        if bot.bot_token is None:
+            self.logger.debug("Skipped saving a new row because of the absense of bot token in it")
+            return
+
+        none = "none"
+        e_id = bot.enterprise_id or none
+        t_id = bot.team_id or none
+        team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}"
+        self._mkdir(team_installation_dir)
+
+        if self.historical_data_enabled:
+            history_version: str = str(bot.installed_at)
+
+            entity: str = json.dumps(bot.__dict__)
+            with open(f"{team_installation_dir}/bot-latest", "w") as f:
+                f.write(entity)
+            with open(f"{team_installation_dir}/bot-{history_version}", "w") as f:
+                f.write(entity)
+        else:
+            with open(f"{team_installation_dir}/bot-latest", "w") as f:
+                entity = json.dumps(bot.__dict__)
+                f.write(entity)
+
+    async def async_find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        return self.find_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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:
+            message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.debug(message)
+            return None
+
+    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]:
+        return self.find_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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]:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        if is_enterprise_install:
+            t_id = none
+        installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-latest"
+        if user_id is not None:
+            installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest"
+
+        try:
+            installation: Optional[Installation] = None
+            with open(installation_filepath) as f:
+                data = json.loads(f.read())
+                installation = Installation(**data)
+
+            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 = self.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.bot_token != latest_bot_installation.bot_token:
+                    # NOTE: this logic is based on the assumption that every single installation has bot scopes
+                    # If you need to installation patterns without bot scopes in the same S3 bucket,
+                    # please fork this code and implement your own logic.
+                    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
+
+        except FileNotFoundError as e:
+            message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}"
+            self.logger.debug(message)
+            return None
+
+    async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        return self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+
+    def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/bot-*"
+        self._delete_by_glob(e_id, t_id, filepath_glob)
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        return self.delete_installation(enterprise_id=enterprise_id, team_id=team_id, user_id=user_id)
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        none = "none"
+        e_id = enterprise_id or none
+        t_id = team_id or none
+        if user_id is not None:
+            filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-*"
+        else:
+            filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-*"
+        self._delete_by_glob(e_id, t_id, filepath_glob)
+
+    def _delete_by_glob(self, e_id: str, t_id: str, filepath_glob: str):
+        for filepath in glob.glob(filepath_glob):
+            try:
+                os.remove(filepath)
+            except FileNotFoundError as e:
+                message = f"Failed to delete installation data for enterprise: {e_id}, team: {t_id}: {e}"
+                self.logger.warning(message)
+
+    @staticmethod
+    def _mkdir(path: Union[str, Path]):
+        if isinstance(path, str):
+            path = Path(path)
+        path.mkdir(parents=True, exist_ok=True)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Inherited members

+ +
+
+class Installation +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
enterprise_url:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β strΒ |Β NoneΒ =Β None,
bot_id:Β strΒ |Β NoneΒ =Β None,
bot_user_id:Β strΒ |Β NoneΒ =Β None,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
user_id:Β str,
user_token:Β strΒ |Β NoneΒ =Β None,
user_scopes:Β strΒ |Β Sequence[str]Β =Β '',
user_refresh_token:Β strΒ |Β NoneΒ =Β None,
user_token_expires_in:Β intΒ |Β NoneΒ =Β None,
user_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
incoming_webhook_url:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel_id:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_configuration_url:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
token_type:Β strΒ |Β NoneΒ =Β None,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Installation:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    enterprise_url: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: Optional[str]
+    bot_id: Optional[str]
+    bot_user_id: Optional[str]
+    bot_scopes: Optional[Sequence[str]]
+    bot_refresh_token: Optional[str]  # only when token rotation is enabled
+    # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    user_id: str
+    user_token: Optional[str]
+    user_scopes: Optional[Sequence[str]]
+    user_refresh_token: Optional[str]  # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    user_token_expires_at: Optional[int]
+    incoming_webhook_url: Optional[str]
+    incoming_webhook_channel: Optional[str]
+    incoming_webhook_channel_id: Optional[str]
+    incoming_webhook_configuration_url: Optional[str]
+    is_enterprise_install: bool
+    token_type: Optional[str]
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        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
+        bot_token: Optional[str] = None,
+        bot_id: Optional[str] = None,
+        bot_user_id: Optional[str] = None,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        bot_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # installer
+        user_id: str,
+        user_token: Optional[str] = None,
+        user_scopes: Union[str, Sequence[str]] = "",
+        user_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        user_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        user_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # incoming webhook
+        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,
+        # org app
+        is_enterprise_install: Optional[bool] = False,
+        token_type: Optional[str] = None,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we supports only ISO datetime format.
+        installed_at: Optional[Union[float, datetime, str]] = None,
+        # custom values
+        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:
+            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:
+            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:
+            self.installed_at = _timestamp_to_type(installed_at, float)
+
+        self.custom_values = custom_values if custom_values is not None else {}
+
+    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,
+        )
+
+    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,
+            "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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "user_id": self.user_id,
+            "user_token": self.user_token,
+            "user_scopes": ",".join(self.user_scopes) if self.user_scopes else None,
+            "user_refresh_token": self.user_refresh_token,
+            "user_token_expires_at": (
+                datetime.utcfromtimestamp(self.user_token_expires_at) if self.user_token_expires_at is not None else None
+            ),
+            "incoming_webhook_url": self.incoming_webhook_url,
+            "incoming_webhook_channel": self.incoming_webhook_channel,
+            "incoming_webhook_channel_id": self.incoming_webhook_channel_id,
+            "incoming_webhook_configuration_url": self.incoming_webhook_configuration_url,
+            "is_enterprise_install": self.is_enterprise_install,
+            "token_type": self.token_type,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var bot_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_configuration_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var token_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_id :Β str
+
+

The type of the None singleton.

+
+
var user_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var user_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_bot(self) ‑>Β Bot +
+
+
+ +Expand source code + +
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,
+    )
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+class InstallationStore +
+
+
+ +Expand source code + +
class InstallationStore:
+    """The installation store interface.
+
+    The minimum required methods are:
+
+    * save(installation)
+    * find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
+
+    If you would like to properly handle app uninstallations and token revocations,
+    the following methods should be implemented.
+
+    * delete_installation(enterprise_id, team_id, user_id)
+    * delete_all(enterprise_id, team_id)
+
+    If your app needs only bot scope installations, the simpler way to implement would be:
+
+    * save(installation)
+    * find_bot(enterprise_id, team_id, is_enterprise_install)
+    * delete_bot(enterprise_id, team_id)
+    * delete_all(enterprise_id, team_id)
+    """
+
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def save(self, installation: Installation):
+        """Saves an installation data"""
+        raise NotImplementedError()
+
+    def save_bot(self, bot: Bot):
+        """Saves a bot installation data"""
+        raise NotImplementedError()
+
+    def find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        """Finds a bot scope installation per workspace / org"""
+        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]:
+        """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()
+
+    def delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        """Deletes a bot scope installation per workspace / org"""
+        raise NotImplementedError()
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        """Deletes an installation that matches the given IDs"""
+        raise NotImplementedError()
+
+    def delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        """Deletes all installation data for the given workspace / org"""
+        self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+        self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def delete_all(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) +
+
+
+ +Expand source code + +
def delete_all(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+):
+    """Deletes all installation data for the given workspace / org"""
+    self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+    self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

Deletes all installation data for the given workspace / org

+
+
+def delete_bot(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+) -> None:
+    """Deletes a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Deletes a bot scope installation per workspace / org

+
+
+def delete_installation(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None, user_id:Β strΒ |Β NoneΒ =Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_installation(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    user_id: Optional[str] = None,
+) -> None:
+    """Deletes an installation that matches the given IDs"""
+    raise NotImplementedError()
+
+

Deletes an installation that matches the given IDs

+
+
+def find_bot(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
def find_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    is_enterprise_install: Optional[bool] = False,
+) -> Optional[Bot]:
+    """Finds a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Finds a bot scope installation per workspace / org

+
+
+def find_installation(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
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]:
+    """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()
+
+

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.

+
+
+def save(self,
installation:Β Installation)
+
+
+
+ +Expand source code + +
def save(self, installation: Installation):
+    """Saves an installation data"""
+    raise NotImplementedError()
+
+

Saves an installation data

+
+
+def save_bot(self,
bot:Β Bot)
+
+
+
+ +Expand source code + +
def save_bot(self, bot: Bot):
+    """Saves a bot installation data"""
+    raise NotImplementedError()
+
+

Saves a bot installation data

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/installation_store.html b/docs/reference/oauth/installation_store/installation_store.html new file mode 100644 index 000000000..86533f424 --- /dev/null +++ b/docs/reference/oauth/installation_store/installation_store.html @@ -0,0 +1,359 @@ + + + + + + +slack_sdk.oauth.installation_store.installation_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.installation_store

+
+
+

Slack installation data store

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/oauth for details.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class InstallationStore +
+
+
+ +Expand source code + +
class InstallationStore:
+    """The installation store interface.
+
+    The minimum required methods are:
+
+    * save(installation)
+    * find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
+
+    If you would like to properly handle app uninstallations and token revocations,
+    the following methods should be implemented.
+
+    * delete_installation(enterprise_id, team_id, user_id)
+    * delete_all(enterprise_id, team_id)
+
+    If your app needs only bot scope installations, the simpler way to implement would be:
+
+    * save(installation)
+    * find_bot(enterprise_id, team_id, is_enterprise_install)
+    * delete_bot(enterprise_id, team_id)
+    * delete_all(enterprise_id, team_id)
+    """
+
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def save(self, installation: Installation):
+        """Saves an installation data"""
+        raise NotImplementedError()
+
+    def save_bot(self, bot: Bot):
+        """Saves a bot installation data"""
+        raise NotImplementedError()
+
+    def find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        """Finds a bot scope installation per workspace / org"""
+        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]:
+        """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()
+
+    def delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        """Deletes a bot scope installation per workspace / org"""
+        raise NotImplementedError()
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        """Deletes an installation that matches the given IDs"""
+        raise NotImplementedError()
+
+    def delete_all(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ):
+        """Deletes all installation data for the given workspace / org"""
+        self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+        self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def delete_all(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) +
+
+
+ +Expand source code + +
def delete_all(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+):
+    """Deletes all installation data for the given workspace / org"""
+    self.delete_bot(enterprise_id=enterprise_id, team_id=team_id)
+    self.delete_installation(enterprise_id=enterprise_id, team_id=team_id)
+
+

Deletes all installation data for the given workspace / org

+
+
+def delete_bot(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+) -> None:
+    """Deletes a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Deletes a bot scope installation per workspace / org

+
+
+def delete_installation(self, *, enterprise_id:Β strΒ |Β None, team_id:Β strΒ |Β None, user_id:Β strΒ |Β NoneΒ =Β None) ‑>Β None +
+
+
+ +Expand source code + +
def delete_installation(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    user_id: Optional[str] = None,
+) -> None:
+    """Deletes an installation that matches the given IDs"""
+    raise NotImplementedError()
+
+

Deletes an installation that matches the given IDs

+
+
+def find_bot(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
def find_bot(
+    self,
+    *,
+    enterprise_id: Optional[str],
+    team_id: Optional[str],
+    is_enterprise_install: Optional[bool] = False,
+) -> Optional[Bot]:
+    """Finds a bot scope installation per workspace / org"""
+    raise NotImplementedError()
+
+

Finds a bot scope installation per workspace / org

+
+
+def find_installation(self,
*,
enterprise_id:Β strΒ |Β None,
team_id:Β strΒ |Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
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]:
+    """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()
+
+

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.

+
+
+def save(self,
installation:Β Installation)
+
+
+
+ +Expand source code + +
def save(self, installation: Installation):
+    """Saves an installation data"""
+    raise NotImplementedError()
+
+

Saves an installation data

+
+
+def save_bot(self,
bot:Β Bot)
+
+
+
+ +Expand source code + +
def save_bot(self, bot: Bot):
+    """Saves a bot installation data"""
+    raise NotImplementedError()
+
+

Saves a bot installation data

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/internals.html b/docs/reference/oauth/installation_store/internals.html new file mode 100644 index 000000000..4bf376755 --- /dev/null +++ b/docs/reference/oauth/installation_store/internals.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.oauth.installation_store.internals API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.internals

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/models/bot.html b/docs/reference/oauth/installation_store/models/bot.html new file mode 100644 index 000000000..bb6182df2 --- /dev/null +++ b/docs/reference/oauth/installation_store/models/bot.html @@ -0,0 +1,332 @@ + + + + + + +slack_sdk.oauth.installation_store.models.bot API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.models.bot

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Bot +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β str,
bot_id:Β str,
bot_user_id:Β str,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β str,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Bot:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: str
+    bot_id: str
+    bot_user_id: str
+    bot_scopes: Sequence[str]
+    # only when token rotation is enabled
+    bot_refresh_token: Optional[str]
+    # only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    is_enterprise_install: bool
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        enterprise_id: Optional[str] = None,
+        enterprise_name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        team_name: Optional[str] = None,
+        # bot
+        bot_token: str,
+        bot_id: str,
+        bot_user_id: str,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        # only when token rotation is enabled
+        bot_refresh_token: Optional[str] = None,
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        is_enterprise_install: Optional[bool] = False,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we support only ISO datetime format.
+        installed_at: Union[float, datetime, str],
+        # custom values
+        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
+        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:
+            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.is_enterprise_install = is_enterprise_install or False
+
+        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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "is_enterprise_install": self.is_enterprise_install,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β str
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]
+
+

The type of the None singleton.

+
+
var bot_token :Β str
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β str
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/models/index.html b/docs/reference/oauth/installation_store/models/index.html new file mode 100644 index 000000000..b96d16179 --- /dev/null +++ b/docs/reference/oauth/installation_store/models/index.html @@ -0,0 +1,776 @@ + + + + + + +slack_sdk.oauth.installation_store.models API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.models

+
+
+
+
+

Sub-modules

+
+
slack_sdk.oauth.installation_store.models.bot
+
+
+
+
slack_sdk.oauth.installation_store.models.installation
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Bot +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β str,
bot_id:Β str,
bot_user_id:Β str,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β str,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Bot:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: str
+    bot_id: str
+    bot_user_id: str
+    bot_scopes: Sequence[str]
+    # only when token rotation is enabled
+    bot_refresh_token: Optional[str]
+    # only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    is_enterprise_install: bool
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        enterprise_id: Optional[str] = None,
+        enterprise_name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        team_name: Optional[str] = None,
+        # bot
+        bot_token: str,
+        bot_id: str,
+        bot_user_id: str,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        # only when token rotation is enabled
+        bot_refresh_token: Optional[str] = None,
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        is_enterprise_install: Optional[bool] = False,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we support only ISO datetime format.
+        installed_at: Union[float, datetime, str],
+        # custom values
+        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
+        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:
+            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.is_enterprise_install = is_enterprise_install or False
+
+        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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "is_enterprise_install": self.is_enterprise_install,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β str
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]
+
+

The type of the None singleton.

+
+
var bot_token :Β str
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β str
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+class Installation +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
enterprise_url:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β strΒ |Β NoneΒ =Β None,
bot_id:Β strΒ |Β NoneΒ =Β None,
bot_user_id:Β strΒ |Β NoneΒ =Β None,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
user_id:Β str,
user_token:Β strΒ |Β NoneΒ =Β None,
user_scopes:Β strΒ |Β Sequence[str]Β =Β '',
user_refresh_token:Β strΒ |Β NoneΒ =Β None,
user_token_expires_in:Β intΒ |Β NoneΒ =Β None,
user_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
incoming_webhook_url:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel_id:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_configuration_url:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
token_type:Β strΒ |Β NoneΒ =Β None,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Installation:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    enterprise_url: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: Optional[str]
+    bot_id: Optional[str]
+    bot_user_id: Optional[str]
+    bot_scopes: Optional[Sequence[str]]
+    bot_refresh_token: Optional[str]  # only when token rotation is enabled
+    # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    user_id: str
+    user_token: Optional[str]
+    user_scopes: Optional[Sequence[str]]
+    user_refresh_token: Optional[str]  # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    user_token_expires_at: Optional[int]
+    incoming_webhook_url: Optional[str]
+    incoming_webhook_channel: Optional[str]
+    incoming_webhook_channel_id: Optional[str]
+    incoming_webhook_configuration_url: Optional[str]
+    is_enterprise_install: bool
+    token_type: Optional[str]
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        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
+        bot_token: Optional[str] = None,
+        bot_id: Optional[str] = None,
+        bot_user_id: Optional[str] = None,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        bot_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # installer
+        user_id: str,
+        user_token: Optional[str] = None,
+        user_scopes: Union[str, Sequence[str]] = "",
+        user_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        user_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        user_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # incoming webhook
+        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,
+        # org app
+        is_enterprise_install: Optional[bool] = False,
+        token_type: Optional[str] = None,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we supports only ISO datetime format.
+        installed_at: Optional[Union[float, datetime, str]] = None,
+        # custom values
+        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:
+            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:
+            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:
+            self.installed_at = _timestamp_to_type(installed_at, float)
+
+        self.custom_values = custom_values if custom_values is not None else {}
+
+    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,
+        )
+
+    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,
+            "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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "user_id": self.user_id,
+            "user_token": self.user_token,
+            "user_scopes": ",".join(self.user_scopes) if self.user_scopes else None,
+            "user_refresh_token": self.user_refresh_token,
+            "user_token_expires_at": (
+                datetime.utcfromtimestamp(self.user_token_expires_at) if self.user_token_expires_at is not None else None
+            ),
+            "incoming_webhook_url": self.incoming_webhook_url,
+            "incoming_webhook_channel": self.incoming_webhook_channel,
+            "incoming_webhook_channel_id": self.incoming_webhook_channel_id,
+            "incoming_webhook_configuration_url": self.incoming_webhook_configuration_url,
+            "is_enterprise_install": self.is_enterprise_install,
+            "token_type": self.token_type,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var bot_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_configuration_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var token_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_id :Β str
+
+

The type of the None singleton.

+
+
var user_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var user_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_bot(self) ‑>Β Bot +
+
+
+ +Expand source code + +
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,
+    )
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/models/installation.html b/docs/reference/oauth/installation_store/models/installation.html new file mode 100644 index 000000000..c0de92807 --- /dev/null +++ b/docs/reference/oauth/installation_store/models/installation.html @@ -0,0 +1,500 @@ + + + + + + +slack_sdk.oauth.installation_store.models.installation API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.models.installation

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Installation +(*,
app_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
enterprise_name:Β strΒ |Β NoneΒ =Β None,
enterprise_url:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
team_name:Β strΒ |Β NoneΒ =Β None,
bot_token:Β strΒ |Β NoneΒ =Β None,
bot_id:Β strΒ |Β NoneΒ =Β None,
bot_user_id:Β strΒ |Β NoneΒ =Β None,
bot_scopes:Β strΒ |Β Sequence[str]Β =Β '',
bot_refresh_token:Β strΒ |Β NoneΒ =Β None,
bot_token_expires_in:Β intΒ |Β NoneΒ =Β None,
bot_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
user_id:Β str,
user_token:Β strΒ |Β NoneΒ =Β None,
user_scopes:Β strΒ |Β Sequence[str]Β =Β '',
user_refresh_token:Β strΒ |Β NoneΒ =Β None,
user_token_expires_in:Β intΒ |Β NoneΒ =Β None,
user_token_expires_at:Β intΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
incoming_webhook_url:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_channel_id:Β strΒ |Β NoneΒ =Β None,
incoming_webhook_configuration_url:Β strΒ |Β NoneΒ =Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β False,
token_type:Β strΒ |Β NoneΒ =Β None,
installed_at:Β floatΒ |Β datetime.datetimeΒ |Β strΒ |Β NoneΒ =Β None,
custom_values:Β Dict[str,Β Any]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Installation:
+    app_id: Optional[str]
+    enterprise_id: Optional[str]
+    enterprise_name: Optional[str]
+    enterprise_url: Optional[str]
+    team_id: Optional[str]
+    team_name: Optional[str]
+    bot_token: Optional[str]
+    bot_id: Optional[str]
+    bot_user_id: Optional[str]
+    bot_scopes: Optional[Sequence[str]]
+    bot_refresh_token: Optional[str]  # only when token rotation is enabled
+    # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    bot_token_expires_at: Optional[int]
+    user_id: str
+    user_token: Optional[str]
+    user_scopes: Optional[Sequence[str]]
+    user_refresh_token: Optional[str]  # only when token rotation is enabled
+    # Unix time (seconds): only when token rotation is enabled
+    user_token_expires_at: Optional[int]
+    incoming_webhook_url: Optional[str]
+    incoming_webhook_channel: Optional[str]
+    incoming_webhook_channel_id: Optional[str]
+    incoming_webhook_configuration_url: Optional[str]
+    is_enterprise_install: bool
+    token_type: Optional[str]
+    installed_at: float
+
+    custom_values: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        # org / workspace
+        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
+        bot_token: Optional[str] = None,
+        bot_id: Optional[str] = None,
+        bot_user_id: Optional[str] = None,
+        bot_scopes: Union[str, Sequence[str]] = "",
+        bot_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        bot_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        bot_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # installer
+        user_id: str,
+        user_token: Optional[str] = None,
+        user_scopes: Union[str, Sequence[str]] = "",
+        user_refresh_token: Optional[str] = None,  # only when token rotation is enabled
+        # only when token rotation is enabled
+        user_token_expires_in: Optional[int] = None,
+        # only for duplicating this object
+        # only when token rotation is enabled
+        user_token_expires_at: Optional[Union[int, datetime, str]] = None,
+        # incoming webhook
+        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,
+        # org app
+        is_enterprise_install: Optional[bool] = False,
+        token_type: Optional[str] = None,
+        # timestamps
+        # The expected value type is float but the internals handle other types too
+        # for str values, we supports only ISO datetime format.
+        installed_at: Optional[Union[float, datetime, str]] = None,
+        # custom values
+        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:
+            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:
+            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:
+            self.installed_at = _timestamp_to_type(installed_at, float)
+
+        self.custom_values = custom_values if custom_values is not None else {}
+
+    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,
+        )
+
+    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,
+            "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.utcfromtimestamp(self.bot_token_expires_at) if self.bot_token_expires_at is not None else None
+            ),
+            "user_id": self.user_id,
+            "user_token": self.user_token,
+            "user_scopes": ",".join(self.user_scopes) if self.user_scopes else None,
+            "user_refresh_token": self.user_refresh_token,
+            "user_token_expires_at": (
+                datetime.utcfromtimestamp(self.user_token_expires_at) if self.user_token_expires_at is not None else None
+            ),
+            "incoming_webhook_url": self.incoming_webhook_url,
+            "incoming_webhook_channel": self.incoming_webhook_channel,
+            "incoming_webhook_channel_id": self.incoming_webhook_channel_id,
+            "incoming_webhook_configuration_url": self.incoming_webhook_configuration_url,
+            "is_enterprise_install": self.is_enterprise_install,
+            "token_type": self.token_type,
+            "installed_at": datetime.utcfromtimestamp(self.installed_at),
+        }
+
+    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()}
+
+
+

Class variables

+
+
var app_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var bot_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var bot_user_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var custom_values :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var enterprise_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var enterprise_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_channel_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_configuration_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var incoming_webhook_url :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var installed_at :Β float
+
+

The type of the None singleton.

+
+
var is_enterprise_install :Β bool
+
+

The type of the None singleton.

+
+
var team_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var team_name :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var token_type :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_id :Β str
+
+

The type of the None singleton.

+
+
var user_refresh_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_scopes :Β Sequence[str]Β |Β None
+
+

The type of the None singleton.

+
+
var user_token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var user_token_expires_at :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def get_custom_value(self, name:Β str) ‑>Β AnyΒ |Β None +
+
+
+ +Expand source code + +
def get_custom_value(self, name: str) -> Optional[Any]:
+    return self.custom_values.get(name)
+
+
+
+
+def set_custom_value(self, name:Β str, value:Β Any) +
+
+
+ +Expand source code + +
def set_custom_value(self, name: str, value: Any):
+    self.custom_values[name] = value
+
+
+
+
+def to_bot(self) ‑>Β Bot +
+
+
+ +Expand source code + +
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,
+    )
+
+
+
+
+def to_dict(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
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()}
+
+
+
+
+def to_dict_for_copying(self) ‑>Β Dict[str,Β Any] +
+
+
+ +Expand source code + +
def to_dict_for_copying(self) -> Dict[str, Any]:
+    return {"custom_values": self.custom_values, **self._to_standard_value_dict()}
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/sqlalchemy/index.html b/docs/reference/oauth/installation_store/sqlalchemy/index.html new file mode 100644 index 000000000..8861dd476 --- /dev/null +++ b/docs/reference/oauth/installation_store/sqlalchemy/index.html @@ -0,0 +1,942 @@ + + + + + + +slack_sdk.oauth.installation_store.sqlalchemy API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.sqlalchemy

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSQLAlchemyInstallationStore +(client_id:Β str,
engine:Β sqlalchemy.ext.asyncio.engine.AsyncEngine,
bots_table_name:Β strΒ =Β 'slack_bots',
installations_table_name:Β strΒ =Β 'slack_installations',
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.sqlalchemy (WARNING)>)
+
+
+
+ +Expand source code + +
class AsyncSQLAlchemyInstallationStore(AsyncInstallationStore):
+    default_bots_table_name: str = "slack_bots"
+    default_installations_table_name: str = "slack_installations"
+
+    client_id: str
+    engine: AsyncEngine
+    metadata: MetaData
+    installations: Table
+
+    def __init__(
+        self,
+        client_id: str,
+        engine: AsyncEngine,
+        bots_table_name: str = default_bots_table_name,
+        installations_table_name: str = default_installations_table_name,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        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._logger = logger
+        self.engine = engine
+
+    @classmethod
+    def build_installations_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return SQLAlchemyInstallationStore.build_installations_table(metadata, table_name)
+
+    @classmethod
+    def build_bots_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return SQLAlchemyInstallationStore.build_bots_table(metadata, table_name)
+
+    async def create_tables(self):
+        async with self.engine.begin() as conn:
+            await conn.run_sync(self.metadata.create_all)
+
+    @property
+    def logger(self) -> Logger:
+        return self._logger
+
+    async def async_save(self, installation: Installation):
+        async with self.engine.begin() as conn:
+            i = installation.to_dict()
+            i["client_id"] = self.client_id
+
+            i_column = self.installations.c
+            installations_rows = await conn.execute(
+                sqlalchemy.select(i_column.id)
+                .where(
+                    and_(
+                        i_column.client_id == self.client_id,
+                        i_column.enterprise_id == installation.enterprise_id,
+                        i_column.team_id == installation.team_id,
+                        i_column.installed_at == i.get("installed_at"),
+                    )
+                )
+                .limit(1)
+            )
+            installations_row_id: Optional[str] = None
+            for row in installations_rows.mappings():
+                installations_row_id = row["id"]
+            if installations_row_id is None:
+                await conn.execute(self.installations.insert(), i)
+            else:
+                update_statement = self.installations.update().where(i_column.id == installations_row_id).values(**i)
+                await conn.execute(update_statement, i)
+
+        # bots
+        await self.async_save_bot(installation.to_bot())
+
+    async def async_save_bot(self, bot: Bot):
+        async with self.engine.begin() as conn:
+            # bots
+            b = bot.to_dict()
+            b["client_id"] = self.client_id
+
+            b_column = self.bots.c
+            bots_rows = await conn.execute(
+                sqlalchemy.select(b_column.id)
+                .where(
+                    and_(
+                        b_column.client_id == self.client_id,
+                        b_column.enterprise_id == bot.enterprise_id,
+                        b_column.team_id == bot.team_id,
+                        b_column.installed_at == b.get("installed_at"),
+                    )
+                )
+                .limit(1)
+            )
+            bots_row_id: Optional[str] = None
+            for row in bots_rows.mappings():
+                bots_row_id = row["id"]
+            if bots_row_id is None:
+                await conn.execute(self.bots.insert(), b)
+            else:
+                update_statement = self.bots.update().where(b_column.id == bots_row_id).values(**b)
+                await conn.execute(update_statement, b)
+
+    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 = None
+
+        c = self.bots.c
+        query = (
+            self.bots.select()
+            .where(
+                and_(
+                    c.client_id == self.client_id,
+                    c.enterprise_id == enterprise_id,
+                    c.team_id == team_id,
+                    c.bot_token.is_not(None),  # the latest one that has a bot token
+                )
+            )
+            .order_by(desc(c.installed_at))
+            .limit(1)
+        )
+
+        async with self.engine.connect() as conn:
+            result: object = await conn.execute(query)
+            for row in result.mappings():  # type: ignore[attr-defined]
+                return SQLAlchemyInstallationStore.build_bot_entity(row)
+            return None
+
+    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
+
+    async def async_delete_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+    ) -> None:
+        table = self.bots
+        c = table.c
+        async with self.engine.begin() as conn:
+            deletion = table.delete().where(
+                and_(
+                    c.client_id == self.client_id,
+                    c.enterprise_id == enterprise_id,
+                    c.team_id == team_id,
+                )
+            )
+            await conn.execute(deletion)
+
+    async def async_delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        table = self.installations
+        c = table.c
+        async with self.engine.begin() as conn:
+            if user_id is not None:
+                deletion = table.delete().where(
+                    and_(
+                        c.client_id == self.client_id,
+                        c.enterprise_id == enterprise_id,
+                        c.team_id == team_id,
+                        c.user_id == user_id,
+                    )
+                )
+                await conn.execute(deletion)
+            else:
+                deletion = table.delete().where(
+                    and_(
+                        c.client_id == self.client_id,
+                        c.enterprise_id == enterprise_id,
+                        c.team_id == team_id,
+                    )
+                )
+                await conn.execute(deletion)
+
+

The installation store interface for asyncio-based apps.

+

The minimum required methods are:

+
    +
  • async_save(installation)
  • +
  • async_find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • async_delete_installation(enterprise_id, team_id, user_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • async_save(installation)
  • +
  • async_find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • async_delete_bot(enterprise_id, team_id)
  • +
  • async_delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Class variables

+
+
var client_id :Β str
+
+

The type of the None singleton.

+
+
var default_bots_table_name :Β str
+
+

The type of the None singleton.

+
+
var default_installations_table_name :Β str
+
+

The type of the None singleton.

+
+
var engine :Β sqlalchemy.ext.asyncio.engine.AsyncEngine
+
+

The type of the None singleton.

+
+
var installations :Β sqlalchemy.sql.schema.Table
+
+

The type of the None singleton.

+
+
var metadata :Β sqlalchemy.sql.schema.MetaData
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_bots_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+def build_installations_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def create_tables(self) +
+
+
+ +Expand source code + +
async def create_tables(self):
+    async with self.engine.begin() as conn:
+        await conn.run_sync(self.metadata.create_all)
+
+
+
+
+

Inherited members

+ +
+
+class SQLAlchemyInstallationStore +(client_id:Β str,
engine:Β sqlalchemy.engine.base.Engine,
bots_table_name:Β strΒ =Β 'slack_bots',
installations_table_name:Β strΒ =Β 'slack_installations',
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.sqlalchemy (WARNING)>)
+
+
+
+ +Expand source code + +
class SQLAlchemyInstallationStore(InstallationStore):
+    default_bots_table_name: str = "slack_bots"
+    default_installations_table_name: str = "slack_installations"
+
+    client_id: str
+    engine: Engine
+    metadata: MetaData
+    installations: Table
+
+    @classmethod
+    def build_installations_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return sqlalchemy.Table(
+            table_name,
+            metadata,
+            Column("id", Integer, primary_key=True, autoincrement=True),
+            Column("client_id", String(32), nullable=False),
+            Column("app_id", String(32), nullable=False),
+            Column("enterprise_id", String(32)),
+            Column("enterprise_name", String(200)),
+            Column("enterprise_url", String(200)),
+            Column("team_id", String(32)),
+            Column("team_name", String(200)),
+            Column("bot_token", String(200)),
+            Column("bot_id", String(32)),
+            Column("bot_user_id", String(32)),
+            Column("bot_scopes", String(1000)),
+            Column("bot_refresh_token", String(200)),  # added in v3.8.0
+            Column("bot_token_expires_at", DateTime),  # added in v3.8.0
+            Column("user_id", String(32), nullable=False),
+            Column("user_token", String(200)),
+            Column("user_scopes", String(1000)),
+            Column("user_refresh_token", String(200)),  # added in v3.8.0
+            Column("user_token_expires_at", DateTime),  # added in v3.8.0
+            Column("incoming_webhook_url", String(200)),
+            Column("incoming_webhook_channel", String(200)),
+            Column("incoming_webhook_channel_id", String(200)),
+            Column("incoming_webhook_configuration_url", String(200)),
+            Column("is_enterprise_install", Boolean, default=False, nullable=False),
+            Column("token_type", String(32)),
+            Column(
+                "installed_at",
+                DateTime,
+                nullable=False,
+                default=sqlalchemy.sql.func.now(),
+            ),
+            Index(
+                f"{table_name}_idx",
+                "client_id",
+                "enterprise_id",
+                "team_id",
+                "user_id",
+                "installed_at",
+            ),
+        )
+
+    @classmethod
+    def build_bots_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return Table(
+            table_name,
+            metadata,
+            Column("id", Integer, primary_key=True, autoincrement=True),
+            Column("client_id", String(32), nullable=False),
+            Column("app_id", String(32), nullable=False),
+            Column("enterprise_id", String(32)),
+            Column("enterprise_name", String(200)),
+            Column("team_id", String(32)),
+            Column("team_name", String(200)),
+            Column("bot_token", String(200)),
+            Column("bot_id", String(32)),
+            Column("bot_user_id", String(32)),
+            Column("bot_scopes", String(1000)),
+            Column("bot_refresh_token", String(200)),  # added in v3.8.0
+            Column("bot_token_expires_at", DateTime),  # added in v3.8.0
+            Column("is_enterprise_install", Boolean, default=False, nullable=False),
+            Column(
+                "installed_at",
+                DateTime,
+                nullable=False,
+                default=sqlalchemy.sql.func.now(),
+            ),
+            Index(
+                f"{table_name}_idx",
+                "client_id",
+                "enterprise_id",
+                "team_id",
+                "installed_at",
+            ),
+        )
+
+    def __init__(
+        self,
+        client_id: str,
+        engine: Engine,
+        bots_table_name: str = default_bots_table_name,
+        installations_table_name: str = default_installations_table_name,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        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._logger = logger
+        self.engine = engine
+
+    def create_tables(self):
+        self.metadata.create_all(self.engine)
+
+    @property
+    def logger(self) -> Logger:
+        return self._logger
+
+    def save(self, installation: Installation):
+        with self.engine.begin() as conn:
+            i = installation.to_dict()
+            i["client_id"] = self.client_id
+
+            i_column = self.installations.c
+            installations_rows = conn.execute(
+                sqlalchemy.select(i_column.id)
+                .where(
+                    and_(
+                        i_column.client_id == self.client_id,
+                        i_column.enterprise_id == installation.enterprise_id,
+                        i_column.team_id == installation.team_id,
+                        i_column.installed_at == i.get("installed_at"),
+                    )
+                )
+                .limit(1)
+            )
+            installations_row_id: Optional[str] = None
+            for row in installations_rows.mappings():
+                installations_row_id = row["id"]
+            if installations_row_id is None:
+                conn.execute(self.installations.insert(), i)
+            else:
+                update_statement = self.installations.update().where(i_column.id == installations_row_id).values(**i)
+                conn.execute(update_statement, i)
+
+        # bots
+        self.save_bot(installation.to_bot())
+
+    def save_bot(self, bot: Bot):
+        with self.engine.begin() as conn:
+            # bots
+            b = bot.to_dict()
+            b["client_id"] = self.client_id
+
+            b_column = self.bots.c
+            bots_rows = conn.execute(
+                sqlalchemy.select(b_column.id)
+                .where(
+                    and_(
+                        b_column.client_id == self.client_id,
+                        b_column.enterprise_id == bot.enterprise_id,
+                        b_column.team_id == bot.team_id,
+                        b_column.installed_at == b.get("installed_at"),
+                    )
+                )
+                .limit(1)
+            )
+            bots_row_id: Optional[str] = None
+            for row in bots_rows.mappings():
+                bots_row_id = row["id"]
+            if bots_row_id is None:
+                conn.execute(self.bots.insert(), b)
+            else:
+                update_statement = self.bots.update().where(b_column.id == bots_row_id).values(**b)
+                conn.execute(update_statement, b)
+
+    def 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 = None
+
+        c = self.bots.c
+        query = (
+            self.bots.select()
+            .where(
+                and_(
+                    c.client_id == self.client_id,
+                    c.enterprise_id == enterprise_id,
+                    c.team_id == team_id,
+                    c.bot_token.is_not(None),  # the latest one that has a bot token
+                )
+            )
+            .order_by(desc(c.installed_at))
+            .limit(1)
+        )
+
+        with self.engine.connect() as conn:
+            result: object = conn.execute(query)
+            for row in result.mappings():  # type: ignore[attr-defined]
+                return self.build_bot_entity(row)
+            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]:
+        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
+        with self.engine.connect() as conn:
+            result: object = conn.execute(query)
+            for row in result.mappings():  # type: ignore[attr-defined]
+                installation = self.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 = self.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
+
+    def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        table = self.bots
+        c = table.c
+        with self.engine.begin() as conn:
+            deletion = table.delete().where(
+                and_(
+                    c.client_id == self.client_id,
+                    c.enterprise_id == enterprise_id,
+                    c.team_id == team_id,
+                )
+            )
+            conn.execute(deletion)
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        table = self.installations
+        c = table.c
+        with self.engine.begin() as conn:
+            if user_id is not None:
+                deletion = table.delete().where(
+                    and_(
+                        c.client_id == self.client_id,
+                        c.enterprise_id == enterprise_id,
+                        c.team_id == team_id,
+                        c.user_id == user_id,
+                    )
+                )
+                conn.execute(deletion)
+            else:
+                deletion = table.delete().where(
+                    and_(
+                        c.client_id == self.client_id,
+                        c.enterprise_id == enterprise_id,
+                        c.team_id == team_id,
+                    )
+                )
+                conn.execute(deletion)
+
+    @classmethod
+    def build_installation_entity(cls, row) -> Installation:
+        return Installation(
+            app_id=row["app_id"],
+            enterprise_id=row["enterprise_id"],
+            enterprise_name=row["enterprise_name"],
+            enterprise_url=row["enterprise_url"],
+            team_id=row["team_id"],
+            team_name=row["team_name"],
+            bot_token=row["bot_token"],
+            bot_id=row["bot_id"],
+            bot_user_id=row["bot_user_id"],
+            bot_scopes=row["bot_scopes"],
+            bot_refresh_token=row["bot_refresh_token"],
+            bot_token_expires_at=row["bot_token_expires_at"],
+            user_id=row["user_id"],
+            user_token=row["user_token"],
+            user_scopes=row["user_scopes"],
+            user_refresh_token=row["user_refresh_token"],
+            user_token_expires_at=row["user_token_expires_at"],
+            # Only the incoming webhook issued in the latest installation is set in this logic
+            incoming_webhook_url=row["incoming_webhook_url"],
+            incoming_webhook_channel=row["incoming_webhook_channel"],
+            incoming_webhook_channel_id=row["incoming_webhook_channel_id"],
+            incoming_webhook_configuration_url=row["incoming_webhook_configuration_url"],
+            is_enterprise_install=row["is_enterprise_install"],
+            token_type=row["token_type"],
+            installed_at=row["installed_at"],
+        )
+
+    @classmethod
+    def build_bot_entity(cls, row) -> Bot:
+        return Bot(
+            app_id=row["app_id"],
+            enterprise_id=row["enterprise_id"],
+            enterprise_name=row["enterprise_name"],
+            team_id=row["team_id"],
+            team_name=row["team_name"],
+            bot_token=row["bot_token"],
+            bot_id=row["bot_id"],
+            bot_user_id=row["bot_user_id"],
+            bot_scopes=row["bot_scopes"],
+            bot_refresh_token=row["bot_refresh_token"],
+            bot_token_expires_at=row["bot_token_expires_at"],
+            is_enterprise_install=row["is_enterprise_install"],
+            installed_at=row["installed_at"],
+        )
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Class variables

+
+
var client_id :Β str
+
+

The type of the None singleton.

+
+
var default_bots_table_name :Β str
+
+

The type of the None singleton.

+
+
var default_installations_table_name :Β str
+
+

The type of the None singleton.

+
+
var engine :Β sqlalchemy.engine.base.Engine
+
+

The type of the None singleton.

+
+
var installations :Β sqlalchemy.sql.schema.Table
+
+

The type of the None singleton.

+
+
var metadata :Β sqlalchemy.sql.schema.MetaData
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_bot_entity(row) ‑>Β Bot +
+
+
+
+
+def build_bots_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+def build_installation_entity(row) ‑>Β Installation +
+
+
+
+
+def build_installations_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    return self._logger
+
+
+
+
+

Methods

+
+
+def create_tables(self) +
+
+
+ +Expand source code + +
def create_tables(self):
+    self.metadata.create_all(self.engine)
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/installation_store/sqlite3/index.html b/docs/reference/oauth/installation_store/sqlite3/index.html new file mode 100644 index 000000000..8fc6c563e --- /dev/null +++ b/docs/reference/oauth/installation_store/sqlite3/index.html @@ -0,0 +1,907 @@ + + + + + + +slack_sdk.oauth.installation_store.sqlite3 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.installation_store.sqlite3

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SQLite3InstallationStore +(*,
database:Β str,
client_id:Β str,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.installation_store.sqlite3 (WARNING)>)
+
+
+
+ +Expand source code + +
class SQLite3InstallationStore(InstallationStore, AsyncInstallationStore):
+    def __init__(
+        self,
+        *,
+        database: str,
+        client_id: str,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.database = database
+        self.client_id = client_id
+        self.init_called = False
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    def init(self):
+        try:
+            with sqlite3.connect(database=self.database) as conn:
+                cur = conn.execute("select count(1) from slack_installations;")
+                row_num = cur.fetchone()[0]
+                self.logger.debug(f"{row_num} installations are stored in {self.database}")
+        except Exception:
+            self.create_tables()
+        self.init_called = True
+
+    def connect(self) -> Connection:
+        if not self.init_called:
+            self.init()
+        return sqlite3.connect(database=self.database)
+
+    def create_tables(self):
+        with sqlite3.connect(database=self.database) as conn:
+            conn.execute(
+                """
+            create table slack_installations (
+                id integer primary key autoincrement,
+                client_id text not null,
+                app_id text not null,
+                enterprise_id text not null default '',
+                enterprise_name text,
+                enterprise_url text,
+                team_id text not null default '',
+                team_name text,
+                bot_token text,
+                bot_id text,
+                bot_user_id text,
+                bot_scopes text,
+                bot_refresh_token text,  -- since v3.8
+                bot_token_expires_at datetime,  -- since v3.8
+                user_id text not null,
+                user_token text,
+                user_scopes text,
+                user_refresh_token text,  -- since v3.8
+                user_token_expires_at datetime,  -- since v3.8
+                incoming_webhook_url text,
+                incoming_webhook_channel text,
+                incoming_webhook_channel_id text,
+                incoming_webhook_configuration_url text,
+                is_enterprise_install boolean not null default 0,
+                token_type text,
+                installed_at datetime not null default current_timestamp
+            );
+            """
+            )
+            conn.execute(
+                """
+            create index slack_installations_idx on slack_installations (
+                client_id,
+                enterprise_id,
+                team_id,
+                user_id,
+                installed_at
+            );
+            """
+            )
+            conn.execute(
+                """
+            create table slack_bots (
+                id integer primary key autoincrement,
+                client_id text not null,
+                app_id text not null,
+                enterprise_id text not null default '',
+                enterprise_name text,
+                team_id text not null default '',
+                team_name text,
+                bot_token text not null,
+                bot_id text not null,
+                bot_user_id text not null,
+                bot_scopes text,
+                bot_refresh_token text,  -- since v3.8
+                bot_token_expires_at datetime,  -- since v3.8
+                is_enterprise_install boolean not null default 0,
+                installed_at datetime not null default current_timestamp
+            );
+            """
+            )
+            conn.execute(
+                """
+            create index slack_bots_idx on slack_bots (
+                client_id,
+                enterprise_id,
+                team_id,
+                installed_at
+            );
+            """
+            )
+            self.logger.debug(f"Tables have been created (database: {self.database})")
+            conn.commit()
+
+    async def async_save(self, installation: Installation):
+        return self.save(installation)
+
+    async def async_save_bot(self, bot: Bot):
+        return self.save_bot(bot)
+
+    def save(self, installation: Installation):
+        with self.connect() as conn:
+            conn.execute(
+                """
+                insert into slack_installations (
+                    client_id,
+                    app_id,
+                    enterprise_id,
+                    enterprise_name,
+                    enterprise_url,
+                    team_id,
+                    team_name,
+                    bot_token,
+                    bot_id,
+                    bot_user_id,
+                    bot_scopes,
+                    bot_refresh_token,  -- since v3.8
+                    bot_token_expires_at,  -- since v3.8
+                    user_id,
+                    user_token,
+                    user_scopes,
+                    user_refresh_token,  -- since v3.8
+                    user_token_expires_at,  -- since v3.8
+                    incoming_webhook_url,
+                    incoming_webhook_channel,
+                    incoming_webhook_channel_id,
+                    incoming_webhook_configuration_url,
+                    is_enterprise_install,
+                    token_type
+                )
+                values
+                (
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?
+                );
+                """,
+                [
+                    self.client_id,
+                    installation.app_id,
+                    installation.enterprise_id or "",
+                    installation.enterprise_name,
+                    installation.enterprise_url,
+                    installation.team_id or "",
+                    installation.team_name,
+                    installation.bot_token,
+                    installation.bot_id,
+                    installation.bot_user_id,
+                    ",".join(installation.bot_scopes),  # type: ignore[arg-type]
+                    installation.bot_refresh_token,
+                    installation.bot_token_expires_at,
+                    installation.user_id,
+                    installation.user_token,
+                    ",".join(installation.user_scopes) if installation.user_scopes else None,
+                    installation.user_refresh_token,
+                    installation.user_token_expires_at,
+                    installation.incoming_webhook_url,
+                    installation.incoming_webhook_channel,
+                    installation.incoming_webhook_channel_id,
+                    installation.incoming_webhook_configuration_url,
+                    1 if installation.is_enterprise_install else 0,
+                    installation.token_type,
+                ],
+            )
+            self.logger.debug(
+                f"New rows in slack_bots and slack_installations have been created (database: {self.database})"
+            )
+            conn.commit()
+
+        self.save_bot(installation.to_bot())
+
+    def save_bot(self, bot: Bot):
+        if bot.bot_token is None:
+            self.logger.debug("Skipped saving a new row because of the absense of bot token in it")
+            return
+
+        with self.connect() as conn:
+            conn.execute(
+                """
+                insert into slack_bots (
+                    client_id,
+                    app_id,
+                    enterprise_id,
+                    enterprise_name,
+                    team_id,
+                    team_name,
+                    bot_token,
+                    bot_id,
+                    bot_user_id,
+                    bot_scopes,
+                    bot_refresh_token,  -- since v3.8
+                    bot_token_expires_at,  -- since v3.8
+                    is_enterprise_install
+                )
+                values
+                (
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?,
+                    ?
+                );
+                """,
+                [
+                    self.client_id,
+                    bot.app_id,
+                    bot.enterprise_id or "",
+                    bot.enterprise_name,
+                    bot.team_id or "",
+                    bot.team_name,
+                    bot.bot_token,
+                    bot.bot_id,
+                    bot.bot_user_id,
+                    ",".join(bot.bot_scopes),
+                    bot.bot_refresh_token,
+                    bot.bot_token_expires_at,
+                    bot.is_enterprise_install,
+                ],
+            )
+            conn.commit()
+
+    async def async_find_bot(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = False,
+    ) -> Optional[Bot]:
+        return self.find_bot(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    def 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 = ""
+
+        try:
+            with self.connect() as conn:
+                cur = conn.execute(
+                    """
+                    select
+                        app_id,
+                        enterprise_id,
+                        enterprise_name,
+                        team_id,
+                        team_name,
+                        bot_token,
+                        bot_id,
+                        bot_user_id,
+                        bot_scopes,
+                        bot_refresh_token,  -- since v3.8
+                        bot_token_expires_at,  -- since v3.8
+                        is_enterprise_install,
+                        installed_at
+                    from
+                        slack_bots
+                    where
+                        client_id = ?
+                        and
+                        enterprise_id = ?
+                        and
+                        team_id = ?
+                    order by installed_at desc
+                    limit 1
+                    """,
+                    [self.client_id, enterprise_id or "", team_id or ""],
+                )
+                row = cur.fetchone()
+                result = "found" if row and len(row) > 0 else "not found"
+                self.logger.debug(f"find_bot's query result: {result} (database: {self.database})")
+                if row and len(row) > 0:
+                    bot = Bot(
+                        app_id=row[0],
+                        enterprise_id=row[1],
+                        enterprise_name=row[2],
+                        team_id=row[3],
+                        team_name=row[4],
+                        bot_token=row[5],
+                        bot_id=row[6],
+                        bot_user_id=row[7],
+                        bot_scopes=row[8],
+                        bot_refresh_token=row[9],
+                        bot_token_expires_at=row[10],
+                        is_enterprise_install=row[11],
+                        installed_at=row[12],
+                    )
+                    return bot
+                return None
+
+        except Exception as e:
+            message = f"Failed to find bot installation data for enterprise: {enterprise_id}, team: {team_id}: {e}"
+            if self.logger.level <= logging.DEBUG:
+                self.logger.exception(message)
+            else:
+                self.logger.warning(message)
+            return None
+
+    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]:
+        return self.find_installation(
+            enterprise_id=enterprise_id,
+            team_id=team_id,
+            user_id=user_id,
+            is_enterprise_install=is_enterprise_install,
+        )
+
+    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 = ""
+
+        try:
+            with self.connect() as conn:
+                row = None
+                columns = """
+                    app_id,
+                    enterprise_id,
+                    enterprise_name,
+                    enterprise_url,
+                    team_id,
+                    team_name,
+                    bot_token,
+                    bot_id,
+                    bot_user_id,
+                    bot_scopes,
+                    bot_refresh_token,  -- since v3.8
+                    bot_token_expires_at,  -- since v3.8
+                    user_id,
+                    user_token,
+                    user_scopes,
+                    user_refresh_token,  -- since v3.8
+                    user_token_expires_at,  -- since v3.8
+                    incoming_webhook_url,
+                    incoming_webhook_channel,
+                    incoming_webhook_channel_id,
+                    incoming_webhook_configuration_url,
+                    is_enterprise_install,
+                    token_type,
+                    installed_at
+                """
+                if user_id is None:
+                    cur = conn.execute(
+                        f"""
+                        select
+                            {columns}
+                        from
+                            slack_installations
+                        where
+                            client_id = ?
+                            and
+                            enterprise_id = ?
+                            and
+                            team_id = ?
+                        order by installed_at desc
+                        limit 1
+                        """,
+                        [self.client_id, enterprise_id or "", team_id],
+                    )
+                    row = cur.fetchone()
+                else:
+                    cur = conn.execute(
+                        f"""
+                        select
+                            {columns}
+                        from
+                            slack_installations
+                        where
+                            client_id = ?
+                            and
+                            enterprise_id = ?
+                            and
+                            team_id = ?
+                            and
+                            user_id = ?
+                        order by installed_at desc
+                        limit 1
+                        """,
+                        [self.client_id, enterprise_id or "", team_id, user_id],
+                    )
+                    row = cur.fetchone()
+
+                if row is None:
+                    return None
+
+                result = "found" if row and len(row) > 0 else "not found"
+                self.logger.debug(f"find_installation's query result: {result} (database: {self.database})")
+                if row and len(row) > 0:
+                    installation = Installation(
+                        app_id=row[0],
+                        enterprise_id=row[1],
+                        enterprise_name=row[2],
+                        enterprise_url=row[3],
+                        team_id=row[4],
+                        team_name=row[5],
+                        bot_token=row[6],
+                        bot_id=row[7],
+                        bot_user_id=row[8],
+                        bot_scopes=row[9],
+                        bot_refresh_token=row[10],
+                        bot_token_expires_at=row[11],
+                        user_id=row[12],
+                        user_token=row[13],
+                        user_scopes=row[14],
+                        user_refresh_token=row[15],
+                        user_token_expires_at=row[16],
+                        incoming_webhook_url=row[17],
+                        incoming_webhook_channel=row[18],
+                        incoming_webhook_channel_id=row[19],
+                        incoming_webhook_configuration_url=row[20],
+                        is_enterprise_install=row[21],
+                        token_type=row[22],
+                        installed_at=row[23],
+                    )
+
+                    if user_id is not None:
+                        # Retrieve the latest bot token, just in case
+                        # See also: https://github.com/slackapi/bolt-python/issues/664
+                        cur = conn.execute(
+                            """
+                            select
+                                bot_token,
+                                bot_id,
+                                bot_user_id,
+                                bot_scopes,
+                                bot_refresh_token,
+                                bot_token_expires_at
+                            from
+                                slack_installations
+                            where
+                                client_id = ?
+                                and
+                                enterprise_id = ?
+                                and
+                                team_id = ?
+                                and
+                                bot_token is not null
+                            order by installed_at desc
+                            limit 1
+                            """,
+                            [self.client_id, enterprise_id or "", team_id],
+                        )
+                        row = cur.fetchone()
+                        installation.bot_token = row[0]
+                        installation.bot_id = row[1]
+                        installation.bot_user_id = row[2]
+                        installation.bot_scopes = row[3]
+                        installation.bot_refresh_token = row[4]
+                        installation.bot_token_expires_at = row[5]
+
+                    return installation
+                return None
+
+        except Exception as e:
+            message = f"Failed to find an installation data for enterprise: {enterprise_id}, team: {team_id}: {e}"
+            if self.logger.level <= logging.DEBUG:
+                self.logger.exception(message)
+            else:
+                self.logger.warning(message)
+            return None
+
+    def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None:
+        try:
+            with self.connect() as conn:
+                conn.execute(
+                    """
+                    delete
+                    from
+                        slack_bots
+                    where
+                        client_id = ?
+                        and
+                        enterprise_id = ?
+                        and
+                        team_id = ?
+                    """,
+                    [self.client_id, enterprise_id or "", team_id or ""],
+                )
+                conn.commit()
+        except Exception as e:
+            message = f"Failed to delete bot installation data for enterprise: {enterprise_id}, team: {team_id}: {e}"
+            if self.logger.level <= logging.DEBUG:
+                self.logger.exception(message)
+            else:
+                self.logger.warning(message)
+
+    def delete_installation(
+        self,
+        *,
+        enterprise_id: Optional[str],
+        team_id: Optional[str],
+        user_id: Optional[str] = None,
+    ) -> None:
+        try:
+            with self.connect() as conn:
+                if user_id is None:
+                    conn.execute(
+                        """
+                        delete
+                        from
+                            slack_installations
+                        where
+                            client_id = ?
+                            and
+                            enterprise_id = ?
+                            and
+                            team_id = ?
+                        """,
+                        [self.client_id, enterprise_id or "", team_id],
+                    )
+                else:
+                    conn.execute(
+                        """
+                        delete
+                        from
+                            slack_installations
+                        where
+                            client_id = ?
+                            and
+                            enterprise_id = ?
+                            and
+                            team_id = ?
+                            and
+                            user_id = ?
+                        """,
+                        [self.client_id, enterprise_id or "", team_id, user_id],
+                    )
+                conn.commit()
+        except Exception as e:
+            message = f"Failed to delete installation data for enterprise: {enterprise_id}, team: {team_id}: {e}"
+            if self.logger.level <= logging.DEBUG:
+                self.logger.exception(message)
+            else:
+                self.logger.warning(message)
+
+

The installation store interface.

+

The minimum required methods are:

+
    +
  • save(installation)
  • +
  • find_installation(enterprise_id, team_id, user_id, is_enterprise_install)
  • +
+

If you would like to properly handle app uninstallations and token revocations, +the following methods should be implemented.

+
    +
  • delete_installation(enterprise_id, team_id, user_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

If your app needs only bot scope installations, the simpler way to implement would be:

+
    +
  • save(installation)
  • +
  • find_bot(enterprise_id, team_id, is_enterprise_install)
  • +
  • delete_bot(enterprise_id, team_id)
  • +
  • delete_all(enterprise_id, team_id)
  • +
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+def connect(self) ‑>Β sqlite3.Connection +
+
+
+ +Expand source code + +
def connect(self) -> Connection:
+    if not self.init_called:
+        self.init()
+    return sqlite3.connect(database=self.database)
+
+
+
+
+def create_tables(self) +
+
+
+ +Expand source code + +
def create_tables(self):
+    with sqlite3.connect(database=self.database) as conn:
+        conn.execute(
+            """
+        create table slack_installations (
+            id integer primary key autoincrement,
+            client_id text not null,
+            app_id text not null,
+            enterprise_id text not null default '',
+            enterprise_name text,
+            enterprise_url text,
+            team_id text not null default '',
+            team_name text,
+            bot_token text,
+            bot_id text,
+            bot_user_id text,
+            bot_scopes text,
+            bot_refresh_token text,  -- since v3.8
+            bot_token_expires_at datetime,  -- since v3.8
+            user_id text not null,
+            user_token text,
+            user_scopes text,
+            user_refresh_token text,  -- since v3.8
+            user_token_expires_at datetime,  -- since v3.8
+            incoming_webhook_url text,
+            incoming_webhook_channel text,
+            incoming_webhook_channel_id text,
+            incoming_webhook_configuration_url text,
+            is_enterprise_install boolean not null default 0,
+            token_type text,
+            installed_at datetime not null default current_timestamp
+        );
+        """
+        )
+        conn.execute(
+            """
+        create index slack_installations_idx on slack_installations (
+            client_id,
+            enterprise_id,
+            team_id,
+            user_id,
+            installed_at
+        );
+        """
+        )
+        conn.execute(
+            """
+        create table slack_bots (
+            id integer primary key autoincrement,
+            client_id text not null,
+            app_id text not null,
+            enterprise_id text not null default '',
+            enterprise_name text,
+            team_id text not null default '',
+            team_name text,
+            bot_token text not null,
+            bot_id text not null,
+            bot_user_id text not null,
+            bot_scopes text,
+            bot_refresh_token text,  -- since v3.8
+            bot_token_expires_at datetime,  -- since v3.8
+            is_enterprise_install boolean not null default 0,
+            installed_at datetime not null default current_timestamp
+        );
+        """
+        )
+        conn.execute(
+            """
+        create index slack_bots_idx on slack_bots (
+            client_id,
+            enterprise_id,
+            team_id,
+            installed_at
+        );
+        """
+        )
+        self.logger.debug(f"Tables have been created (database: {self.database})")
+        conn.commit()
+
+
+
+
+def init(self) +
+
+
+ +Expand source code + +
def init(self):
+    try:
+        with sqlite3.connect(database=self.database) as conn:
+            cur = conn.execute("select count(1) from slack_installations;")
+            row_num = cur.fetchone()[0]
+            self.logger.debug(f"{row_num} installations are stored in {self.database}")
+    except Exception:
+        self.create_tables()
+    self.init_called = True
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/redirect_uri_page_renderer/index.html b/docs/reference/oauth/redirect_uri_page_renderer/index.html new file mode 100644 index 000000000..627904d44 --- /dev/null +++ b/docs/reference/oauth/redirect_uri_page_renderer/index.html @@ -0,0 +1,238 @@ + + + + + + +slack_sdk.oauth.redirect_uri_page_renderer API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.redirect_uri_page_renderer

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RedirectUriPageRenderer +(*,
install_path:Β str,
redirect_uri_path:Β str,
success_url:Β strΒ |Β NoneΒ =Β None,
failure_url:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class RedirectUriPageRenderer:
+    def __init__(
+        self,
+        *,
+        install_path: str,
+        redirect_uri_path: str,
+        success_url: Optional[str] = None,
+        failure_url: Optional[str] = None,
+    ):
+        self.install_path = install_path
+        self.redirect_uri_path = redirect_uri_path
+        self.success_url = success_url
+        self.failure_url = failure_url
+
+    def render_success_page(
+        self,
+        app_id: str,
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = None,
+        enterprise_url: Optional[str] = None,
+    ) -> str:
+        url = self.success_url
+        if url is None:
+            if is_enterprise_install is True and enterprise_url is not None and app_id is not None:
+                url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add"
+            elif team_id is None or app_id is None:
+                url = "slack://open"
+            else:
+                url = f"slack://app?team={team_id}&id={app_id}"
+        browser_url = f"https://app.slack.com/client/{team_id}"
+
+        return f"""
+<html>
+<head>
+<meta http-equiv="refresh" content="0; URL={html.escape(url)}">
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Thank you!</h2>
+<p>Redirecting to the Slack App... click <a href="{html.escape(url)}">here</a>. If you use the browser version of Slack, click <a href="{html.escape(browser_url)}" target="_blank">this link</a> instead.</p>
+</body>
+</html>
+"""  # noqa: E501
+
+    def render_failure_page(self, reason: str) -> str:
+        return f"""
+<html>
+<head>
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Oops, Something Went Wrong!</h2>
+<p>Please try again from <a href="{html.escape(self.install_path)}">here</a> or contact the app owner (reason: {html.escape(reason)})</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+

Methods

+
+
+def render_failure_page(self, reason:Β str) ‑>Β str +
+
+
+ +Expand source code + +
    def render_failure_page(self, reason: str) -> str:
+        return f"""
+<html>
+<head>
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Oops, Something Went Wrong!</h2>
+<p>Please try again from <a href="{html.escape(self.install_path)}">here</a> or contact the app owner (reason: {html.escape(reason)})</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+
+
+def render_success_page(self,
app_id:Β str,
team_id:Β strΒ |Β None,
is_enterprise_install:Β boolΒ |Β NoneΒ =Β None,
enterprise_url:Β strΒ |Β NoneΒ =Β None) ‑>Β str
+
+
+
+ +Expand source code + +
    def render_success_page(
+        self,
+        app_id: str,
+        team_id: Optional[str],
+        is_enterprise_install: Optional[bool] = None,
+        enterprise_url: Optional[str] = None,
+    ) -> str:
+        url = self.success_url
+        if url is None:
+            if is_enterprise_install is True and enterprise_url is not None and app_id is not None:
+                url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add"
+            elif team_id is None or app_id is None:
+                url = "slack://open"
+            else:
+                url = f"slack://app?team={team_id}&id={app_id}"
+        browser_url = f"https://app.slack.com/client/{team_id}"
+
+        return f"""
+<html>
+<head>
+<meta http-equiv="refresh" content="0; URL={html.escape(url)}">
+<style>
+body {{
+  padding: 10px 15px;
+  font-family: verdana;
+  text-align: center;
+}}
+</style>
+</head>
+<body>
+<h2>Thank you!</h2>
+<p>Redirecting to the Slack App... click <a href="{html.escape(url)}">here</a>. If you use the browser version of Slack, click <a href="{html.escape(browser_url)}" target="_blank">this link</a> instead.</p>
+</body>
+</html>
+"""  # noqa: E501
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/amazon_s3/index.html b/docs/reference/oauth/state_store/amazon_s3/index.html new file mode 100644 index 000000000..40c6d5c4e --- /dev/null +++ b/docs/reference/oauth/state_store/amazon_s3/index.html @@ -0,0 +1,257 @@ + + + + + + +slack_sdk.oauth.state_store.amazon_s3 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.amazon_s3

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AmazonS3OAuthStateStore +(*,
s3_client:Β botocore.client.BaseClient,
bucket_name:Β str,
expiration_seconds:Β int,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.amazon_s3 (WARNING)>)
+
+
+
+ +Expand source code + +
class AmazonS3OAuthStateStore(OAuthStateStore, AsyncOAuthStateStore):
+    def __init__(
+        self,
+        *,
+        s3_client: BaseClient,
+        bucket_name: str,
+        expiration_seconds: int,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.s3_client = s3_client
+        self.bucket_name = bucket_name
+        self.expiration_seconds = expiration_seconds
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        return self.issue(*args, **kwargs)
+
+    async def async_consume(self, state: str) -> bool:
+        return self.consume(state)
+
+    def issue(self, *args, **kwargs) -> str:
+        state = str(uuid4())
+        response = self.s3_client.put_object(
+            Bucket=self.bucket_name,
+            Body=str(time.time()),
+            Key=state,
+        )
+        self.logger.debug(f"S3 put_object response: {response}")
+        return state
+
+    def consume(self, state: str) -> bool:
+        try:
+            fetch_response = self.s3_client.get_object(
+                Bucket=self.bucket_name,
+                Key=state,
+            )
+            self.logger.debug(f"S3 get_object response: {fetch_response}")
+            body = fetch_response["Body"].read().decode("utf-8")
+            created = float(body)
+            expiration = created + self.expiration_seconds
+            still_valid: bool = time.time() < expiration
+
+            deletion_response = self.s3_client.delete_object(
+                Bucket=self.bucket_name,
+                Key=state,
+            )
+            self.logger.debug(f"S3 delete_object response: {deletion_response}")
+            return still_valid
+        except Exception as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    return self.consume(state)
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    return self.issue(*args, **kwargs)
+
+
+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    try:
+        fetch_response = self.s3_client.get_object(
+            Bucket=self.bucket_name,
+            Key=state,
+        )
+        self.logger.debug(f"S3 get_object response: {fetch_response}")
+        body = fetch_response["Body"].read().decode("utf-8")
+        created = float(body)
+        expiration = created + self.expiration_seconds
+        still_valid: bool = time.time() < expiration
+
+        deletion_response = self.s3_client.delete_object(
+            Bucket=self.bucket_name,
+            Key=state,
+        )
+        self.logger.debug(f"S3 delete_object response: {deletion_response}")
+        return still_valid
+    except Exception as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    state = str(uuid4())
+    response = self.s3_client.put_object(
+        Bucket=self.bucket_name,
+        Body=str(time.time()),
+        Key=state,
+    )
+    self.logger.debug(f"S3 put_object response: {response}")
+    return state
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/async_state_store.html b/docs/reference/oauth/state_store/async_state_store.html new file mode 100644 index 000000000..3f1fa969b --- /dev/null +++ b/docs/reference/oauth/state_store/async_state_store.html @@ -0,0 +1,153 @@ + + + + + + +slack_sdk.oauth.state_store.async_state_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.async_state_store

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncOAuthStateStore +
+
+
+ +Expand source code + +
class AsyncOAuthStateStore:
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        raise NotImplementedError()
+
+    async def async_consume(self, state: str) -> bool:
+        raise NotImplementedError()
+
+
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    raise NotImplementedError()
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    raise NotImplementedError()
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/file/index.html b/docs/reference/oauth/state_store/file/index.html new file mode 100644 index 000000000..62e7be40e --- /dev/null +++ b/docs/reference/oauth/state_store/file/index.html @@ -0,0 +1,250 @@ + + + + + + +slack_sdk.oauth.state_store.file API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.file

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class FileOAuthStateStore +(*,
expiration_seconds:Β int,
base_dir:Β strΒ =Β '$HOME/.bolt-app-oauth-state',
client_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.file (WARNING)>)
+
+
+
+ +Expand source code + +
class FileOAuthStateStore(OAuthStateStore, AsyncOAuthStateStore):
+    def __init__(
+        self,
+        *,
+        expiration_seconds: int,
+        base_dir: str = str(Path.home()) + "/.bolt-app-oauth-state",
+        client_id: Optional[str] = None,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.expiration_seconds = expiration_seconds
+
+        self.base_dir = base_dir
+        self.client_id = client_id
+        if self.client_id is not None:
+            self.base_dir = f"{self.base_dir}/{self.client_id}"
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        return self.issue(*args, **kwargs)
+
+    async def async_consume(self, state: str) -> bool:
+        return self.consume(state)
+
+    def issue(self, *args, **kwargs) -> str:
+        state = str(uuid4())
+        self._mkdir(self.base_dir)
+        filepath = f"{self.base_dir}/{state}"
+        with open(filepath, "w") as f:
+            content = str(time.time())
+            f.write(content)
+        return state
+
+    def consume(self, state: str) -> bool:
+        filepath = f"{self.base_dir}/{state}"
+        try:
+            with open(filepath) as f:
+                created = float(f.read())
+                expiration = created + self.expiration_seconds
+                still_valid: bool = time.time() < expiration
+
+            os.remove(filepath)  # consume the file by deleting it
+            return still_valid
+
+        except FileNotFoundError as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+    @staticmethod
+    def _mkdir(path: Union[str, Path]):
+        if isinstance(path, str):
+            path = Path(path)
+        path.mkdir(parents=True, exist_ok=True)
+
+
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    return self.consume(state)
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    return self.issue(*args, **kwargs)
+
+
+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    filepath = f"{self.base_dir}/{state}"
+    try:
+        with open(filepath) as f:
+            created = float(f.read())
+            expiration = created + self.expiration_seconds
+            still_valid: bool = time.time() < expiration
+
+        os.remove(filepath)  # consume the file by deleting it
+        return still_valid
+
+    except FileNotFoundError as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    state = str(uuid4())
+    self._mkdir(self.base_dir)
+    filepath = f"{self.base_dir}/{state}"
+    with open(filepath, "w") as f:
+        content = str(time.time())
+        f.write(content)
+    return state
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/index.html b/docs/reference/oauth/state_store/index.html new file mode 100644 index 000000000..38a016b32 --- /dev/null +++ b/docs/reference/oauth/state_store/index.html @@ -0,0 +1,369 @@ + + + + + + +slack_sdk.oauth.state_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store

+
+
+

OAuth state parameter data store

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/oauth for details.

+
+
+

Sub-modules

+
+
slack_sdk.oauth.state_store.amazon_s3
+
+
+
+
slack_sdk.oauth.state_store.async_state_store
+
+
+
+
slack_sdk.oauth.state_store.file
+
+
+
+
slack_sdk.oauth.state_store.sqlalchemy
+
+
+
+
slack_sdk.oauth.state_store.sqlite3
+
+
+
+
slack_sdk.oauth.state_store.state_store
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class FileOAuthStateStore +(*,
expiration_seconds:Β int,
base_dir:Β strΒ =Β '$HOME/.bolt-app-oauth-state',
client_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.file (WARNING)>)
+
+
+
+ +Expand source code + +
class FileOAuthStateStore(OAuthStateStore, AsyncOAuthStateStore):
+    def __init__(
+        self,
+        *,
+        expiration_seconds: int,
+        base_dir: str = str(Path.home()) + "/.bolt-app-oauth-state",
+        client_id: Optional[str] = None,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.expiration_seconds = expiration_seconds
+
+        self.base_dir = base_dir
+        self.client_id = client_id
+        if self.client_id is not None:
+            self.base_dir = f"{self.base_dir}/{self.client_id}"
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        return self.issue(*args, **kwargs)
+
+    async def async_consume(self, state: str) -> bool:
+        return self.consume(state)
+
+    def issue(self, *args, **kwargs) -> str:
+        state = str(uuid4())
+        self._mkdir(self.base_dir)
+        filepath = f"{self.base_dir}/{state}"
+        with open(filepath, "w") as f:
+            content = str(time.time())
+            f.write(content)
+        return state
+
+    def consume(self, state: str) -> bool:
+        filepath = f"{self.base_dir}/{state}"
+        try:
+            with open(filepath) as f:
+                created = float(f.read())
+                expiration = created + self.expiration_seconds
+                still_valid: bool = time.time() < expiration
+
+            os.remove(filepath)  # consume the file by deleting it
+            return still_valid
+
+        except FileNotFoundError as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+    @staticmethod
+    def _mkdir(path: Union[str, Path]):
+        if isinstance(path, str):
+            path = Path(path)
+        path.mkdir(parents=True, exist_ok=True)
+
+
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    return self.consume(state)
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    return self.issue(*args, **kwargs)
+
+
+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    filepath = f"{self.base_dir}/{state}"
+    try:
+        with open(filepath) as f:
+            created = float(f.read())
+            expiration = created + self.expiration_seconds
+            still_valid: bool = time.time() < expiration
+
+        os.remove(filepath)  # consume the file by deleting it
+        return still_valid
+
+    except FileNotFoundError as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    state = str(uuid4())
+    self._mkdir(self.base_dir)
+    filepath = f"{self.base_dir}/{state}"
+    with open(filepath, "w") as f:
+        content = str(time.time())
+        f.write(content)
+    return state
+
+
+
+
+
+
+class OAuthStateStore +
+
+
+ +Expand source code + +
class OAuthStateStore:
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def issue(self, *args, **kwargs) -> str:
+        raise NotImplementedError()
+
+    def consume(self, state: str) -> bool:
+        raise NotImplementedError()
+
+
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    raise NotImplementedError()
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    raise NotImplementedError()
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/sqlalchemy/index.html b/docs/reference/oauth/state_store/sqlalchemy/index.html new file mode 100644 index 000000000..29fe36884 --- /dev/null +++ b/docs/reference/oauth/state_store/sqlalchemy/index.html @@ -0,0 +1,491 @@ + + + + + + +slack_sdk.oauth.state_store.sqlalchemy API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.sqlalchemy

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSQLAlchemyOAuthStateStore +(expiration_seconds:Β int,
engine:Β sqlalchemy.ext.asyncio.engine.AsyncEngine,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.sqlalchemy (WARNING)>,
table_name:Β strΒ =Β 'slack_oauth_states')
+
+
+
+ +Expand source code + +
class AsyncSQLAlchemyOAuthStateStore(AsyncOAuthStateStore):
+    default_table_name: str = "slack_oauth_states"
+
+    expiration_seconds: int
+    engine: AsyncEngine
+    metadata: MetaData
+    oauth_states: Table
+
+    @classmethod
+    def build_oauth_states_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return sqlalchemy.Table(
+            table_name,
+            metadata,
+            metadata,
+            Column("id", Integer, primary_key=True, autoincrement=True),
+            Column("state", String(200), nullable=False),
+            Column("expire_at", DateTime, nullable=False),
+        )
+
+    def __init__(
+        self,
+        expiration_seconds: int,
+        engine: AsyncEngine,
+        logger: Logger = logging.getLogger(__name__),
+        table_name: str = default_table_name,
+    ):
+        self.expiration_seconds = expiration_seconds
+        self._logger = logger
+        self.engine = engine
+        self.metadata = MetaData()
+        self.oauth_states = self.build_oauth_states_table(self.metadata, table_name)
+
+    async def create_tables(self):
+        async with self.engine.begin() as conn:
+            await conn.run_sync(self.metadata.create_all)
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        state: str = str(uuid4())
+        now = datetime.utcfromtimestamp(time.time() + self.expiration_seconds)
+        async with self.engine.begin() as conn:
+            await conn.execute(
+                self.oauth_states.insert(),
+                {"state": state, "expire_at": now},
+            )
+        return state
+
+    async def async_consume(self, state: str) -> bool:
+        try:
+            async with self.engine.begin() as conn:
+                c = self.oauth_states.c
+                query = self.oauth_states.select().where(and_(c.state == state, c.expire_at > datetime.utcnow()))
+                result = await conn.execute(query)
+                for row in result.mappings():
+                    self.logger.debug(f"consume's query result: {row}")
+                    await conn.execute(self.oauth_states.delete().where(c.id == row["id"]))
+                    return True
+            return False
+        except Exception as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+
+

Ancestors

+ +

Class variables

+
+
var default_table_name :Β str
+
+

The type of the None singleton.

+
+
var engine :Β sqlalchemy.ext.asyncio.engine.AsyncEngine
+
+

The type of the None singleton.

+
+
var expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
var metadata :Β sqlalchemy.sql.schema.MetaData
+
+

The type of the None singleton.

+
+
var oauth_states :Β sqlalchemy.sql.schema.Table
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_oauth_states_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    try:
+        async with self.engine.begin() as conn:
+            c = self.oauth_states.c
+            query = self.oauth_states.select().where(and_(c.state == state, c.expire_at > datetime.utcnow()))
+            result = await conn.execute(query)
+            for row in result.mappings():
+                self.logger.debug(f"consume's query result: {row}")
+                await conn.execute(self.oauth_states.delete().where(c.id == row["id"]))
+                return True
+        return False
+    except Exception as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    state: str = str(uuid4())
+    now = datetime.utcfromtimestamp(time.time() + self.expiration_seconds)
+    async with self.engine.begin() as conn:
+        await conn.execute(
+            self.oauth_states.insert(),
+            {"state": state, "expire_at": now},
+        )
+    return state
+
+
+
+
+async def create_tables(self) +
+
+
+ +Expand source code + +
async def create_tables(self):
+    async with self.engine.begin() as conn:
+        await conn.run_sync(self.metadata.create_all)
+
+
+
+
+
+
+class SQLAlchemyOAuthStateStore +(expiration_seconds:Β int,
engine:Β sqlalchemy.engine.base.Engine,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.sqlalchemy (WARNING)>,
table_name:Β strΒ =Β 'slack_oauth_states')
+
+
+
+ +Expand source code + +
class SQLAlchemyOAuthStateStore(OAuthStateStore):
+    default_table_name: str = "slack_oauth_states"
+
+    expiration_seconds: int
+    engine: Engine
+    metadata: MetaData
+    oauth_states: Table
+
+    @classmethod
+    def build_oauth_states_table(cls, metadata: MetaData, table_name: str) -> Table:
+        return sqlalchemy.Table(
+            table_name,
+            metadata,
+            metadata,
+            Column("id", Integer, primary_key=True, autoincrement=True),
+            Column("state", String(200), nullable=False),
+            Column("expire_at", DateTime, nullable=False),
+        )
+
+    def __init__(
+        self,
+        expiration_seconds: int,
+        engine: Engine,
+        logger: Logger = logging.getLogger(__name__),
+        table_name: str = default_table_name,
+    ):
+        self.expiration_seconds = expiration_seconds
+        self._logger = logger
+        self.engine = engine
+        self.metadata = MetaData()
+        self.oauth_states = self.build_oauth_states_table(self.metadata, table_name)
+
+    def create_tables(self):
+        self.metadata.create_all(self.engine)
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    def issue(self, *args, **kwargs) -> str:
+        state: str = str(uuid4())
+        now = datetime.utcfromtimestamp(time.time() + self.expiration_seconds)
+        with self.engine.begin() as conn:
+            conn.execute(
+                self.oauth_states.insert(),
+                {"state": state, "expire_at": now},
+            )
+        return state
+
+    def consume(self, state: str) -> bool:
+        try:
+            with self.engine.begin() as conn:
+                c = self.oauth_states.c
+                query = self.oauth_states.select().where(and_(c.state == state, c.expire_at > datetime.utcnow()))
+                result = conn.execute(query)
+                for row in result.mappings():
+                    self.logger.debug(f"consume's query result: {row}")
+                    conn.execute(self.oauth_states.delete().where(c.id == row["id"]))
+                    return True
+            return False
+        except Exception as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+
+

Ancestors

+ +

Class variables

+
+
var default_table_name :Β str
+
+

The type of the None singleton.

+
+
var engine :Β sqlalchemy.engine.base.Engine
+
+

The type of the None singleton.

+
+
var expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
var metadata :Β sqlalchemy.sql.schema.MetaData
+
+

The type of the None singleton.

+
+
var oauth_states :Β sqlalchemy.sql.schema.Table
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_oauth_states_table(metadata:Β sqlalchemy.sql.schema.MetaData, table_name:Β str) ‑>Β sqlalchemy.sql.schema.Table +
+
+
+
+
+

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    try:
+        with self.engine.begin() as conn:
+            c = self.oauth_states.c
+            query = self.oauth_states.select().where(and_(c.state == state, c.expire_at > datetime.utcnow()))
+            result = conn.execute(query)
+            for row in result.mappings():
+                self.logger.debug(f"consume's query result: {row}")
+                conn.execute(self.oauth_states.delete().where(c.id == row["id"]))
+                return True
+        return False
+    except Exception as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+def create_tables(self) +
+
+
+ +Expand source code + +
def create_tables(self):
+    self.metadata.create_all(self.engine)
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    state: str = str(uuid4())
+    now = datetime.utcfromtimestamp(time.time() + self.expiration_seconds)
+    with self.engine.begin() as conn:
+        conn.execute(
+            self.oauth_states.insert(),
+            {"state": state, "expire_at": now},
+        )
+    return state
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/sqlite3/index.html b/docs/reference/oauth/state_store/sqlite3/index.html new file mode 100644 index 000000000..cd0b75b8b --- /dev/null +++ b/docs/reference/oauth/state_store/sqlite3/index.html @@ -0,0 +1,345 @@ + + + + + + +slack_sdk.oauth.state_store.sqlite3 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.sqlite3

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SQLite3OAuthStateStore +(*,
database:Β str,
expiration_seconds:Β int,
logger:Β logging.LoggerΒ =Β <Logger slack_sdk.oauth.state_store.sqlite3 (WARNING)>)
+
+
+
+ +Expand source code + +
class SQLite3OAuthStateStore(OAuthStateStore, AsyncOAuthStateStore):
+    def __init__(
+        self,
+        *,
+        database: str,
+        expiration_seconds: int,
+        logger: Logger = logging.getLogger(__name__),
+    ):
+        self.database = database
+        self.expiration_seconds = expiration_seconds
+        self.init_called = False
+        self._logger = logger
+
+    @property
+    def logger(self) -> Logger:
+        if self._logger is None:
+            self._logger = logging.getLogger(__name__)
+        return self._logger
+
+    def init(self):
+        try:
+            with sqlite3.connect(database=self.database) as conn:
+                cur = conn.execute("select count(1) from oauth_states;")
+                row_num = cur.fetchone()[0]
+                self.logger.debug(f"{row_num} oauth states are stored in {self.database}")
+        except Exception:
+            self.create_tables()
+        self.init_called = True
+
+    def connect(self) -> Connection:
+        if not self.init_called:
+            self.init()
+        return sqlite3.connect(database=self.database)
+
+    def create_tables(self):
+        with sqlite3.connect(database=self.database) as conn:
+            conn.execute(
+                """
+            create table oauth_states (
+                id integer primary key autoincrement,
+                state text not null,
+                expire_at datetime not null
+            );
+            """
+            )
+            self.logger.debug(f"Tables have been created (database: {self.database})")
+            conn.commit()
+
+    async def async_issue(self, *args, **kwargs) -> str:
+        return self.issue(*args, **kwargs)
+
+    async def async_consume(self, state: str) -> bool:
+        return self.consume(state)
+
+    def issue(self, *args, **kwargs) -> str:
+        state: str = str(uuid4())
+        with self.connect() as conn:
+            parameters = [
+                state,
+                time.time() + self.expiration_seconds,
+            ]
+            conn.execute("insert into oauth_states (state, expire_at) values (?, ?);", parameters)
+            self.logger.debug(f"issue's insertion result: {parameters} (database: {self.database})")
+            conn.commit()
+        return state
+
+    def consume(self, state: str) -> bool:
+        try:
+            with self.connect() as conn:
+                cur = conn.execute(
+                    "select id, state from oauth_states where state = ? and expire_at > ?;",
+                    [state, time.time()],
+                )
+                row = cur.fetchone()
+                self.logger.debug(f"consume's query result: {row} (database: {self.database})")
+                if row and len(row) > 0:
+                    id = row[0]
+                    conn.execute("delete from oauth_states where id = ?;", [id])
+                    conn.commit()
+                    return True
+            return False
+        except Exception as e:
+            message = f"Failed to find any persistent data for state: {state} - {e}"
+            self.logger.warning(message)
+            return False
+
+
+

Ancestors

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    if self._logger is None:
+        self._logger = logging.getLogger(__name__)
+    return self._logger
+
+
+
+
+

Methods

+
+
+async def async_consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
async def async_consume(self, state: str) -> bool:
+    return self.consume(state)
+
+
+
+
+async def async_issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
async def async_issue(self, *args, **kwargs) -> str:
+    return self.issue(*args, **kwargs)
+
+
+
+
+def connect(self) ‑>Β sqlite3.Connection +
+
+
+ +Expand source code + +
def connect(self) -> Connection:
+    if not self.init_called:
+        self.init()
+    return sqlite3.connect(database=self.database)
+
+
+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    try:
+        with self.connect() as conn:
+            cur = conn.execute(
+                "select id, state from oauth_states where state = ? and expire_at > ?;",
+                [state, time.time()],
+            )
+            row = cur.fetchone()
+            self.logger.debug(f"consume's query result: {row} (database: {self.database})")
+            if row and len(row) > 0:
+                id = row[0]
+                conn.execute("delete from oauth_states where id = ?;", [id])
+                conn.commit()
+                return True
+        return False
+    except Exception as e:
+        message = f"Failed to find any persistent data for state: {state} - {e}"
+        self.logger.warning(message)
+        return False
+
+
+
+
+def create_tables(self) +
+
+
+ +Expand source code + +
def create_tables(self):
+    with sqlite3.connect(database=self.database) as conn:
+        conn.execute(
+            """
+        create table oauth_states (
+            id integer primary key autoincrement,
+            state text not null,
+            expire_at datetime not null
+        );
+        """
+        )
+        self.logger.debug(f"Tables have been created (database: {self.database})")
+        conn.commit()
+
+
+
+
+def init(self) +
+
+
+ +Expand source code + +
def init(self):
+    try:
+        with sqlite3.connect(database=self.database) as conn:
+            cur = conn.execute("select count(1) from oauth_states;")
+            row_num = cur.fetchone()[0]
+            self.logger.debug(f"{row_num} oauth states are stored in {self.database}")
+    except Exception:
+        self.create_tables()
+    self.init_called = True
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    state: str = str(uuid4())
+    with self.connect() as conn:
+        parameters = [
+            state,
+            time.time() + self.expiration_seconds,
+        ]
+        conn.execute("insert into oauth_states (state, expire_at) values (?, ?);", parameters)
+        self.logger.debug(f"issue's insertion result: {parameters} (database: {self.database})")
+        conn.commit()
+    return state
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_store/state_store.html b/docs/reference/oauth/state_store/state_store.html new file mode 100644 index 000000000..9734a2bba --- /dev/null +++ b/docs/reference/oauth/state_store/state_store.html @@ -0,0 +1,153 @@ + + + + + + +slack_sdk.oauth.state_store.state_store API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_store.state_store

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class OAuthStateStore +
+
+
+ +Expand source code + +
class OAuthStateStore:
+    @property
+    def logger(self) -> Logger:
+        raise NotImplementedError()
+
+    def issue(self, *args, **kwargs) -> str:
+        raise NotImplementedError()
+
+    def consume(self, state: str) -> bool:
+        raise NotImplementedError()
+
+
+

Subclasses

+ +

Instance variables

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> Logger:
+    raise NotImplementedError()
+
+
+
+
+

Methods

+
+
+def consume(self, state:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def consume(self, state: str) -> bool:
+    raise NotImplementedError()
+
+
+
+
+def issue(self, *args, **kwargs) ‑>Β str +
+
+
+ +Expand source code + +
def issue(self, *args, **kwargs) -> str:
+    raise NotImplementedError()
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/state_utils/index.html b/docs/reference/oauth/state_utils/index.html new file mode 100644 index 000000000..d732babfd --- /dev/null +++ b/docs/reference/oauth/state_utils/index.html @@ -0,0 +1,212 @@ + + + + + + +slack_sdk.oauth.state_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.state_utils

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class OAuthStateUtils +(*, cookie_name:Β strΒ =Β 'slack-app-oauth-state', expiration_seconds:Β intΒ =Β 600) +
+
+
+ +Expand source code + +
class OAuthStateUtils:
+    cookie_name: str
+    expiration_seconds: int
+
+    default_cookie_name: str = "slack-app-oauth-state"
+    default_expiration_seconds: int = 60 * 10  # 10 minutes
+
+    def __init__(
+        self,
+        *,
+        cookie_name: str = default_cookie_name,
+        expiration_seconds: int = default_expiration_seconds,
+    ):
+        self.cookie_name = cookie_name
+        self.expiration_seconds = expiration_seconds
+
+    def build_set_cookie_for_new_state(self, state: str) -> str:
+        return f"{self.cookie_name}={state}; " "Secure; " "HttpOnly; " "Path=/; " f"Max-Age={self.expiration_seconds}"
+
+    def build_set_cookie_for_deletion(self) -> str:
+        return f"{self.cookie_name}=deleted; " "Secure; " "HttpOnly; " "Path=/; " "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
+
+    def is_valid_browser(
+        self,
+        state: Optional[str],
+        request_headers: Dict[str, Union[str, Sequence[str]]],
+    ) -> bool:
+        if state is None or request_headers is None or request_headers.get("cookie", None) is None:
+            return False
+        cookies = request_headers["cookie"]
+        if isinstance(cookies, str):
+            cookies = [cookies]
+        for cookie in cookies:
+            values = cookie.split(";")
+            for value in values:
+                # handle quoted cookie values (e.g. due to base64 encoding)
+                if value.strip().replace('"', "").replace("'", "") == f"{self.cookie_name}={state}":
+                    return True
+        return False
+
+
+

Class variables

+
+
var cookie_name :Β str
+
+

The type of the None singleton.

+
+ +
+

The type of the None singleton.

+
+
var default_expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
var expiration_seconds :Β int
+
+

The type of the None singleton.

+
+
+

Methods

+
+ +
+
+ +Expand source code + +
def build_set_cookie_for_deletion(self) -> str:
+    return f"{self.cookie_name}=deleted; " "Secure; " "HttpOnly; " "Path=/; " "Expires=Thu, 01 Jan 1970 00:00:00 GMT"
+
+
+
+ +
+
+ +Expand source code + +
def build_set_cookie_for_new_state(self, state: str) -> str:
+    return f"{self.cookie_name}={state}; " "Secure; " "HttpOnly; " "Path=/; " f"Max-Age={self.expiration_seconds}"
+
+
+
+
+def is_valid_browser(self, state:Β strΒ |Β None, request_headers:Β Dict[str,Β strΒ |Β Sequence[str]]) ‑>Β bool +
+
+
+ +Expand source code + +
def is_valid_browser(
+    self,
+    state: Optional[str],
+    request_headers: Dict[str, Union[str, Sequence[str]]],
+) -> bool:
+    if state is None or request_headers is None or request_headers.get("cookie", None) is None:
+        return False
+    cookies = request_headers["cookie"]
+    if isinstance(cookies, str):
+        cookies = [cookies]
+    for cookie in cookies:
+        values = cookie.split(";")
+        for value in values:
+            # handle quoted cookie values (e.g. due to base64 encoding)
+            if value.strip().replace('"', "").replace("'", "") == f"{self.cookie_name}={state}":
+                return True
+    return False
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/token_rotation/async_rotator.html b/docs/reference/oauth/token_rotation/async_rotator.html new file mode 100644 index 000000000..35d64f362 --- /dev/null +++ b/docs/reference/oauth/token_rotation/async_rotator.html @@ -0,0 +1,424 @@ + + + + + + +slack_sdk.oauth.token_rotation.async_rotator API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.token_rotation.async_rotator

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncTokenRotator +(*,
client_id:Β str,
client_secret:Β str,
client:Β AsyncWebClientΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncTokenRotator:
+    client: AsyncWebClient
+    client_id: str
+    client_secret: str
+
+    def __init__(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        client: Optional[AsyncWebClient] = None,
+    ):
+        self.client = client if client is not None else AsyncWebClient(token=None)
+        self.client_id = client_id
+        self.client_secret = client_secret
+
+    async def perform_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+
+        # TODO: make the following two calls in parallel for better performance
+
+        # bot
+        rotated_bot: Optional[Bot] = await self.perform_bot_token_rotation(
+            bot=installation.to_bot(),
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        # user
+        rotated_installation = await self.perform_user_token_rotation(
+            installation=installation,
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        if rotated_bot is not None:
+            if rotated_installation is None:
+                rotated_installation = Installation(**installation.to_dict_for_copying())
+            rotated_installation.bot_token = rotated_bot.bot_token
+            rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+            rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+        return rotated_installation
+
+    async def perform_bot_token_rotation(
+        self,
+        *,
+        bot: Bot,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Bot]:
+        """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+        Args:
+            bot: the current bot installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if bot.bot_token_expires_at is None:
+            return None
+        if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = await self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=bot.bot_refresh_token,
+            )
+            # TODO: error handling
+
+            if refresh_response.get("token_type") != "bot":
+                return None
+
+            refreshed_bot = Bot(**bot.to_dict_for_copying())
+            refreshed_bot.bot_token = refresh_response["access_token"]
+            refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+            refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+            return refreshed_bot
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+    async def perform_user_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs user token rotation if the underlying user token is expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if installation.user_token_expires_at is None:
+            return None
+        if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = await self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=installation.user_refresh_token,
+            )
+            if refresh_response.get("token_type") != "user":
+                return None
+
+            refreshed_installation = Installation(**installation.to_dict_for_copying())
+            refreshed_installation.user_token = refresh_response.get("access_token")
+            refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+            refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response.get("expires_in"))  # type: ignore[arg-type] # noqa: E501
+            return refreshed_installation
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+
+

Class variables

+
+
var client :Β AsyncWebClient
+
+

The type of the None singleton.

+
+
var client_id :Β str
+
+

The type of the None singleton.

+
+
var client_secret :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def perform_bot_token_rotation(self,
*,
bot:Β Bot,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
async def perform_bot_token_rotation(
+    self,
+    *,
+    bot: Bot,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Bot]:
+    """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+    Args:
+        bot: the current bot installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if bot.bot_token_expires_at is None:
+        return None
+    if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = await self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=bot.bot_refresh_token,
+        )
+        # TODO: error handling
+
+        if refresh_response.get("token_type") != "bot":
+            return None
+
+        refreshed_bot = Bot(**bot.to_dict_for_copying())
+        refreshed_bot.bot_token = refresh_response["access_token"]
+        refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+        refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+        return refreshed_bot
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs bot token rotation if the underlying bot token is expired / expiring.

+

Args

+
+
bot
+
the current bot installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+async def perform_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
async def perform_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+
+    # TODO: make the following two calls in parallel for better performance
+
+    # bot
+    rotated_bot: Optional[Bot] = await self.perform_bot_token_rotation(
+        bot=installation.to_bot(),
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    # user
+    rotated_installation = await self.perform_user_token_rotation(
+        installation=installation,
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    if rotated_bot is not None:
+        if rotated_installation is None:
+            rotated_installation = Installation(**installation.to_dict_for_copying())
+        rotated_installation.bot_token = rotated_bot.bot_token
+        rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+        rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+    return rotated_installation
+
+

Performs token rotation if the underlying tokens (bot / user) are expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+async def perform_user_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
async def perform_user_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs user token rotation if the underlying user token is expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if installation.user_token_expires_at is None:
+        return None
+    if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = await self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=installation.user_refresh_token,
+        )
+        if refresh_response.get("token_type") != "user":
+            return None
+
+        refreshed_installation = Installation(**installation.to_dict_for_copying())
+        refreshed_installation.user_token = refresh_response.get("access_token")
+        refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+        refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response.get("expires_in"))  # type: ignore[arg-type] # noqa: E501
+        return refreshed_installation
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs user token rotation if the underlying user token is expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/token_rotation/index.html b/docs/reference/oauth/token_rotation/index.html new file mode 100644 index 000000000..979f9f80c --- /dev/null +++ b/docs/reference/oauth/token_rotation/index.html @@ -0,0 +1,433 @@ + + + + + + +slack_sdk.oauth.token_rotation API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.token_rotation

+
+
+
+
+

Sub-modules

+
+
slack_sdk.oauth.token_rotation.async_rotator
+
+
+
+
slack_sdk.oauth.token_rotation.rotator
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class TokenRotator +(*,
client_id:Β str,
client_secret:Β str,
client:Β WebClientΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class TokenRotator:
+    client: WebClient
+    client_id: str
+    client_secret: str
+
+    def __init__(self, *, client_id: str, client_secret: str, client: Optional[WebClient] = None):
+        self.client = client if client is not None else WebClient(token=None)
+        self.client_id = client_id
+        self.client_secret = client_secret
+
+    def perform_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+
+        # TODO: make the following two calls in parallel for better performance
+
+        # bot
+        rotated_bot: Optional[Bot] = self.perform_bot_token_rotation(
+            bot=installation.to_bot(),
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        # user
+        rotated_installation: Optional[Installation] = self.perform_user_token_rotation(
+            installation=installation,
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        if rotated_bot is not None:
+            if rotated_installation is None:
+                rotated_installation = Installation(**installation.to_dict_for_copying())
+            rotated_installation.bot_token = rotated_bot.bot_token
+            rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+            rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+        return rotated_installation
+
+    def perform_bot_token_rotation(
+        self,
+        *,
+        bot: Bot,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Bot]:
+        """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+        Args:
+            bot: the current bot installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if bot.bot_token_expires_at is None:
+            return None
+        if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=bot.bot_refresh_token,
+            )
+            if refresh_response.get("token_type") != "bot":
+                return None
+
+            refreshed_bot = Bot(**bot.to_dict_for_copying())
+            refreshed_bot.bot_token = refresh_response["access_token"]
+            refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+            refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+            return refreshed_bot
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+    def perform_user_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs user token rotation if the underlying user token is expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if installation.user_token_expires_at is None:
+            return None
+        if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=installation.user_refresh_token,
+            )
+
+            if refresh_response.get("token_type") != "user":
+                return None
+
+            refreshed_installation = Installation(**installation.to_dict_for_copying())
+            refreshed_installation.user_token = refresh_response.get("access_token")
+            refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+            refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+            return refreshed_installation
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+
+

Class variables

+
+
var client :Β WebClient
+
+

The type of the None singleton.

+
+
var client_id :Β str
+
+

The type of the None singleton.

+
+
var client_secret :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def perform_bot_token_rotation(self,
*,
bot:Β Bot,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
def perform_bot_token_rotation(
+    self,
+    *,
+    bot: Bot,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Bot]:
+    """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+    Args:
+        bot: the current bot installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if bot.bot_token_expires_at is None:
+        return None
+    if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=bot.bot_refresh_token,
+        )
+        if refresh_response.get("token_type") != "bot":
+            return None
+
+        refreshed_bot = Bot(**bot.to_dict_for_copying())
+        refreshed_bot.bot_token = refresh_response["access_token"]
+        refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+        refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+        return refreshed_bot
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs bot token rotation if the underlying bot token is expired / expiring.

+

Args

+
+
bot
+
the current bot installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+def perform_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
def perform_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+
+    # TODO: make the following two calls in parallel for better performance
+
+    # bot
+    rotated_bot: Optional[Bot] = self.perform_bot_token_rotation(
+        bot=installation.to_bot(),
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    # user
+    rotated_installation: Optional[Installation] = self.perform_user_token_rotation(
+        installation=installation,
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    if rotated_bot is not None:
+        if rotated_installation is None:
+            rotated_installation = Installation(**installation.to_dict_for_copying())
+        rotated_installation.bot_token = rotated_bot.bot_token
+        rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+        rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+    return rotated_installation
+
+

Performs token rotation if the underlying tokens (bot / user) are expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+def perform_user_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
def perform_user_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs user token rotation if the underlying user token is expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if installation.user_token_expires_at is None:
+        return None
+    if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=installation.user_refresh_token,
+        )
+
+        if refresh_response.get("token_type") != "user":
+            return None
+
+        refreshed_installation = Installation(**installation.to_dict_for_copying())
+        refreshed_installation.user_token = refresh_response.get("access_token")
+        refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+        refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+        return refreshed_installation
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs user token rotation if the underlying user token is expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/oauth/token_rotation/rotator.html b/docs/reference/oauth/token_rotation/rotator.html new file mode 100644 index 000000000..afcccb48c --- /dev/null +++ b/docs/reference/oauth/token_rotation/rotator.html @@ -0,0 +1,416 @@ + + + + + + +slack_sdk.oauth.token_rotation.rotator API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.oauth.token_rotation.rotator

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class TokenRotator +(*,
client_id:Β str,
client_secret:Β str,
client:Β WebClientΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class TokenRotator:
+    client: WebClient
+    client_id: str
+    client_secret: str
+
+    def __init__(self, *, client_id: str, client_secret: str, client: Optional[WebClient] = None):
+        self.client = client if client is not None else WebClient(token=None)
+        self.client_id = client_id
+        self.client_secret = client_secret
+
+    def perform_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+
+        # TODO: make the following two calls in parallel for better performance
+
+        # bot
+        rotated_bot: Optional[Bot] = self.perform_bot_token_rotation(
+            bot=installation.to_bot(),
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        # user
+        rotated_installation: Optional[Installation] = self.perform_user_token_rotation(
+            installation=installation,
+            minutes_before_expiration=minutes_before_expiration,
+        )
+
+        if rotated_bot is not None:
+            if rotated_installation is None:
+                rotated_installation = Installation(**installation.to_dict_for_copying())
+            rotated_installation.bot_token = rotated_bot.bot_token
+            rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+            rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+        return rotated_installation
+
+    def perform_bot_token_rotation(
+        self,
+        *,
+        bot: Bot,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Bot]:
+        """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+        Args:
+            bot: the current bot installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if bot.bot_token_expires_at is None:
+            return None
+        if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=bot.bot_refresh_token,
+            )
+            if refresh_response.get("token_type") != "bot":
+                return None
+
+            refreshed_bot = Bot(**bot.to_dict_for_copying())
+            refreshed_bot.bot_token = refresh_response["access_token"]
+            refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+            refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+            return refreshed_bot
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+    def perform_user_token_rotation(
+        self,
+        *,
+        installation: Installation,
+        minutes_before_expiration: int = 120,  # 2 hours by default
+    ) -> Optional[Installation]:
+        """Performs user token rotation if the underlying user token is expired / expiring.
+
+        Args:
+            installation: the current installation data
+            minutes_before_expiration: the minutes before the token expiration
+
+        Returns:
+            None if no rotation is necessary for now.
+        """
+        if installation.user_token_expires_at is None:
+            return None
+        if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+            return None
+
+        try:
+            refresh_response = self.client.oauth_v2_access(
+                client_id=self.client_id,
+                client_secret=self.client_secret,
+                grant_type="refresh_token",
+                refresh_token=installation.user_refresh_token,
+            )
+
+            if refresh_response.get("token_type") != "user":
+                return None
+
+            refreshed_installation = Installation(**installation.to_dict_for_copying())
+            refreshed_installation.user_token = refresh_response.get("access_token")
+            refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+            refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+            return refreshed_installation
+
+        except SlackApiError as e:
+            raise SlackTokenRotationError(e)
+
+
+

Class variables

+
+
var client :Β WebClient
+
+

The type of the None singleton.

+
+
var client_id :Β str
+
+

The type of the None singleton.

+
+
var client_secret :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def perform_bot_token_rotation(self,
*,
bot:Β Bot,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β BotΒ |Β None
+
+
+
+ +Expand source code + +
def perform_bot_token_rotation(
+    self,
+    *,
+    bot: Bot,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Bot]:
+    """Performs bot token rotation if the underlying bot token is expired / expiring.
+
+    Args:
+        bot: the current bot installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if bot.bot_token_expires_at is None:
+        return None
+    if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=bot.bot_refresh_token,
+        )
+        if refresh_response.get("token_type") != "bot":
+            return None
+
+        refreshed_bot = Bot(**bot.to_dict_for_copying())
+        refreshed_bot.bot_token = refresh_response["access_token"]
+        refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
+        refreshed_bot.bot_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+        return refreshed_bot
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs bot token rotation if the underlying bot token is expired / expiring.

+

Args

+
+
bot
+
the current bot installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+def perform_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
def perform_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+
+    # TODO: make the following two calls in parallel for better performance
+
+    # bot
+    rotated_bot: Optional[Bot] = self.perform_bot_token_rotation(
+        bot=installation.to_bot(),
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    # user
+    rotated_installation: Optional[Installation] = self.perform_user_token_rotation(
+        installation=installation,
+        minutes_before_expiration=minutes_before_expiration,
+    )
+
+    if rotated_bot is not None:
+        if rotated_installation is None:
+            rotated_installation = Installation(**installation.to_dict_for_copying())
+        rotated_installation.bot_token = rotated_bot.bot_token
+        rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
+        rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at
+
+    return rotated_installation
+
+

Performs token rotation if the underlying tokens (bot / user) are expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+def perform_user_token_rotation(self,
*,
installation:Β Installation,
minutes_before_expiration:Β intΒ =Β 120) ‑>Β InstallationΒ |Β None
+
+
+
+ +Expand source code + +
def perform_user_token_rotation(
+    self,
+    *,
+    installation: Installation,
+    minutes_before_expiration: int = 120,  # 2 hours by default
+) -> Optional[Installation]:
+    """Performs user token rotation if the underlying user token is expired / expiring.
+
+    Args:
+        installation: the current installation data
+        minutes_before_expiration: the minutes before the token expiration
+
+    Returns:
+        None if no rotation is necessary for now.
+    """
+    if installation.user_token_expires_at is None:
+        return None
+    if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
+        return None
+
+    try:
+        refresh_response = self.client.oauth_v2_access(
+            client_id=self.client_id,
+            client_secret=self.client_secret,
+            grant_type="refresh_token",
+            refresh_token=installation.user_refresh_token,
+        )
+
+        if refresh_response.get("token_type") != "user":
+            return None
+
+        refreshed_installation = Installation(**installation.to_dict_for_copying())
+        refreshed_installation.user_token = refresh_response.get("access_token")
+        refreshed_installation.user_refresh_token = refresh_response.get("refresh_token")
+        refreshed_installation.user_token_expires_at = int(time()) + int(refresh_response["expires_in"])
+        return refreshed_installation
+
+    except SlackApiError as e:
+        raise SlackTokenRotationError(e)
+
+

Performs user token rotation if the underlying user token is expired / expiring.

+

Args

+
+
installation
+
the current installation data
+
minutes_before_expiration
+
the minutes before the token expiration
+
+

Returns

+

None if no rotation is necessary for now.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/proxy_env_variable_loader.html b/docs/reference/proxy_env_variable_loader.html new file mode 100644 index 000000000..f1eee3af3 --- /dev/null +++ b/docs/reference/proxy_env_variable_loader.html @@ -0,0 +1,102 @@ + + + + + + +slack_sdk.proxy_env_variable_loader API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.proxy_env_variable_loader

+
+
+

Internal module for loading proxy-related env variables

+
+
+
+
+
+
+

Functions

+
+
+def load_http_proxy_from_env(logger:Β logging.LoggerΒ =Β <Logger slack_sdk.proxy_env_variable_loader (WARNING)>) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def load_http_proxy_from_env(logger: logging.Logger = _default_logger) -> Optional[str]:
+    proxy_url = (
+        os.environ.get("HTTPS_PROXY")
+        or os.environ.get("https_proxy")
+        or os.environ.get("HTTP_PROXY")
+        or os.environ.get("http_proxy")
+    )
+    if proxy_url is None:
+        return None
+    if len(proxy_url.strip()) == 0:
+        # If the value is an empty string, the intention should be unsetting it
+        logger.debug("The Slack SDK ignored the proxy env variable as an empty value is set.")
+        return None
+
+    logger.debug(f"HTTP proxy URL has been loaded from an env variable: {proxy_url}")
+    return proxy_url
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/rtm/index.html b/docs/reference/rtm/index.html new file mode 100644 index 000000000..870fa3797 --- /dev/null +++ b/docs/reference/rtm/index.html @@ -0,0 +1,1004 @@ + + + + + + +slack_sdk.rtm API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.rtm

+
+
+

A Python module for interacting with Slack's RTM API.

+
+
+

Sub-modules

+
+
slack_sdk.rtm.v2
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RTMClient +(*,
token:Β str,
run_async:Β boolΒ |Β NoneΒ =Β False,
auto_reconnect:Β boolΒ |Β NoneΒ =Β True,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
timeout:Β intΒ |Β NoneΒ =Β 30,
base_url:Β strΒ |Β NoneΒ =Β 'https://slack.com/api/',
connect_method:Β strΒ |Β NoneΒ =Β None,
ping_interval:Β intΒ |Β NoneΒ =Β 30,
loop:Β asyncio.events.AbstractEventLoopΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β {})
+
+
+
+ +Expand source code + +
class RTMClient(object):
+    """An RTMClient allows apps to communicate with the Slack Platform's RTM API.
+
+    The event-driven architecture of this client allows you to simply
+    link callbacks to their corresponding events. When an event occurs
+    this client executes your callback while passing along any
+    information it receives.
+
+    Attributes:
+        token (str): A string specifying an xoxp or xoxb token.
+        run_async (bool): A boolean specifying if the client should
+            be run in async mode. Default is False.
+        auto_reconnect (bool): When true the client will automatically
+            reconnect when (not manually) disconnected. Default is True.
+        ssl (SSLContext): To use SSL support, pass an SSLContext object here.
+            Default is None.
+        proxy (str): To use proxy support, pass the string of the proxy server.
+            e.g. "http://proxy.com"
+            Authentication credentials can be passed in proxy URL.
+            e.g. "http://user:pass@some.proxy.com"
+            Default is None.
+        timeout (int): The amount of seconds the session should wait before timing out.
+            Default is 30.
+        base_url (str): The base url for all HTTP requests.
+            Note: This is only used in the WebClient.
+            Default is "https://slack.com/api/".
+        connect_method (str): An string specifying if the client
+            will connect with `rtm.connect` or `rtm.start`.
+            Default is `rtm.connect`.
+        ping_interval (int): automatically send "ping" command every
+            specified period of seconds. If set to 0, do not send automatically.
+            Default is 30.
+        loop (AbstractEventLoop): An event loop provided by asyncio.
+            If None is specified we attempt to use the current loop
+            with `get_event_loop`. Default is None.
+
+    Methods:
+        ping: Sends a ping message over the websocket to Slack.
+        typing: Sends a typing indicator to the specified channel.
+        on: Stores and links callbacks to websocket and Slack events.
+        run_on: Decorator that stores and links callbacks to websocket and Slack events.
+        start: Starts an RTM Session with Slack.
+        stop: Closes the websocket connection and ensures it won't reconnect.
+
+    Example:
+    ```python
+    import os
+    from slack import RTMClient
+
+    @RTMClient.run_on(event="message")
+    def say_hello(**payload):
+        data = payload['data']
+        web_client = payload['web_client']
+        if 'Hello' in data['text']:
+            channel_id = data['channel']
+            thread_ts = data['ts']
+            user = data['user']
+
+            web_client.chat_postMessage(
+                channel=channel_id,
+                text=f"Hi <@{user}>!",
+                thread_ts=thread_ts
+            )
+
+    slack_token = os.environ["SLACK_API_TOKEN"]
+    rtm_client = RTMClient(token=slack_token)
+    rtm_client.start()
+    ```
+
+    Note:
+        The initial state returned when establishing an RTM connection will
+        be available as the data in payload for the 'open' event. This data is not and
+        will not be stored on the RTM Client.
+
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+    """
+
+    _callbacks: DefaultDict = collections.defaultdict(list)
+
+    def __init__(
+        self,
+        *,
+        token: str,
+        run_async: Optional[bool] = False,
+        auto_reconnect: Optional[bool] = True,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        timeout: Optional[int] = 30,
+        base_url: Optional[str] = WebClient.BASE_URL,
+        connect_method: Optional[str] = None,
+        ping_interval: Optional[int] = 30,
+        loop: Optional[asyncio.AbstractEventLoop] = None,
+        headers: Optional[dict] = {},
+    ):
+        self.token = token.strip()
+        self.run_async = run_async
+        self.auto_reconnect = auto_reconnect
+        self.ssl = ssl
+        self.proxy = proxy
+        self.timeout = timeout
+        self.base_url = base_url
+        self.connect_method = connect_method
+        self.ping_interval = ping_interval
+        self.headers = headers
+        self._event_loop = loop or asyncio.get_event_loop()
+        self._web_client = None
+        self._websocket = None
+        self._session = None
+        self._logger = logging.getLogger(__name__)
+        self._last_message_id = 0
+        self._connection_attempts = 0
+        self._stopped = False
+        self._web_client = WebClient(
+            token=self.token,
+            base_url=self.base_url,  # type: ignore[arg-type]
+            timeout=self.timeout,  # type: ignore[arg-type]
+            ssl=self.ssl,
+            proxy=self.proxy,
+            run_async=self.run_async,  # type: ignore[arg-type]
+            loop=self._event_loop,
+            session=self._session,
+            headers=self.headers,
+        )
+
+    @staticmethod
+    def run_on(*, event: str):
+        """A decorator to store and link a callback to an event."""
+
+        def decorator(callback):
+            RTMClient.on(event=event, callback=callback)
+            return callback
+
+        return decorator
+
+    @classmethod
+    def on(cls, *, event: str, callback: Callable):
+        """Stores and links the callback(s) to the event.
+
+        Args:
+            event (str): A string that specifies a Slack or websocket event.
+                e.g. 'channel_joined' or 'open'
+            callback (Callable): Any object or a list of objects that can be called.
+                e.g. <function say_hello at 0x101234567> or
+                [<function say_hello at 0x10123>,<function say_bye at 0x10456>]
+
+        Raises:
+            SlackClientError: The specified callback is not callable.
+            SlackClientError: The callback must accept keyword arguments (**kwargs).
+        """
+        if isinstance(callback, list):
+            for cb in callback:
+                cls._validate_callback(cb)
+            previous_callbacks = cls._callbacks[event]
+            cls._callbacks[event] = list(set(previous_callbacks + callback))
+        else:
+            cls._validate_callback(callback)
+            cls._callbacks[event].append(callback)
+
+    def start(self) -> Union[asyncio.Future, Any]:
+        """Starts an RTM Session with Slack.
+
+        Makes an authenticated call to Slack's RTM API to retrieve
+        a websocket URL and then connects to the message server.
+        As events stream-in we run any associated callbacks stored
+        on the client.
+
+        If 'auto_reconnect' is specified we
+        retrieve a new url and reconnect any time the connection
+        is lost unintentionally or an exception is thrown.
+
+        Raises:
+            SlackApiError: Unable to retrieve RTM URL from Slack.
+        """
+        # Not yet implemented: Add Windows support for graceful shutdowns.
+        if os.name != "nt" and current_thread() == main_thread():
+            signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
+            for s in signals:
+                self._event_loop.add_signal_handler(s, self.stop)
+
+        future: Future[Any] = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop)
+
+        if self.run_async:
+            return future
+        return self._event_loop.run_until_complete(future)
+
+    def stop(self):
+        """Closes the websocket connection and ensures it won't reconnect.
+
+        If your application outputs the following errors,
+        call #async_stop() instead and await for the completion on your application side.
+
+        asyncio/base_events.py:641: RuntimeWarning:
+          coroutine 'ClientWebSocketResponse.close' was never awaited self._ready.clear()
+        """
+        self._logger.debug("The Slack RTMClient is shutting down.")
+        self._stopped = True
+        self._close_websocket()
+
+    async def async_stop(self):
+        """Closes the websocket connection and ensures it won't reconnect."""
+        self._logger.debug("The Slack RTMClient is shutting down.")
+        remaining_futures = self._close_websocket()
+        for future in remaining_futures:
+            await future
+        self._stopped = True
+
+    def send_over_websocket(self, *, payload: dict):
+        """Sends a message to Slack over the WebSocket connection.
+
+        Note:
+            The RTM API only supports posting simple messages formatted using
+            our default message formatting mode. It does not support
+            attachments or other message formatting modes. For this reason
+            we recommend users send messages via the Web API methods.
+            e.g. web_client.chat_postMessage()
+
+            If the message "id" is not specified in the payload, it'll be added.
+
+        Args:
+            payload (dict): The message to send over the wesocket.
+            e.g.
+            {
+                "id": 1,
+                "type": "typing",
+                "channel": "C024BE91L"
+            }
+
+        Raises:
+            SlackClientNotConnectedError: Websocket connection is closed.
+        """
+        return asyncio.ensure_future(self._send_json(payload), loop=self._event_loop)
+
+    async def _send_json(self, payload):
+        if self._websocket is None or self._event_loop is None:
+            raise client_err.SlackClientNotConnectedError("Websocket connection is closed.")
+        if "id" not in payload:
+            payload["id"] = self._next_msg_id()
+
+        return await self._websocket.send_json(payload)
+
+    async def ping(self):
+        """Sends a ping message over the websocket to Slack.
+
+        Not all web browsers support the WebSocket ping spec,
+        so the RTM protocol also supports ping/pong messages.
+
+        Raises:
+            SlackClientNotConnectedError: Websocket connection is closed.
+        """
+        payload = {"id": self._next_msg_id(), "type": "ping"}
+        await self._send_json(payload=payload)
+
+    async def typing(self, *, channel: str):
+        """Sends a typing indicator to the specified channel.
+
+        This indicates that this app is currently
+        writing a message to send to a channel.
+
+        Args:
+            channel (str): The channel id. e.g. 'C024BE91L'
+
+        Raises:
+            SlackClientNotConnectedError: Websocket connection is closed.
+        """
+        payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel}
+        await self._send_json(payload=payload)
+
+    @staticmethod
+    def _validate_callback(callback):
+        """Checks if the specified callback is callable and accepts a kwargs param.
+
+        Args:
+            callback (obj): Any object or a list of objects that can be called.
+                e.g. <function say_hello at 0x101234567>
+
+        Raises:
+            SlackClientError: The specified callback is not callable.
+            SlackClientError: The callback must accept keyword arguments (**kwargs).
+        """
+
+        cb_name = callback.__name__ if hasattr(callback, "__name__") else callback
+        if not callable(callback):
+            msg = "The specified callback '{}' is not callable.".format(cb_name)
+            raise client_err.SlackClientError(msg)
+        callback_params = inspect.signature(callback).parameters.values()
+        if not any(param for param in callback_params if param.kind == param.VAR_KEYWORD):
+            msg = "The callback '{}' must accept keyword arguments (**kwargs).".format(cb_name)
+            raise client_err.SlackClientError(msg)
+
+    def _next_msg_id(self):
+        """Retrieves the next message id.
+
+        When sending messages to Slack every event should
+        have a unique (for that connection) positive integer ID.
+
+        Returns:
+            An integer representing the message id. e.g. 98
+        """
+        self._last_message_id += 1
+        return self._last_message_id
+
+    async def _connect_and_read(self):
+        """Retrieves the WS url and connects to Slack's RTM API.
+
+        Makes an authenticated call to Slack's Web API to retrieve
+        a websocket URL. Then connects to the message server and
+        reads event messages as they come in.
+
+        If 'auto_reconnect' is specified we
+        retrieve a new url and reconnect any time the connection
+        is lost unintentionally or an exception is thrown.
+
+        Raises:
+            SlackApiError: Unable to retrieve RTM URL from Slack.
+            websockets.exceptions: Errors thrown by the 'websockets' library.
+        """
+        while not self._stopped:
+            try:
+                self._connection_attempts += 1
+                async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout)) as session:
+                    self._session = session
+                    url, data = await self._retrieve_websocket_info()
+                    async with session.ws_connect(
+                        url,
+                        heartbeat=self.ping_interval,
+                        ssl=self.ssl,
+                        proxy=self.proxy,
+                    ) as websocket:
+                        self._logger.debug("The Websocket connection has been opened.")
+                        self._websocket = websocket
+                        await self._dispatch_event(event="open", data=data)
+                        await self._read_messages()
+                        # The websocket has been disconnected, or self._stopped is True
+                        if not self._stopped and not self.auto_reconnect:
+                            self._logger.warning("Not reconnecting the Websocket because auto_reconnect is False")
+                            return
+                        # No need to wait exponentially here, since the connection was
+                        # established OK, but timed out, or was closed remotely
+            except (
+                client_err.SlackClientNotConnectedError,
+                client_err.SlackApiError,
+                # Not yet implemented: Catch websocket exceptions thrown by aiohttp.
+            ) as exception:
+                await self._dispatch_event(event="error", data=exception)
+                error_code = exception.response.get("error", None) if hasattr(exception, "response") else None
+                if (
+                    self.auto_reconnect
+                    and not self._stopped
+                    and error_code != "invalid_auth"  # "invalid_auth" is unrecoverable
+                ):
+                    await self._wait_exponentially(exception)
+                    continue
+                self._logger.exception("The Websocket encountered an error. Closing the connection...")
+                self._close_websocket()
+                raise
+
+    async def _read_messages(self):
+        """Process messages received on the WebSocket connection."""
+        while not self._stopped and self._websocket is not None:
+            try:
+                # Wait for a message to be received, but timeout after a second so that
+                # we can check if the socket has been closed, or if self._stopped is
+                # True
+                message = await self._websocket.receive(timeout=1)
+            except asyncio.TimeoutError:
+                if not self._websocket.closed:
+                    # We didn't receive a message within the timeout interval, but
+                    # aiohttp hasn't closed the socket, so ping responses must still be
+                    # returning
+                    continue
+                self._logger.warning(
+                    "Websocket was closed (%s).",
+                    self._websocket.close_code if self._websocket else "",
+                )
+                await self._dispatch_event(
+                    event="error",
+                    data=self._websocket.exception() if self._websocket else "",
+                )
+                self._websocket = None
+                await self._dispatch_event(event="close")
+                return
+
+            if message.type == aiohttp.WSMsgType.TEXT:
+                try:
+                    payload = message.json()
+                    event = payload.pop("type", "Unknown")
+                    await self._dispatch_event(event, data=payload)
+                except Exception as err:
+                    data = message.data if message else message
+                    self._logger.info(f"Caught a raised exception ({err}) while dispatching a TEXT message ({data})")
+                    # Raised exceptions here happen in users' code and were just unhandled.
+                    # As they're not intended for closing current WebSocket connection,
+                    # this exception should not be propagated to higher level (#_connect_and_read()).
+                    continue
+            elif message.type == aiohttp.WSMsgType.ERROR:
+                self._logger.error("Received an error on the websocket: %r", message)
+                await self._dispatch_event(event="error", data=message)
+            elif message.type in (
+                aiohttp.WSMsgType.CLOSE,
+                aiohttp.WSMsgType.CLOSING,
+                aiohttp.WSMsgType.CLOSED,
+            ):
+                self._logger.warning("Websocket was closed.")
+                self._websocket = None
+                await self._dispatch_event(event="close")
+            else:
+                self._logger.debug("Received unhandled message type: %r", message)
+
+    async def _dispatch_event(self, event, data=None):
+        """Dispatches the event and executes any associated callbacks.
+
+        Note: To prevent the app from crashing due to callback errors. We
+        catch all exceptions and send all data to the logger.
+
+        Args:
+            event (str): The type of event. e.g. 'bot_added'
+            data (dict): The data Slack sent. e.g.
+            {
+                "type": "bot_added",
+                "bot": {
+                    "id": "B024BE7LH",
+                    "app_id": "A4H1JB4AZ",
+                    "name": "hugbot"
+                }
+            }
+        """
+        if self._logger.level <= logging.DEBUG:
+            self._logger.debug("Received an event: '%s' - %s", event, data)
+        for callback in self._callbacks[event]:
+            self._logger.debug(
+                "Running %s callbacks for event: '%s'",
+                len(self._callbacks[event]),
+                event,
+            )
+            try:
+                if self._stopped and event not in ["close", "error"]:
+                    # Don't run callbacks if client was stopped unless they're
+                    # close/error callbacks.
+                    break
+
+                if inspect.iscoroutinefunction(callback):
+                    await callback(rtm_client=self, web_client=self._web_client, data=data)
+                else:
+                    if self.run_async is True:
+                        raise client_err.SlackRequestError(
+                            f'The callback "{callback.__name__}" is NOT a coroutine. '
+                            "Running such with run_async=True is unsupported. "
+                            "Consider adding async/await to the method "
+                            "or going with run_async=False if your app is not really non-blocking."
+                        )
+                    payload = {
+                        "rtm_client": self,
+                        "web_client": self._web_client,
+                        "data": data,
+                    }
+                    callback(**payload)
+            except Exception as err:
+                name = callback.__name__
+                module = callback.__module__
+                msg = f"When calling '#{name}()' in the '{module}' module the following error was raised: {err}"
+                self._logger.error(msg)
+                raise
+
+    async def _retrieve_websocket_info(self):
+        """Retrieves the WebSocket info from Slack.
+
+        Returns:
+            A tuple of websocket information.
+            e.g.
+            (
+                "wss://...",
+                {
+                    "self": {"id": "U01234ABC","name": "robotoverlord"},
+                    "team": {
+                        "domain": "exampledomain",
+                        "id": "T123450FP",
+                        "name": "ExampleName"
+                    }
+                }
+            )
+
+        Raises:
+            SlackApiError: Unable to retrieve RTM URL from Slack.
+        """
+        if self._web_client is None:
+            self._web_client = WebClient(
+                token=self.token,
+                base_url=self.base_url,
+                timeout=self.timeout,
+                ssl=self.ssl,
+                proxy=self.proxy,
+                run_async=True,
+                loop=self._event_loop,
+                session=self._session,
+                headers=self.headers,
+            )
+        self._logger.debug("Retrieving websocket info.")
+        use_rtm_start = self.connect_method in ["rtm.start", "rtm_start"]
+        if self.run_async:
+            if use_rtm_start:
+                resp = await self._web_client.rtm_start()
+            else:
+                resp = await self._web_client.rtm_connect()
+        else:
+            if use_rtm_start:
+                resp = self._web_client.rtm_start()
+            else:
+                resp = self._web_client.rtm_connect()
+
+        url = resp.get("url")
+        if url is None:
+            msg = "Unable to retrieve RTM URL from Slack."
+            raise client_err.SlackApiError(message=msg, response=resp)
+        return url, resp.data
+
+    async def _wait_exponentially(self, exception, max_wait_time=300):
+        """Wait exponentially longer for each connection attempt.
+
+        Calculate the number of seconds to wait and then add
+        a random number of milliseconds to avoid coincidental
+        synchronized client retries. Wait up to the maximum amount
+        of wait time specified via 'max_wait_time'. However,
+        if Slack returned how long to wait use that.
+        """
+        if hasattr(exception, "response"):
+            wait_time = exception.response.get("headers", {}).get(
+                "Retry-After",
+                min((2**self._connection_attempts) + random.random(), max_wait_time),
+            )
+            self._logger.debug("Waiting %s seconds before reconnecting.", wait_time)
+            await asyncio.sleep(float(wait_time))
+
+    def _close_websocket(self) -> Sequence[Future]:
+        """Closes the websocket connection."""
+        futures = []
+        close_method = getattr(self._websocket, "close", None)
+        if callable(close_method):
+            future = asyncio.ensure_future(close_method(), loop=self._event_loop)
+            futures.append(future)
+        self._websocket = None
+        event_f = asyncio.ensure_future(self._dispatch_event(event="close"), loop=self._event_loop)
+        futures.append(event_f)
+        return futures
+
+

An RTMClient allows apps to communicate with the Slack Platform's RTM API.

+

The event-driven architecture of this client allows you to simply +link callbacks to their corresponding events. When an event occurs +this client executes your callback while passing along any +information it receives.

+

Attributes

+
+
token : str
+
A string specifying an xoxp or xoxb token.
+
run_async : bool
+
A boolean specifying if the client should +be run in async mode. Default is False.
+
auto_reconnect : bool
+
When true the client will automatically +reconnect when (not manually) disconnected. Default is True.
+
ssl : SSLContext
+
To use SSL support, pass an SSLContext object here. +Default is None.
+
proxy : str
+
To use proxy support, pass the string of the proxy server. +e.g. "http://proxy.com" +Authentication credentials can be passed in proxy URL. +e.g. "http://user:pass@some.proxy.com" +Default is None.
+
timeout : int
+
The amount of seconds the session should wait before timing out. +Default is 30.
+
base_url : str
+
The base url for all HTTP requests. +Note: This is only used in the WebClient. +Default is "https://slack.com/api/".
+
connect_method : str
+
An string specifying if the client +will connect with rtm.connect or rtm.start. +Default is rtm.connect.
+
ping_interval : int
+
automatically send "ping" command every +specified period of seconds. If set to 0, do not send automatically. +Default is 30.
+
loop : AbstractEventLoop
+
An event loop provided by asyncio. +If None is specified we attempt to use the current loop +with get_event_loop. Default is None.
+
+

Methods

+

ping: Sends a ping message over the websocket to Slack. +typing: Sends a typing indicator to the specified channel. +on: Stores and links callbacks to websocket and Slack events. +run_on: Decorator that stores and links callbacks to websocket and Slack events. +start: Starts an RTM Session with Slack. +stop: Closes the websocket connection and ensures it won't reconnect.

+

Example:

+
import os
+from slack import RTMClient
+
+@RTMClient.run_on(event="message")
+def say_hello(**payload):
+    data = payload['data']
+    web_client = payload['web_client']
+    if 'Hello' in data['text']:
+        channel_id = data['channel']
+        thread_ts = data['ts']
+        user = data['user']
+
+        web_client.chat_postMessage(
+            channel=channel_id,
+            text=f"Hi <@{user}>!",
+            thread_ts=thread_ts
+        )
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+rtm_client = RTMClient(token=slack_token)
+rtm_client.start()
+
+

Note

+

The initial state returned when establishing an RTM connection will +be available as the data in payload for the 'open' event. This data is not and +will not be stored on the RTM Client.

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Static methods

+
+
+def on(*, event:Β str, callback:Β Callable) +
+
+

Stores and links the callback(s) to the event.

+

Args

+
+
event : str
+
A string that specifies a Slack or websocket event. +e.g. 'channel_joined' or 'open'
+
callback : Callable
+
Any object or a list of objects that can be called. +e.g. or +[,]
+
+

Raises

+
+
SlackClientError
+
The specified callback is not callable.
+
SlackClientError
+
The callback must accept keyword arguments (**kwargs).
+
+
+
+def run_on(*, event:Β str) +
+
+
+ +Expand source code + +
@staticmethod
+def run_on(*, event: str):
+    """A decorator to store and link a callback to an event."""
+
+    def decorator(callback):
+        RTMClient.on(event=event, callback=callback)
+        return callback
+
+    return decorator
+
+

A decorator to store and link a callback to an event.

+
+
+

Methods

+
+
+async def async_stop(self) +
+
+
+ +Expand source code + +
async def async_stop(self):
+    """Closes the websocket connection and ensures it won't reconnect."""
+    self._logger.debug("The Slack RTMClient is shutting down.")
+    remaining_futures = self._close_websocket()
+    for future in remaining_futures:
+        await future
+    self._stopped = True
+
+

Closes the websocket connection and ensures it won't reconnect.

+
+
+async def ping(self) +
+
+
+ +Expand source code + +
async def ping(self):
+    """Sends a ping message over the websocket to Slack.
+
+    Not all web browsers support the WebSocket ping spec,
+    so the RTM protocol also supports ping/pong messages.
+
+    Raises:
+        SlackClientNotConnectedError: Websocket connection is closed.
+    """
+    payload = {"id": self._next_msg_id(), "type": "ping"}
+    await self._send_json(payload=payload)
+
+

Sends a ping message over the websocket to Slack.

+

Not all web browsers support the WebSocket ping spec, +so the RTM protocol also supports ping/pong messages.

+

Raises

+
+
SlackClientNotConnectedError
+
Websocket connection is closed.
+
+
+
+def send_over_websocket(self, *, payload:Β dict) +
+
+
+ +Expand source code + +
def send_over_websocket(self, *, payload: dict):
+    """Sends a message to Slack over the WebSocket connection.
+
+    Note:
+        The RTM API only supports posting simple messages formatted using
+        our default message formatting mode. It does not support
+        attachments or other message formatting modes. For this reason
+        we recommend users send messages via the Web API methods.
+        e.g. web_client.chat_postMessage()
+
+        If the message "id" is not specified in the payload, it'll be added.
+
+    Args:
+        payload (dict): The message to send over the wesocket.
+        e.g.
+        {
+            "id": 1,
+            "type": "typing",
+            "channel": "C024BE91L"
+        }
+
+    Raises:
+        SlackClientNotConnectedError: Websocket connection is closed.
+    """
+    return asyncio.ensure_future(self._send_json(payload), loop=self._event_loop)
+
+

Sends a message to Slack over the WebSocket connection.

+

Note

+

The RTM API only supports posting simple messages formatted using +our default message formatting mode. It does not support +attachments or other message formatting modes. For this reason +we recommend users send messages via the Web API methods. +e.g. web_client.chat_postMessage()

+

If the message "id" is not specified in the payload, it'll be added.

+

Args

+
+
payload : dict
+
The message to send over the wesocket.
+
+

e.g. +{ +"id": 1, +"type": "typing", +"channel": "C024BE91L" +}

+

Raises

+
+
SlackClientNotConnectedError
+
Websocket connection is closed.
+
+
+
+def start(self) ‑>Β _asyncio.FutureΒ |Β Any +
+
+
+ +Expand source code + +
def start(self) -> Union[asyncio.Future, Any]:
+    """Starts an RTM Session with Slack.
+
+    Makes an authenticated call to Slack's RTM API to retrieve
+    a websocket URL and then connects to the message server.
+    As events stream-in we run any associated callbacks stored
+    on the client.
+
+    If 'auto_reconnect' is specified we
+    retrieve a new url and reconnect any time the connection
+    is lost unintentionally or an exception is thrown.
+
+    Raises:
+        SlackApiError: Unable to retrieve RTM URL from Slack.
+    """
+    # Not yet implemented: Add Windows support for graceful shutdowns.
+    if os.name != "nt" and current_thread() == main_thread():
+        signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
+        for s in signals:
+            self._event_loop.add_signal_handler(s, self.stop)
+
+    future: Future[Any] = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop)
+
+    if self.run_async:
+        return future
+    return self._event_loop.run_until_complete(future)
+
+

Starts an RTM Session with Slack.

+

Makes an authenticated call to Slack's RTM API to retrieve +a websocket URL and then connects to the message server. +As events stream-in we run any associated callbacks stored +on the client.

+

If 'auto_reconnect' is specified we +retrieve a new url and reconnect any time the connection +is lost unintentionally or an exception is thrown.

+

Raises

+
+
SlackApiError
+
Unable to retrieve RTM URL from Slack.
+
+
+
+def stop(self) +
+
+
+ +Expand source code + +
def stop(self):
+    """Closes the websocket connection and ensures it won't reconnect.
+
+    If your application outputs the following errors,
+    call #async_stop() instead and await for the completion on your application side.
+
+    asyncio/base_events.py:641: RuntimeWarning:
+      coroutine 'ClientWebSocketResponse.close' was never awaited self._ready.clear()
+    """
+    self._logger.debug("The Slack RTMClient is shutting down.")
+    self._stopped = True
+    self._close_websocket()
+
+

Closes the websocket connection and ensures it won't reconnect.

+

If your application outputs the following errors, +call #async_stop() instead and await for the completion on your application side.

+

asyncio/base_events.py:641: RuntimeWarning: +coroutine 'ClientWebSocketResponse.close' was never awaited self._ready.clear()

+
+
+async def typing(self, *, channel:Β str) +
+
+
+ +Expand source code + +
async def typing(self, *, channel: str):
+    """Sends a typing indicator to the specified channel.
+
+    This indicates that this app is currently
+    writing a message to send to a channel.
+
+    Args:
+        channel (str): The channel id. e.g. 'C024BE91L'
+
+    Raises:
+        SlackClientNotConnectedError: Websocket connection is closed.
+    """
+    payload = {"id": self._next_msg_id(), "type": "typing", "channel": channel}
+    await self._send_json(payload=payload)
+
+

Sends a typing indicator to the specified channel.

+

This indicates that this app is currently +writing a message to send to a channel.

+

Args

+
+
channel : str
+
The channel id. e.g. 'C024BE91L'
+
+

Raises

+
+
SlackClientNotConnectedError
+
Websocket connection is closed.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/rtm/v2/index.html b/docs/reference/rtm/v2/index.html new file mode 100644 index 000000000..d0c0591ec --- /dev/null +++ b/docs/reference/rtm/v2/index.html @@ -0,0 +1,990 @@ + + + + + + +slack_sdk.rtm.v2 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.rtm.v2

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class RTMClient +(*,
token:Β strΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
timeout:Β intΒ =Β 30,
base_url:Β strΒ =Β 'https://slack.com/api/',
headers:Β dictΒ |Β NoneΒ =Β None,
ping_interval:Β intΒ =Β 5,
concurrency:Β intΒ =Β 10,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[int,Β strΒ |Β None],Β None]]Β |Β NoneΒ =Β None,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False)
+
+
+
+ +Expand source code + +
class RTMClient:
+    token: Optional[str]
+    bot_id: Optional[str]
+    default_auto_reconnect_enabled: bool
+    auto_reconnect_enabled: bool
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    timeout: int
+    base_url: str
+    ping_interval: int
+    logger: Logger
+    web_client: WebClient
+
+    current_session: Optional[Connection]
+    current_session_state: Optional[ConnectionState]
+    wss_uri: Optional[str]
+
+    message_queue: Queue
+    message_listeners: List[Callable[["RTMClient", dict], None]]
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    closed: bool
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[str], None]]
+    on_error_listeners: List[Callable[[Exception], None]]
+    on_close_listeners: List[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        *,
+        token: Optional[str] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        timeout: int = 30,
+        base_url: str = WebClient.BASE_URL,
+        headers: Optional[dict] = None,
+        ping_interval: int = 5,
+        concurrency: int = 10,
+        logger: Optional[logging.Logger] = None,
+        on_message_listeners: Optional[List[Callable[[str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+    ):
+        self.token = token.strip() if token is not None else None
+        self.bot_id = None
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        # You may want temporarily turn off the auto_reconnect as necessary
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.ssl = ssl
+        self.proxy = proxy
+        self.timeout = timeout
+        self.base_url = base_url
+        self.headers = headers
+        self.ping_interval = ping_interval
+        self.logger = logger or logging.getLogger(__name__)
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+        self.web_client = web_client or WebClient(
+            token=self.token,
+            base_url=self.base_url,
+            timeout=self.timeout,
+            ssl=self.ssl,
+            proxy=self.proxy,
+            headers=self.headers,
+            logger=logger,
+        )
+
+        self.on_message_listeners = on_message_listeners or []
+
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+
+        self.message_queue = Queue()
+
+        def goodbye_listener(_self, event: dict):
+            if event.get("type") == "goodbye":
+                message = "Got a goodbye message. Reconnecting to the server ..."
+                self.logger.info(message)
+                self.connect_to_new_endpoint(force=True)
+
+        self.message_listeners = [goodbye_listener]
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_state = ConnectionState()
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
+        self.wss_uri = None
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(
+            self._monitor_current_session,
+            self.ping_interval,
+        )
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+    # --------------------------------------------------------------
+    # Decorator to register listeners
+    # --------------------------------------------------------------
+
+    def on(self, event_type: str) -> Callable:
+        """Registers a new event listener.
+
+        Args:
+            event_type: str representing an event's type (e.g., message, reaction_added)
+        """
+
+        def __call__(*args, **kwargs):
+            func = args[0]
+            if func is not None:
+                if isinstance(func, Callable):
+                    name = (
+                        func.__name__
+                        if hasattr(func, "__name__")
+                        else f"{func.__class__.__module__}.{func.__class__.__name__}"
+                    )
+                    inspect_result: inspect.FullArgSpec = inspect.getfullargspec(func)
+                    if inspect_result is not None and len(inspect_result.args) != 2:
+                        actual_args = ", ".join(inspect_result.args)
+                        error = f"The listener '{name}' must accept two args: client, event (actual: {actual_args})"
+                        raise SlackClientError(error)
+
+                    def new_message_listener(_self, event: dict):
+                        actual_event_type = event.get("type")
+                        if event.get("bot_id") == self.bot_id:
+                            # SKip the events generated by this bot user
+                            return
+                        # https://github.com/slackapi/python-slack-sdk/issues/533
+                        if event_type == "*" or (actual_event_type is not None and actual_event_type == event_type):
+                            func(_self, event)
+
+                    self.message_listeners.append(new_message_listener)
+                else:
+                    error = f"The listener '{func}' is not a Callable (actual: {type(func).__name__})"
+                    raise SlackClientError(error)
+            # Not to cause modification to the decorated method
+            return func
+
+        return __call__
+
+    # --------------------------------------------------------------
+    # Connections
+    # --------------------------------------------------------------
+
+    def is_connected(self) -> bool:
+        """Returns True if this client is connected."""
+        return self.current_session is not None and self.current_session.is_active()
+
+    def issue_new_wss_url(self) -> str:
+        """Acquires a new WSS URL using rtm.connect API method"""
+        try:
+            api_response = self.web_client.rtm_connect()
+            return api_response["url"]
+        except SlackApiError as e:
+            if e.response["error"] == "ratelimited":
+                delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+                self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+                time.sleep(delay)
+                # Retry to issue a new WSS URL
+                return self.issue_new_wss_url()
+            else:
+                # other errors
+                self.logger.error(f"Failed to retrieve WSS URL: {e}")
+                raise e
+
+    def connect_to_new_endpoint(self, force: bool = False):
+        """Acquires a new WSS URL and tries to connect to the endpoint."""
+        with self.connect_operation_lock:
+            if force or not self.is_connected():
+                self.logger.info("Connecting to a new endpoint...")
+                self.wss_uri = self.issue_new_wss_url()
+                self.connect()
+                self.logger.info("Connected to a new endpoint...")
+
+    def connect(self):
+        """Starts talking to the RTM server through a WebSocket connection"""
+        if self.bot_id is None:
+            self.bot_id = self.web_client.auth_test()["bot_id"]
+
+        old_session: Optional[Connection] = self.current_session
+        old_current_session_state: ConnectionState = self.current_session_state
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        current_session = Connection(
+            url=self.wss_uri,
+            logger=self.logger,
+            ping_interval=self.ping_interval,
+            trace_enabled=self.trace_enabled,
+            all_message_trace_enabled=self.all_message_trace_enabled,
+            ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+            receive_buffer_size=1024,
+            proxy=self.proxy,
+            on_message_listener=self.run_all_message_listeners,
+            on_error_listener=self.run_all_error_listeners,
+            on_close_listener=self.run_all_close_listeners,
+            connection_type_name="RTM",
+        )
+        current_session.connect()
+
+        if old_current_session_state is not None:
+            old_current_session_state.terminated = True
+        if old_session is not None:
+            old_session.close()
+
+        self.current_session = current_session
+        self.current_session_state = ConnectionState()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+    def disconnect(self):
+        """Disconnects the current session."""
+        self.current_session.disconnect()
+
+    def close(self) -> None:
+        """
+        Closes this instance and cleans up underlying resources.
+        After calling this method, this instance is no longer usable.
+        """
+        self.closed = True
+        self.disconnect()
+        self.current_session.close()
+
+    def start(self) -> None:
+        """Establishes an RTM connection and blocks the current thread."""
+        self.connect()
+        Event().wait()
+
+    def send(self, payload: Union[dict, str]) -> None:
+        if payload is None:
+            return
+        if self.current_session is None or not self.current_session.is_active():
+            raise SlackClientError("The RTM client is not connected to the Slack servers")
+        if isinstance(payload, str):
+            self.current_session.send(payload)
+        else:
+            self.current_session.send(json.dumps(payload))
+
+    # --------------------------------------------------------------
+    # WS Message Processor
+    # --------------------------------------------------------------
+
+    def enqueue_message(self, message: str):
+        self.message_queue.put(message)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+    def process_message(self):
+        try:
+            raw_message = self.message_queue.get(timeout=1)
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+            if raw_message is not None:
+                message: dict = {}
+                if raw_message.startswith("{"):
+                    message = json.loads(raw_message)
+
+                def _run_message_listeners():
+                    self.run_message_listeners(message)
+
+                self.message_workers.submit(_run_message_listeners)
+        except Empty:
+            pass
+
+    def process_messages(self) -> None:
+        while not self.closed:
+            try:
+                self.process_message()
+            except Exception as e:
+                self.logger.exception(f"Failed to process a message: {e}")
+
+    def run_message_listeners(self, message: dict) -> None:
+        type = message.get("type")
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing started (type: {type})")
+        try:
+            for listener in self.message_listeners:
+                try:
+                    listener(self, message)
+                except Exception as e:
+                    self.logger.exception(f"Failed to run a message listener: {e}")
+        except Exception as e:
+            self.logger.exception(f"Failed to run message listeners: {e}")
+        finally:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"Message processing completed (type: {type})")
+
+    # --------------------------------------------------------------
+    # Internals
+    # --------------------------------------------------------------
+
+    def session_id(self) -> Optional[str]:
+        if self.current_session is not None:
+            return self.current_session.session_id
+        return None
+
+    def run_all_message_listeners(self, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {message})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(message)
+
+    def run_all_error_listeners(self, error: Exception):
+        self.logger.exception(
+            f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+        )
+        for listener in self.on_error_listeners:
+            listener(error)
+
+    def run_all_close_listeners(self, code: int, reason: Optional[str] = None):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Going to reconnect... " f"(session id: {self.session_id()})")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(code, reason)
+
+    def _run_current_session(self):
+        if self.current_session is not None and self.current_session.is_active():
+            session_id = self.session_id()
+            try:
+                self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})")
+                self.current_session_state.terminated = False
+                self.current_session.run_until_completion(self.current_session_state)
+                self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})")
+            except Exception as e:
+                self.logger.exception(
+                    "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})"
+                )
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                self.current_session.check_state()
+
+                if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()):
+                    self.logger.info(
+                        "The session seems to be already closed. Going to reconnect... " f"(session id: {self.session_id()})"
+                    )
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(session id: {self.session_id()}, error: {type(e).__name__}, message: {e})"
+                )
+
+
+

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var closed :Β bool
+
+

The type of the None singleton.

+
+
var connect_operation_lock :Β _thread.lock
+
+

The type of the None singleton.

+
+
var current_session :Β ConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_state :Β ConnectionStateΒ |Β None
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var message_listeners :Β List[Callable[[RTMClient,Β dict],Β None]]
+
+

The type of the None singleton.

+
+
var message_processor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var message_queue :Β queue.Queue
+
+

The type of the None singleton.

+
+
var message_workers :Β concurrent.futures.thread.ThreadPoolExecutor
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[int,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[str],Β None]]
+
+

The type of the None singleton.

+
+
var ping_interval :Β int
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var web_client :Β WebClient
+
+

The type of the None singleton.

+
+
var wss_uri :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) ‑>Β None +
+
+
+ +Expand source code + +
def close(self) -> None:
+    """
+    Closes this instance and cleans up underlying resources.
+    After calling this method, this instance is no longer usable.
+    """
+    self.closed = True
+    self.disconnect()
+    self.current_session.close()
+
+

Closes this instance and cleans up underlying resources. +After calling this method, this instance is no longer usable.

+
+
+def connect(self) +
+
+
+ +Expand source code + +
def connect(self):
+    """Starts talking to the RTM server through a WebSocket connection"""
+    if self.bot_id is None:
+        self.bot_id = self.web_client.auth_test()["bot_id"]
+
+    old_session: Optional[Connection] = self.current_session
+    old_current_session_state: ConnectionState = self.current_session_state
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    current_session = Connection(
+        url=self.wss_uri,
+        logger=self.logger,
+        ping_interval=self.ping_interval,
+        trace_enabled=self.trace_enabled,
+        all_message_trace_enabled=self.all_message_trace_enabled,
+        ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+        receive_buffer_size=1024,
+        proxy=self.proxy,
+        on_message_listener=self.run_all_message_listeners,
+        on_error_listener=self.run_all_error_listeners,
+        on_close_listener=self.run_all_close_listeners,
+        connection_type_name="RTM",
+    )
+    current_session.connect()
+
+    if old_current_session_state is not None:
+        old_current_session_state.terminated = True
+    if old_session is not None:
+        old_session.close()
+
+    self.current_session = current_session
+    self.current_session_state = ConnectionState()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+

Starts talking to the RTM server through a WebSocket connection

+
+
+def connect_to_new_endpoint(self, force:Β boolΒ =Β False) +
+
+
+ +Expand source code + +
def connect_to_new_endpoint(self, force: bool = False):
+    """Acquires a new WSS URL and tries to connect to the endpoint."""
+    with self.connect_operation_lock:
+        if force or not self.is_connected():
+            self.logger.info("Connecting to a new endpoint...")
+            self.wss_uri = self.issue_new_wss_url()
+            self.connect()
+            self.logger.info("Connected to a new endpoint...")
+
+

Acquires a new WSS URL and tries to connect to the endpoint.

+
+
+def disconnect(self) +
+
+
+ +Expand source code + +
def disconnect(self):
+    """Disconnects the current session."""
+    self.current_session.disconnect()
+
+

Disconnects the current session.

+
+
+def enqueue_message(self, message:Β str) +
+
+
+ +Expand source code + +
def enqueue_message(self, message: str):
+    self.message_queue.put(message)
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    """Returns True if this client is connected."""
+    return self.current_session is not None and self.current_session.is_active()
+
+

Returns True if this client is connected.

+
+
+def issue_new_wss_url(self) ‑>Β str +
+
+
+ +Expand source code + +
def issue_new_wss_url(self) -> str:
+    """Acquires a new WSS URL using rtm.connect API method"""
+    try:
+        api_response = self.web_client.rtm_connect()
+        return api_response["url"]
+    except SlackApiError as e:
+        if e.response["error"] == "ratelimited":
+            delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+            self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+            time.sleep(delay)
+            # Retry to issue a new WSS URL
+            return self.issue_new_wss_url()
+        else:
+            # other errors
+            self.logger.error(f"Failed to retrieve WSS URL: {e}")
+            raise e
+
+

Acquires a new WSS URL using rtm.connect API method

+
+
+def on(self, event_type:Β str) ‑>Β Callable +
+
+
+ +Expand source code + +
def on(self, event_type: str) -> Callable:
+    """Registers a new event listener.
+
+    Args:
+        event_type: str representing an event's type (e.g., message, reaction_added)
+    """
+
+    def __call__(*args, **kwargs):
+        func = args[0]
+        if func is not None:
+            if isinstance(func, Callable):
+                name = (
+                    func.__name__
+                    if hasattr(func, "__name__")
+                    else f"{func.__class__.__module__}.{func.__class__.__name__}"
+                )
+                inspect_result: inspect.FullArgSpec = inspect.getfullargspec(func)
+                if inspect_result is not None and len(inspect_result.args) != 2:
+                    actual_args = ", ".join(inspect_result.args)
+                    error = f"The listener '{name}' must accept two args: client, event (actual: {actual_args})"
+                    raise SlackClientError(error)
+
+                def new_message_listener(_self, event: dict):
+                    actual_event_type = event.get("type")
+                    if event.get("bot_id") == self.bot_id:
+                        # SKip the events generated by this bot user
+                        return
+                    # https://github.com/slackapi/python-slack-sdk/issues/533
+                    if event_type == "*" or (actual_event_type is not None and actual_event_type == event_type):
+                        func(_self, event)
+
+                self.message_listeners.append(new_message_listener)
+            else:
+                error = f"The listener '{func}' is not a Callable (actual: {type(func).__name__})"
+                raise SlackClientError(error)
+        # Not to cause modification to the decorated method
+        return func
+
+    return __call__
+
+

Registers a new event listener.

+

Args

+
+
event_type
+
str representing an event's type (e.g., message, reaction_added)
+
+
+
+def process_message(self) +
+
+
+ +Expand source code + +
def process_message(self):
+    try:
+        raw_message = self.message_queue.get(timeout=1)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+        if raw_message is not None:
+            message: dict = {}
+            if raw_message.startswith("{"):
+                message = json.loads(raw_message)
+
+            def _run_message_listeners():
+                self.run_message_listeners(message)
+
+            self.message_workers.submit(_run_message_listeners)
+    except Empty:
+        pass
+
+
+
+
+def process_messages(self) ‑>Β None +
+
+
+ +Expand source code + +
def process_messages(self) -> None:
+    while not self.closed:
+        try:
+            self.process_message()
+        except Exception as e:
+            self.logger.exception(f"Failed to process a message: {e}")
+
+
+
+
+def run_all_close_listeners(self, code:Β int, reason:Β strΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
def run_all_close_listeners(self, code: int, reason: Optional[str] = None):
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+    if self.auto_reconnect_enabled:
+        self.logger.info("Received CLOSE event. Going to reconnect... " f"(session id: {self.session_id()})")
+        self.connect_to_new_endpoint()
+    for listener in self.on_close_listeners:
+        listener(code, reason)
+
+
+
+
+def run_all_error_listeners(self, error:Β Exception) +
+
+
+ +Expand source code + +
def run_all_error_listeners(self, error: Exception):
+    self.logger.exception(
+        f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+    )
+    for listener in self.on_error_listeners:
+        listener(error)
+
+
+
+
+def run_all_message_listeners(self, message:Β str) +
+
+
+ +Expand source code + +
def run_all_message_listeners(self, message: str):
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"on_message invoked: (message: {message})")
+    self.enqueue_message(message)
+    for listener in self.on_message_listeners:
+        listener(message)
+
+
+
+
+def run_message_listeners(self, message:Β dict) ‑>Β None +
+
+
+ +Expand source code + +
def run_message_listeners(self, message: dict) -> None:
+    type = message.get("type")
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Message processing started (type: {type})")
+    try:
+        for listener in self.message_listeners:
+            try:
+                listener(self, message)
+            except Exception as e:
+                self.logger.exception(f"Failed to run a message listener: {e}")
+    except Exception as e:
+        self.logger.exception(f"Failed to run message listeners: {e}")
+    finally:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing completed (type: {type})")
+
+
+
+
+def send(self, payload:Β dictΒ |Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send(self, payload: Union[dict, str]) -> None:
+    if payload is None:
+        return
+    if self.current_session is None or not self.current_session.is_active():
+        raise SlackClientError("The RTM client is not connected to the Slack servers")
+    if isinstance(payload, str):
+        self.current_session.send(payload)
+    else:
+        self.current_session.send(json.dumps(payload))
+
+
+
+
+def session_id(self) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def session_id(self) -> Optional[str]:
+    if self.current_session is not None:
+        return self.current_session.session_id
+    return None
+
+
+
+
+def start(self) ‑>Β None +
+
+
+ +Expand source code + +
def start(self) -> None:
+    """Establishes an RTM connection and blocks the current thread."""
+    self.connect()
+    Event().wait()
+
+

Establishes an RTM connection and blocks the current thread.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/rtm_v2/index.html b/docs/reference/rtm_v2/index.html new file mode 100644 index 000000000..5d65bdc74 --- /dev/null +++ b/docs/reference/rtm_v2/index.html @@ -0,0 +1,991 @@ + + + + + + +slack_sdk.rtm_v2 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.rtm_v2

+
+
+

A Python module for interacting with Slack's RTM API.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class RTMClient +(*,
token:Β strΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
timeout:Β intΒ =Β 30,
base_url:Β strΒ =Β 'https://slack.com/api/',
headers:Β dictΒ |Β NoneΒ =Β None,
ping_interval:Β intΒ =Β 5,
concurrency:Β intΒ =Β 10,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[int,Β strΒ |Β None],Β None]]Β |Β NoneΒ =Β None,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False)
+
+
+
+ +Expand source code + +
class RTMClient:
+    token: Optional[str]
+    bot_id: Optional[str]
+    default_auto_reconnect_enabled: bool
+    auto_reconnect_enabled: bool
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    timeout: int
+    base_url: str
+    ping_interval: int
+    logger: Logger
+    web_client: WebClient
+
+    current_session: Optional[Connection]
+    current_session_state: Optional[ConnectionState]
+    wss_uri: Optional[str]
+
+    message_queue: Queue
+    message_listeners: List[Callable[["RTMClient", dict], None]]
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    closed: bool
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[str], None]]
+    on_error_listeners: List[Callable[[Exception], None]]
+    on_close_listeners: List[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        *,
+        token: Optional[str] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        timeout: int = 30,
+        base_url: str = WebClient.BASE_URL,
+        headers: Optional[dict] = None,
+        ping_interval: int = 5,
+        concurrency: int = 10,
+        logger: Optional[logging.Logger] = None,
+        on_message_listeners: Optional[List[Callable[[str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+    ):
+        self.token = token.strip() if token is not None else None
+        self.bot_id = None
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        # You may want temporarily turn off the auto_reconnect as necessary
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.ssl = ssl
+        self.proxy = proxy
+        self.timeout = timeout
+        self.base_url = base_url
+        self.headers = headers
+        self.ping_interval = ping_interval
+        self.logger = logger or logging.getLogger(__name__)
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+        self.web_client = web_client or WebClient(
+            token=self.token,
+            base_url=self.base_url,
+            timeout=self.timeout,
+            ssl=self.ssl,
+            proxy=self.proxy,
+            headers=self.headers,
+            logger=logger,
+        )
+
+        self.on_message_listeners = on_message_listeners or []
+
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+
+        self.message_queue = Queue()
+
+        def goodbye_listener(_self, event: dict):
+            if event.get("type") == "goodbye":
+                message = "Got a goodbye message. Reconnecting to the server ..."
+                self.logger.info(message)
+                self.connect_to_new_endpoint(force=True)
+
+        self.message_listeners = [goodbye_listener]
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_state = ConnectionState()
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
+        self.wss_uri = None
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(
+            self._monitor_current_session,
+            self.ping_interval,
+        )
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+    # --------------------------------------------------------------
+    # Decorator to register listeners
+    # --------------------------------------------------------------
+
+    def on(self, event_type: str) -> Callable:
+        """Registers a new event listener.
+
+        Args:
+            event_type: str representing an event's type (e.g., message, reaction_added)
+        """
+
+        def __call__(*args, **kwargs):
+            func = args[0]
+            if func is not None:
+                if isinstance(func, Callable):
+                    name = (
+                        func.__name__
+                        if hasattr(func, "__name__")
+                        else f"{func.__class__.__module__}.{func.__class__.__name__}"
+                    )
+                    inspect_result: inspect.FullArgSpec = inspect.getfullargspec(func)
+                    if inspect_result is not None and len(inspect_result.args) != 2:
+                        actual_args = ", ".join(inspect_result.args)
+                        error = f"The listener '{name}' must accept two args: client, event (actual: {actual_args})"
+                        raise SlackClientError(error)
+
+                    def new_message_listener(_self, event: dict):
+                        actual_event_type = event.get("type")
+                        if event.get("bot_id") == self.bot_id:
+                            # SKip the events generated by this bot user
+                            return
+                        # https://github.com/slackapi/python-slack-sdk/issues/533
+                        if event_type == "*" or (actual_event_type is not None and actual_event_type == event_type):
+                            func(_self, event)
+
+                    self.message_listeners.append(new_message_listener)
+                else:
+                    error = f"The listener '{func}' is not a Callable (actual: {type(func).__name__})"
+                    raise SlackClientError(error)
+            # Not to cause modification to the decorated method
+            return func
+
+        return __call__
+
+    # --------------------------------------------------------------
+    # Connections
+    # --------------------------------------------------------------
+
+    def is_connected(self) -> bool:
+        """Returns True if this client is connected."""
+        return self.current_session is not None and self.current_session.is_active()
+
+    def issue_new_wss_url(self) -> str:
+        """Acquires a new WSS URL using rtm.connect API method"""
+        try:
+            api_response = self.web_client.rtm_connect()
+            return api_response["url"]
+        except SlackApiError as e:
+            if e.response["error"] == "ratelimited":
+                delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+                self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+                time.sleep(delay)
+                # Retry to issue a new WSS URL
+                return self.issue_new_wss_url()
+            else:
+                # other errors
+                self.logger.error(f"Failed to retrieve WSS URL: {e}")
+                raise e
+
+    def connect_to_new_endpoint(self, force: bool = False):
+        """Acquires a new WSS URL and tries to connect to the endpoint."""
+        with self.connect_operation_lock:
+            if force or not self.is_connected():
+                self.logger.info("Connecting to a new endpoint...")
+                self.wss_uri = self.issue_new_wss_url()
+                self.connect()
+                self.logger.info("Connected to a new endpoint...")
+
+    def connect(self):
+        """Starts talking to the RTM server through a WebSocket connection"""
+        if self.bot_id is None:
+            self.bot_id = self.web_client.auth_test()["bot_id"]
+
+        old_session: Optional[Connection] = self.current_session
+        old_current_session_state: ConnectionState = self.current_session_state
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        current_session = Connection(
+            url=self.wss_uri,
+            logger=self.logger,
+            ping_interval=self.ping_interval,
+            trace_enabled=self.trace_enabled,
+            all_message_trace_enabled=self.all_message_trace_enabled,
+            ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+            receive_buffer_size=1024,
+            proxy=self.proxy,
+            on_message_listener=self.run_all_message_listeners,
+            on_error_listener=self.run_all_error_listeners,
+            on_close_listener=self.run_all_close_listeners,
+            connection_type_name="RTM",
+        )
+        current_session.connect()
+
+        if old_current_session_state is not None:
+            old_current_session_state.terminated = True
+        if old_session is not None:
+            old_session.close()
+
+        self.current_session = current_session
+        self.current_session_state = ConnectionState()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+    def disconnect(self):
+        """Disconnects the current session."""
+        self.current_session.disconnect()
+
+    def close(self) -> None:
+        """
+        Closes this instance and cleans up underlying resources.
+        After calling this method, this instance is no longer usable.
+        """
+        self.closed = True
+        self.disconnect()
+        self.current_session.close()
+
+    def start(self) -> None:
+        """Establishes an RTM connection and blocks the current thread."""
+        self.connect()
+        Event().wait()
+
+    def send(self, payload: Union[dict, str]) -> None:
+        if payload is None:
+            return
+        if self.current_session is None or not self.current_session.is_active():
+            raise SlackClientError("The RTM client is not connected to the Slack servers")
+        if isinstance(payload, str):
+            self.current_session.send(payload)
+        else:
+            self.current_session.send(json.dumps(payload))
+
+    # --------------------------------------------------------------
+    # WS Message Processor
+    # --------------------------------------------------------------
+
+    def enqueue_message(self, message: str):
+        self.message_queue.put(message)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+    def process_message(self):
+        try:
+            raw_message = self.message_queue.get(timeout=1)
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+            if raw_message is not None:
+                message: dict = {}
+                if raw_message.startswith("{"):
+                    message = json.loads(raw_message)
+
+                def _run_message_listeners():
+                    self.run_message_listeners(message)
+
+                self.message_workers.submit(_run_message_listeners)
+        except Empty:
+            pass
+
+    def process_messages(self) -> None:
+        while not self.closed:
+            try:
+                self.process_message()
+            except Exception as e:
+                self.logger.exception(f"Failed to process a message: {e}")
+
+    def run_message_listeners(self, message: dict) -> None:
+        type = message.get("type")
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing started (type: {type})")
+        try:
+            for listener in self.message_listeners:
+                try:
+                    listener(self, message)
+                except Exception as e:
+                    self.logger.exception(f"Failed to run a message listener: {e}")
+        except Exception as e:
+            self.logger.exception(f"Failed to run message listeners: {e}")
+        finally:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"Message processing completed (type: {type})")
+
+    # --------------------------------------------------------------
+    # Internals
+    # --------------------------------------------------------------
+
+    def session_id(self) -> Optional[str]:
+        if self.current_session is not None:
+            return self.current_session.session_id
+        return None
+
+    def run_all_message_listeners(self, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {message})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(message)
+
+    def run_all_error_listeners(self, error: Exception):
+        self.logger.exception(
+            f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+        )
+        for listener in self.on_error_listeners:
+            listener(error)
+
+    def run_all_close_listeners(self, code: int, reason: Optional[str] = None):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Going to reconnect... " f"(session id: {self.session_id()})")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(code, reason)
+
+    def _run_current_session(self):
+        if self.current_session is not None and self.current_session.is_active():
+            session_id = self.session_id()
+            try:
+                self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})")
+                self.current_session_state.terminated = False
+                self.current_session.run_until_completion(self.current_session_state)
+                self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})")
+            except Exception as e:
+                self.logger.exception(
+                    "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})"
+                )
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                self.current_session.check_state()
+
+                if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()):
+                    self.logger.info(
+                        "The session seems to be already closed. Going to reconnect... " f"(session id: {self.session_id()})"
+                    )
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(session id: {self.session_id()}, error: {type(e).__name__}, message: {e})"
+                )
+
+
+

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var bot_id :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var closed :Β bool
+
+

The type of the None singleton.

+
+
var connect_operation_lock :Β _thread.lock
+
+

The type of the None singleton.

+
+
var current_session :Β ConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_state :Β ConnectionStateΒ |Β None
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var message_listeners :Β List[Callable[[RTMClient,Β dict],Β None]]
+
+

The type of the None singleton.

+
+
var message_processor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var message_queue :Β queue.Queue
+
+

The type of the None singleton.

+
+
var message_workers :Β concurrent.futures.thread.ThreadPoolExecutor
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[int,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[str],Β None]]
+
+

The type of the None singleton.

+
+
var ping_interval :Β int
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var web_client :Β WebClient
+
+

The type of the None singleton.

+
+
var wss_uri :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) ‑>Β None +
+
+
+ +Expand source code + +
def close(self) -> None:
+    """
+    Closes this instance and cleans up underlying resources.
+    After calling this method, this instance is no longer usable.
+    """
+    self.closed = True
+    self.disconnect()
+    self.current_session.close()
+
+

Closes this instance and cleans up underlying resources. +After calling this method, this instance is no longer usable.

+
+
+def connect(self) +
+
+
+ +Expand source code + +
def connect(self):
+    """Starts talking to the RTM server through a WebSocket connection"""
+    if self.bot_id is None:
+        self.bot_id = self.web_client.auth_test()["bot_id"]
+
+    old_session: Optional[Connection] = self.current_session
+    old_current_session_state: ConnectionState = self.current_session_state
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    current_session = Connection(
+        url=self.wss_uri,
+        logger=self.logger,
+        ping_interval=self.ping_interval,
+        trace_enabled=self.trace_enabled,
+        all_message_trace_enabled=self.all_message_trace_enabled,
+        ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+        receive_buffer_size=1024,
+        proxy=self.proxy,
+        on_message_listener=self.run_all_message_listeners,
+        on_error_listener=self.run_all_error_listeners,
+        on_close_listener=self.run_all_close_listeners,
+        connection_type_name="RTM",
+    )
+    current_session.connect()
+
+    if old_current_session_state is not None:
+        old_current_session_state.terminated = True
+    if old_session is not None:
+        old_session.close()
+
+    self.current_session = current_session
+    self.current_session_state = ConnectionState()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+

Starts talking to the RTM server through a WebSocket connection

+
+
+def connect_to_new_endpoint(self, force:Β boolΒ =Β False) +
+
+
+ +Expand source code + +
def connect_to_new_endpoint(self, force: bool = False):
+    """Acquires a new WSS URL and tries to connect to the endpoint."""
+    with self.connect_operation_lock:
+        if force or not self.is_connected():
+            self.logger.info("Connecting to a new endpoint...")
+            self.wss_uri = self.issue_new_wss_url()
+            self.connect()
+            self.logger.info("Connected to a new endpoint...")
+
+

Acquires a new WSS URL and tries to connect to the endpoint.

+
+
+def disconnect(self) +
+
+
+ +Expand source code + +
def disconnect(self):
+    """Disconnects the current session."""
+    self.current_session.disconnect()
+
+

Disconnects the current session.

+
+
+def enqueue_message(self, message:Β str) +
+
+
+ +Expand source code + +
def enqueue_message(self, message: str):
+    self.message_queue.put(message)
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    """Returns True if this client is connected."""
+    return self.current_session is not None and self.current_session.is_active()
+
+

Returns True if this client is connected.

+
+
+def issue_new_wss_url(self) ‑>Β str +
+
+
+ +Expand source code + +
def issue_new_wss_url(self) -> str:
+    """Acquires a new WSS URL using rtm.connect API method"""
+    try:
+        api_response = self.web_client.rtm_connect()
+        return api_response["url"]
+    except SlackApiError as e:
+        if e.response["error"] == "ratelimited":
+            delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+            self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+            time.sleep(delay)
+            # Retry to issue a new WSS URL
+            return self.issue_new_wss_url()
+        else:
+            # other errors
+            self.logger.error(f"Failed to retrieve WSS URL: {e}")
+            raise e
+
+

Acquires a new WSS URL using rtm.connect API method

+
+
+def on(self, event_type:Β str) ‑>Β Callable +
+
+
+ +Expand source code + +
def on(self, event_type: str) -> Callable:
+    """Registers a new event listener.
+
+    Args:
+        event_type: str representing an event's type (e.g., message, reaction_added)
+    """
+
+    def __call__(*args, **kwargs):
+        func = args[0]
+        if func is not None:
+            if isinstance(func, Callable):
+                name = (
+                    func.__name__
+                    if hasattr(func, "__name__")
+                    else f"{func.__class__.__module__}.{func.__class__.__name__}"
+                )
+                inspect_result: inspect.FullArgSpec = inspect.getfullargspec(func)
+                if inspect_result is not None and len(inspect_result.args) != 2:
+                    actual_args = ", ".join(inspect_result.args)
+                    error = f"The listener '{name}' must accept two args: client, event (actual: {actual_args})"
+                    raise SlackClientError(error)
+
+                def new_message_listener(_self, event: dict):
+                    actual_event_type = event.get("type")
+                    if event.get("bot_id") == self.bot_id:
+                        # SKip the events generated by this bot user
+                        return
+                    # https://github.com/slackapi/python-slack-sdk/issues/533
+                    if event_type == "*" or (actual_event_type is not None and actual_event_type == event_type):
+                        func(_self, event)
+
+                self.message_listeners.append(new_message_listener)
+            else:
+                error = f"The listener '{func}' is not a Callable (actual: {type(func).__name__})"
+                raise SlackClientError(error)
+        # Not to cause modification to the decorated method
+        return func
+
+    return __call__
+
+

Registers a new event listener.

+

Args

+
+
event_type
+
str representing an event's type (e.g., message, reaction_added)
+
+
+
+def process_message(self) +
+
+
+ +Expand source code + +
def process_message(self):
+    try:
+        raw_message = self.message_queue.get(timeout=1)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+        if raw_message is not None:
+            message: dict = {}
+            if raw_message.startswith("{"):
+                message = json.loads(raw_message)
+
+            def _run_message_listeners():
+                self.run_message_listeners(message)
+
+            self.message_workers.submit(_run_message_listeners)
+    except Empty:
+        pass
+
+
+
+
+def process_messages(self) ‑>Β None +
+
+
+ +Expand source code + +
def process_messages(self) -> None:
+    while not self.closed:
+        try:
+            self.process_message()
+        except Exception as e:
+            self.logger.exception(f"Failed to process a message: {e}")
+
+
+
+
+def run_all_close_listeners(self, code:Β int, reason:Β strΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
def run_all_close_listeners(self, code: int, reason: Optional[str] = None):
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+    if self.auto_reconnect_enabled:
+        self.logger.info("Received CLOSE event. Going to reconnect... " f"(session id: {self.session_id()})")
+        self.connect_to_new_endpoint()
+    for listener in self.on_close_listeners:
+        listener(code, reason)
+
+
+
+
+def run_all_error_listeners(self, error:Β Exception) +
+
+
+ +Expand source code + +
def run_all_error_listeners(self, error: Exception):
+    self.logger.exception(
+        f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+    )
+    for listener in self.on_error_listeners:
+        listener(error)
+
+
+
+
+def run_all_message_listeners(self, message:Β str) +
+
+
+ +Expand source code + +
def run_all_message_listeners(self, message: str):
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"on_message invoked: (message: {message})")
+    self.enqueue_message(message)
+    for listener in self.on_message_listeners:
+        listener(message)
+
+
+
+
+def run_message_listeners(self, message:Β dict) ‑>Β None +
+
+
+ +Expand source code + +
def run_message_listeners(self, message: dict) -> None:
+    type = message.get("type")
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Message processing started (type: {type})")
+    try:
+        for listener in self.message_listeners:
+            try:
+                listener(self, message)
+            except Exception as e:
+                self.logger.exception(f"Failed to run a message listener: {e}")
+    except Exception as e:
+        self.logger.exception(f"Failed to run message listeners: {e}")
+    finally:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing completed (type: {type})")
+
+
+
+
+def send(self, payload:Β dictΒ |Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send(self, payload: Union[dict, str]) -> None:
+    if payload is None:
+        return
+    if self.current_session is None or not self.current_session.is_active():
+        raise SlackClientError("The RTM client is not connected to the Slack servers")
+    if isinstance(payload, str):
+        self.current_session.send(payload)
+    else:
+        self.current_session.send(json.dumps(payload))
+
+
+
+
+def session_id(self) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def session_id(self) -> Optional[str]:
+    if self.current_session is not None:
+        return self.current_session.session_id
+    return None
+
+
+
+
+def start(self) ‑>Β None +
+
+
+ +Expand source code + +
def start(self) -> None:
+    """Establishes an RTM connection and blocks the current thread."""
+    self.connect()
+    Event().wait()
+
+

Establishes an RTM connection and blocks the current thread.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/async_client.html b/docs/reference/scim/async_client.html new file mode 100644 index 000000000..c91441c29 --- /dev/null +++ b/docs/reference/scim/async_client.html @@ -0,0 +1,838 @@ + + + + + + +slack_sdk.scim.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.async_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSCIMClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/scim/v1/',
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
auth:Β aiohttp.helpers.BasicAuthΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncSCIMClient:
+    BASE_URL = "https://api.slack.com/scim/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    session: Optional[ClientSession]
+    trust_env_in_session: bool
+    auth: Optional[BasicAuth]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[AsyncRetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        session: Optional[ClientSession] = None,
+        trust_env_in_session: bool = False,
+        auth: Optional[BasicAuth] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        """API client for SCIM API
+        See https://docs.slack.dev/admins/scim-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            session: `aiohttp.ClientSession` instance
+            trust_env_in_session: True/False for `aiohttp.ClientSession`
+            auth: Basic auth info for `aiohttp.ClientSession`
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.session = session
+        self.trust_env_in_session = trust_env_in_session
+        self.auth = auth
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # Users
+    # -------------------------
+
+    async def search_users(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchUsersResponse:
+        return SearchUsersResponse(
+            await self.api_call(
+                http_verb="GET",
+                path="Users",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    async def read_user(self, id: str) -> ReadUserResponse:
+        return ReadUserResponse(await self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+    async def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+        return UserCreateResponse(
+            await self.api_call(
+                http_verb="POST",
+                path="Users",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    async def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+        return UserPatchResponse(
+            await self.api_call(
+                http_verb="PATCH",
+                path=f"Users/{quote(id)}",
+                body_params=(
+                    partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+                ),
+            )
+        )
+
+    async def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+        user_id = user.id if isinstance(user, User) else user["id"]
+        return UserUpdateResponse(
+            await self.api_call(
+                http_verb="PUT",
+                path=f"Users/{quote(user_id)}",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    async def delete_user(self, id: str) -> UserDeleteResponse:
+        return UserDeleteResponse(
+            await self.api_call(
+                http_verb="DELETE",
+                path=f"Users/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+    # Groups
+    # -------------------------
+
+    async def search_groups(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchGroupsResponse:
+        return SearchGroupsResponse(
+            await self.api_call(
+                http_verb="GET",
+                path="Groups",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    async def read_group(self, id: str) -> ReadGroupResponse:
+        return ReadGroupResponse(await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+    async def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+        return GroupCreateResponse(
+            await self.api_call(
+                http_verb="POST",
+                path="Groups",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    async def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+        return GroupPatchResponse(
+            await self.api_call(
+                http_verb="PATCH",
+                path=f"Groups/{quote(id)}",
+                body_params=(
+                    partial_group.to_dict()
+                    if isinstance(partial_group, Group)
+                    else _to_dict_without_not_given(partial_group)
+                ),
+            )
+        )
+
+    async def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+        group_id = group.id if isinstance(group, Group) else group["id"]
+        return GroupUpdateResponse(
+            await self.api_call(
+                http_verb="PUT",
+                path=f"Groups/{quote(group_id)}",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    async def delete_group(self, id: str) -> GroupDeleteResponse:
+        return GroupDeleteResponse(
+            await self.api_call(
+                http_verb="DELETE",
+                path=f"Groups/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+
+    async def api_call(
+        self,
+        *,
+        http_verb: str,
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> SCIMResponse:
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+        return await self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body_params=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    async def _perform_http_request(
+        self,
+        *,
+        http_verb: str,
+        url: str,
+        body_params: Optional[Dict[str, Any]],
+        headers: Dict[str, str],
+    ) -> SCIMResponse:
+        if body_params is not None:
+            if body_params.get("schemas") is None:
+                body_params["schemas"] = ["urn:scim:schemas:core:1.0"]
+            body_params = json.dumps(body_params)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        session: Optional[ClientSession] = None
+        use_running_session = self.session and not self.session.closed
+        if use_running_session:
+            session = self.session
+        else:
+            session = aiohttp.ClientSession(
+                timeout=aiohttp.ClientTimeout(total=self.timeout),
+                auth=self.auth,
+                trust_env=self.trust_env_in_session,
+            )
+
+        last_error: Optional[Exception] = None
+        resp: Optional[SCIMResponse] = None
+        try:
+            request_kwargs = {
+                "headers": headers,
+                "data": body_params,
+                "ssl": self.ssl,
+                "proxy": self.proxy,
+            }
+            retry_request = RetryHttpRequest(
+                method=http_verb,
+                url=url,
+                headers=headers,
+                body_params=body_params,
+            )
+
+            retry_state = RetryState()
+            counter_for_safety = 0
+            while counter_for_safety < 100:
+                counter_for_safety += 1
+                # If this is a retry, the next try started here. We can reset the flag.
+                retry_state.next_attempt_requested = False
+                retry_response: Optional[RetryHttpResponse] = None
+                response_body = ""
+
+                if self.logger.level <= logging.DEBUG:
+                    headers_for_logging = {
+                        k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()
+                    }
+                    self.logger.debug(
+                        f"Sending a request - url: {url}, params: {body_params}, headers: {headers_for_logging}"
+                    )
+
+                try:
+                    async with session.request(http_verb, url, **request_kwargs) as res:
+                        try:
+                            response_body = await res.text()
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,
+                                data=response_body.encode("utf-8") if response_body is not None else None,
+                            )
+                        except aiohttp.ContentTypeError:
+                            self.logger.debug(f"No response data returned from the following API call: {url}.")
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,
+                            )
+
+                        if res.status == 429:
+                            for handler in self.retry_handlers:
+                                if await handler.can_retry_async(
+                                    state=retry_state,
+                                    request=retry_request,
+                                    response=retry_response,
+                                ):
+                                    if self.logger.level <= logging.DEBUG:
+                                        self.logger.info(
+                                            f"A retry handler found: {type(handler).__name__} "
+                                            f"for {http_verb} {url} - rate_limited"
+                                        )
+                                    await handler.prepare_for_next_attempt_async(
+                                        state=retry_state,
+                                        request=retry_request,
+                                        response=retry_response,
+                                    )
+                                    break
+
+                        if retry_state.next_attempt_requested is False:
+                            resp = SCIMResponse(
+                                url=url,
+                                status_code=res.status,
+                                raw_body=response_body,
+                                headers=res.headers,
+                            )
+                            _debug_log_response(self.logger, resp)
+                            return resp
+
+                except Exception as e:
+                    last_error = e
+                    for handler in self.retry_handlers:
+                        if await handler.can_retry_async(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        ):
+                            if self.logger.level <= logging.DEBUG:
+                                self.logger.info(
+                                    f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}"
+                                )
+                            await handler.prepare_for_next_attempt_async(
+                                state=retry_state,
+                                request=retry_request,
+                                response=retry_response,
+                                error=e,
+                            )
+                            break
+
+                    if retry_state.next_attempt_requested is False:
+                        raise last_error
+
+            if resp is not None:
+                return resp
+            raise last_error
+
+        finally:
+            if not use_running_session:
+                await session.close()
+
+        return resp
+
+

API client for SCIM API +See https://docs.slack.dev/admins/scim-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
session
+
aiohttp.ClientSession instance
+
trust_env_in_session
+
True/False for aiohttp.ClientSession
+
auth
+
Basic auth info for aiohttp.ClientSession
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var auth :Β aiohttp.helpers.BasicAuthΒ |Β None
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]
+
+

The type of the None singleton.

+
+
var session :Β aiohttp.client.ClientSessionΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
var trust_env_in_session :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def api_call(self,
*,
http_verb:Β str,
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β SCIMResponse
+
+
+
+ +Expand source code + +
async def api_call(
+    self,
+    *,
+    http_verb: str,
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> SCIMResponse:
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+    return await self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body_params=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+
+
+
+async def create_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupCreateResponse
+
+
+
+ +Expand source code + +
async def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+    return GroupCreateResponse(
+        await self.api_call(
+            http_verb="POST",
+            path="Groups",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+async def create_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserCreateResponse
+
+
+
+ +Expand source code + +
async def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+    return UserCreateResponse(
+        await self.api_call(
+            http_verb="POST",
+            path="Users",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+async def delete_group(self, id:Β str) ‑>Β GroupDeleteResponse +
+
+
+ +Expand source code + +
async def delete_group(self, id: str) -> GroupDeleteResponse:
+    return GroupDeleteResponse(
+        await self.api_call(
+            http_verb="DELETE",
+            path=f"Groups/{quote(id)}",
+        )
+    )
+
+
+
+
+async def delete_user(self, id:Β str) ‑>Β UserDeleteResponse +
+
+
+ +Expand source code + +
async def delete_user(self, id: str) -> UserDeleteResponse:
+    return UserDeleteResponse(
+        await self.api_call(
+            http_verb="DELETE",
+            path=f"Users/{quote(id)}",
+        )
+    )
+
+
+
+
+async def patch_group(self,
id:Β str,
partial_group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupPatchResponse
+
+
+
+ +Expand source code + +
async def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+    return GroupPatchResponse(
+        await self.api_call(
+            http_verb="PATCH",
+            path=f"Groups/{quote(id)}",
+            body_params=(
+                partial_group.to_dict()
+                if isinstance(partial_group, Group)
+                else _to_dict_without_not_given(partial_group)
+            ),
+        )
+    )
+
+
+
+
+async def patch_user(self,
id:Β str,
partial_user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserPatchResponse
+
+
+
+ +Expand source code + +
async def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+    return UserPatchResponse(
+        await self.api_call(
+            http_verb="PATCH",
+            path=f"Users/{quote(id)}",
+            body_params=(
+                partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+            ),
+        )
+    )
+
+
+
+
+async def read_group(self, id:Β str) ‑>Β ReadGroupResponse +
+
+
+ +Expand source code + +
async def read_group(self, id: str) -> ReadGroupResponse:
+    return ReadGroupResponse(await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+
+
+
+async def read_user(self, id:Β str) ‑>Β ReadUserResponse +
+
+
+ +Expand source code + +
async def read_user(self, id: str) -> ReadUserResponse:
+    return ReadUserResponse(await self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+
+
+
+async def search_groups(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchGroupsResponse +
+
+
+ +Expand source code + +
async def search_groups(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchGroupsResponse:
+    return SearchGroupsResponse(
+        await self.api_call(
+            http_verb="GET",
+            path="Groups",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+async def search_users(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchUsersResponse +
+
+
+ +Expand source code + +
async def search_users(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchUsersResponse:
+    return SearchUsersResponse(
+        await self.api_call(
+            http_verb="GET",
+            path="Users",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+async def update_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupUpdateResponse
+
+
+
+ +Expand source code + +
async def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+    group_id = group.id if isinstance(group, Group) else group["id"]
+    return GroupUpdateResponse(
+        await self.api_call(
+            http_verb="PUT",
+            path=f"Groups/{quote(group_id)}",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+async def update_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserUpdateResponse
+
+
+
+ +Expand source code + +
async def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+    user_id = user.id if isinstance(user, User) else user["id"]
+    return UserUpdateResponse(
+        await self.api_call(
+            http_verb="PUT",
+            path=f"Users/{quote(user_id)}",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/index.html b/docs/reference/scim/index.html new file mode 100644 index 000000000..1e6e1e228 --- /dev/null +++ b/docs/reference/scim/index.html @@ -0,0 +1,1572 @@ + + + + + + +slack_sdk.scim API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim

+
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers to manage people across a variety of tools, +including Slack.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/scim for details.

+
+
+

Sub-modules

+
+
slack_sdk.scim.async_client
+
+
+
+
slack_sdk.scim.v1
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers …

+
+
+
+
+
+
+
+
+

Classes

+
+
+class Group +(*,
display_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
members:Β List[GroupMember]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
meta:Β GroupMetaΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
schemas:Β List[str]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class Group:
+    display_name: Union[Optional[str], DefaultArg]
+    id: Union[Optional[str], DefaultArg]
+    members: Union[Optional[List[GroupMember]], DefaultArg]
+    meta: Union[Optional[GroupMeta], DefaultArg]
+    schemas: Union[Optional[List[str]], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        display_name: Union[Optional[str], DefaultArg] = NotGiven,
+        id: Union[Optional[str], DefaultArg] = NotGiven,
+        members: Union[Optional[List[GroupMember]], DefaultArg] = NotGiven,
+        meta: Union[Optional[GroupMeta], DefaultArg] = NotGiven,
+        schemas: Union[Optional[List[str]], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.display_name = display_name
+        self.id = id
+        self.members = (
+            [a if isinstance(a, GroupMember) else GroupMember(**a) for a in members] if _is_iterable(members) else members
+        )
+        self.meta = GroupMeta(**meta) if meta is not None and isinstance(meta, dict) else meta
+        self.schemas = schemas
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+    def __repr__(self):
+        return f"<slack_sdk.scim.{self.__class__.__name__}: {self.to_dict()}>"
+
+
+

Class variables

+
+
var display_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var members :Β List[GroupMember]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var meta :Β GroupMetaΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var schemas :Β List[str]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class ReadGroupResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class ReadGroupResponse(SCIMResponse):
+    group: Group
+
+    @property
+    def group(self) -> Group:
+        return Group(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop group :Β Group
+
+
+ +Expand source code + +
@property
+def group(self) -> Group:
+    return Group(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class ReadUserResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class ReadUserResponse(SCIMResponse):
+    user: User
+
+    @property
+    def user(self) -> User:
+        return User(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop user :Β User
+
+
+ +Expand source code + +
@property
+def user(self) -> User:
+    return User(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class SCIMClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/scim/v1/',
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SCIMClient:
+    BASE_URL = "https://api.slack.com/scim/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for SCIM API
+        See https://docs.slack.dev/admins/scim-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # Users
+    # -------------------------
+
+    def search_users(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchUsersResponse:
+        return SearchUsersResponse(
+            self.api_call(
+                http_verb="GET",
+                path="Users",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    def read_user(self, id: str) -> ReadUserResponse:
+        return ReadUserResponse(self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+    def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+        return UserCreateResponse(
+            self.api_call(
+                http_verb="POST",
+                path="Users",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+        return UserPatchResponse(
+            self.api_call(
+                http_verb="PATCH",
+                path=f"Users/{quote(id)}",
+                body_params=(
+                    partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+                ),
+            )
+        )
+
+    def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+        user_id = user.id if isinstance(user, User) else user["id"]
+        return UserUpdateResponse(
+            self.api_call(
+                http_verb="PUT",
+                path=f"Users/{quote(user_id)}",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    def delete_user(self, id: str) -> UserDeleteResponse:
+        return UserDeleteResponse(
+            self.api_call(
+                http_verb="DELETE",
+                path=f"Users/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+    # Groups
+    # -------------------------
+
+    def search_groups(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchGroupsResponse:
+        return SearchGroupsResponse(
+            self.api_call(
+                http_verb="GET",
+                path="Groups",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    def read_group(self, id: str) -> ReadGroupResponse:
+        return ReadGroupResponse(self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+    def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+        return GroupCreateResponse(
+            self.api_call(
+                http_verb="POST",
+                path="Groups",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+        return GroupPatchResponse(
+            self.api_call(
+                http_verb="PATCH",
+                path=f"Groups/{quote(id)}",
+                body_params=(
+                    partial_group.to_dict()
+                    if isinstance(partial_group, Group)
+                    else _to_dict_without_not_given(partial_group)
+                ),
+            )
+        )
+
+    def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+        group_id = group.id if isinstance(group, Group) else group["id"]
+        return GroupUpdateResponse(
+            self.api_call(
+                http_verb="PUT",
+                path=f"Groups/{quote(group_id)}",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    def delete_group(self, id: str) -> GroupDeleteResponse:
+        return GroupDeleteResponse(
+            self.api_call(
+                http_verb="DELETE",
+                path=f"Groups/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+
+    def api_call(
+        self,
+        *,
+        http_verb: str,
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> SCIMResponse:
+        """Performs a Slack API request and returns the result."""
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+
+        return self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    def _perform_http_request(
+        self,
+        *,
+        http_verb: str = "GET",
+        url: str,
+        body: Optional[Dict[str, Any]] = None,
+        headers: Dict[str, str],
+    ) -> SCIMResponse:
+        if body is not None:
+            if body.get("schemas") is None:
+                body["schemas"] = ["urn:scim:schemas:core:1.0"]
+            body = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()}
+            self.logger.debug(f"Sending a request - {http_verb} url: {url}, body: {body}, headers: {headers_for_logging}")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(
+            method=http_verb,
+            url=url,
+            data=body.encode("utf-8") if body is not None else None,
+            headers=headers,
+        )
+        resp = None
+        last_error = None
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = SCIMResponse(
+                    url=url,
+                    status_code=e.code,
+                    raw_body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error
+
+    def _perform_http_request_internal(self, url: str, req: Request) -> SCIMResponse:
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        # NOTE: BAN-B310 is already checked above
+        http_resp: Optional[HTTPResponse] = None
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = SCIMResponse(
+            url=url,
+            status_code=http_resp.status,
+            raw_body=response_body,
+            headers=http_resp.headers,
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for SCIM API +See https://docs.slack.dev/admins/scim-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def api_call(self,
*,
http_verb:Β str,
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β SCIMResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    *,
+    http_verb: str,
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> SCIMResponse:
+    """Performs a Slack API request and returns the result."""
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+
+    return self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+

Performs a Slack API request and returns the result.

+
+
+def create_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupCreateResponse
+
+
+
+ +Expand source code + +
def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+    return GroupCreateResponse(
+        self.api_call(
+            http_verb="POST",
+            path="Groups",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+def create_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserCreateResponse
+
+
+
+ +Expand source code + +
def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+    return UserCreateResponse(
+        self.api_call(
+            http_verb="POST",
+            path="Users",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+def delete_group(self, id:Β str) ‑>Β GroupDeleteResponse +
+
+
+ +Expand source code + +
def delete_group(self, id: str) -> GroupDeleteResponse:
+    return GroupDeleteResponse(
+        self.api_call(
+            http_verb="DELETE",
+            path=f"Groups/{quote(id)}",
+        )
+    )
+
+
+
+
+def delete_user(self, id:Β str) ‑>Β UserDeleteResponse +
+
+
+ +Expand source code + +
def delete_user(self, id: str) -> UserDeleteResponse:
+    return UserDeleteResponse(
+        self.api_call(
+            http_verb="DELETE",
+            path=f"Users/{quote(id)}",
+        )
+    )
+
+
+
+
+def patch_group(self,
id:Β str,
partial_group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupPatchResponse
+
+
+
+ +Expand source code + +
def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+    return GroupPatchResponse(
+        self.api_call(
+            http_verb="PATCH",
+            path=f"Groups/{quote(id)}",
+            body_params=(
+                partial_group.to_dict()
+                if isinstance(partial_group, Group)
+                else _to_dict_without_not_given(partial_group)
+            ),
+        )
+    )
+
+
+
+
+def patch_user(self,
id:Β str,
partial_user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserPatchResponse
+
+
+
+ +Expand source code + +
def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+    return UserPatchResponse(
+        self.api_call(
+            http_verb="PATCH",
+            path=f"Users/{quote(id)}",
+            body_params=(
+                partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+            ),
+        )
+    )
+
+
+
+
+def read_group(self, id:Β str) ‑>Β ReadGroupResponse +
+
+
+ +Expand source code + +
def read_group(self, id: str) -> ReadGroupResponse:
+    return ReadGroupResponse(self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+
+
+
+def read_user(self, id:Β str) ‑>Β ReadUserResponse +
+
+
+ +Expand source code + +
def read_user(self, id: str) -> ReadUserResponse:
+    return ReadUserResponse(self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+
+
+
+def search_groups(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchGroupsResponse +
+
+
+ +Expand source code + +
def search_groups(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchGroupsResponse:
+    return SearchGroupsResponse(
+        self.api_call(
+            http_verb="GET",
+            path="Groups",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+def search_users(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchUsersResponse +
+
+
+ +Expand source code + +
def search_users(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchUsersResponse:
+    return SearchUsersResponse(
+        self.api_call(
+            http_verb="GET",
+            path="Users",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+def update_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupUpdateResponse
+
+
+
+ +Expand source code + +
def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+    group_id = group.id if isinstance(group, Group) else group["id"]
+    return GroupUpdateResponse(
+        self.api_call(
+            http_verb="PUT",
+            path=f"Groups/{quote(group_id)}",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+def update_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserUpdateResponse
+
+
+
+ +Expand source code + +
def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+    user_id = user.id if isinstance(user, User) else user["id"]
+    return UserUpdateResponse(
+        self.api_call(
+            http_verb="PUT",
+            path=f"Users/{quote(user_id)}",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+
+
+class SCIMResponse +(*, url:Β str, status_code:Β int, raw_body:Β strΒ |Β None, headers:Β dict) +
+
+
+ +Expand source code + +
class SCIMResponse:
+    url: str
+    status_code: int
+    headers: Dict[str, Any]
+    raw_body: Optional[str]
+    body: Optional[Dict[str, Any]]
+    snake_cased_body: Optional[Dict[str, Any]]
+
+    errors: Optional[Errors]
+
+    @property
+    def snake_cased_body(self) -> Optional[Dict[str, Any]]:
+        if self._snake_cased_body is None:
+            self._snake_cased_body = _to_snake_cased(self.body)
+        return self._snake_cased_body
+
+    @property
+    def errors(self) -> Optional[Errors]:
+        errors = self.snake_cased_body.get("errors")
+        if errors is None:
+            return None
+        return Errors(**errors)
+
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        raw_body: Optional[str],
+        headers: dict,
+    ):
+        self.url = url
+        self.status_code = status_code
+        self.headers = headers
+        self.raw_body = raw_body
+        self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None
+        self._snake_cased_body = None  # build this when it's accessed for the first time
+
+    def __repr__(self):
+        dict_value = {}
+        for key, value in vars(self).items():
+            dict_value[key] = value.to_dict() if hasattr(value, "to_dict") else value
+
+        if dict_value:
+            return f"<slack_sdk.scim.v1.{self.__class__.__name__}: {dict_value}>"
+        else:
+            return self.__str__()
+
+
+

Subclasses

+ +

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var raw_body :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop errors :Β ErrorsΒ |Β None
+
+
+ +Expand source code + +
@property
+def errors(self) -> Optional[Errors]:
+    errors = self.snake_cased_body.get("errors")
+    if errors is None:
+        return None
+    return Errors(**errors)
+
+
+
+
prop snake_cased_body :Β Dict[str,Β Any]Β |Β None
+
+
+ +Expand source code + +
@property
+def snake_cased_body(self) -> Optional[Dict[str, Any]]:
+    if self._snake_cased_body is None:
+        self._snake_cased_body = _to_snake_cased(self.body)
+    return self._snake_cased_body
+
+
+
+
+
+
+class SearchGroupsResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class SearchGroupsResponse(SCIMResponse):
+    groups: List[Group]
+
+    @property
+    def groups(self) -> List[Group]:
+        return [Group(**r) for r in self.snake_cased_body.get("resources")]
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop groups :Β List[Group]
+
+
+ +Expand source code + +
@property
+def groups(self) -> List[Group]:
+    return [Group(**r) for r in self.snake_cased_body.get("resources")]
+
+
+
+
+

Inherited members

+ +
+
+class SearchUsersResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class SearchUsersResponse(SCIMResponse):
+    users: List[User]
+
+    @property
+    def users(self) -> List[User]:
+        return [User(**r) for r in self.snake_cased_body.get("resources")]
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop users :Β List[User]
+
+
+ +Expand source code + +
@property
+def users(self) -> List[User]:
+    return [User(**r) for r in self.snake_cased_body.get("resources")]
+
+
+
+
+

Inherited members

+ +
+
+class User +(*,
active:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
addresses:Β List[UserAddressΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
display_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
emails:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
external_id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
groups:Β List[UserGroupΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
meta:Β UserMetaΒ |Β Dict[str,Β Any]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
name:Β UserNameΒ |Β Dict[str,Β Any]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
nick_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
phone_numbers:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
photos:Β List[UserPhotoΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
profile_url:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
roles:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
schemas:Β List[str]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
timezone:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
title:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
user_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class User:
+    active: Union[Optional[bool], DefaultArg]
+    addresses: Union[Optional[List[UserAddress]], DefaultArg]
+    display_name: Union[Optional[str], DefaultArg]
+    emails: Union[Optional[List[TypeAndValue]], DefaultArg]
+    external_id: Union[Optional[str], DefaultArg]
+    groups: Union[Optional[List[UserGroup]], DefaultArg]
+    id: Union[Optional[str], DefaultArg]
+    meta: Union[Optional[UserMeta], DefaultArg]
+    name: Union[Optional[UserName], DefaultArg]
+    nick_name: Union[Optional[str], DefaultArg]
+    phone_numbers: Union[Optional[List[TypeAndValue]], DefaultArg]
+    photos: Union[Optional[List[UserPhoto]], DefaultArg]
+    profile_url: Union[Optional[str], DefaultArg]
+    roles: Union[Optional[List[TypeAndValue]], DefaultArg]
+    schemas: Union[Optional[List[str]], DefaultArg]
+    timezone: Union[Optional[str], DefaultArg]
+    title: Union[Optional[str], DefaultArg]
+    user_name: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        active: Union[Optional[bool], DefaultArg] = NotGiven,
+        addresses: Union[Optional[List[Union[UserAddress, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        display_name: Union[Optional[str], DefaultArg] = NotGiven,
+        emails: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        external_id: Union[Optional[str], DefaultArg] = NotGiven,
+        groups: Union[Optional[List[Union[UserGroup, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        id: Union[Optional[str], DefaultArg] = NotGiven,
+        meta: Union[Optional[Union[UserMeta, Dict[str, Any]]], DefaultArg] = NotGiven,
+        name: Union[Optional[Union[UserName, Dict[str, Any]]], DefaultArg] = NotGiven,
+        nick_name: Union[Optional[str], DefaultArg] = NotGiven,
+        phone_numbers: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        photos: Union[Optional[List[Union[UserPhoto, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        profile_url: Union[Optional[str], DefaultArg] = NotGiven,
+        roles: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        schemas: Union[Optional[List[str]], DefaultArg] = NotGiven,
+        timezone: Union[Optional[str], DefaultArg] = NotGiven,
+        title: Union[Optional[str], DefaultArg] = NotGiven,
+        user_name: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.active = active
+        self.addresses = (
+            [a if isinstance(a, UserAddress) else UserAddress(**a) for a in addresses]  # type: ignore
+            if _is_iterable(addresses)
+            else addresses
+        )
+        self.display_name = display_name
+        self.emails = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in emails]  # type: ignore
+            if _is_iterable(emails)
+            else emails
+        )
+        self.external_id = external_id
+        self.groups = (
+            [a if isinstance(a, UserGroup) else UserGroup(**a) for a in groups]  # type: ignore
+            if _is_iterable(groups)
+            else groups
+        )
+        self.id = id
+        self.meta = UserMeta(**meta) if meta is not None and isinstance(meta, dict) else meta
+        self.name = UserName(**name) if name is not None and isinstance(name, dict) else name
+        self.nick_name = nick_name
+        self.phone_numbers = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in phone_numbers]  # type: ignore
+            if _is_iterable(phone_numbers)
+            else phone_numbers
+        )
+        self.photos = (
+            [a if isinstance(a, UserPhoto) else UserPhoto(**a) for a in photos]  # type: ignore
+            if _is_iterable(photos)
+            else photos
+        )
+        self.profile_url = profile_url
+        self.roles = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in roles]  # type: ignore
+            if _is_iterable(roles)
+            else roles
+        )
+        self.schemas = schemas
+        self.timezone = timezone
+        self.title = title
+        self.user_name = user_name
+
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+    def __repr__(self):
+        return f"<slack_sdk.scim.{self.__class__.__name__}: {self.to_dict()}>"
+
+
+

Class variables

+
+
var active :Β boolΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var addresses :Β List[UserAddress]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var display_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var emails :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var external_id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var groups :Β List[UserGroup]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var meta :Β UserMetaΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β UserNameΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var nick_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var phone_numbers :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var photos :Β List[UserPhoto]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var profile_url :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var roles :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var schemas :Β List[str]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var timezone :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var title :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var user_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/async_client.html b/docs/reference/scim/v1/async_client.html new file mode 100644 index 000000000..6a971bb80 --- /dev/null +++ b/docs/reference/scim/v1/async_client.html @@ -0,0 +1,838 @@ + + + + + + +slack_sdk.scim.v1.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.async_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSCIMClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/scim/v1/',
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
auth:Β aiohttp.helpers.BasicAuthΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncSCIMClient:
+    BASE_URL = "https://api.slack.com/scim/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    session: Optional[ClientSession]
+    trust_env_in_session: bool
+    auth: Optional[BasicAuth]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[AsyncRetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        session: Optional[ClientSession] = None,
+        trust_env_in_session: bool = False,
+        auth: Optional[BasicAuth] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        """API client for SCIM API
+        See https://docs.slack.dev/admins/scim-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            session: `aiohttp.ClientSession` instance
+            trust_env_in_session: True/False for `aiohttp.ClientSession`
+            auth: Basic auth info for `aiohttp.ClientSession`
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.session = session
+        self.trust_env_in_session = trust_env_in_session
+        self.auth = auth
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # Users
+    # -------------------------
+
+    async def search_users(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchUsersResponse:
+        return SearchUsersResponse(
+            await self.api_call(
+                http_verb="GET",
+                path="Users",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    async def read_user(self, id: str) -> ReadUserResponse:
+        return ReadUserResponse(await self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+    async def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+        return UserCreateResponse(
+            await self.api_call(
+                http_verb="POST",
+                path="Users",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    async def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+        return UserPatchResponse(
+            await self.api_call(
+                http_verb="PATCH",
+                path=f"Users/{quote(id)}",
+                body_params=(
+                    partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+                ),
+            )
+        )
+
+    async def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+        user_id = user.id if isinstance(user, User) else user["id"]
+        return UserUpdateResponse(
+            await self.api_call(
+                http_verb="PUT",
+                path=f"Users/{quote(user_id)}",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    async def delete_user(self, id: str) -> UserDeleteResponse:
+        return UserDeleteResponse(
+            await self.api_call(
+                http_verb="DELETE",
+                path=f"Users/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+    # Groups
+    # -------------------------
+
+    async def search_groups(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchGroupsResponse:
+        return SearchGroupsResponse(
+            await self.api_call(
+                http_verb="GET",
+                path="Groups",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    async def read_group(self, id: str) -> ReadGroupResponse:
+        return ReadGroupResponse(await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+    async def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+        return GroupCreateResponse(
+            await self.api_call(
+                http_verb="POST",
+                path="Groups",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    async def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+        return GroupPatchResponse(
+            await self.api_call(
+                http_verb="PATCH",
+                path=f"Groups/{quote(id)}",
+                body_params=(
+                    partial_group.to_dict()
+                    if isinstance(partial_group, Group)
+                    else _to_dict_without_not_given(partial_group)
+                ),
+            )
+        )
+
+    async def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+        group_id = group.id if isinstance(group, Group) else group["id"]
+        return GroupUpdateResponse(
+            await self.api_call(
+                http_verb="PUT",
+                path=f"Groups/{quote(group_id)}",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    async def delete_group(self, id: str) -> GroupDeleteResponse:
+        return GroupDeleteResponse(
+            await self.api_call(
+                http_verb="DELETE",
+                path=f"Groups/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+
+    async def api_call(
+        self,
+        *,
+        http_verb: str,
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> SCIMResponse:
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+        return await self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body_params=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    async def _perform_http_request(
+        self,
+        *,
+        http_verb: str,
+        url: str,
+        body_params: Optional[Dict[str, Any]],
+        headers: Dict[str, str],
+    ) -> SCIMResponse:
+        if body_params is not None:
+            if body_params.get("schemas") is None:
+                body_params["schemas"] = ["urn:scim:schemas:core:1.0"]
+            body_params = json.dumps(body_params)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        session: Optional[ClientSession] = None
+        use_running_session = self.session and not self.session.closed
+        if use_running_session:
+            session = self.session
+        else:
+            session = aiohttp.ClientSession(
+                timeout=aiohttp.ClientTimeout(total=self.timeout),
+                auth=self.auth,
+                trust_env=self.trust_env_in_session,
+            )
+
+        last_error: Optional[Exception] = None
+        resp: Optional[SCIMResponse] = None
+        try:
+            request_kwargs = {
+                "headers": headers,
+                "data": body_params,
+                "ssl": self.ssl,
+                "proxy": self.proxy,
+            }
+            retry_request = RetryHttpRequest(
+                method=http_verb,
+                url=url,
+                headers=headers,
+                body_params=body_params,
+            )
+
+            retry_state = RetryState()
+            counter_for_safety = 0
+            while counter_for_safety < 100:
+                counter_for_safety += 1
+                # If this is a retry, the next try started here. We can reset the flag.
+                retry_state.next_attempt_requested = False
+                retry_response: Optional[RetryHttpResponse] = None
+                response_body = ""
+
+                if self.logger.level <= logging.DEBUG:
+                    headers_for_logging = {
+                        k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()
+                    }
+                    self.logger.debug(
+                        f"Sending a request - url: {url}, params: {body_params}, headers: {headers_for_logging}"
+                    )
+
+                try:
+                    async with session.request(http_verb, url, **request_kwargs) as res:
+                        try:
+                            response_body = await res.text()
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,
+                                data=response_body.encode("utf-8") if response_body is not None else None,
+                            )
+                        except aiohttp.ContentTypeError:
+                            self.logger.debug(f"No response data returned from the following API call: {url}.")
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,
+                            )
+
+                        if res.status == 429:
+                            for handler in self.retry_handlers:
+                                if await handler.can_retry_async(
+                                    state=retry_state,
+                                    request=retry_request,
+                                    response=retry_response,
+                                ):
+                                    if self.logger.level <= logging.DEBUG:
+                                        self.logger.info(
+                                            f"A retry handler found: {type(handler).__name__} "
+                                            f"for {http_verb} {url} - rate_limited"
+                                        )
+                                    await handler.prepare_for_next_attempt_async(
+                                        state=retry_state,
+                                        request=retry_request,
+                                        response=retry_response,
+                                    )
+                                    break
+
+                        if retry_state.next_attempt_requested is False:
+                            resp = SCIMResponse(
+                                url=url,
+                                status_code=res.status,
+                                raw_body=response_body,
+                                headers=res.headers,
+                            )
+                            _debug_log_response(self.logger, resp)
+                            return resp
+
+                except Exception as e:
+                    last_error = e
+                    for handler in self.retry_handlers:
+                        if await handler.can_retry_async(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        ):
+                            if self.logger.level <= logging.DEBUG:
+                                self.logger.info(
+                                    f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}"
+                                )
+                            await handler.prepare_for_next_attempt_async(
+                                state=retry_state,
+                                request=retry_request,
+                                response=retry_response,
+                                error=e,
+                            )
+                            break
+
+                    if retry_state.next_attempt_requested is False:
+                        raise last_error
+
+            if resp is not None:
+                return resp
+            raise last_error
+
+        finally:
+            if not use_running_session:
+                await session.close()
+
+        return resp
+
+

API client for SCIM API +See https://docs.slack.dev/admins/scim-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
session
+
aiohttp.ClientSession instance
+
trust_env_in_session
+
True/False for aiohttp.ClientSession
+
auth
+
Basic auth info for aiohttp.ClientSession
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var auth :Β aiohttp.helpers.BasicAuthΒ |Β None
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]
+
+

The type of the None singleton.

+
+
var session :Β aiohttp.client.ClientSessionΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
var trust_env_in_session :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def api_call(self,
*,
http_verb:Β str,
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β SCIMResponse
+
+
+
+ +Expand source code + +
async def api_call(
+    self,
+    *,
+    http_verb: str,
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> SCIMResponse:
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+    return await self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body_params=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+
+
+
+async def create_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupCreateResponse
+
+
+
+ +Expand source code + +
async def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+    return GroupCreateResponse(
+        await self.api_call(
+            http_verb="POST",
+            path="Groups",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+async def create_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserCreateResponse
+
+
+
+ +Expand source code + +
async def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+    return UserCreateResponse(
+        await self.api_call(
+            http_verb="POST",
+            path="Users",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+async def delete_group(self, id:Β str) ‑>Β GroupDeleteResponse +
+
+
+ +Expand source code + +
async def delete_group(self, id: str) -> GroupDeleteResponse:
+    return GroupDeleteResponse(
+        await self.api_call(
+            http_verb="DELETE",
+            path=f"Groups/{quote(id)}",
+        )
+    )
+
+
+
+
+async def delete_user(self, id:Β str) ‑>Β UserDeleteResponse +
+
+
+ +Expand source code + +
async def delete_user(self, id: str) -> UserDeleteResponse:
+    return UserDeleteResponse(
+        await self.api_call(
+            http_verb="DELETE",
+            path=f"Users/{quote(id)}",
+        )
+    )
+
+
+
+
+async def patch_group(self,
id:Β str,
partial_group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupPatchResponse
+
+
+
+ +Expand source code + +
async def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+    return GroupPatchResponse(
+        await self.api_call(
+            http_verb="PATCH",
+            path=f"Groups/{quote(id)}",
+            body_params=(
+                partial_group.to_dict()
+                if isinstance(partial_group, Group)
+                else _to_dict_without_not_given(partial_group)
+            ),
+        )
+    )
+
+
+
+
+async def patch_user(self,
id:Β str,
partial_user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserPatchResponse
+
+
+
+ +Expand source code + +
async def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+    return UserPatchResponse(
+        await self.api_call(
+            http_verb="PATCH",
+            path=f"Users/{quote(id)}",
+            body_params=(
+                partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+            ),
+        )
+    )
+
+
+
+
+async def read_group(self, id:Β str) ‑>Β ReadGroupResponse +
+
+
+ +Expand source code + +
async def read_group(self, id: str) -> ReadGroupResponse:
+    return ReadGroupResponse(await self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+
+
+
+async def read_user(self, id:Β str) ‑>Β ReadUserResponse +
+
+
+ +Expand source code + +
async def read_user(self, id: str) -> ReadUserResponse:
+    return ReadUserResponse(await self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+
+
+
+async def search_groups(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchGroupsResponse +
+
+
+ +Expand source code + +
async def search_groups(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchGroupsResponse:
+    return SearchGroupsResponse(
+        await self.api_call(
+            http_verb="GET",
+            path="Groups",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+async def search_users(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchUsersResponse +
+
+
+ +Expand source code + +
async def search_users(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchUsersResponse:
+    return SearchUsersResponse(
+        await self.api_call(
+            http_verb="GET",
+            path="Users",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+async def update_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupUpdateResponse
+
+
+
+ +Expand source code + +
async def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+    group_id = group.id if isinstance(group, Group) else group["id"]
+    return GroupUpdateResponse(
+        await self.api_call(
+            http_verb="PUT",
+            path=f"Groups/{quote(group_id)}",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+async def update_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserUpdateResponse
+
+
+
+ +Expand source code + +
async def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+    user_id = user.id if isinstance(user, User) else user["id"]
+    return UserUpdateResponse(
+        await self.api_call(
+            http_verb="PUT",
+            path=f"Users/{quote(user_id)}",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/client.html b/docs/reference/scim/v1/client.html new file mode 100644 index 000000000..4317f2394 --- /dev/null +++ b/docs/reference/scim/v1/client.html @@ -0,0 +1,832 @@ + + + + + + +slack_sdk.scim.v1.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.client

+
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers to manage people across a variety of tools, +including Slack.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/scim/ for details.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class SCIMClient +(token:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://api.slack.com/scim/v1/',
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SCIMClient:
+    BASE_URL = "https://api.slack.com/scim/v1/"
+
+    token: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    base_url: str
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        token: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        base_url: str = BASE_URL,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for SCIM API
+        See https://docs.slack.dev/admins/scim-api/ for more details
+
+        Args:
+            token: An admin user's token, which starts with `xoxp-`
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            base_url: The base URL for API calls
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.token = token
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.base_url = base_url
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # Users
+    # -------------------------
+
+    def search_users(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchUsersResponse:
+        return SearchUsersResponse(
+            self.api_call(
+                http_verb="GET",
+                path="Users",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    def read_user(self, id: str) -> ReadUserResponse:
+        return ReadUserResponse(self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+    def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+        return UserCreateResponse(
+            self.api_call(
+                http_verb="POST",
+                path="Users",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+        return UserPatchResponse(
+            self.api_call(
+                http_verb="PATCH",
+                path=f"Users/{quote(id)}",
+                body_params=(
+                    partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+                ),
+            )
+        )
+
+    def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+        user_id = user.id if isinstance(user, User) else user["id"]
+        return UserUpdateResponse(
+            self.api_call(
+                http_verb="PUT",
+                path=f"Users/{quote(user_id)}",
+                body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+            )
+        )
+
+    def delete_user(self, id: str) -> UserDeleteResponse:
+        return UserDeleteResponse(
+            self.api_call(
+                http_verb="DELETE",
+                path=f"Users/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+    # Groups
+    # -------------------------
+
+    def search_groups(
+        self,
+        *,
+        # Pagination required as of August 30, 2019.
+        count: int,
+        start_index: int,
+        filter: Optional[str] = None,
+    ) -> SearchGroupsResponse:
+        return SearchGroupsResponse(
+            self.api_call(
+                http_verb="GET",
+                path="Groups",
+                query_params={
+                    "filter": filter,
+                    "count": count,
+                    "startIndex": start_index,
+                },
+            )
+        )
+
+    def read_group(self, id: str) -> ReadGroupResponse:
+        return ReadGroupResponse(self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+    def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+        return GroupCreateResponse(
+            self.api_call(
+                http_verb="POST",
+                path="Groups",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+        return GroupPatchResponse(
+            self.api_call(
+                http_verb="PATCH",
+                path=f"Groups/{quote(id)}",
+                body_params=(
+                    partial_group.to_dict()
+                    if isinstance(partial_group, Group)
+                    else _to_dict_without_not_given(partial_group)
+                ),
+            )
+        )
+
+    def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+        group_id = group.id if isinstance(group, Group) else group["id"]
+        return GroupUpdateResponse(
+            self.api_call(
+                http_verb="PUT",
+                path=f"Groups/{quote(group_id)}",
+                body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+            )
+        )
+
+    def delete_group(self, id: str) -> GroupDeleteResponse:
+        return GroupDeleteResponse(
+            self.api_call(
+                http_verb="DELETE",
+                path=f"Groups/{quote(id)}",
+            )
+        )
+
+    # -------------------------
+
+    def api_call(
+        self,
+        *,
+        http_verb: str,
+        path: str,
+        query_params: Optional[Dict[str, Any]] = None,
+        body_params: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> SCIMResponse:
+        """Performs a Slack API request and returns the result."""
+        url = f"{self.base_url}{path}"
+        query = _build_query(query_params)
+        if len(query) > 0:
+            url += f"?{query}"
+
+        return self._perform_http_request(
+            http_verb=http_verb,
+            url=url,
+            body=body_params,
+            headers=_build_request_headers(
+                token=self.token,
+                default_headers=self.default_headers,
+                additional_headers=headers,
+            ),
+        )
+
+    def _perform_http_request(
+        self,
+        *,
+        http_verb: str = "GET",
+        url: str,
+        body: Optional[Dict[str, Any]] = None,
+        headers: Dict[str, str],
+    ) -> SCIMResponse:
+        if body is not None:
+            if body.get("schemas") is None:
+                body["schemas"] = ["urn:scim:schemas:core:1.0"]
+            body = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()}
+            self.logger.debug(f"Sending a request - {http_verb} url: {url}, body: {body}, headers: {headers_for_logging}")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(
+            method=http_verb,
+            url=url,
+            data=body.encode("utf-8") if body is not None else None,
+            headers=headers,
+        )
+        resp = None
+        last_error = None
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = SCIMResponse(
+                    url=url,
+                    status_code=e.code,
+                    raw_body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error
+
+    def _perform_http_request_internal(self, url: str, req: Request) -> SCIMResponse:
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        # NOTE: BAN-B310 is already checked above
+        http_resp: Optional[HTTPResponse] = None
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = SCIMResponse(
+            url=url,
+            status_code=http_resp.status,
+            raw_body=response_body,
+            headers=http_resp.headers,
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for SCIM API +See https://docs.slack.dev/admins/scim-api/ for more details

+

Args

+
+
token
+
An admin user's token, which starts with xoxp-
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
base_url
+
The base URL for API calls
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
var base_url :Β str
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var token :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def api_call(self,
*,
http_verb:Β str,
path:Β str,
query_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
body_params:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β SCIMResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    *,
+    http_verb: str,
+    path: str,
+    query_params: Optional[Dict[str, Any]] = None,
+    body_params: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> SCIMResponse:
+    """Performs a Slack API request and returns the result."""
+    url = f"{self.base_url}{path}"
+    query = _build_query(query_params)
+    if len(query) > 0:
+        url += f"?{query}"
+
+    return self._perform_http_request(
+        http_verb=http_verb,
+        url=url,
+        body=body_params,
+        headers=_build_request_headers(
+            token=self.token,
+            default_headers=self.default_headers,
+            additional_headers=headers,
+        ),
+    )
+
+

Performs a Slack API request and returns the result.

+
+
+def create_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupCreateResponse
+
+
+
+ +Expand source code + +
def create_group(self, group: Union[Dict[str, Any], Group]) -> GroupCreateResponse:
+    return GroupCreateResponse(
+        self.api_call(
+            http_verb="POST",
+            path="Groups",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+def create_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserCreateResponse
+
+
+
+ +Expand source code + +
def create_user(self, user: Union[Dict[str, Any], User]) -> UserCreateResponse:
+    return UserCreateResponse(
+        self.api_call(
+            http_verb="POST",
+            path="Users",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+def delete_group(self, id:Β str) ‑>Β GroupDeleteResponse +
+
+
+ +Expand source code + +
def delete_group(self, id: str) -> GroupDeleteResponse:
+    return GroupDeleteResponse(
+        self.api_call(
+            http_verb="DELETE",
+            path=f"Groups/{quote(id)}",
+        )
+    )
+
+
+
+
+def delete_user(self, id:Β str) ‑>Β UserDeleteResponse +
+
+
+ +Expand source code + +
def delete_user(self, id: str) -> UserDeleteResponse:
+    return UserDeleteResponse(
+        self.api_call(
+            http_verb="DELETE",
+            path=f"Users/{quote(id)}",
+        )
+    )
+
+
+
+
+def patch_group(self,
id:Β str,
partial_group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupPatchResponse
+
+
+
+ +Expand source code + +
def patch_group(self, id: str, partial_group: Union[Dict[str, Any], Group]) -> GroupPatchResponse:
+    return GroupPatchResponse(
+        self.api_call(
+            http_verb="PATCH",
+            path=f"Groups/{quote(id)}",
+            body_params=(
+                partial_group.to_dict()
+                if isinstance(partial_group, Group)
+                else _to_dict_without_not_given(partial_group)
+            ),
+        )
+    )
+
+
+
+
+def patch_user(self,
id:Β str,
partial_user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserPatchResponse
+
+
+
+ +Expand source code + +
def patch_user(self, id: str, partial_user: Union[Dict[str, Any], User]) -> UserPatchResponse:
+    return UserPatchResponse(
+        self.api_call(
+            http_verb="PATCH",
+            path=f"Users/{quote(id)}",
+            body_params=(
+                partial_user.to_dict() if isinstance(partial_user, User) else _to_dict_without_not_given(partial_user)
+            ),
+        )
+    )
+
+
+
+
+def read_group(self, id:Β str) ‑>Β ReadGroupResponse +
+
+
+ +Expand source code + +
def read_group(self, id: str) -> ReadGroupResponse:
+    return ReadGroupResponse(self.api_call(http_verb="GET", path=f"Groups/{quote(id)}"))
+
+
+
+
+def read_user(self, id:Β str) ‑>Β ReadUserResponse +
+
+
+ +Expand source code + +
def read_user(self, id: str) -> ReadUserResponse:
+    return ReadUserResponse(self.api_call(http_verb="GET", path=f"Users/{quote(id)}"))
+
+
+
+
+def search_groups(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchGroupsResponse +
+
+
+ +Expand source code + +
def search_groups(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchGroupsResponse:
+    return SearchGroupsResponse(
+        self.api_call(
+            http_verb="GET",
+            path="Groups",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+def search_users(self, *, count:Β int, start_index:Β int, filter:Β strΒ |Β NoneΒ =Β None) ‑>Β SearchUsersResponse +
+
+
+ +Expand source code + +
def search_users(
+    self,
+    *,
+    # Pagination required as of August 30, 2019.
+    count: int,
+    start_index: int,
+    filter: Optional[str] = None,
+) -> SearchUsersResponse:
+    return SearchUsersResponse(
+        self.api_call(
+            http_verb="GET",
+            path="Users",
+            query_params={
+                "filter": filter,
+                "count": count,
+                "startIndex": start_index,
+            },
+        )
+    )
+
+
+
+
+def update_group(self,
group:Β Dict[str,Β Any]Β |Β Group) ‑>Β GroupUpdateResponse
+
+
+
+ +Expand source code + +
def update_group(self, group: Union[Dict[str, Any], Group]) -> GroupUpdateResponse:
+    group_id = group.id if isinstance(group, Group) else group["id"]
+    return GroupUpdateResponse(
+        self.api_call(
+            http_verb="PUT",
+            path=f"Groups/{quote(group_id)}",
+            body_params=group.to_dict() if isinstance(group, Group) else _to_dict_without_not_given(group),
+        )
+    )
+
+
+
+
+def update_user(self,
user:Β Dict[str,Β Any]Β |Β User) ‑>Β UserUpdateResponse
+
+
+
+ +Expand source code + +
def update_user(self, user: Union[Dict[str, Any], User]) -> UserUpdateResponse:
+    user_id = user.id if isinstance(user, User) else user["id"]
+    return UserUpdateResponse(
+        self.api_call(
+            http_verb="PUT",
+            path=f"Users/{quote(user_id)}",
+            body_params=user.to_dict() if isinstance(user, User) else _to_dict_without_not_given(user),
+        )
+    )
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/default_arg.html b/docs/reference/scim/v1/default_arg.html new file mode 100644 index 000000000..071fa3ca8 --- /dev/null +++ b/docs/reference/scim/v1/default_arg.html @@ -0,0 +1,89 @@ + + + + + + +slack_sdk.scim.v1.default_arg API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.default_arg

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class DefaultArg +
+
+
+ +Expand source code + +
class DefaultArg:
+    pass
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/group.html b/docs/reference/scim/v1/group.html new file mode 100644 index 000000000..615d75d06 --- /dev/null +++ b/docs/reference/scim/v1/group.html @@ -0,0 +1,312 @@ + + + + + + +slack_sdk.scim.v1.group API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.group

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Group +(*,
display_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
members:Β List[GroupMember]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
meta:Β GroupMetaΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
schemas:Β List[str]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class Group:
+    display_name: Union[Optional[str], DefaultArg]
+    id: Union[Optional[str], DefaultArg]
+    members: Union[Optional[List[GroupMember]], DefaultArg]
+    meta: Union[Optional[GroupMeta], DefaultArg]
+    schemas: Union[Optional[List[str]], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        display_name: Union[Optional[str], DefaultArg] = NotGiven,
+        id: Union[Optional[str], DefaultArg] = NotGiven,
+        members: Union[Optional[List[GroupMember]], DefaultArg] = NotGiven,
+        meta: Union[Optional[GroupMeta], DefaultArg] = NotGiven,
+        schemas: Union[Optional[List[str]], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.display_name = display_name
+        self.id = id
+        self.members = (
+            [a if isinstance(a, GroupMember) else GroupMember(**a) for a in members] if _is_iterable(members) else members
+        )
+        self.meta = GroupMeta(**meta) if meta is not None and isinstance(meta, dict) else meta
+        self.schemas = schemas
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+    def __repr__(self):
+        return f"<slack_sdk.scim.{self.__class__.__name__}: {self.to_dict()}>"
+
+
+

Class variables

+
+
var display_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var members :Β List[GroupMember]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var meta :Β GroupMetaΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var schemas :Β List[str]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class GroupMember +(*,
display:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class GroupMember:
+    display: Union[Optional[str], DefaultArg]
+    value: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        display: Union[Optional[str], DefaultArg] = NotGiven,
+        value: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.display = display
+        self.value = value
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var display :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var value :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class GroupMeta +(*,
created:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
location:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class GroupMeta:
+    created: Union[Optional[str], DefaultArg]
+    location: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        created: Union[Optional[str], DefaultArg] = NotGiven,
+        location: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.created = created
+        self.location = location
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var created :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var location :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/index.html b/docs/reference/scim/v1/index.html new file mode 100644 index 000000000..2cbda3da0 --- /dev/null +++ b/docs/reference/scim/v1/index.html @@ -0,0 +1,119 @@ + + + + + + +slack_sdk.scim.v1 API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1

+
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers to manage people across a variety of tools, +including Slack.

+

Refer to https://docs.slack.dev/tools/python-slack-sdk/scim for details.

+
+
+

Sub-modules

+
+
slack_sdk.scim.v1.async_client
+
+
+
+
slack_sdk.scim.v1.client
+
+

SCIM API is a set of APIs for provisioning and managing user accounts and groups. +SCIM is used by Single Sign-On (SSO) services and identity providers …

+
+
slack_sdk.scim.v1.default_arg
+
+
+
+
slack_sdk.scim.v1.group
+
+
+
+
slack_sdk.scim.v1.internal_utils
+
+
+
+
slack_sdk.scim.v1.response
+
+
+
+
slack_sdk.scim.v1.types
+
+
+
+
slack_sdk.scim.v1.user
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/internal_utils.html b/docs/reference/scim/v1/internal_utils.html new file mode 100644 index 000000000..c8aecfd94 --- /dev/null +++ b/docs/reference/scim/v1/internal_utils.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.scim.v1.internal_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.internal_utils

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/response.html b/docs/reference/scim/v1/response.html new file mode 100644 index 000000000..83b638f69 --- /dev/null +++ b/docs/reference/scim/v1/response.html @@ -0,0 +1,967 @@ + + + + + + +slack_sdk.scim.v1.response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.response

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Errors +(code:Β int, description:Β str) +
+
+
+ +Expand source code + +
class Errors:
+    code: int
+    description: str
+
+    def __init__(self, code: int, description: str) -> None:
+        self.code = code
+        self.description = description
+
+    def to_dict(self) -> dict:
+        return {"code": self.code, "description": self.description}
+
+
+

Class variables

+
+
var code :Β int
+
+

The type of the None singleton.

+
+
var description :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return {"code": self.code, "description": self.description}
+
+
+
+
+
+
+class GroupCreateResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class GroupCreateResponse(SCIMResponse):
+    group: Group
+
+    @property
+    def group(self) -> Group:
+        return Group(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop group :Β Group
+
+
+ +Expand source code + +
@property
+def group(self) -> Group:
+    return Group(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class GroupDeleteResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class GroupDeleteResponse(SCIMResponse):
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+class GroupPatchResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class GroupPatchResponse(SCIMResponse):
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+class GroupUpdateResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class GroupUpdateResponse(SCIMResponse):
+    group: Group
+
+    @property
+    def group(self) -> Group:
+        return Group(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop group :Β Group
+
+
+ +Expand source code + +
@property
+def group(self) -> Group:
+    return Group(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class ReadGroupResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class ReadGroupResponse(SCIMResponse):
+    group: Group
+
+    @property
+    def group(self) -> Group:
+        return Group(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop group :Β Group
+
+
+ +Expand source code + +
@property
+def group(self) -> Group:
+    return Group(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class ReadUserResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class ReadUserResponse(SCIMResponse):
+    user: User
+
+    @property
+    def user(self) -> User:
+        return User(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop user :Β User
+
+
+ +Expand source code + +
@property
+def user(self) -> User:
+    return User(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class SCIMResponse +(*, url:Β str, status_code:Β int, raw_body:Β strΒ |Β None, headers:Β dict) +
+
+
+ +Expand source code + +
class SCIMResponse:
+    url: str
+    status_code: int
+    headers: Dict[str, Any]
+    raw_body: Optional[str]
+    body: Optional[Dict[str, Any]]
+    snake_cased_body: Optional[Dict[str, Any]]
+
+    errors: Optional[Errors]
+
+    @property
+    def snake_cased_body(self) -> Optional[Dict[str, Any]]:
+        if self._snake_cased_body is None:
+            self._snake_cased_body = _to_snake_cased(self.body)
+        return self._snake_cased_body
+
+    @property
+    def errors(self) -> Optional[Errors]:
+        errors = self.snake_cased_body.get("errors")
+        if errors is None:
+            return None
+        return Errors(**errors)
+
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        raw_body: Optional[str],
+        headers: dict,
+    ):
+        self.url = url
+        self.status_code = status_code
+        self.headers = headers
+        self.raw_body = raw_body
+        self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None
+        self._snake_cased_body = None  # build this when it's accessed for the first time
+
+    def __repr__(self):
+        dict_value = {}
+        for key, value in vars(self).items():
+            dict_value[key] = value.to_dict() if hasattr(value, "to_dict") else value
+
+        if dict_value:
+            return f"<slack_sdk.scim.v1.{self.__class__.__name__}: {dict_value}>"
+        else:
+            return self.__str__()
+
+
+

Subclasses

+ +

Class variables

+
+
var body :Β Dict[str,Β Any]Β |Β None
+
+

The type of the None singleton.

+
+
var headers :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var raw_body :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var status_code :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
prop errors :Β ErrorsΒ |Β None
+
+
+ +Expand source code + +
@property
+def errors(self) -> Optional[Errors]:
+    errors = self.snake_cased_body.get("errors")
+    if errors is None:
+        return None
+    return Errors(**errors)
+
+
+
+
prop snake_cased_body :Β Dict[str,Β Any]Β |Β None
+
+
+ +Expand source code + +
@property
+def snake_cased_body(self) -> Optional[Dict[str, Any]]:
+    if self._snake_cased_body is None:
+        self._snake_cased_body = _to_snake_cased(self.body)
+    return self._snake_cased_body
+
+
+
+
+
+
+class SearchGroupsResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class SearchGroupsResponse(SCIMResponse):
+    groups: List[Group]
+
+    @property
+    def groups(self) -> List[Group]:
+        return [Group(**r) for r in self.snake_cased_body.get("resources")]
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop groups :Β List[Group]
+
+
+ +Expand source code + +
@property
+def groups(self) -> List[Group]:
+    return [Group(**r) for r in self.snake_cased_body.get("resources")]
+
+
+
+
+

Inherited members

+ +
+
+class SearchUsersResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class SearchUsersResponse(SCIMResponse):
+    users: List[User]
+
+    @property
+    def users(self) -> List[User]:
+        return [User(**r) for r in self.snake_cased_body.get("resources")]
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop users :Β List[User]
+
+
+ +Expand source code + +
@property
+def users(self) -> List[User]:
+    return [User(**r) for r in self.snake_cased_body.get("resources")]
+
+
+
+
+

Inherited members

+ +
+
+class UserCreateResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class UserCreateResponse(SCIMResponse):
+    user: User
+
+    @property
+    def user(self) -> User:
+        return User(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop user :Β User
+
+
+ +Expand source code + +
@property
+def user(self) -> User:
+    return User(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class UserDeleteResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class UserDeleteResponse(SCIMResponse):
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+class UserPatchResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class UserPatchResponse(SCIMResponse):
+    user: User
+
+    @property
+    def user(self) -> User:
+        return User(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop user :Β User
+
+
+ +Expand source code + +
@property
+def user(self) -> User:
+    return User(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+class UserUpdateResponse +(underlying:Β SCIMResponse) +
+
+
+ +Expand source code + +
class UserUpdateResponse(SCIMResponse):
+    user: User
+
+    @property
+    def user(self) -> User:
+        return User(**self.snake_cased_body)
+
+    def __init__(self, underlying: SCIMResponse):
+        self.underlying = underlying
+        self.url = underlying.url
+        self.status_code = underlying.status_code
+        self.headers = underlying.headers
+        self.raw_body = underlying.raw_body
+        self.body = underlying.body
+        self._snake_cased_body = None
+
+
+

Ancestors

+ +

Instance variables

+
+
prop user :Β User
+
+
+ +Expand source code + +
@property
+def user(self) -> User:
+    return User(**self.snake_cased_body)
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/types.html b/docs/reference/scim/v1/types.html new file mode 100644 index 000000000..2d8b58aeb --- /dev/null +++ b/docs/reference/scim/v1/types.html @@ -0,0 +1,157 @@ + + + + + + +slack_sdk.scim.v1.types API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.types

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class TypeAndValue +(*,
primary:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
type:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class TypeAndValue:
+    primary: Union[Optional[bool], DefaultArg]
+    type: Union[Optional[str], DefaultArg]
+    value: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        primary: Union[Optional[bool], DefaultArg] = NotGiven,
+        type: Union[Optional[str], DefaultArg] = NotGiven,
+        value: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.primary = primary
+        self.type = type
+        self.value = value
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Subclasses

+ +

Class variables

+
+
var primary :Β boolΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var value :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/scim/v1/user.html b/docs/reference/scim/v1/user.html new file mode 100644 index 000000000..49e328355 --- /dev/null +++ b/docs/reference/scim/v1/user.html @@ -0,0 +1,774 @@ + + + + + + +slack_sdk.scim.v1.user API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.scim.v1.user

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class User +(*,
active:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
addresses:Β List[UserAddressΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
display_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
emails:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
external_id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
groups:Β List[UserGroupΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
id:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
meta:Β UserMetaΒ |Β Dict[str,Β Any]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
name:Β UserNameΒ |Β Dict[str,Β Any]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
nick_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
phone_numbers:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
photos:Β List[UserPhotoΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
profile_url:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
roles:Β List[TypeAndValueΒ |Β Dict[str,Β Any]]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
schemas:Β List[str]Β |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
timezone:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
title:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
user_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class User:
+    active: Union[Optional[bool], DefaultArg]
+    addresses: Union[Optional[List[UserAddress]], DefaultArg]
+    display_name: Union[Optional[str], DefaultArg]
+    emails: Union[Optional[List[TypeAndValue]], DefaultArg]
+    external_id: Union[Optional[str], DefaultArg]
+    groups: Union[Optional[List[UserGroup]], DefaultArg]
+    id: Union[Optional[str], DefaultArg]
+    meta: Union[Optional[UserMeta], DefaultArg]
+    name: Union[Optional[UserName], DefaultArg]
+    nick_name: Union[Optional[str], DefaultArg]
+    phone_numbers: Union[Optional[List[TypeAndValue]], DefaultArg]
+    photos: Union[Optional[List[UserPhoto]], DefaultArg]
+    profile_url: Union[Optional[str], DefaultArg]
+    roles: Union[Optional[List[TypeAndValue]], DefaultArg]
+    schemas: Union[Optional[List[str]], DefaultArg]
+    timezone: Union[Optional[str], DefaultArg]
+    title: Union[Optional[str], DefaultArg]
+    user_name: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        active: Union[Optional[bool], DefaultArg] = NotGiven,
+        addresses: Union[Optional[List[Union[UserAddress, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        display_name: Union[Optional[str], DefaultArg] = NotGiven,
+        emails: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        external_id: Union[Optional[str], DefaultArg] = NotGiven,
+        groups: Union[Optional[List[Union[UserGroup, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        id: Union[Optional[str], DefaultArg] = NotGiven,
+        meta: Union[Optional[Union[UserMeta, Dict[str, Any]]], DefaultArg] = NotGiven,
+        name: Union[Optional[Union[UserName, Dict[str, Any]]], DefaultArg] = NotGiven,
+        nick_name: Union[Optional[str], DefaultArg] = NotGiven,
+        phone_numbers: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        photos: Union[Optional[List[Union[UserPhoto, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        profile_url: Union[Optional[str], DefaultArg] = NotGiven,
+        roles: Union[Optional[List[Union[TypeAndValue, Dict[str, Any]]]], DefaultArg] = NotGiven,
+        schemas: Union[Optional[List[str]], DefaultArg] = NotGiven,
+        timezone: Union[Optional[str], DefaultArg] = NotGiven,
+        title: Union[Optional[str], DefaultArg] = NotGiven,
+        user_name: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.active = active
+        self.addresses = (
+            [a if isinstance(a, UserAddress) else UserAddress(**a) for a in addresses]  # type: ignore
+            if _is_iterable(addresses)
+            else addresses
+        )
+        self.display_name = display_name
+        self.emails = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in emails]  # type: ignore
+            if _is_iterable(emails)
+            else emails
+        )
+        self.external_id = external_id
+        self.groups = (
+            [a if isinstance(a, UserGroup) else UserGroup(**a) for a in groups]  # type: ignore
+            if _is_iterable(groups)
+            else groups
+        )
+        self.id = id
+        self.meta = UserMeta(**meta) if meta is not None and isinstance(meta, dict) else meta
+        self.name = UserName(**name) if name is not None and isinstance(name, dict) else name
+        self.nick_name = nick_name
+        self.phone_numbers = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in phone_numbers]  # type: ignore
+            if _is_iterable(phone_numbers)
+            else phone_numbers
+        )
+        self.photos = (
+            [a if isinstance(a, UserPhoto) else UserPhoto(**a) for a in photos]  # type: ignore
+            if _is_iterable(photos)
+            else photos
+        )
+        self.profile_url = profile_url
+        self.roles = (
+            [a if isinstance(a, TypeAndValue) else TypeAndValue(**a) for a in roles]  # type: ignore
+            if _is_iterable(roles)
+            else roles
+        )
+        self.schemas = schemas
+        self.timezone = timezone
+        self.title = title
+        self.user_name = user_name
+
+        self.unknown_fields = kwargs
+
+    def to_dict(self):
+        return _to_dict_without_not_given(self)
+
+    def __repr__(self):
+        return f"<slack_sdk.scim.{self.__class__.__name__}: {self.to_dict()}>"
+
+
+

Class variables

+
+
var active :Β boolΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var addresses :Β List[UserAddress]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var display_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var emails :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var external_id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var groups :Β List[UserGroup]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var id :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var meta :Β UserMetaΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var name :Β UserNameΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var nick_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var phone_numbers :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var photos :Β List[UserPhoto]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var profile_url :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var roles :Β List[TypeAndValue]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var schemas :Β List[str]Β |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var timezone :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var title :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var user_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) +
+
+
+ +Expand source code + +
def to_dict(self):
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserAddress +(*,
country:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
locality:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
postal_code:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
primary:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
region:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
street_address:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserAddress:
+    country: Union[Optional[str], DefaultArg]
+    locality: Union[Optional[str], DefaultArg]
+    postal_code: Union[Optional[str], DefaultArg]
+    primary: Union[Optional[bool], DefaultArg]
+    region: Union[Optional[str], DefaultArg]
+    street_address: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        country: Union[Optional[str], DefaultArg] = NotGiven,
+        locality: Union[Optional[str], DefaultArg] = NotGiven,
+        postal_code: Union[Optional[str], DefaultArg] = NotGiven,
+        primary: Union[Optional[bool], DefaultArg] = NotGiven,
+        region: Union[Optional[str], DefaultArg] = NotGiven,
+        street_address: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.country = country
+        self.locality = locality
+        self.postal_code = postal_code
+        self.primary = primary
+        self.region = region
+        self.street_address = street_address
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var country :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var locality :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var postal_code :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var primary :Β boolΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var region :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var street_address :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserEmail +(*,
primary:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
type:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserEmail(TypeAndValue):
+    pass
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+class UserGroup +(*,
display:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserGroup:
+    display: Union[Optional[str], DefaultArg]
+    value: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        *,
+        display: Union[Optional[str], DefaultArg] = NotGiven,
+        value: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.display = display
+        self.value = value
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var display :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var value :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserMeta +(created:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
location:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserMeta:
+    created: Union[Optional[str], DefaultArg]
+    location: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        created: Union[Optional[str], DefaultArg] = NotGiven,
+        location: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.created = created
+        self.location = location
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var created :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var location :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserName +(family_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
given_name:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserName:
+    family_name: Union[Optional[str], DefaultArg]
+    given_name: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        family_name: Union[Optional[str], DefaultArg] = NotGiven,
+        given_name: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.family_name = family_name
+        self.given_name = given_name
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var family_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var given_name :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserPhoneNumber +(*,
primary:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
type:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserPhoneNumber(TypeAndValue):
+    pass
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+class UserPhoto +(type:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserPhoto:
+    type: Union[Optional[str], DefaultArg]
+    value: Union[Optional[str], DefaultArg]
+    unknown_fields: Dict[str, Any]
+
+    def __init__(
+        self,
+        type: Union[Optional[str], DefaultArg] = NotGiven,
+        value: Union[Optional[str], DefaultArg] = NotGiven,
+        **kwargs,
+    ) -> None:
+        self.type = type
+        self.value = value
+        self.unknown_fields = kwargs
+
+    def to_dict(self) -> dict:
+        return _to_dict_without_not_given(self)
+
+
+

Class variables

+
+
var type :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
var unknown_fields :Β Dict[str,Β Any]
+
+

The type of the None singleton.

+
+
var value :Β strΒ |Β DefaultArgΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    return _to_dict_without_not_given(self)
+
+
+
+
+
+
+class UserRole +(*,
primary:Β boolΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
type:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
value:Β strΒ |Β DefaultArgΒ |Β NoneΒ =Β <slack_sdk.scim.v1.default_arg.DefaultArg object>,
**kwargs)
+
+
+
+ +Expand source code + +
class UserRole(TypeAndValue):
+    pass
+
+
+

Ancestors

+ +

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/signature/index.html b/docs/reference/signature/index.html new file mode 100644 index 000000000..ecc1f0831 --- /dev/null +++ b/docs/reference/signature/index.html @@ -0,0 +1,274 @@ + + + + + + +slack_sdk.signature API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.signature

+
+
+

Slack request signature verifier

+
+
+
+
+
+
+
+
+

Classes

+
+
+class Clock +
+
+
+ +Expand source code + +
class Clock:
+    def now(self) -> float:
+        return time()
+
+
+

Methods

+
+
+def now(self) ‑>Β float +
+
+
+ +Expand source code + +
def now(self) -> float:
+    return time()
+
+
+
+
+
+
+class SignatureVerifier +(signing_secret:Β str,
clock:Β ClockΒ =Β <slack_sdk.signature.Clock object>)
+
+
+
+ +Expand source code + +
class SignatureVerifier:
+    def __init__(self, signing_secret: str, clock: Clock = Clock()):
+        """Slack request signature verifier
+
+        Slack signs its requests using a secret that's unique to your app.
+        With the help of signing secrets, your app can more confidently verify
+        whether requests from us are authentic.
+        https://docs.slack.dev/authentication/verifying-requests-from-slack/
+        """
+        self.signing_secret = signing_secret
+        self.clock = clock
+
+    def is_valid_request(
+        self,
+        body: Union[str, bytes],
+        headers: Dict[str, str],
+    ) -> bool:
+        """Verifies if the given signature is valid"""
+        if headers is None:
+            return False
+        normalized_headers = {k.lower(): v for k, v in headers.items()}
+        return self.is_valid(
+            body=body,
+            timestamp=normalized_headers.get("x-slack-request-timestamp", None),  # type: ignore[arg-type]
+            signature=normalized_headers.get("x-slack-signature", None),  # type: ignore[arg-type]
+        )
+
+    def is_valid(
+        self,
+        body: Union[str, bytes],
+        timestamp: str,
+        signature: str,
+    ) -> bool:
+        """Verifies if the given signature is valid"""
+        if timestamp is None or signature is None:
+            return False
+
+        if abs(self.clock.now() - int(timestamp)) > 60 * 5:
+            return False
+
+        calculated_signature = self.generate_signature(timestamp=timestamp, body=body)
+        if calculated_signature is None:
+            return False
+        return hmac.compare_digest(calculated_signature, signature)
+
+    def generate_signature(self, *, timestamp: str, body: Union[str, bytes]) -> Optional[str]:
+        """Generates a signature"""
+        if timestamp is None:
+            return None
+        if body is None:
+            body = ""
+        if isinstance(body, bytes):
+            body = body.decode("utf-8")
+
+        format_req = str.encode(f"v0:{timestamp}:{body}")
+        encoded_secret = str.encode(self.signing_secret)
+        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+        calculated_signature = f"v0={request_hash}"
+        return calculated_signature
+
+

Slack request signature verifier

+

Slack signs its requests using a secret that's unique to your app. +With the help of signing secrets, your app can more confidently verify +whether requests from us are authentic. +https://docs.slack.dev/authentication/verifying-requests-from-slack/

+

Methods

+
+
+def generate_signature(self, *, timestamp:Β str, body:Β strΒ |Β bytes) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def generate_signature(self, *, timestamp: str, body: Union[str, bytes]) -> Optional[str]:
+    """Generates a signature"""
+    if timestamp is None:
+        return None
+    if body is None:
+        body = ""
+    if isinstance(body, bytes):
+        body = body.decode("utf-8")
+
+    format_req = str.encode(f"v0:{timestamp}:{body}")
+    encoded_secret = str.encode(self.signing_secret)
+    request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+    calculated_signature = f"v0={request_hash}"
+    return calculated_signature
+
+

Generates a signature

+
+
+def is_valid(self, body:Β strΒ |Β bytes, timestamp:Β str, signature:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
def is_valid(
+    self,
+    body: Union[str, bytes],
+    timestamp: str,
+    signature: str,
+) -> bool:
+    """Verifies if the given signature is valid"""
+    if timestamp is None or signature is None:
+        return False
+
+    if abs(self.clock.now() - int(timestamp)) > 60 * 5:
+        return False
+
+    calculated_signature = self.generate_signature(timestamp=timestamp, body=body)
+    if calculated_signature is None:
+        return False
+    return hmac.compare_digest(calculated_signature, signature)
+
+

Verifies if the given signature is valid

+
+
+def is_valid_request(self, body:Β strΒ |Β bytes, headers:Β Dict[str,Β str]) ‑>Β bool +
+
+
+ +Expand source code + +
def is_valid_request(
+    self,
+    body: Union[str, bytes],
+    headers: Dict[str, str],
+) -> bool:
+    """Verifies if the given signature is valid"""
+    if headers is None:
+        return False
+    normalized_headers = {k.lower(): v for k, v in headers.items()}
+    return self.is_valid(
+        body=body,
+        timestamp=normalized_headers.get("x-slack-request-timestamp", None),  # type: ignore[arg-type]
+        signature=normalized_headers.get("x-slack-signature", None),  # type: ignore[arg-type]
+    )
+
+

Verifies if the given signature is valid

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/aiohttp/index.html b/docs/reference/socket_mode/aiohttp/index.html new file mode 100644 index 000000000..92c6225c1 --- /dev/null +++ b/docs/reference/socket_mode/aiohttp/index.html @@ -0,0 +1,1071 @@ + + + + + + +slack_sdk.socket_mode.aiohttp API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.aiohttp

+
+
+

aiohttp based Socket Mode client

+ +
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β AsyncWebClientΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
ping_interval:Β floatΒ =Β 5,
trace_enabled:Β boolΒ =Β False,
on_message_listeners:Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]Β |Β NoneΒ =Β None,
loop:Β asyncio.events.AbstractEventLoopΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeClient(AsyncBaseSocketModeClient):
+    logger: Logger
+    web_client: AsyncWebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    auto_reconnect_enabled: bool
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            AsyncWebSocketMessageListener,
+            Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            AsyncSocketModeRequestListener,
+            Callable[["AsyncBaseSocketModeClient", SocketModeRequest], Awaitable[None]],
+        ]
+    ]
+
+    message_receiver: Optional[Future]
+    message_processor: Future
+
+    proxy: Optional[str]
+    ping_interval: float
+    trace_enabled: bool
+
+    last_ping_pong_time: Optional[float]
+    current_session: Optional[ClientWebSocketResponse]
+    current_session_monitor: Optional[Future]
+
+    default_auto_reconnect_enabled: bool
+    closed: bool
+    stale: bool
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[WSMessage], Awaitable[None]]]
+    on_error_listeners: List[Callable[[WSMessage], Awaitable[None]]]
+    on_close_listeners: List[Callable[[WSMessage], Awaitable[None]]]
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[AsyncWebClient] = None,
+        proxy: Optional[str] = None,
+        auto_reconnect_enabled: bool = True,
+        ping_interval: float = 5,
+        trace_enabled: bool = False,
+        on_message_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None,
+        on_error_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None,
+        on_close_listeners: Optional[List[Callable[[WSMessage], Awaitable[None]]]] = None,
+        loop: Optional[AbstractEventLoop] = None,
+    ):
+        """Socket Mode client
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            trace_enabled: True if more verbose logs to see what's happening under the hood
+            proxy: the HTTP proxy URL
+            on_message_listeners: listener functions for on_message
+            on_error_listeners: listener functions for on_error
+            on_close_listeners: listener functions for on_close
+            loop: an existing asyncio event loop
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or AsyncWebClient()
+        self.closed = False
+        self.stale = False
+        self.connect_operation_lock = Lock()
+        self.proxy = proxy
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.ping_interval = ping_interval
+        self.trace_enabled = trace_enabled
+        self.last_ping_pong_time = None
+
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+        self.current_session = None
+        self.current_session_monitor = None
+
+        # https://docs.aiohttp.org/en/stable/client_reference.html
+        # Unless you are connecting to a large, unknown number of different servers
+        # over the lifetime of your application,
+        # it is suggested you use a single session for the lifetime of your application
+        # to benefit from connection pooling.
+        self.aiohttp_client_session = aiohttp.ClientSession(loop=loop)
+
+        self.on_message_listeners = on_message_listeners or []
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+        self.message_receiver = None
+        self.message_processor = asyncio.ensure_future(self.process_messages())
+
+    async def monitor_current_session(self) -> None:
+        # In the asyncio runtime, accessing a shared object (self.current_session here) from
+        # multiple tasks can cause race conditions and errors.
+        # To avoid such, we access only the session that is active when this loop starts.
+        session: ClientWebSocketResponse = self.current_session  # type: ignore[assignment]
+        session_id: str = self.build_session_id(session)
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started")
+        try:
+            logging_interval = 100
+            counter_for_logging = 0
+
+            while not self.closed:
+                if session != self.current_session:
+                    if self.logger.level <= logging.DEBUG:
+                        self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+                    break
+                try:
+                    if self.trace_enabled and self.logger.level <= logging.DEBUG:
+                        # The logging here is for detailed investigation on potential issues in this client.
+                        # If you don't see this log for a while, it means that
+                        # this receive_messages execution is no longer working for some reason.
+                        counter_for_logging += 1
+                        if counter_for_logging >= logging_interval:
+                            counter_for_logging = 0
+                            log_message = (
+                                "#monitor_current_session method has been verifying if this session is active "
+                                f"(session: {session_id}, logging interval: {logging_interval})"
+                            )
+                            self.logger.debug(log_message)
+
+                    await asyncio.sleep(self.ping_interval)
+
+                    if session is not None and session.closed is False:
+                        t = time.time()
+                        if self.last_ping_pong_time is None:
+                            self.last_ping_pong_time = float(t)
+                        try:
+                            await session.ping(f"sdk-ping-pong:{t}".encode("utf-8"))
+                        except Exception as e:
+                            # The ping() method can fail for some reason.
+                            # To establish a new connection even in this scenario,
+                            # we ignore the exception here.
+                            self.logger.warning(f"Failed to send a ping message ({session_id}): {e}")
+
+                    if self.auto_reconnect_enabled:
+                        should_reconnect = False
+                        if session is None or session.closed:
+                            self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...")
+                            should_reconnect = True
+
+                        if await self.is_ping_pong_failing():
+                            disconnected_seconds = int(time.time() - self.last_ping_pong_time)  # type: ignore[operator]
+                            self.logger.info(
+                                f"The session ({session_id}) seems to be stale. Reconnecting..."
+                                f" reason: disconnected for {disconnected_seconds}+ seconds)"
+                            )
+                            self.stale = True
+                            self.last_ping_pong_time = None
+                            should_reconnect = True
+
+                        if should_reconnect is True or not await self.is_connected():
+                            await self.connect_to_new_endpoint()
+
+                except Exception as e:
+                    self.logger.error(
+                        f"Failed to check the current session ({session_id}) or reconnect to the server "
+                        f"(error: {type(e).__name__}, message: {e})"
+                    )
+        except asyncio.CancelledError:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+            raise
+
+    async def receive_messages(self) -> None:
+        # In the asyncio runtime, accessing a shared object (self.current_session here) from
+        # multiple tasks can cause race conditions and errors.
+        # To avoid such, we access only the session that is active when this loop starts.
+        session = self.current_session
+        session_id = self.build_session_id(session)  # type: ignore[arg-type]
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new receive_messages() execution loop with {session_id} started")
+        try:
+            consecutive_error_count = 0
+            logging_interval = 100
+            counter_for_logging = 0
+
+            while not self.closed:
+                if session != self.current_session:
+                    if self.logger.level <= logging.DEBUG:
+                        self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+                    break
+                try:
+                    message: WSMessage = await session.receive()  # type: ignore[union-attr]
+                    # just in case, checking if the value is not None
+                    if message is not None:
+                        if self.logger.level <= logging.DEBUG:
+                            # The following logging prints every single received message
+                            # except empty message data ones.
+                            m_type = WSMsgType(message.type)
+                            message_type = m_type.name if m_type is not None else message.type
+                            message_data = message.data
+                            if isinstance(message_data, bytes):
+                                message_data = message_data.decode("utf-8")
+                            if message_data is not None and isinstance(message_data, (str, bytes)) and len(message_data) > 0:
+                                # To skip the empty message that Slack server-side often sends
+                                self.logger.debug(
+                                    f"Received message "
+                                    f"(type: {message_type}, "
+                                    f"data: {message_data}, "
+                                    f"extra: {message.extra}, "
+                                    f"session: {session_id})"
+                                )
+
+                            if self.trace_enabled:
+                                # The logging here is for detailed trouble shooting of potential issues in this client.
+                                # If you don't see this log for a while, it can mean that
+                                # this receive_messages execution is no longer working for some reason.
+                                counter_for_logging += 1
+                                if counter_for_logging >= logging_interval:
+                                    counter_for_logging = 0
+                                    log_message = (
+                                        "#receive_messages method has been working without any issues "
+                                        f"(session: {session_id}, logging interval: {logging_interval})"
+                                    )
+                                    self.logger.debug(log_message)
+
+                        if message.type == WSMsgType.TEXT:
+                            message_data = message.data
+                            await self.enqueue_message(message_data)
+                            for listener in self.on_message_listeners:
+                                await listener(message)
+                        elif message.type == WSMsgType.CLOSE:
+                            if self.auto_reconnect_enabled:
+                                self.logger.info(f"Received CLOSE event from {session_id}. Reconnecting...")
+                                await self.connect_to_new_endpoint()
+                            for listener in self.on_close_listeners:
+                                await listener(message)
+                        elif message.type == WSMsgType.ERROR:
+                            for listener in self.on_error_listeners:
+                                await listener(message)
+                        elif message.type == WSMsgType.CLOSED:
+                            await asyncio.sleep(self.ping_interval)
+                            continue
+                        elif message.type == WSMsgType.PING:
+                            await session.pong(message.data)  # type: ignore[union-attr]
+                            continue
+                        elif message.type == WSMsgType.PONG:
+                            if message.data is not None:
+                                str_message_data = message.data.decode("utf-8")
+                                elements = str_message_data.split(":")
+                                if len(elements) == 2 and elements[0] == "sdk-ping-pong":
+                                    try:
+                                        self.last_ping_pong_time = float(elements[1])
+                                    except Exception as e:
+                                        self.logger.warning(
+                                            f"Failed to parse the last_ping_pong_time value from {str_message_data}"
+                                            f" - error : {e}, session: {session_id}"
+                                        )
+                            continue
+
+                    consecutive_error_count = 0
+
+                except Exception as e:
+                    consecutive_error_count += 1
+                    self.logger.error(f"Failed to receive or enqueue a message: {type(e).__name__}, {e} ({session_id})")
+                    if isinstance(e, ClientConnectionError):
+                        await asyncio.sleep(self.ping_interval)
+                    else:
+                        await asyncio.sleep(consecutive_error_count)
+        except asyncio.CancelledError:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+            raise
+
+    async def is_ping_pong_failing(self) -> bool:
+        if self.last_ping_pong_time is None:
+            return False
+        disconnected_seconds = int(time.time() - self.last_ping_pong_time)
+        return disconnected_seconds >= (self.ping_interval * 4)
+
+    async def is_connected(self) -> bool:
+        connected: bool = (
+            not self.closed
+            and not self.stale
+            and self.current_session is not None
+            and not self.current_session.closed
+            and not await self.is_ping_pong_failing()
+        )
+        if self.logger.level <= logging.DEBUG and connected is False:
+            # Prints more detailed information about the inactive connection
+            is_ping_pong_failing = await self.is_ping_pong_failing()
+            session_id = await self.session_id()
+            self.logger.debug(
+                "Inactive connection detected ("
+                f"session_id: {session_id}, "
+                f"closed: {self.closed}, "
+                f"stale: {self.stale}, "
+                f"current_session.closed: {self.current_session and self.current_session.closed}, "
+                f"is_ping_pong_failing: {is_ping_pong_failing}"
+                ")"
+            )
+        return connected
+
+    async def session_id(self) -> str:
+        return self.build_session_id(self.current_session)  # type: ignore[arg-type]
+
+    async def connect(self):
+        # This loop is used to ensure when a new session is created,
+        # a new monitor and a new message receiver are also created.
+        # If a new session is created but we failed to create the new
+        # monitor or the new message, we should try it.
+        while True:
+            try:
+                old_session: Optional[ClientWebSocketResponse] = (
+                    None if self.current_session is None else self.current_session
+                )
+
+                # If the old session is broken (e.g. reset by peer), it might fail to close it.
+                # We don't want to retry when this kind of cases happen.
+                try:
+                    # We should close old session before create a new one. Because when disconnect
+                    # reason is `too_many_websockets`, we need to close the old one first to
+                    # to decrease the number of connections.
+                    self.auto_reconnect_enabled = False
+                    if old_session is not None:
+                        await old_session.close()
+                        old_session_id = self.build_session_id(old_session)
+                        self.logger.info(f"The old session ({old_session_id}) has been abandoned")
+                except Exception as e:
+                    self.logger.exception(f"Failed to close the old session : {e}")
+
+                if self.wss_uri is None:
+                    # If the underlying WSS URL does not exist,
+                    # acquiring a new active WSS URL from the server-side first
+                    self.wss_uri = await self.issue_new_wss_url()
+
+                self.current_session = await self.aiohttp_client_session.ws_connect(
+                    self.wss_uri,
+                    autoping=False,
+                    heartbeat=self.ping_interval,
+                    proxy=self.proxy,
+                    ssl=self.web_client.ssl,
+                )
+                session_id: str = await self.session_id()
+                self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+                self.stale = False
+                self.logger.info(f"A new session ({session_id}) has been established")
+
+                # The first ping from the new connection
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"Sending a ping message with the newly established connection ({session_id})...")
+                t = time.time()
+                await self.current_session.ping(f"sdk-ping-pong:{t}".encode("utf-8"))
+
+                if self.current_session_monitor is not None:
+                    self.current_session_monitor.cancel()
+                self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session())
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}")
+
+                if self.message_receiver is not None:
+                    self.message_receiver.cancel()
+                self.message_receiver = asyncio.ensure_future(self.receive_messages())
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}")
+                break
+            except Exception as e:
+                self.logger.exception(f"Failed to connect (error: {e}); Retrying...")
+                await asyncio.sleep(self.ping_interval)
+
+    async def disconnect(self):
+        if self.current_session is not None:
+            await self.current_session.close()
+        session_id = await self.session_id()
+        self.logger.info(f"The current session ({session_id}) has been abandoned by disconnect() method call")
+
+    async def send_message(self, message: str):
+        session_id = await self.session_id()
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message: {message} from session: {session_id}")
+        try:
+            await self.current_session.send_str(message)  # type: ignore[union-attr]
+        except ConnectionError as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (error: {e}, message: {message}, session: {session_id})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            try:
+                await self.connect_operation_lock.acquire()
+                if await self.is_connected():
+                    await self.current_session.send_str(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(
+                        f"The current session ({session_id}) is no longer active. " "Failed to send a message"
+                    )
+                    raise e
+            finally:
+                if self.connect_operation_lock.locked() is True:
+                    self.connect_operation_lock.release()
+
+    async def close(self):
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        await self.disconnect()
+        if self.message_processor is not None:
+            self.message_processor.cancel()
+        if self.current_session_monitor is not None:
+            self.current_session_monitor.cancel()
+        if self.message_receiver is not None:
+            self.message_receiver.cancel()
+        if self.aiohttp_client_session is not None:
+            await self.aiohttp_client_session.close()
+
+    @classmethod
+    def build_session_id(cls, session: ClientWebSocketResponse) -> str:
+        if session is None:
+            return ""
+        return "s_" + str(hash(session))
+
+

Socket Mode client

+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
trace_enabled
+
True if more verbose logs to see what's happening under the hood
+
proxy
+
the HTTP proxy URL
+
on_message_listeners
+
listener functions for on_message
+
on_error_listeners
+
listener functions for on_error
+
on_close_listeners
+
listener functions for on_close
+
loop
+
an existing asyncio event loop
+
+

Ancestors

+ +

Class variables

+
+
var current_session :Β aiohttp.client_ws.ClientWebSocketResponseΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_monitor :Β _asyncio.FutureΒ |Β None
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var last_ping_pong_time :Β floatΒ |Β None
+
+

The type of the None singleton.

+
+
var message_processor :Β _asyncio.Future
+
+

The type of the None singleton.

+
+
var message_receiver :Β _asyncio.FutureΒ |Β None
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[aiohttp._websocket.models.WSMessage],Β Awaitable[None]]]
+
+

The type of the None singleton.

+
+
var ping_interval :Β float
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var stale :Β bool
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_session_id(session:Β aiohttp.client_ws.ClientWebSocketResponse) ‑>Β str +
+
+
+
+
+

Methods

+
+
+async def close(self) +
+
+
+ +Expand source code + +
async def close(self):
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    await self.disconnect()
+    if self.message_processor is not None:
+        self.message_processor.cancel()
+    if self.current_session_monitor is not None:
+        self.current_session_monitor.cancel()
+    if self.message_receiver is not None:
+        self.message_receiver.cancel()
+    if self.aiohttp_client_session is not None:
+        await self.aiohttp_client_session.close()
+
+
+
+
+async def connect(self) +
+
+
+ +Expand source code + +
async def connect(self):
+    # This loop is used to ensure when a new session is created,
+    # a new monitor and a new message receiver are also created.
+    # If a new session is created but we failed to create the new
+    # monitor or the new message, we should try it.
+    while True:
+        try:
+            old_session: Optional[ClientWebSocketResponse] = (
+                None if self.current_session is None else self.current_session
+            )
+
+            # If the old session is broken (e.g. reset by peer), it might fail to close it.
+            # We don't want to retry when this kind of cases happen.
+            try:
+                # We should close old session before create a new one. Because when disconnect
+                # reason is `too_many_websockets`, we need to close the old one first to
+                # to decrease the number of connections.
+                self.auto_reconnect_enabled = False
+                if old_session is not None:
+                    await old_session.close()
+                    old_session_id = self.build_session_id(old_session)
+                    self.logger.info(f"The old session ({old_session_id}) has been abandoned")
+            except Exception as e:
+                self.logger.exception(f"Failed to close the old session : {e}")
+
+            if self.wss_uri is None:
+                # If the underlying WSS URL does not exist,
+                # acquiring a new active WSS URL from the server-side first
+                self.wss_uri = await self.issue_new_wss_url()
+
+            self.current_session = await self.aiohttp_client_session.ws_connect(
+                self.wss_uri,
+                autoping=False,
+                heartbeat=self.ping_interval,
+                proxy=self.proxy,
+                ssl=self.web_client.ssl,
+            )
+            session_id: str = await self.session_id()
+            self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+            self.stale = False
+            self.logger.info(f"A new session ({session_id}) has been established")
+
+            # The first ping from the new connection
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"Sending a ping message with the newly established connection ({session_id})...")
+            t = time.time()
+            await self.current_session.ping(f"sdk-ping-pong:{t}".encode("utf-8"))
+
+            if self.current_session_monitor is not None:
+                self.current_session_monitor.cancel()
+            self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session())
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}")
+
+            if self.message_receiver is not None:
+                self.message_receiver.cancel()
+            self.message_receiver = asyncio.ensure_future(self.receive_messages())
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}")
+            break
+        except Exception as e:
+            self.logger.exception(f"Failed to connect (error: {e}); Retrying...")
+            await asyncio.sleep(self.ping_interval)
+
+
+
+
+async def disconnect(self) +
+
+
+ +Expand source code + +
async def disconnect(self):
+    if self.current_session is not None:
+        await self.current_session.close()
+    session_id = await self.session_id()
+    self.logger.info(f"The current session ({session_id}) has been abandoned by disconnect() method call")
+
+
+
+
+async def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
async def is_connected(self) -> bool:
+    connected: bool = (
+        not self.closed
+        and not self.stale
+        and self.current_session is not None
+        and not self.current_session.closed
+        and not await self.is_ping_pong_failing()
+    )
+    if self.logger.level <= logging.DEBUG and connected is False:
+        # Prints more detailed information about the inactive connection
+        is_ping_pong_failing = await self.is_ping_pong_failing()
+        session_id = await self.session_id()
+        self.logger.debug(
+            "Inactive connection detected ("
+            f"session_id: {session_id}, "
+            f"closed: {self.closed}, "
+            f"stale: {self.stale}, "
+            f"current_session.closed: {self.current_session and self.current_session.closed}, "
+            f"is_ping_pong_failing: {is_ping_pong_failing}"
+            ")"
+        )
+    return connected
+
+
+
+
+async def is_ping_pong_failing(self) ‑>Β bool +
+
+
+ +Expand source code + +
async def is_ping_pong_failing(self) -> bool:
+    if self.last_ping_pong_time is None:
+        return False
+    disconnected_seconds = int(time.time() - self.last_ping_pong_time)
+    return disconnected_seconds >= (self.ping_interval * 4)
+
+
+
+
+async def monitor_current_session(self) ‑>Β None +
+
+
+ +Expand source code + +
async def monitor_current_session(self) -> None:
+    # In the asyncio runtime, accessing a shared object (self.current_session here) from
+    # multiple tasks can cause race conditions and errors.
+    # To avoid such, we access only the session that is active when this loop starts.
+    session: ClientWebSocketResponse = self.current_session  # type: ignore[assignment]
+    session_id: str = self.build_session_id(session)
+
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started")
+    try:
+        logging_interval = 100
+        counter_for_logging = 0
+
+        while not self.closed:
+            if session != self.current_session:
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+                break
+            try:
+                if self.trace_enabled and self.logger.level <= logging.DEBUG:
+                    # The logging here is for detailed investigation on potential issues in this client.
+                    # If you don't see this log for a while, it means that
+                    # this receive_messages execution is no longer working for some reason.
+                    counter_for_logging += 1
+                    if counter_for_logging >= logging_interval:
+                        counter_for_logging = 0
+                        log_message = (
+                            "#monitor_current_session method has been verifying if this session is active "
+                            f"(session: {session_id}, logging interval: {logging_interval})"
+                        )
+                        self.logger.debug(log_message)
+
+                await asyncio.sleep(self.ping_interval)
+
+                if session is not None and session.closed is False:
+                    t = time.time()
+                    if self.last_ping_pong_time is None:
+                        self.last_ping_pong_time = float(t)
+                    try:
+                        await session.ping(f"sdk-ping-pong:{t}".encode("utf-8"))
+                    except Exception as e:
+                        # The ping() method can fail for some reason.
+                        # To establish a new connection even in this scenario,
+                        # we ignore the exception here.
+                        self.logger.warning(f"Failed to send a ping message ({session_id}): {e}")
+
+                if self.auto_reconnect_enabled:
+                    should_reconnect = False
+                    if session is None or session.closed:
+                        self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...")
+                        should_reconnect = True
+
+                    if await self.is_ping_pong_failing():
+                        disconnected_seconds = int(time.time() - self.last_ping_pong_time)  # type: ignore[operator]
+                        self.logger.info(
+                            f"The session ({session_id}) seems to be stale. Reconnecting..."
+                            f" reason: disconnected for {disconnected_seconds}+ seconds)"
+                        )
+                        self.stale = True
+                        self.last_ping_pong_time = None
+                        should_reconnect = True
+
+                    if should_reconnect is True or not await self.is_connected():
+                        await self.connect_to_new_endpoint()
+
+            except Exception as e:
+                self.logger.error(
+                    f"Failed to check the current session ({session_id}) or reconnect to the server "
+                    f"(error: {type(e).__name__}, message: {e})"
+                )
+    except asyncio.CancelledError:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+        raise
+
+
+
+
+async def receive_messages(self) ‑>Β None +
+
+
+ +Expand source code + +
async def receive_messages(self) -> None:
+    # In the asyncio runtime, accessing a shared object (self.current_session here) from
+    # multiple tasks can cause race conditions and errors.
+    # To avoid such, we access only the session that is active when this loop starts.
+    session = self.current_session
+    session_id = self.build_session_id(session)  # type: ignore[arg-type]
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new receive_messages() execution loop with {session_id} started")
+    try:
+        consecutive_error_count = 0
+        logging_interval = 100
+        counter_for_logging = 0
+
+        while not self.closed:
+            if session != self.current_session:
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+                break
+            try:
+                message: WSMessage = await session.receive()  # type: ignore[union-attr]
+                # just in case, checking if the value is not None
+                if message is not None:
+                    if self.logger.level <= logging.DEBUG:
+                        # The following logging prints every single received message
+                        # except empty message data ones.
+                        m_type = WSMsgType(message.type)
+                        message_type = m_type.name if m_type is not None else message.type
+                        message_data = message.data
+                        if isinstance(message_data, bytes):
+                            message_data = message_data.decode("utf-8")
+                        if message_data is not None and isinstance(message_data, (str, bytes)) and len(message_data) > 0:
+                            # To skip the empty message that Slack server-side often sends
+                            self.logger.debug(
+                                f"Received message "
+                                f"(type: {message_type}, "
+                                f"data: {message_data}, "
+                                f"extra: {message.extra}, "
+                                f"session: {session_id})"
+                            )
+
+                        if self.trace_enabled:
+                            # The logging here is for detailed trouble shooting of potential issues in this client.
+                            # If you don't see this log for a while, it can mean that
+                            # this receive_messages execution is no longer working for some reason.
+                            counter_for_logging += 1
+                            if counter_for_logging >= logging_interval:
+                                counter_for_logging = 0
+                                log_message = (
+                                    "#receive_messages method has been working without any issues "
+                                    f"(session: {session_id}, logging interval: {logging_interval})"
+                                )
+                                self.logger.debug(log_message)
+
+                    if message.type == WSMsgType.TEXT:
+                        message_data = message.data
+                        await self.enqueue_message(message_data)
+                        for listener in self.on_message_listeners:
+                            await listener(message)
+                    elif message.type == WSMsgType.CLOSE:
+                        if self.auto_reconnect_enabled:
+                            self.logger.info(f"Received CLOSE event from {session_id}. Reconnecting...")
+                            await self.connect_to_new_endpoint()
+                        for listener in self.on_close_listeners:
+                            await listener(message)
+                    elif message.type == WSMsgType.ERROR:
+                        for listener in self.on_error_listeners:
+                            await listener(message)
+                    elif message.type == WSMsgType.CLOSED:
+                        await asyncio.sleep(self.ping_interval)
+                        continue
+                    elif message.type == WSMsgType.PING:
+                        await session.pong(message.data)  # type: ignore[union-attr]
+                        continue
+                    elif message.type == WSMsgType.PONG:
+                        if message.data is not None:
+                            str_message_data = message.data.decode("utf-8")
+                            elements = str_message_data.split(":")
+                            if len(elements) == 2 and elements[0] == "sdk-ping-pong":
+                                try:
+                                    self.last_ping_pong_time = float(elements[1])
+                                except Exception as e:
+                                    self.logger.warning(
+                                        f"Failed to parse the last_ping_pong_time value from {str_message_data}"
+                                        f" - error : {e}, session: {session_id}"
+                                    )
+                        continue
+
+                consecutive_error_count = 0
+
+            except Exception as e:
+                consecutive_error_count += 1
+                self.logger.error(f"Failed to receive or enqueue a message: {type(e).__name__}, {e} ({session_id})")
+                if isinstance(e, ClientConnectionError):
+                    await asyncio.sleep(self.ping_interval)
+                else:
+                    await asyncio.sleep(consecutive_error_count)
+    except asyncio.CancelledError:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+        raise
+
+
+
+
+async def send_message(self, message:Β str) +
+
+
+ +Expand source code + +
async def send_message(self, message: str):
+    session_id = await self.session_id()
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message: {message} from session: {session_id}")
+    try:
+        await self.current_session.send_str(message)  # type: ignore[union-attr]
+    except ConnectionError as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (error: {e}, message: {message}, session: {session_id})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        try:
+            await self.connect_operation_lock.acquire()
+            if await self.is_connected():
+                await self.current_session.send_str(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(
+                    f"The current session ({session_id}) is no longer active. " "Failed to send a message"
+                )
+                raise e
+        finally:
+            if self.connect_operation_lock.locked() is True:
+                self.connect_operation_lock.release()
+
+
+
+
+async def session_id(self) ‑>Β str +
+
+
+ +Expand source code + +
async def session_id(self) -> str:
+    return self.build_session_id(self.current_session)  # type: ignore[arg-type]
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/async_client.html b/docs/reference/socket_mode/async_client.html new file mode 100644 index 000000000..20d07951a --- /dev/null +++ b/docs/reference/socket_mode/async_client.html @@ -0,0 +1,575 @@ + + + + + + +slack_sdk.socket_mode.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.async_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncBaseSocketModeClient +
+
+
+ +Expand source code + +
class AsyncBaseSocketModeClient:
+    logger: Logger
+    web_client: AsyncWebClient
+    app_token: str
+    wss_uri: str
+    auto_reconnect_enabled: bool
+    trace_enabled: bool
+    closed: bool
+    connect_operation_lock: Lock
+
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            AsyncWebSocketMessageListener,
+            Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            AsyncSocketModeRequestListener,
+            Callable[["AsyncBaseSocketModeClient", SocketModeRequest], Awaitable[None]],
+        ]
+    ]
+
+    async def issue_new_wss_url(self) -> str:
+        try:
+            response = await self.web_client.apps_connections_open(app_token=self.app_token)
+            return response["url"]
+        except SlackApiError as e:
+            if e.response["error"] == "ratelimited":
+                # NOTE: ratelimited errors rarely occur with this endpoint
+                delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+                self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+                await asyncio.sleep(delay)
+                # Retry to issue a new WSS URL
+                return await self.issue_new_wss_url()
+            else:
+                # other errors
+                self.logger.error(f"Failed to retrieve WSS URL: {e}")
+                raise e
+
+    async def is_connected(self) -> bool:
+        return False
+
+    async def session_id(self) -> str:
+        return ""
+
+    async def connect(self):
+        raise NotImplementedError()
+
+    async def disconnect(self):
+        raise NotImplementedError()
+
+    async def connect_to_new_endpoint(self, force: bool = False):
+        session_id = await self.session_id()
+        try:
+            await self.connect_operation_lock.acquire()
+            if self.trace_enabled:
+                self.logger.debug(f"For reconnection, the connect_operation_lock was acquired (session: {session_id})")
+            if force or not await self.is_connected():
+                self.wss_uri = await self.issue_new_wss_url()
+                await self.connect()
+        finally:
+            if self.connect_operation_lock.locked() is True:
+                self.connect_operation_lock.release()
+                if self.trace_enabled:
+                    self.logger.debug(f"The connect_operation_lock for reconnection was released (session: {session_id})")
+
+    async def close(self):
+        self.closed = True
+        await self.disconnect()
+
+    async def send_message(self, message: str):
+        raise NotImplementedError()
+
+    async def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]):
+        if isinstance(response, SocketModeResponse):
+            await self.send_message(json.dumps(response.to_dict()))
+        else:
+            await self.send_message(json.dumps(response))
+
+    async def enqueue_message(self, message: str):
+        await self.message_queue.put(message)
+        if self.logger.level <= logging.DEBUG:
+            queue_size = self.message_queue.qsize()
+            session_id = await self.session_id()
+            self.logger.debug(f"A new message enqueued (current queue size: {queue_size}, session: {session_id})")
+
+    async def process_messages(self):
+        session_id = await self.session_id()
+        try:
+            while not self.closed:
+                try:
+                    await self.process_message()
+                except asyncio.CancelledError:
+                    # if self.closed is True, the connection is already closed
+                    # In this case, we can ignore the exception here
+                    if not self.closed:
+                        raise
+                except Exception as e:
+                    self.logger.exception(f"Failed to process a message: {e}, session: {session_id}")
+        except asyncio.CancelledError:
+            if self.trace_enabled:
+                self.logger.debug(f"The running process_messages task for {session_id} is now cancelled")
+            raise
+
+    async def process_message(self):
+        raw_message = await self.message_queue.get()
+        if raw_message is not None:
+            message: dict = {}
+            if raw_message.startswith("{"):
+                message = json.loads(raw_message)
+            _: Future[None] = asyncio.ensure_future(self.run_message_listeners(message, raw_message))
+
+    async def run_message_listeners(self, message: dict, raw_message: str) -> None:
+        session_id = await self.session_id()
+        type, envelope_id = message.get("type"), message.get("envelope_id")
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Message processing started (type: {type}, envelope_id: {envelope_id}, session: {session_id})"
+            )
+        try:
+            if message.get("type") == "disconnect":
+                await self.connect_to_new_endpoint(force=True)
+                return
+
+            for listener in self.message_listeners:
+                try:
+                    await listener(self, message, raw_message)  # type: ignore[call-arg, arg-type, misc]
+                except Exception as e:
+                    self.logger.exception(f"Failed to run a message listener: {e}, session: {session_id}")
+
+            if len(self.socket_mode_request_listeners) > 0:
+                request = SocketModeRequest.from_dict(message)
+                if request is not None:
+                    for listener in self.socket_mode_request_listeners:  # type: ignore[assignment]
+                        try:
+                            await listener(self, request)  # type: ignore[call-arg, arg-type]
+                        except Exception as e:
+                            self.logger.exception(f"Failed to run a request listener: {e}, session: {session_id}")
+        except Exception as e:
+            self.logger.exception(f"Failed to run message listeners: {e}, session: {session_id}")
+        finally:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Message processing completed ("
+                    f"type: {type}, "
+                    f"envelope_id: {envelope_id}, "
+                    f"session: {session_id})"
+                )
+
+
+

Subclasses

+ +

Class variables

+
+
var app_token :Β str
+
+

The type of the None singleton.

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var closed :Β bool
+
+

The type of the None singleton.

+
+
var connect_operation_lock :Β asyncio.locks.Lock
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var message_listeners :Β List[AsyncWebSocketMessageListenerΒ |Β Callable[[AsyncBaseSocketModeClient,Β dict,Β strΒ |Β None],Β Awaitable[None]]]
+
+

The type of the None singleton.

+
+
var message_queue :Β asyncio.queues.Queue
+
+

The type of the None singleton.

+
+
var socket_mode_request_listeners :Β List[AsyncSocketModeRequestListenerΒ |Β Callable[[AsyncBaseSocketModeClient,Β SocketModeRequest],Β Awaitable[None]]]
+
+

The type of the None singleton.

+
+
var trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
var web_client :Β AsyncWebClient
+
+

The type of the None singleton.

+
+
var wss_uri :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def close(self) +
+
+
+ +Expand source code + +
async def close(self):
+    self.closed = True
+    await self.disconnect()
+
+
+
+
+async def connect(self) +
+
+
+ +Expand source code + +
async def connect(self):
+    raise NotImplementedError()
+
+
+
+
+async def connect_to_new_endpoint(self, force:Β boolΒ =Β False) +
+
+
+ +Expand source code + +
async def connect_to_new_endpoint(self, force: bool = False):
+    session_id = await self.session_id()
+    try:
+        await self.connect_operation_lock.acquire()
+        if self.trace_enabled:
+            self.logger.debug(f"For reconnection, the connect_operation_lock was acquired (session: {session_id})")
+        if force or not await self.is_connected():
+            self.wss_uri = await self.issue_new_wss_url()
+            await self.connect()
+    finally:
+        if self.connect_operation_lock.locked() is True:
+            self.connect_operation_lock.release()
+            if self.trace_enabled:
+                self.logger.debug(f"The connect_operation_lock for reconnection was released (session: {session_id})")
+
+
+
+
+async def disconnect(self) +
+
+
+ +Expand source code + +
async def disconnect(self):
+    raise NotImplementedError()
+
+
+
+
+async def enqueue_message(self, message:Β str) +
+
+
+ +Expand source code + +
async def enqueue_message(self, message: str):
+    await self.message_queue.put(message)
+    if self.logger.level <= logging.DEBUG:
+        queue_size = self.message_queue.qsize()
+        session_id = await self.session_id()
+        self.logger.debug(f"A new message enqueued (current queue size: {queue_size}, session: {session_id})")
+
+
+
+
+async def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
async def is_connected(self) -> bool:
+    return False
+
+
+
+
+async def issue_new_wss_url(self) ‑>Β str +
+
+
+ +Expand source code + +
async def issue_new_wss_url(self) -> str:
+    try:
+        response = await self.web_client.apps_connections_open(app_token=self.app_token)
+        return response["url"]
+    except SlackApiError as e:
+        if e.response["error"] == "ratelimited":
+            # NOTE: ratelimited errors rarely occur with this endpoint
+            delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+            self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+            await asyncio.sleep(delay)
+            # Retry to issue a new WSS URL
+            return await self.issue_new_wss_url()
+        else:
+            # other errors
+            self.logger.error(f"Failed to retrieve WSS URL: {e}")
+            raise e
+
+
+
+
+async def process_message(self) +
+
+
+ +Expand source code + +
async def process_message(self):
+    raw_message = await self.message_queue.get()
+    if raw_message is not None:
+        message: dict = {}
+        if raw_message.startswith("{"):
+            message = json.loads(raw_message)
+        _: Future[None] = asyncio.ensure_future(self.run_message_listeners(message, raw_message))
+
+
+
+
+async def process_messages(self) +
+
+
+ +Expand source code + +
async def process_messages(self):
+    session_id = await self.session_id()
+    try:
+        while not self.closed:
+            try:
+                await self.process_message()
+            except asyncio.CancelledError:
+                # if self.closed is True, the connection is already closed
+                # In this case, we can ignore the exception here
+                if not self.closed:
+                    raise
+            except Exception as e:
+                self.logger.exception(f"Failed to process a message: {e}, session: {session_id}")
+    except asyncio.CancelledError:
+        if self.trace_enabled:
+            self.logger.debug(f"The running process_messages task for {session_id} is now cancelled")
+        raise
+
+
+
+
+async def run_message_listeners(self, message:Β dict, raw_message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
async def run_message_listeners(self, message: dict, raw_message: str) -> None:
+    session_id = await self.session_id()
+    type, envelope_id = message.get("type"), message.get("envelope_id")
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(
+            f"Message processing started (type: {type}, envelope_id: {envelope_id}, session: {session_id})"
+        )
+    try:
+        if message.get("type") == "disconnect":
+            await self.connect_to_new_endpoint(force=True)
+            return
+
+        for listener in self.message_listeners:
+            try:
+                await listener(self, message, raw_message)  # type: ignore[call-arg, arg-type, misc]
+            except Exception as e:
+                self.logger.exception(f"Failed to run a message listener: {e}, session: {session_id}")
+
+        if len(self.socket_mode_request_listeners) > 0:
+            request = SocketModeRequest.from_dict(message)
+            if request is not None:
+                for listener in self.socket_mode_request_listeners:  # type: ignore[assignment]
+                    try:
+                        await listener(self, request)  # type: ignore[call-arg, arg-type]
+                    except Exception as e:
+                        self.logger.exception(f"Failed to run a request listener: {e}, session: {session_id}")
+    except Exception as e:
+        self.logger.exception(f"Failed to run message listeners: {e}, session: {session_id}")
+    finally:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Message processing completed ("
+                f"type: {type}, "
+                f"envelope_id: {envelope_id}, "
+                f"session: {session_id})"
+            )
+
+
+
+
+async def send_message(self, message:Β str) +
+
+
+ +Expand source code + +
async def send_message(self, message: str):
+    raise NotImplementedError()
+
+
+
+
+async def send_socket_mode_response(self,
response:Β Dict[str,Β Any]Β |Β SocketModeResponse)
+
+
+
+ +Expand source code + +
async def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]):
+    if isinstance(response, SocketModeResponse):
+        await self.send_message(json.dumps(response.to_dict()))
+    else:
+        await self.send_message(json.dumps(response))
+
+
+
+
+async def session_id(self) ‑>Β str +
+
+
+ +Expand source code + +
async def session_id(self) -> str:
+    return ""
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/async_listeners.html b/docs/reference/socket_mode/async_listeners.html new file mode 100644 index 000000000..e78b3c29e --- /dev/null +++ b/docs/reference/socket_mode/async_listeners.html @@ -0,0 +1,158 @@ + + + + + + +slack_sdk.socket_mode.async_listeners API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.async_listeners

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSocketModeRequestListener +
+
+
+ +Expand source code + +
class AsyncSocketModeRequestListener(Callable):  # type: ignore[misc]
+    async def __call__(
+        client: "AsyncBaseSocketModeClient",  # type: ignore[name-defined] # noqa: F821
+        request: SocketModeRequest,
+    ):  # noqa: F821
+        raise NotImplementedError()
+
+

Abstract base class for generic types.

+

On Python 3.12 and newer, generic classes implicitly inherit from +Generic when they declare a parameter list after the class's name::

+
class Mapping[KT, VT]:
+    def __getitem__(self, key: KT) -> VT:
+        ...
+    # Etc.
+
+

On older versions of Python, however, generic classes have to +explicitly inherit from Generic.

+

After a class has been declared to be generic, it can then be used as +follows::

+
def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
+    try:
+        return mapping[key]
+    except KeyError:
+        return default
+
+

Ancestors

+
    +
  • collections.abc.Callable
  • +
  • typing.Generic
  • +
+
+
+class AsyncWebSocketMessageListener +
+
+
+ +Expand source code + +
class AsyncWebSocketMessageListener(Callable):  # type: ignore[misc]
+    async def __call__(
+        client: "AsyncBaseSocketModeClient",  # type: ignore[name-defined] # noqa: F821
+        message: dict,
+        raw_message: Optional[str] = None,
+    ):  # noqa: F821
+        raise NotImplementedError()
+
+

Abstract base class for generic types.

+

On Python 3.12 and newer, generic classes implicitly inherit from +Generic when they declare a parameter list after the class's name::

+
class Mapping[KT, VT]:
+    def __getitem__(self, key: KT) -> VT:
+        ...
+    # Etc.
+
+

On older versions of Python, however, generic classes have to +explicitly inherit from Generic.

+

After a class has been declared to be generic, it can then be used as +follows::

+
def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
+    try:
+        return mapping[key]
+    except KeyError:
+        return default
+
+

Ancestors

+
    +
  • collections.abc.Callable
  • +
  • typing.Generic
  • +
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/builtin/client.html b/docs/reference/socket_mode/builtin/client.html new file mode 100644 index 000000000..8e55f2347 --- /dev/null +++ b/docs/reference/socket_mode/builtin/client.html @@ -0,0 +1,631 @@ + + + + + + +slack_sdk.socket_mode.builtin.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.builtin.client

+
+
+

The built-in Socket Mode client

+ +
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False,
ping_interval:Β floatΒ =Β 5,
receive_buffer_size:Β intΒ =Β 1024,
concurrency:Β intΒ =Β 10,
proxy:Β strΒ |Β NoneΒ =Β None,
proxy_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[int,Β strΒ |Β None],Β None]]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeClient(BaseSocketModeClient):
+    logger: Logger
+    web_client: WebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            WebSocketMessageListener,
+            Callable[["BaseSocketModeClient", dict, Optional[str]], None],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            SocketModeRequestListener,
+            Callable[["BaseSocketModeClient", SocketModeRequest], None],
+        ]
+    ]
+
+    current_session: Optional[Connection]
+    current_session_state: ConnectionState
+    current_session_runner: IntervalRunner
+
+    current_app_monitor: IntervalRunner
+    current_app_monitor_started: bool
+
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    auto_reconnect_enabled: bool
+    default_auto_reconnect_enabled: bool
+    trace_enabled: bool
+    receive_buffer_size: int  # bytes size
+
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[str], None]]
+    on_error_listeners: List[Callable[[Exception], None]]
+    on_close_listeners: List[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+        ping_interval: float = 5,
+        receive_buffer_size: int = 1024,
+        concurrency: int = 10,
+        proxy: Optional[str] = None,
+        proxy_headers: Optional[Dict[str, str]] = None,
+        on_message_listeners: Optional[List[Callable[[str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
+    ):
+        """Socket Mode client
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            trace_enabled: True if more detailed debug-logging is enabled (default: False)
+            all_message_trace_enabled: True if all message dump in debug logs is enabled (default: False)
+            ping_pong_trace_enabled: True if trace logging for all ping-pong communications is enabled (default: False)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            receive_buffer_size: the chunk size of a single socket recv operation (default: 1024)
+            concurrency: the size of thread pool (default: 10)
+            proxy: the HTTP proxy URL
+            proxy_headers: additional HTTP header for proxy connection
+            on_message_listeners: listener functions for on_message
+            on_error_listeners: listener functions for on_error
+            on_close_listeners: listener functions for on_close
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or WebClient()
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+        self.ping_interval = ping_interval
+        self.receive_buffer_size = receive_buffer_size
+        if self.receive_buffer_size < 16:
+            raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
+
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_state = ConnectionState()
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval)
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+        self.proxy = proxy
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+        self.proxy_headers = proxy_headers
+
+        self.on_message_listeners = on_message_listeners or []
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+    def session_id(self) -> Optional[str]:
+        if self.current_session is not None:
+            return self.current_session.session_id
+        return None
+
+    def is_connected(self) -> bool:
+        return self.current_session is not None and self.current_session.is_active()
+
+    def connect(self) -> None:
+        old_session: Optional[Connection] = self.current_session
+        old_current_session_state: ConnectionState = self.current_session_state
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        current_session = Connection(
+            url=self.wss_uri,
+            logger=self.logger,
+            ping_interval=self.ping_interval,
+            trace_enabled=self.trace_enabled,
+            all_message_trace_enabled=self.all_message_trace_enabled,
+            ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+            receive_buffer_size=self.receive_buffer_size,
+            proxy=self.proxy,
+            proxy_headers=self.proxy_headers,
+            on_message_listener=self._on_message,
+            on_error_listener=self._on_error,
+            on_close_listener=self._on_close,
+            ssl_context=self.web_client.ssl,
+        )
+        current_session.connect()
+
+        if old_current_session_state is not None:
+            old_current_session_state.terminated = True
+        if old_session is not None:
+            old_session.close()
+
+        self.current_session = current_session
+        self.current_session_state = ConnectionState()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+    def disconnect(self) -> None:
+        if self.current_session is not None:
+            self.current_session.close()
+
+    def send_message(self, message: str) -> None:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+        try:
+            self.current_session.send(message)  # type: ignore[union-attr]
+        except SlackClientNotConnectedError as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            with self.connect_operation_lock:
+                if self.is_connected():
+                    self.current_session.send(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(
+                        f"The current session (session id: {self.session_id()}) is no longer active. "
+                        "Failed to send a message"
+                    )
+                    raise e
+
+    def close(self):
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        self.disconnect()
+        if self.current_app_monitor.is_alive():
+            self.current_app_monitor.shutdown()
+        if self.message_processor.is_alive():
+            self.message_processor.shutdown()
+        self.message_workers.shutdown()
+
+    def _on_message(self, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {debug_redacted_message_string(message)})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(message)
+
+    def _on_error(self, error: Exception):
+        error_message = (
+            f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+        )
+        if self.trace_enabled:
+            self.logger.exception(error_message)
+        else:
+            self.logger.error(error_message)
+
+        for listener in self.on_error_listeners:
+            listener(error)
+
+    def _on_close(self, code: int, reason: Optional[str] = None):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Reconnecting... " f"(session id: {self.session_id()})")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(code, reason)
+
+    def _run_current_session(self):
+        if self.current_session is not None and self.current_session.is_active():
+            session_id = self.session_id()
+            try:
+                self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})")
+                self.current_session_state.terminated = False
+                self.current_session.run_until_completion(self.current_session_state)
+                self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})")
+            except Exception as e:
+                error_message = "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})"
+                if self.trace_enabled:
+                    self.logger.exception(error_message)
+                else:
+                    self.logger.error(error_message)
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                self.current_session.check_state()
+
+                if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()):
+                    self.logger.info(
+                        "The session seems to be already closed. Reconnecting... " f"(session id: {self.session_id()})"
+                    )
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(session id: {self.session_id()}, error: {type(e).__name__}, message: {e})"
+                )
+
+

Socket Mode client

+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
trace_enabled
+
True if more detailed debug-logging is enabled (default: False)
+
all_message_trace_enabled
+
True if all message dump in debug logs is enabled (default: False)
+
ping_pong_trace_enabled
+
True if trace logging for all ping-pong communications is enabled (default: False)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
receive_buffer_size
+
the chunk size of a single socket recv operation (default: 1024)
+
concurrency
+
the size of thread pool (default: 10)
+
proxy
+
the HTTP proxy URL
+
proxy_headers
+
additional HTTP header for proxy connection
+
on_message_listeners
+
listener functions for on_message
+
on_error_listeners
+
listener functions for on_error
+
on_close_listeners
+
listener functions for on_close
+
+

Ancestors

+ +

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var current_app_monitor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_app_monitor_started :Β bool
+
+

The type of the None singleton.

+
+
var current_session :Β ConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_runner :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_session_state :Β ConnectionState
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[int,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[str],Β None]]
+
+

The type of the None singleton.

+
+
var receive_buffer_size :Β int
+
+

The type of the None singleton.

+
+
var trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) +
+
+
+ +Expand source code + +
def close(self):
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    self.disconnect()
+    if self.current_app_monitor.is_alive():
+        self.current_app_monitor.shutdown()
+    if self.message_processor.is_alive():
+        self.message_processor.shutdown()
+    self.message_workers.shutdown()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    old_session: Optional[Connection] = self.current_session
+    old_current_session_state: ConnectionState = self.current_session_state
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    current_session = Connection(
+        url=self.wss_uri,
+        logger=self.logger,
+        ping_interval=self.ping_interval,
+        trace_enabled=self.trace_enabled,
+        all_message_trace_enabled=self.all_message_trace_enabled,
+        ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+        receive_buffer_size=self.receive_buffer_size,
+        proxy=self.proxy,
+        proxy_headers=self.proxy_headers,
+        on_message_listener=self._on_message,
+        on_error_listener=self._on_error,
+        on_close_listener=self._on_close,
+        ssl_context=self.web_client.ssl,
+    )
+    current_session.connect()
+
+    if old_current_session_state is not None:
+        old_current_session_state.terminated = True
+    if old_session is not None:
+        old_session.close()
+
+    self.current_session = current_session
+    self.current_session_state = ConnectionState()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    if self.current_session is not None:
+        self.current_session.close()
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    return self.current_session is not None and self.current_session.is_active()
+
+
+
+
+def send_message(self, message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send_message(self, message: str) -> None:
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+    try:
+        self.current_session.send(message)  # type: ignore[union-attr]
+    except SlackClientNotConnectedError as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        with self.connect_operation_lock:
+            if self.is_connected():
+                self.current_session.send(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(
+                    f"The current session (session id: {self.session_id()}) is no longer active. "
+                    "Failed to send a message"
+                )
+                raise e
+
+
+
+
+def session_id(self) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def session_id(self) -> Optional[str]:
+    if self.current_session is not None:
+        return self.current_session.session_id
+    return None
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/builtin/connection.html b/docs/reference/socket_mode/builtin/connection.html new file mode 100644 index 000000000..5c85bef91 --- /dev/null +++ b/docs/reference/socket_mode/builtin/connection.html @@ -0,0 +1,1061 @@ + + + + + + +slack_sdk.socket_mode.builtin.connection API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.builtin.connection

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class Connection +(url:Β str,
logger:Β logging.Logger,
proxy:Β strΒ |Β NoneΒ =Β None,
proxy_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
ping_interval:Β floatΒ =Β 5,
receive_timeout:Β floatΒ =Β 3,
receive_buffer_size:Β intΒ =Β 1024,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False,
on_message_listener:Β Callable[[str],Β None]Β |Β NoneΒ =Β None,
on_error_listener:Β Callable[[Exception],Β None]Β |Β NoneΒ =Β None,
on_close_listener:Β Callable[[int,Β strΒ |Β None],Β None]Β |Β NoneΒ =Β None,
connection_type_name:Β strΒ =Β 'Socket Mode',
ssl_context:Β ssl.SSLContextΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class Connection:
+    url: str
+    logger: Logger
+    proxy: Optional[str]
+    proxy_headers: Optional[Dict[str, str]]
+
+    trace_enabled: bool
+    ping_pong_trace_enabled: bool
+    last_ping_pong_time: Optional[float]
+
+    session_id: str
+    sock: Optional[ssl.SSLSocket]
+
+    on_message_listener: Optional[Callable[[str], None]]
+    on_error_listener: Optional[Callable[[Exception], None]]
+    on_close_listener: Optional[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        url: str,
+        logger: Logger,
+        proxy: Optional[str] = None,
+        proxy_headers: Optional[Dict[str, str]] = None,
+        ping_interval: float = 5,  # seconds
+        receive_timeout: float = 3,
+        receive_buffer_size: int = 1024,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+        on_message_listener: Optional[Callable[[str], None]] = None,
+        on_error_listener: Optional[Callable[[Exception], None]] = None,
+        on_close_listener: Optional[Callable[[int, Optional[str]], None]] = None,
+        connection_type_name: str = "Socket Mode",
+        ssl_context: Optional[ssl.SSLContext] = None,
+    ):
+        self.url = url
+        self.logger = logger
+        self.proxy = proxy
+        self.proxy_headers = proxy_headers
+
+        self.ping_interval = ping_interval
+        self.receive_timeout = receive_timeout
+        self.receive_buffer_size = receive_buffer_size
+        if self.receive_buffer_size < 16:
+            raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
+
+        self.session_id = str(uuid4())
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+        self.last_ping_pong_time = None
+        self.consecutive_check_state_error_count = 0
+        self.sock = None
+        # To avoid ssl.SSLError: [SSL: BAD_LENGTH] bad length
+        self.sock_receive_lock = Lock()
+        self.sock_send_lock = Lock()
+
+        self.on_message_listener = on_message_listener
+        self.on_error_listener = on_error_listener
+        self.on_close_listener = on_close_listener
+        self.connection_type_name = connection_type_name
+
+        self.ssl_context = ssl_context
+
+    def connect(self) -> None:
+        try:
+            parsed_url = urlparse(self.url.strip())
+            hostname: str = parsed_url.hostname  # type: ignore[assignment]
+            port: int = parsed_url.port or (443 if parsed_url.scheme == "wss" else 80)
+            if self.trace_enabled:
+                self.logger.debug(
+                    f"Connecting to the address for handshake: {hostname}:{port} " f"(session id: {self.session_id})"
+                )
+            sock: Union[ssl.SSLSocket, socket] = _establish_new_socket_connection(  # type: ignore[valid-type]
+                session_id=self.session_id,
+                server_hostname=hostname,
+                server_port=port,
+                logger=self.logger,
+                sock_send_lock=self.sock_send_lock,
+                receive_timeout=self.receive_timeout,
+                proxy=self.proxy,
+                proxy_headers=self.proxy_headers,
+                trace_enabled=self.trace_enabled,
+                ssl_context=self.ssl_context,
+            )
+
+            # WebSocket handshake
+            try:
+                path = f"{parsed_url.path}?{parsed_url.query}"
+                sec_websocket_key = _generate_sec_websocket_key()
+                message = f"""GET {path} HTTP/1.1
+                    Host: {parsed_url.hostname}
+                    Upgrade: websocket
+                    Connection: Upgrade
+                    Sec-WebSocket-Key: {sec_websocket_key}
+                    Sec-WebSocket-Version: 13
+
+                """
+                req: str = "\r\n".join([line.lstrip() for line in message.split("\n")])
+                if self.trace_enabled:
+                    self.logger.debug(
+                        f"{self.connection_type_name} handshake request (session id: {self.session_id}):\n{req}"
+                    )
+                with self.sock_send_lock:
+                    sock.send(req.encode("utf-8"))  # type: ignore[union-attr]
+
+                status, headers, text = _parse_handshake_response(sock)
+                if self.trace_enabled:
+                    self.logger.debug(
+                        f"{self.connection_type_name} handshake response (session id: {self.session_id}):\n{text}"
+                    )
+                # HTTP/1.1 101 Switching Protocols
+                if status == 101:
+                    if not _validate_sec_websocket_accept(sec_websocket_key, headers):
+                        raise SlackClientNotConnectedError(
+                            f"Invalid response header detected in {self.connection_type_name} handshake response"
+                            f" (session id: {self.session_id})"
+                        )
+                    # set this successfully connected socket
+                    self.sock = sock
+                    self.ping(f"{self.session_id}:{time.time()}")
+                else:
+                    message = (
+                        f"Received an unexpected response for handshake "
+                        f"(status: {status}, response: {text}, session id: {self.session_id})"
+                    )
+                    self.logger.warning(message)
+
+            except socket.error as e:
+                code: Optional[int] = None
+                if e.args and len(e.args) > 1 and isinstance(e.args[0], int):
+                    code = e.args[0]
+                if code is not None:
+                    error_message = f"Error code: {code} (session id: {self.session_id}, error: {e})"
+                    if self.trace_enabled:
+                        self.logger.exception(error_message)
+                    else:
+                        self.logger.error(error_message)
+                raise
+
+        except Exception as e:
+            error_message = f"Failed to establish a connection (session id: {self.session_id}, error: {e})"
+            if self.trace_enabled:
+                self.logger.exception(error_message)
+            else:
+                self.logger.error(error_message)
+
+            if self.on_error_listener is not None:
+                self.on_error_listener(e)
+
+            self.disconnect()
+
+    def disconnect(self) -> None:
+        if self.sock is not None:
+            with self.sock_send_lock:
+                with self.sock_receive_lock:
+                    # Synchronize before closing this instance's socket
+                    self.sock.close()
+                    self.sock = None
+                    # After this, all operations using self.sock will be skipped
+
+        self.logger.info(f"The connection has been closed (session id: {self.session_id})")
+
+    def is_active(self) -> bool:
+        return self.sock is not None
+
+    def close(self) -> None:
+        self.disconnect()
+
+    def ping(self, payload: Union[str, bytes] = "") -> None:
+        if self.trace_enabled and self.ping_pong_trace_enabled:
+            if isinstance(payload, bytes):
+                payload = payload.decode("utf-8")
+            self.logger.debug("Sending a ping data frame " f"(session id: {self.session_id}, payload: {payload})")
+        data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PING)
+        with self.sock_send_lock:
+            if self.sock is not None:
+                self.sock.send(data)
+            else:
+                if self.ping_pong_trace_enabled:
+                    self.logger.debug("Skipped sending a ping message as the underlying socket is no longer available.")
+
+    def pong(self, payload: Union[str, bytes] = "") -> None:
+        if self.trace_enabled and self.ping_pong_trace_enabled:
+            if isinstance(payload, bytes):
+                payload = payload.decode("utf-8")
+            self.logger.debug("Sending a pong data frame " f"(session id: {self.session_id}, payload: {payload})")
+        data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PONG)
+        with self.sock_send_lock:
+            if self.sock is not None:
+                self.sock.send(data)
+            else:
+                if self.ping_pong_trace_enabled:
+                    self.logger.debug("Skipped sending a pong message as the underlying socket is no longer available.")
+
+    def send(self, payload: str) -> None:
+        if self.trace_enabled:
+            if isinstance(payload, bytes):
+                payload = payload.decode("utf-8")
+            self.logger.debug("Sending a text data frame " f"(session id: {self.session_id}, payload: {payload})")
+        data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_TEXT)
+        with self.sock_send_lock:
+            try:
+                self.sock.send(data)  # type: ignore[union-attr]
+            except Exception as e:
+                # In most cases, we want to retry this operation with a newly established connection.
+                # Getting this exception means that this connection has been replaced with a new one
+                # and it's no longer usable.
+                # The SocketModeClient implementation can do one retry when it gets this exception.
+                raise SlackClientNotConnectedError(
+                    f"Failed to send a message as the connection is no longer active "
+                    f"(session_id: {self.session_id}, error: {e})"
+                )
+
+    def check_state(self) -> None:
+        try:
+            if self.sock is not None:
+                try:
+                    self.ping(f"{self.session_id}:{time.time()}")
+                except ssl.SSLZeroReturnError as e:
+                    self.logger.info(
+                        "Unable to send a ping message. Closing the connection..."
+                        f" (session id: {self.session_id}, reason: {e})"
+                    )
+                    self.disconnect()
+                    return
+
+                if self.last_ping_pong_time is not None:
+                    disconnected_seconds = int(time.time() - self.last_ping_pong_time)
+                    if self.trace_enabled and disconnected_seconds > self.ping_interval:
+                        message = (
+                            f"{disconnected_seconds} seconds have passed "
+                            f"since this client last received a pong response from the server "
+                            f"(session id: {self.session_id})"
+                        )
+                        self.logger.debug(message)
+
+                    is_stale = disconnected_seconds > self.ping_interval * 4
+                    if is_stale:
+                        self.logger.info(
+                            "The connection seems to be stale. Disconnecting..."
+                            f" (session id: {self.session_id},"
+                            f" reason: disconnected for {disconnected_seconds}+ seconds)"
+                        )
+                        self.disconnect()
+                        return
+            else:
+                self.logger.debug("This connection is already closed." f" (session id: {self.session_id})")
+            self.consecutive_check_state_error_count = 0
+        except Exception as e:
+            error_message = (
+                "Failed to check the state of sock "
+                f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
+            )
+            if self.trace_enabled:
+                self.logger.exception(error_message)
+            else:
+                self.logger.error(error_message)
+
+            self.consecutive_check_state_error_count += 1
+            if self.consecutive_check_state_error_count >= 5:
+                self.disconnect()
+
+    def run_until_completion(self, state: ConnectionState) -> None:
+        repeated_messages = {"payload": 0}
+        ping_count = 0
+        pong_count = 0
+        ping_pong_log_summary_size = 1000
+        while not state.terminated:
+            try:
+                if self.is_active():
+                    received_messages: List[Tuple[Optional[FrameHeader], bytes]] = _receive_messages(
+                        sock=self.sock,  # type: ignore[arg-type]
+                        sock_receive_lock=self.sock_receive_lock,
+                        logger=self.logger,
+                        receive_buffer_size=self.receive_buffer_size,
+                        all_message_trace_enabled=self.all_message_trace_enabled,
+                    )
+                    for message in received_messages:
+                        header, data = message
+
+                        # -----------------
+                        # trace logging
+
+                        if self.trace_enabled is True:
+                            opcode: str = _to_readable_opcode(header.opcode) if header else "-"
+                            payload: str = _parse_text_payload(data, self.logger)
+                            count: Optional[int] = repeated_messages.get(payload)
+                            if count is None:
+                                count = 1
+                            else:
+                                count += 1
+                            repeated_messages = {payload: count}
+                            if not self.ping_pong_trace_enabled and header is not None and header.opcode is not None:
+                                if header.opcode == FrameHeader.OPCODE_PING:
+                                    ping_count += 1
+                                    if ping_count % ping_pong_log_summary_size == 0:
+                                        self.logger.debug(
+                                            f"Received {ping_pong_log_summary_size} ping data frame "
+                                            f"(session id: {self.session_id})"
+                                        )
+                                        ping_count = 0
+                                if header.opcode == FrameHeader.OPCODE_PONG:
+                                    pong_count += 1
+                                    if pong_count % ping_pong_log_summary_size == 0:
+                                        self.logger.debug(
+                                            f"Received {ping_pong_log_summary_size} pong data frame "
+                                            f"(session id: {self.session_id})"
+                                        )
+                                        pong_count = 0
+
+                            ping_pong_to_skip = (
+                                header is not None
+                                and header.opcode is not None
+                                and (header.opcode == FrameHeader.OPCODE_PING or header.opcode == FrameHeader.OPCODE_PONG)
+                                and not self.ping_pong_trace_enabled
+                            )
+                            if not ping_pong_to_skip and count < 5:
+                                # if so many same payloads came in, the trace logging should be skipped.
+                                # e.g., after receiving "UNAUTHENTICATED: cache_error", many "opcode: -, payload: "
+                                self.logger.debug(
+                                    "Received a new data frame "
+                                    f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
+                                )
+
+                        if header is None:
+                            # Skip no header message
+                            continue
+
+                        # -----------------
+                        # message with opcode
+
+                        if header.opcode == FrameHeader.OPCODE_PING:
+                            self.pong(data)
+                        elif header.opcode == FrameHeader.OPCODE_PONG:
+                            str_message = data.decode("utf-8")
+                            elements = str_message.split(":")
+                            if len(elements) >= 2:
+                                session_id, ping_time = elements[0], elements[1]
+                                if self.session_id == session_id:
+                                    try:
+                                        self.last_ping_pong_time = float(ping_time)
+                                    except Exception as e:
+                                        self.logger.debug(
+                                            "Failed to parse a pong message " f" (message: {str_message}, error: {e}"
+                                        )
+                        elif header.opcode == FrameHeader.OPCODE_TEXT:
+                            if self.on_message_listener is not None:
+                                text = data.decode("utf-8")
+                                self.on_message_listener(text)
+                        elif header.opcode == FrameHeader.OPCODE_CLOSE:
+                            if self.on_close_listener is not None:
+                                if len(data) >= 2:
+                                    (code,) = struct.unpack("!H", data[:2])
+                                    reason = data[2:].decode("utf-8")
+                                    self.on_close_listener(code, reason)
+                                else:
+                                    self.on_close_listener(1005, "")
+                            self.disconnect()
+                            state.terminated = True
+                        else:
+                            # Just warn logging
+                            opcode = _to_readable_opcode(header.opcode) if header else "-"
+                            payload: Union[bytes, str] = data  # type: ignore[no-redef]
+                            if header.opcode != FrameHeader.OPCODE_BINARY:
+                                try:
+                                    payload = data.decode("utf-8") if data is not None else ""
+                                except Exception as e:
+                                    self.logger.info(f"Failed to convert the data to text {e}")
+                            message = (
+                                "Received an unsupported data frame "  # type: ignore[assignment]
+                                f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
+                            )
+                            self.logger.warning(message)
+                else:
+                    time.sleep(0.2)
+            except socket.timeout:
+                time.sleep(0.01)
+            except OSError as e:
+                # getting errno.EBADF and the socket is no longer available
+                if e.errno == 9 and state.terminated:
+                    self.logger.debug(
+                        "The reason why you got [Errno 9] Bad file descriptor here is " "the socket is no longer available."
+                    )
+                else:
+                    if self.on_error_listener is not None:
+                        self.on_error_listener(e)
+                    else:
+                        error_message = "Got an OSError while receiving data" f" (session id: {self.session_id}, error: {e})"
+                        if self.trace_enabled:
+                            self.logger.exception(error_message)
+                        else:
+                            self.logger.error(error_message)
+
+                # As this connection no longer works in any way, terminating it
+                if self.is_active():
+                    try:
+                        self.disconnect()
+                    except Exception as disconnection_error:
+                        error_message = (
+                            "Failed to disconnect" f" (session id: {self.session_id}, error: {disconnection_error})"
+                        )
+                        if self.trace_enabled:
+                            self.logger.exception(error_message)
+                        else:
+                            self.logger.error(error_message)
+                state.terminated = True
+                break
+            except Exception as e:
+                if self.on_error_listener is not None:
+                    self.on_error_listener(e)
+                else:
+                    error_message = "Got an exception while receiving data" f" (session id: {self.session_id}, error: {e})"
+                    if self.trace_enabled:
+                        self.logger.exception(error_message)
+                    else:
+                        self.logger.error(error_message)
+
+        state.terminated = True
+
+
+

Class variables

+
+
var last_ping_pong_time :Β floatΒ |Β None
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var on_close_listener :Β Callable[[int,Β strΒ |Β None],Β None]Β |Β None
+
+

The type of the None singleton.

+
+
var on_error_listener :Β Callable[[Exception],Β None]Β |Β None
+
+

The type of the None singleton.

+
+
var on_message_listener :Β Callable[[str],Β None]Β |Β None
+
+

The type of the None singleton.

+
+
var ping_pong_trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var proxy_headers :Β Dict[str,Β str]Β |Β None
+
+

The type of the None singleton.

+
+
var session_id :Β str
+
+

The type of the None singleton.

+
+
var sock :Β ssl.SSLSocketΒ |Β None
+
+

The type of the None singleton.

+
+
var trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def check_state(self) ‑>Β None +
+
+
+ +Expand source code + +
def check_state(self) -> None:
+    try:
+        if self.sock is not None:
+            try:
+                self.ping(f"{self.session_id}:{time.time()}")
+            except ssl.SSLZeroReturnError as e:
+                self.logger.info(
+                    "Unable to send a ping message. Closing the connection..."
+                    f" (session id: {self.session_id}, reason: {e})"
+                )
+                self.disconnect()
+                return
+
+            if self.last_ping_pong_time is not None:
+                disconnected_seconds = int(time.time() - self.last_ping_pong_time)
+                if self.trace_enabled and disconnected_seconds > self.ping_interval:
+                    message = (
+                        f"{disconnected_seconds} seconds have passed "
+                        f"since this client last received a pong response from the server "
+                        f"(session id: {self.session_id})"
+                    )
+                    self.logger.debug(message)
+
+                is_stale = disconnected_seconds > self.ping_interval * 4
+                if is_stale:
+                    self.logger.info(
+                        "The connection seems to be stale. Disconnecting..."
+                        f" (session id: {self.session_id},"
+                        f" reason: disconnected for {disconnected_seconds}+ seconds)"
+                    )
+                    self.disconnect()
+                    return
+        else:
+            self.logger.debug("This connection is already closed." f" (session id: {self.session_id})")
+        self.consecutive_check_state_error_count = 0
+    except Exception as e:
+        error_message = (
+            "Failed to check the state of sock "
+            f"(session id: {self.session_id}, error: {type(e).__name__}, message: {e})"
+        )
+        if self.trace_enabled:
+            self.logger.exception(error_message)
+        else:
+            self.logger.error(error_message)
+
+        self.consecutive_check_state_error_count += 1
+        if self.consecutive_check_state_error_count >= 5:
+            self.disconnect()
+
+
+
+
+def close(self) ‑>Β None +
+
+
+ +Expand source code + +
def close(self) -> None:
+    self.disconnect()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    try:
+        parsed_url = urlparse(self.url.strip())
+        hostname: str = parsed_url.hostname  # type: ignore[assignment]
+        port: int = parsed_url.port or (443 if parsed_url.scheme == "wss" else 80)
+        if self.trace_enabled:
+            self.logger.debug(
+                f"Connecting to the address for handshake: {hostname}:{port} " f"(session id: {self.session_id})"
+            )
+        sock: Union[ssl.SSLSocket, socket] = _establish_new_socket_connection(  # type: ignore[valid-type]
+            session_id=self.session_id,
+            server_hostname=hostname,
+            server_port=port,
+            logger=self.logger,
+            sock_send_lock=self.sock_send_lock,
+            receive_timeout=self.receive_timeout,
+            proxy=self.proxy,
+            proxy_headers=self.proxy_headers,
+            trace_enabled=self.trace_enabled,
+            ssl_context=self.ssl_context,
+        )
+
+        # WebSocket handshake
+        try:
+            path = f"{parsed_url.path}?{parsed_url.query}"
+            sec_websocket_key = _generate_sec_websocket_key()
+            message = f"""GET {path} HTTP/1.1
+                Host: {parsed_url.hostname}
+                Upgrade: websocket
+                Connection: Upgrade
+                Sec-WebSocket-Key: {sec_websocket_key}
+                Sec-WebSocket-Version: 13
+
+            """
+            req: str = "\r\n".join([line.lstrip() for line in message.split("\n")])
+            if self.trace_enabled:
+                self.logger.debug(
+                    f"{self.connection_type_name} handshake request (session id: {self.session_id}):\n{req}"
+                )
+            with self.sock_send_lock:
+                sock.send(req.encode("utf-8"))  # type: ignore[union-attr]
+
+            status, headers, text = _parse_handshake_response(sock)
+            if self.trace_enabled:
+                self.logger.debug(
+                    f"{self.connection_type_name} handshake response (session id: {self.session_id}):\n{text}"
+                )
+            # HTTP/1.1 101 Switching Protocols
+            if status == 101:
+                if not _validate_sec_websocket_accept(sec_websocket_key, headers):
+                    raise SlackClientNotConnectedError(
+                        f"Invalid response header detected in {self.connection_type_name} handshake response"
+                        f" (session id: {self.session_id})"
+                    )
+                # set this successfully connected socket
+                self.sock = sock
+                self.ping(f"{self.session_id}:{time.time()}")
+            else:
+                message = (
+                    f"Received an unexpected response for handshake "
+                    f"(status: {status}, response: {text}, session id: {self.session_id})"
+                )
+                self.logger.warning(message)
+
+        except socket.error as e:
+            code: Optional[int] = None
+            if e.args and len(e.args) > 1 and isinstance(e.args[0], int):
+                code = e.args[0]
+            if code is not None:
+                error_message = f"Error code: {code} (session id: {self.session_id}, error: {e})"
+                if self.trace_enabled:
+                    self.logger.exception(error_message)
+                else:
+                    self.logger.error(error_message)
+            raise
+
+    except Exception as e:
+        error_message = f"Failed to establish a connection (session id: {self.session_id}, error: {e})"
+        if self.trace_enabled:
+            self.logger.exception(error_message)
+        else:
+            self.logger.error(error_message)
+
+        if self.on_error_listener is not None:
+            self.on_error_listener(e)
+
+        self.disconnect()
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    if self.sock is not None:
+        with self.sock_send_lock:
+            with self.sock_receive_lock:
+                # Synchronize before closing this instance's socket
+                self.sock.close()
+                self.sock = None
+                # After this, all operations using self.sock will be skipped
+
+    self.logger.info(f"The connection has been closed (session id: {self.session_id})")
+
+
+
+
+def is_active(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_active(self) -> bool:
+    return self.sock is not None
+
+
+
+
+def ping(self, payload:Β strΒ |Β bytesΒ =Β '') ‑>Β None +
+
+
+ +Expand source code + +
def ping(self, payload: Union[str, bytes] = "") -> None:
+    if self.trace_enabled and self.ping_pong_trace_enabled:
+        if isinstance(payload, bytes):
+            payload = payload.decode("utf-8")
+        self.logger.debug("Sending a ping data frame " f"(session id: {self.session_id}, payload: {payload})")
+    data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PING)
+    with self.sock_send_lock:
+        if self.sock is not None:
+            self.sock.send(data)
+        else:
+            if self.ping_pong_trace_enabled:
+                self.logger.debug("Skipped sending a ping message as the underlying socket is no longer available.")
+
+
+
+
+def pong(self, payload:Β strΒ |Β bytesΒ =Β '') ‑>Β None +
+
+
+ +Expand source code + +
def pong(self, payload: Union[str, bytes] = "") -> None:
+    if self.trace_enabled and self.ping_pong_trace_enabled:
+        if isinstance(payload, bytes):
+            payload = payload.decode("utf-8")
+        self.logger.debug("Sending a pong data frame " f"(session id: {self.session_id}, payload: {payload})")
+    data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_PONG)
+    with self.sock_send_lock:
+        if self.sock is not None:
+            self.sock.send(data)
+        else:
+            if self.ping_pong_trace_enabled:
+                self.logger.debug("Skipped sending a pong message as the underlying socket is no longer available.")
+
+
+
+
+def run_until_completion(self,
state:Β ConnectionState) ‑>Β None
+
+
+
+ +Expand source code + +
def run_until_completion(self, state: ConnectionState) -> None:
+    repeated_messages = {"payload": 0}
+    ping_count = 0
+    pong_count = 0
+    ping_pong_log_summary_size = 1000
+    while not state.terminated:
+        try:
+            if self.is_active():
+                received_messages: List[Tuple[Optional[FrameHeader], bytes]] = _receive_messages(
+                    sock=self.sock,  # type: ignore[arg-type]
+                    sock_receive_lock=self.sock_receive_lock,
+                    logger=self.logger,
+                    receive_buffer_size=self.receive_buffer_size,
+                    all_message_trace_enabled=self.all_message_trace_enabled,
+                )
+                for message in received_messages:
+                    header, data = message
+
+                    # -----------------
+                    # trace logging
+
+                    if self.trace_enabled is True:
+                        opcode: str = _to_readable_opcode(header.opcode) if header else "-"
+                        payload: str = _parse_text_payload(data, self.logger)
+                        count: Optional[int] = repeated_messages.get(payload)
+                        if count is None:
+                            count = 1
+                        else:
+                            count += 1
+                        repeated_messages = {payload: count}
+                        if not self.ping_pong_trace_enabled and header is not None and header.opcode is not None:
+                            if header.opcode == FrameHeader.OPCODE_PING:
+                                ping_count += 1
+                                if ping_count % ping_pong_log_summary_size == 0:
+                                    self.logger.debug(
+                                        f"Received {ping_pong_log_summary_size} ping data frame "
+                                        f"(session id: {self.session_id})"
+                                    )
+                                    ping_count = 0
+                            if header.opcode == FrameHeader.OPCODE_PONG:
+                                pong_count += 1
+                                if pong_count % ping_pong_log_summary_size == 0:
+                                    self.logger.debug(
+                                        f"Received {ping_pong_log_summary_size} pong data frame "
+                                        f"(session id: {self.session_id})"
+                                    )
+                                    pong_count = 0
+
+                        ping_pong_to_skip = (
+                            header is not None
+                            and header.opcode is not None
+                            and (header.opcode == FrameHeader.OPCODE_PING or header.opcode == FrameHeader.OPCODE_PONG)
+                            and not self.ping_pong_trace_enabled
+                        )
+                        if not ping_pong_to_skip and count < 5:
+                            # if so many same payloads came in, the trace logging should be skipped.
+                            # e.g., after receiving "UNAUTHENTICATED: cache_error", many "opcode: -, payload: "
+                            self.logger.debug(
+                                "Received a new data frame "
+                                f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
+                            )
+
+                    if header is None:
+                        # Skip no header message
+                        continue
+
+                    # -----------------
+                    # message with opcode
+
+                    if header.opcode == FrameHeader.OPCODE_PING:
+                        self.pong(data)
+                    elif header.opcode == FrameHeader.OPCODE_PONG:
+                        str_message = data.decode("utf-8")
+                        elements = str_message.split(":")
+                        if len(elements) >= 2:
+                            session_id, ping_time = elements[0], elements[1]
+                            if self.session_id == session_id:
+                                try:
+                                    self.last_ping_pong_time = float(ping_time)
+                                except Exception as e:
+                                    self.logger.debug(
+                                        "Failed to parse a pong message " f" (message: {str_message}, error: {e}"
+                                    )
+                    elif header.opcode == FrameHeader.OPCODE_TEXT:
+                        if self.on_message_listener is not None:
+                            text = data.decode("utf-8")
+                            self.on_message_listener(text)
+                    elif header.opcode == FrameHeader.OPCODE_CLOSE:
+                        if self.on_close_listener is not None:
+                            if len(data) >= 2:
+                                (code,) = struct.unpack("!H", data[:2])
+                                reason = data[2:].decode("utf-8")
+                                self.on_close_listener(code, reason)
+                            else:
+                                self.on_close_listener(1005, "")
+                        self.disconnect()
+                        state.terminated = True
+                    else:
+                        # Just warn logging
+                        opcode = _to_readable_opcode(header.opcode) if header else "-"
+                        payload: Union[bytes, str] = data  # type: ignore[no-redef]
+                        if header.opcode != FrameHeader.OPCODE_BINARY:
+                            try:
+                                payload = data.decode("utf-8") if data is not None else ""
+                            except Exception as e:
+                                self.logger.info(f"Failed to convert the data to text {e}")
+                        message = (
+                            "Received an unsupported data frame "  # type: ignore[assignment]
+                            f"(session id: {self.session_id}, opcode: {opcode}, payload: {payload})"
+                        )
+                        self.logger.warning(message)
+            else:
+                time.sleep(0.2)
+        except socket.timeout:
+            time.sleep(0.01)
+        except OSError as e:
+            # getting errno.EBADF and the socket is no longer available
+            if e.errno == 9 and state.terminated:
+                self.logger.debug(
+                    "The reason why you got [Errno 9] Bad file descriptor here is " "the socket is no longer available."
+                )
+            else:
+                if self.on_error_listener is not None:
+                    self.on_error_listener(e)
+                else:
+                    error_message = "Got an OSError while receiving data" f" (session id: {self.session_id}, error: {e})"
+                    if self.trace_enabled:
+                        self.logger.exception(error_message)
+                    else:
+                        self.logger.error(error_message)
+
+            # As this connection no longer works in any way, terminating it
+            if self.is_active():
+                try:
+                    self.disconnect()
+                except Exception as disconnection_error:
+                    error_message = (
+                        "Failed to disconnect" f" (session id: {self.session_id}, error: {disconnection_error})"
+                    )
+                    if self.trace_enabled:
+                        self.logger.exception(error_message)
+                    else:
+                        self.logger.error(error_message)
+            state.terminated = True
+            break
+        except Exception as e:
+            if self.on_error_listener is not None:
+                self.on_error_listener(e)
+            else:
+                error_message = "Got an exception while receiving data" f" (session id: {self.session_id}, error: {e})"
+                if self.trace_enabled:
+                    self.logger.exception(error_message)
+                else:
+                    self.logger.error(error_message)
+
+    state.terminated = True
+
+
+
+
+def send(self, payload:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send(self, payload: str) -> None:
+    if self.trace_enabled:
+        if isinstance(payload, bytes):
+            payload = payload.decode("utf-8")
+        self.logger.debug("Sending a text data frame " f"(session id: {self.session_id}, payload: {payload})")
+    data = _build_data_frame_for_sending(payload, FrameHeader.OPCODE_TEXT)
+    with self.sock_send_lock:
+        try:
+            self.sock.send(data)  # type: ignore[union-attr]
+        except Exception as e:
+            # In most cases, we want to retry this operation with a newly established connection.
+            # Getting this exception means that this connection has been replaced with a new one
+            # and it's no longer usable.
+            # The SocketModeClient implementation can do one retry when it gets this exception.
+            raise SlackClientNotConnectedError(
+                f"Failed to send a message as the connection is no longer active "
+                f"(session_id: {self.session_id}, error: {e})"
+            )
+
+
+
+
+
+
+class ConnectionState +
+
+
+ +Expand source code + +
class ConnectionState:
+    # The flag supposed to be used for telling SocketModeClient
+    # when this connection is no longer available
+    terminated: bool
+
+    def __init__(self):
+        self.terminated = False
+
+
+

Class variables

+
+
var terminated :Β bool
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/builtin/frame_header.html b/docs/reference/socket_mode/builtin/frame_header.html new file mode 100644 index 000000000..b728e0926 --- /dev/null +++ b/docs/reference/socket_mode/builtin/frame_header.html @@ -0,0 +1,205 @@ + + + + + + +slack_sdk.socket_mode.builtin.frame_header API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.builtin.frame_header

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class FrameHeader +(opcode:Β int,
fin:Β intΒ =Β 1,
rsv1:Β intΒ =Β 0,
rsv2:Β intΒ =Β 0,
rsv3:Β intΒ =Β 0,
masked:Β intΒ =Β 0,
length:Β intΒ =Β 0)
+
+
+
+ +Expand source code + +
class FrameHeader:
+    fin: int
+    rsv1: int
+    rsv2: int
+    rsv3: int
+    opcode: int
+    masked: int
+    length: int
+
+    # Opcode
+    # https://tools.ietf.org/html/rfc6455#section-5.2
+    # Non-control frames
+    # %x0 denotes a continuation frame
+    OPCODE_CONTINUATION = 0x0
+    # %x1 denotes a text frame
+    OPCODE_TEXT = 0x1
+    # %x2 denotes a binary frame
+    OPCODE_BINARY = 0x2
+    # %x3-7 are reserved for further non-control frames
+
+    # Control frames
+    # %x8 denotes a connection close
+    OPCODE_CLOSE = 0x8
+    # %x9 denotes a ping
+    OPCODE_PING = 0x9
+    # %xA denotes a pong
+    OPCODE_PONG = 0xA
+
+    # %xB-F are reserved for further control frames
+
+    def __init__(
+        self,
+        opcode: int,
+        fin: int = 1,
+        rsv1: int = 0,
+        rsv2: int = 0,
+        rsv3: int = 0,
+        masked: int = 0,
+        length: int = 0,
+    ):
+        self.opcode = opcode
+        self.fin = fin
+        self.rsv1 = rsv1
+        self.rsv2 = rsv2
+        self.rsv3 = rsv3
+        self.masked = masked
+        self.length = length
+
+
+

Class variables

+
+
var OPCODE_BINARY
+
+

The type of the None singleton.

+
+
var OPCODE_CLOSE
+
+

The type of the None singleton.

+
+
var OPCODE_CONTINUATION
+
+

The type of the None singleton.

+
+
var OPCODE_PING
+
+

The type of the None singleton.

+
+
var OPCODE_PONG
+
+

The type of the None singleton.

+
+
var OPCODE_TEXT
+
+

The type of the None singleton.

+
+
var fin :Β int
+
+

The type of the None singleton.

+
+
var length :Β int
+
+

The type of the None singleton.

+
+
var masked :Β int
+
+

The type of the None singleton.

+
+
var opcode :Β int
+
+

The type of the None singleton.

+
+
var rsv1 :Β int
+
+

The type of the None singleton.

+
+
var rsv2 :Β int
+
+

The type of the None singleton.

+
+
var rsv3 :Β int
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/builtin/index.html b/docs/reference/socket_mode/builtin/index.html new file mode 100644 index 000000000..9f710eaf6 --- /dev/null +++ b/docs/reference/socket_mode/builtin/index.html @@ -0,0 +1,653 @@ + + + + + + +slack_sdk.socket_mode.builtin API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.builtin

+
+
+
+
+

Sub-modules

+
+
slack_sdk.socket_mode.builtin.client
+
+

The built-in Socket Mode client …

+
+
slack_sdk.socket_mode.builtin.connection
+
+
+
+
slack_sdk.socket_mode.builtin.frame_header
+
+
+
+
slack_sdk.socket_mode.builtin.internals
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False,
ping_interval:Β floatΒ =Β 5,
receive_buffer_size:Β intΒ =Β 1024,
concurrency:Β intΒ =Β 10,
proxy:Β strΒ |Β NoneΒ =Β None,
proxy_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[int,Β strΒ |Β None],Β None]]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeClient(BaseSocketModeClient):
+    logger: Logger
+    web_client: WebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            WebSocketMessageListener,
+            Callable[["BaseSocketModeClient", dict, Optional[str]], None],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            SocketModeRequestListener,
+            Callable[["BaseSocketModeClient", SocketModeRequest], None],
+        ]
+    ]
+
+    current_session: Optional[Connection]
+    current_session_state: ConnectionState
+    current_session_runner: IntervalRunner
+
+    current_app_monitor: IntervalRunner
+    current_app_monitor_started: bool
+
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    auto_reconnect_enabled: bool
+    default_auto_reconnect_enabled: bool
+    trace_enabled: bool
+    receive_buffer_size: int  # bytes size
+
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[str], None]]
+    on_error_listeners: List[Callable[[Exception], None]]
+    on_close_listeners: List[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+        ping_interval: float = 5,
+        receive_buffer_size: int = 1024,
+        concurrency: int = 10,
+        proxy: Optional[str] = None,
+        proxy_headers: Optional[Dict[str, str]] = None,
+        on_message_listeners: Optional[List[Callable[[str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
+    ):
+        """Socket Mode client
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            trace_enabled: True if more detailed debug-logging is enabled (default: False)
+            all_message_trace_enabled: True if all message dump in debug logs is enabled (default: False)
+            ping_pong_trace_enabled: True if trace logging for all ping-pong communications is enabled (default: False)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            receive_buffer_size: the chunk size of a single socket recv operation (default: 1024)
+            concurrency: the size of thread pool (default: 10)
+            proxy: the HTTP proxy URL
+            proxy_headers: additional HTTP header for proxy connection
+            on_message_listeners: listener functions for on_message
+            on_error_listeners: listener functions for on_error
+            on_close_listeners: listener functions for on_close
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or WebClient()
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+        self.ping_interval = ping_interval
+        self.receive_buffer_size = receive_buffer_size
+        if self.receive_buffer_size < 16:
+            raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
+
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_state = ConnectionState()
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval)
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+        self.proxy = proxy
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+        self.proxy_headers = proxy_headers
+
+        self.on_message_listeners = on_message_listeners or []
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+    def session_id(self) -> Optional[str]:
+        if self.current_session is not None:
+            return self.current_session.session_id
+        return None
+
+    def is_connected(self) -> bool:
+        return self.current_session is not None and self.current_session.is_active()
+
+    def connect(self) -> None:
+        old_session: Optional[Connection] = self.current_session
+        old_current_session_state: ConnectionState = self.current_session_state
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        current_session = Connection(
+            url=self.wss_uri,
+            logger=self.logger,
+            ping_interval=self.ping_interval,
+            trace_enabled=self.trace_enabled,
+            all_message_trace_enabled=self.all_message_trace_enabled,
+            ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+            receive_buffer_size=self.receive_buffer_size,
+            proxy=self.proxy,
+            proxy_headers=self.proxy_headers,
+            on_message_listener=self._on_message,
+            on_error_listener=self._on_error,
+            on_close_listener=self._on_close,
+            ssl_context=self.web_client.ssl,
+        )
+        current_session.connect()
+
+        if old_current_session_state is not None:
+            old_current_session_state.terminated = True
+        if old_session is not None:
+            old_session.close()
+
+        self.current_session = current_session
+        self.current_session_state = ConnectionState()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+    def disconnect(self) -> None:
+        if self.current_session is not None:
+            self.current_session.close()
+
+    def send_message(self, message: str) -> None:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+        try:
+            self.current_session.send(message)  # type: ignore[union-attr]
+        except SlackClientNotConnectedError as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            with self.connect_operation_lock:
+                if self.is_connected():
+                    self.current_session.send(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(
+                        f"The current session (session id: {self.session_id()}) is no longer active. "
+                        "Failed to send a message"
+                    )
+                    raise e
+
+    def close(self):
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        self.disconnect()
+        if self.current_app_monitor.is_alive():
+            self.current_app_monitor.shutdown()
+        if self.message_processor.is_alive():
+            self.message_processor.shutdown()
+        self.message_workers.shutdown()
+
+    def _on_message(self, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {debug_redacted_message_string(message)})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(message)
+
+    def _on_error(self, error: Exception):
+        error_message = (
+            f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+        )
+        if self.trace_enabled:
+            self.logger.exception(error_message)
+        else:
+            self.logger.error(error_message)
+
+        for listener in self.on_error_listeners:
+            listener(error)
+
+    def _on_close(self, code: int, reason: Optional[str] = None):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Reconnecting... " f"(session id: {self.session_id()})")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(code, reason)
+
+    def _run_current_session(self):
+        if self.current_session is not None and self.current_session.is_active():
+            session_id = self.session_id()
+            try:
+                self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})")
+                self.current_session_state.terminated = False
+                self.current_session.run_until_completion(self.current_session_state)
+                self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})")
+            except Exception as e:
+                error_message = "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})"
+                if self.trace_enabled:
+                    self.logger.exception(error_message)
+                else:
+                    self.logger.error(error_message)
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                self.current_session.check_state()
+
+                if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()):
+                    self.logger.info(
+                        "The session seems to be already closed. Reconnecting... " f"(session id: {self.session_id()})"
+                    )
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(session id: {self.session_id()}, error: {type(e).__name__}, message: {e})"
+                )
+
+

Socket Mode client

+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
trace_enabled
+
True if more detailed debug-logging is enabled (default: False)
+
all_message_trace_enabled
+
True if all message dump in debug logs is enabled (default: False)
+
ping_pong_trace_enabled
+
True if trace logging for all ping-pong communications is enabled (default: False)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
receive_buffer_size
+
the chunk size of a single socket recv operation (default: 1024)
+
concurrency
+
the size of thread pool (default: 10)
+
proxy
+
the HTTP proxy URL
+
proxy_headers
+
additional HTTP header for proxy connection
+
on_message_listeners
+
listener functions for on_message
+
on_error_listeners
+
listener functions for on_error
+
on_close_listeners
+
listener functions for on_close
+
+

Ancestors

+ +

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var current_app_monitor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_app_monitor_started :Β bool
+
+

The type of the None singleton.

+
+
var current_session :Β ConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_runner :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_session_state :Β ConnectionState
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[int,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[str],Β None]]
+
+

The type of the None singleton.

+
+
var receive_buffer_size :Β int
+
+

The type of the None singleton.

+
+
var trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) +
+
+
+ +Expand source code + +
def close(self):
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    self.disconnect()
+    if self.current_app_monitor.is_alive():
+        self.current_app_monitor.shutdown()
+    if self.message_processor.is_alive():
+        self.message_processor.shutdown()
+    self.message_workers.shutdown()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    old_session: Optional[Connection] = self.current_session
+    old_current_session_state: ConnectionState = self.current_session_state
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    current_session = Connection(
+        url=self.wss_uri,
+        logger=self.logger,
+        ping_interval=self.ping_interval,
+        trace_enabled=self.trace_enabled,
+        all_message_trace_enabled=self.all_message_trace_enabled,
+        ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+        receive_buffer_size=self.receive_buffer_size,
+        proxy=self.proxy,
+        proxy_headers=self.proxy_headers,
+        on_message_listener=self._on_message,
+        on_error_listener=self._on_error,
+        on_close_listener=self._on_close,
+        ssl_context=self.web_client.ssl,
+    )
+    current_session.connect()
+
+    if old_current_session_state is not None:
+        old_current_session_state.terminated = True
+    if old_session is not None:
+        old_session.close()
+
+    self.current_session = current_session
+    self.current_session_state = ConnectionState()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    if self.current_session is not None:
+        self.current_session.close()
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    return self.current_session is not None and self.current_session.is_active()
+
+
+
+
+def send_message(self, message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send_message(self, message: str) -> None:
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+    try:
+        self.current_session.send(message)  # type: ignore[union-attr]
+    except SlackClientNotConnectedError as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        with self.connect_operation_lock:
+            if self.is_connected():
+                self.current_session.send(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(
+                    f"The current session (session id: {self.session_id()}) is no longer active. "
+                    "Failed to send a message"
+                )
+                raise e
+
+
+
+
+def session_id(self) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def session_id(self) -> Optional[str]:
+    if self.current_session is not None:
+        return self.current_session.session_id
+    return None
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/builtin/internals.html b/docs/reference/socket_mode/builtin/internals.html new file mode 100644 index 000000000..2977bc6c4 --- /dev/null +++ b/docs/reference/socket_mode/builtin/internals.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.socket_mode.builtin.internals API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.builtin.internals

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/client.html b/docs/reference/socket_mode/client.html new file mode 100644 index 000000000..3c8c615f9 --- /dev/null +++ b/docs/reference/socket_mode/client.html @@ -0,0 +1,537 @@ + + + + + + +slack_sdk.socket_mode.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class BaseSocketModeClient +
+
+
+ +Expand source code + +
class BaseSocketModeClient:
+    logger: Logger
+    web_client: WebClient
+    app_token: str
+    wss_uri: str
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            WebSocketMessageListener,
+            Callable[["BaseSocketModeClient", dict, Optional[str]], None],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            SocketModeRequestListener,
+            Callable[["BaseSocketModeClient", SocketModeRequest], None],
+        ]
+    ]
+
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    closed: bool
+    connect_operation_lock: Lock
+
+    def issue_new_wss_url(self) -> str:
+        try:
+            response = self.web_client.apps_connections_open(app_token=self.app_token)
+            return response["url"]
+        except SlackApiError as e:
+            if e.response["error"] == "ratelimited":
+                # NOTE: ratelimited errors rarely occur with this endpoint
+                delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+                self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+                time.sleep(delay)
+                # Retry to issue a new WSS URL
+                return self.issue_new_wss_url()
+            else:
+                # other errors
+                self.logger.error(f"Failed to retrieve WSS URL: {e}")
+                raise e
+
+    def is_connected(self) -> bool:
+        return False
+
+    def connect(self) -> None:
+        raise NotImplementedError()
+
+    def disconnect(self) -> None:
+        raise NotImplementedError()
+
+    def connect_to_new_endpoint(self, force: bool = False):
+        try:
+            self.connect_operation_lock.acquire(blocking=True, timeout=5)
+            if force or not self.is_connected():
+                self.logger.info("Connecting to a new endpoint...")
+                self.wss_uri = self.issue_new_wss_url()
+                self.connect()
+                self.logger.info("Connected to a new endpoint...")
+        finally:
+            self.connect_operation_lock.release()
+
+    def close(self) -> None:
+        self.closed = True
+        self.disconnect()
+
+    def send_message(self, message: str) -> None:
+        raise NotImplementedError()
+
+    def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]) -> None:
+        if isinstance(response, SocketModeResponse):
+            self.send_message(json.dumps(response.to_dict()))
+        else:
+            self.send_message(json.dumps(response))
+
+    def enqueue_message(self, message: str):
+        self.message_queue.put(message)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+    def process_message(self):
+        try:
+            raw_message = self.message_queue.get(timeout=1)
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+            if raw_message is not None:
+                message: dict = {}
+                if raw_message.startswith("{"):
+                    message = json.loads(raw_message)
+                if message.get("type") == "disconnect":
+                    self.connect_to_new_endpoint(force=True)
+                else:
+
+                    def _run_message_listeners():
+                        self.run_message_listeners(message, raw_message)
+
+                    self.message_workers.submit(_run_message_listeners)
+        except Empty:
+            pass
+
+    def run_message_listeners(self, message: dict, raw_message: str) -> None:
+        type, envelope_id = message.get("type"), message.get("envelope_id")
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing started (type: {type}, envelope_id: {envelope_id})")
+        try:
+            # just in case, adding the same logic to reconnect here
+            if message.get("type") == "disconnect":
+                self.connect_to_new_endpoint(force=True)
+                return
+
+            for listener in self.message_listeners:
+                try:
+                    listener(self, message, raw_message)  # type: ignore[call-arg, arg-type, misc]
+                except Exception as e:
+                    self.logger.exception(f"Failed to run a message listener: {e}")
+
+            if len(self.socket_mode_request_listeners) > 0:
+                request = SocketModeRequest.from_dict(message)
+                if request is not None:
+                    for listener in self.socket_mode_request_listeners:  # type: ignore[assignment]
+                        try:
+                            listener(self, request)  # type: ignore[call-arg, arg-type]
+                        except Exception as e:
+                            self.logger.exception(f"Failed to run a request listener: {e}")
+        except Exception as e:
+            self.logger.exception(f"Failed to run message listeners: {e}")
+        finally:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"Message processing completed (type: {type}, envelope_id: {envelope_id})")
+
+    def process_messages(self) -> None:
+        while not self.closed:
+            try:
+                self.process_message()
+            except Exception as e:
+                self.logger.exception(f"Failed to process a message: {e}")
+
+
+

Subclasses

+ +

Class variables

+
+
var app_token :Β str
+
+

The type of the None singleton.

+
+
var closed :Β bool
+
+

The type of the None singleton.

+
+
var connect_operation_lock :Β _thread.lock
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var message_listeners :Β List[WebSocketMessageListenerΒ |Β Callable[[BaseSocketModeClient,Β dict,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var message_processor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var message_queue :Β queue.Queue
+
+

The type of the None singleton.

+
+
var message_workers :Β concurrent.futures.thread.ThreadPoolExecutor
+
+

The type of the None singleton.

+
+
var socket_mode_request_listeners :Β List[SocketModeRequestListenerΒ |Β Callable[[BaseSocketModeClient,Β SocketModeRequest],Β None]]
+
+

The type of the None singleton.

+
+
var web_client :Β WebClient
+
+

The type of the None singleton.

+
+
var wss_uri :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) ‑>Β None +
+
+
+ +Expand source code + +
def close(self) -> None:
+    self.closed = True
+    self.disconnect()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    raise NotImplementedError()
+
+
+
+
+def connect_to_new_endpoint(self, force:Β boolΒ =Β False) +
+
+
+ +Expand source code + +
def connect_to_new_endpoint(self, force: bool = False):
+    try:
+        self.connect_operation_lock.acquire(blocking=True, timeout=5)
+        if force or not self.is_connected():
+            self.logger.info("Connecting to a new endpoint...")
+            self.wss_uri = self.issue_new_wss_url()
+            self.connect()
+            self.logger.info("Connected to a new endpoint...")
+    finally:
+        self.connect_operation_lock.release()
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    raise NotImplementedError()
+
+
+
+
+def enqueue_message(self, message:Β str) +
+
+
+ +Expand source code + +
def enqueue_message(self, message: str):
+    self.message_queue.put(message)
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new message enqueued (current queue size: {self.message_queue.qsize()})")
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    return False
+
+
+
+
+def issue_new_wss_url(self) ‑>Β str +
+
+
+ +Expand source code + +
def issue_new_wss_url(self) -> str:
+    try:
+        response = self.web_client.apps_connections_open(app_token=self.app_token)
+        return response["url"]
+    except SlackApiError as e:
+        if e.response["error"] == "ratelimited":
+            # NOTE: ratelimited errors rarely occur with this endpoint
+            delay = int(e.response.headers.get("Retry-After", "30"))  # Tier1
+            self.logger.info(f"Rate limited. Retrying in {delay} seconds...")
+            time.sleep(delay)
+            # Retry to issue a new WSS URL
+            return self.issue_new_wss_url()
+        else:
+            # other errors
+            self.logger.error(f"Failed to retrieve WSS URL: {e}")
+            raise e
+
+
+
+
+def process_message(self) +
+
+
+ +Expand source code + +
def process_message(self):
+    try:
+        raw_message = self.message_queue.get(timeout=1)
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A message dequeued (current queue size: {self.message_queue.qsize()})")
+
+        if raw_message is not None:
+            message: dict = {}
+            if raw_message.startswith("{"):
+                message = json.loads(raw_message)
+            if message.get("type") == "disconnect":
+                self.connect_to_new_endpoint(force=True)
+            else:
+
+                def _run_message_listeners():
+                    self.run_message_listeners(message, raw_message)
+
+                self.message_workers.submit(_run_message_listeners)
+    except Empty:
+        pass
+
+
+
+
+def process_messages(self) ‑>Β None +
+
+
+ +Expand source code + +
def process_messages(self) -> None:
+    while not self.closed:
+        try:
+            self.process_message()
+        except Exception as e:
+            self.logger.exception(f"Failed to process a message: {e}")
+
+
+
+
+def run_message_listeners(self, message:Β dict, raw_message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def run_message_listeners(self, message: dict, raw_message: str) -> None:
+    type, envelope_id = message.get("type"), message.get("envelope_id")
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Message processing started (type: {type}, envelope_id: {envelope_id})")
+    try:
+        # just in case, adding the same logic to reconnect here
+        if message.get("type") == "disconnect":
+            self.connect_to_new_endpoint(force=True)
+            return
+
+        for listener in self.message_listeners:
+            try:
+                listener(self, message, raw_message)  # type: ignore[call-arg, arg-type, misc]
+            except Exception as e:
+                self.logger.exception(f"Failed to run a message listener: {e}")
+
+        if len(self.socket_mode_request_listeners) > 0:
+            request = SocketModeRequest.from_dict(message)
+            if request is not None:
+                for listener in self.socket_mode_request_listeners:  # type: ignore[assignment]
+                    try:
+                        listener(self, request)  # type: ignore[call-arg, arg-type]
+                    except Exception as e:
+                        self.logger.exception(f"Failed to run a request listener: {e}")
+    except Exception as e:
+        self.logger.exception(f"Failed to run message listeners: {e}")
+    finally:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Message processing completed (type: {type}, envelope_id: {envelope_id})")
+
+
+
+
+def send_message(self, message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send_message(self, message: str) -> None:
+    raise NotImplementedError()
+
+
+
+
+def send_socket_mode_response(self,
response:Β Dict[str,Β Any]Β |Β SocketModeResponse) ‑>Β None
+
+
+
+ +Expand source code + +
def send_socket_mode_response(self, response: Union[Dict[str, Any], SocketModeResponse]) -> None:
+    if isinstance(response, SocketModeResponse):
+        self.send_message(json.dumps(response.to_dict()))
+    else:
+        self.send_message(json.dumps(response))
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/index.html b/docs/reference/socket_mode/index.html new file mode 100644 index 000000000..381e969e5 --- /dev/null +++ b/docs/reference/socket_mode/index.html @@ -0,0 +1,698 @@ + + + + + + +slack_sdk.socket_mode API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode

+
+
+

Socket Mode is a method of connecting your app to Slack’s APIs using WebSockets instead of HTTP. +You can use slack_sdk.socket_mode.SocketModeClient for managing Socket Mode connections +and performing interactions with Slack.

+

https://docs.slack.dev/apis/events-api/using-socket-mode/

+
+
+

Sub-modules

+
+
slack_sdk.socket_mode.aiohttp
+
+

aiohttp based Socket Mode client …

+
+
slack_sdk.socket_mode.async_client
+
+
+
+
slack_sdk.socket_mode.async_listeners
+
+
+
+
slack_sdk.socket_mode.builtin
+
+
+
+
slack_sdk.socket_mode.client
+
+
+
+
slack_sdk.socket_mode.interval_runner
+
+
+
+
slack_sdk.socket_mode.listeners
+
+
+
+
slack_sdk.socket_mode.logger
+
+
+
+
slack_sdk.socket_mode.request
+
+
+
+
slack_sdk.socket_mode.response
+
+
+
+
slack_sdk.socket_mode.websocket_client
+
+

websocket-client bassd Socket Mode client …

+
+
slack_sdk.socket_mode.websockets
+
+

websockets bassd Socket Mode client …

+
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
trace_enabled:Β boolΒ =Β False,
all_message_trace_enabled:Β boolΒ =Β False,
ping_pong_trace_enabled:Β boolΒ =Β False,
ping_interval:Β floatΒ =Β 5,
receive_buffer_size:Β intΒ =Β 1024,
concurrency:Β intΒ =Β 10,
proxy:Β strΒ |Β NoneΒ =Β None,
proxy_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[int,Β strΒ |Β None],Β None]]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeClient(BaseSocketModeClient):
+    logger: Logger
+    web_client: WebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            WebSocketMessageListener,
+            Callable[["BaseSocketModeClient", dict, Optional[str]], None],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            SocketModeRequestListener,
+            Callable[["BaseSocketModeClient", SocketModeRequest], None],
+        ]
+    ]
+
+    current_session: Optional[Connection]
+    current_session_state: ConnectionState
+    current_session_runner: IntervalRunner
+
+    current_app_monitor: IntervalRunner
+    current_app_monitor_started: bool
+
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    auto_reconnect_enabled: bool
+    default_auto_reconnect_enabled: bool
+    trace_enabled: bool
+    receive_buffer_size: int  # bytes size
+
+    connect_operation_lock: Lock
+
+    on_message_listeners: List[Callable[[str], None]]
+    on_error_listeners: List[Callable[[Exception], None]]
+    on_close_listeners: List[Callable[[int, Optional[str]], None]]
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        trace_enabled: bool = False,
+        all_message_trace_enabled: bool = False,
+        ping_pong_trace_enabled: bool = False,
+        ping_interval: float = 5,
+        receive_buffer_size: int = 1024,
+        concurrency: int = 10,
+        proxy: Optional[str] = None,
+        proxy_headers: Optional[Dict[str, str]] = None,
+        on_message_listeners: Optional[List[Callable[[str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[int, Optional[str]], None]]] = None,
+    ):
+        """Socket Mode client
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            trace_enabled: True if more detailed debug-logging is enabled (default: False)
+            all_message_trace_enabled: True if all message dump in debug logs is enabled (default: False)
+            ping_pong_trace_enabled: True if trace logging for all ping-pong communications is enabled (default: False)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            receive_buffer_size: the chunk size of a single socket recv operation (default: 1024)
+            concurrency: the size of thread pool (default: 10)
+            proxy: the HTTP proxy URL
+            proxy_headers: additional HTTP header for proxy connection
+            on_message_listeners: listener functions for on_message
+            on_error_listeners: listener functions for on_error
+            on_close_listeners: listener functions for on_close
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or WebClient()
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.trace_enabled = trace_enabled
+        self.all_message_trace_enabled = all_message_trace_enabled
+        self.ping_pong_trace_enabled = ping_pong_trace_enabled
+        self.ping_interval = ping_interval
+        self.receive_buffer_size = receive_buffer_size
+        if self.receive_buffer_size < 16:
+            raise SlackClientConfigurationError("Too small receive_buffer_size detected.")
+
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_state = ConnectionState()
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.1).start()
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval)
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+        self.proxy = proxy
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+        self.proxy_headers = proxy_headers
+
+        self.on_message_listeners = on_message_listeners or []
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+    def session_id(self) -> Optional[str]:
+        if self.current_session is not None:
+            return self.current_session.session_id
+        return None
+
+    def is_connected(self) -> bool:
+        return self.current_session is not None and self.current_session.is_active()
+
+    def connect(self) -> None:
+        old_session: Optional[Connection] = self.current_session
+        old_current_session_state: ConnectionState = self.current_session_state
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        current_session = Connection(
+            url=self.wss_uri,
+            logger=self.logger,
+            ping_interval=self.ping_interval,
+            trace_enabled=self.trace_enabled,
+            all_message_trace_enabled=self.all_message_trace_enabled,
+            ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+            receive_buffer_size=self.receive_buffer_size,
+            proxy=self.proxy,
+            proxy_headers=self.proxy_headers,
+            on_message_listener=self._on_message,
+            on_error_listener=self._on_error,
+            on_close_listener=self._on_close,
+            ssl_context=self.web_client.ssl,
+        )
+        current_session.connect()
+
+        if old_current_session_state is not None:
+            old_current_session_state.terminated = True
+        if old_session is not None:
+            old_session.close()
+
+        self.current_session = current_session
+        self.current_session_state = ConnectionState()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+    def disconnect(self) -> None:
+        if self.current_session is not None:
+            self.current_session.close()
+
+    def send_message(self, message: str) -> None:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+        try:
+            self.current_session.send(message)  # type: ignore[union-attr]
+        except SlackClientNotConnectedError as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            with self.connect_operation_lock:
+                if self.is_connected():
+                    self.current_session.send(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(
+                        f"The current session (session id: {self.session_id()}) is no longer active. "
+                        "Failed to send a message"
+                    )
+                    raise e
+
+    def close(self):
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        self.disconnect()
+        if self.current_app_monitor.is_alive():
+            self.current_app_monitor.shutdown()
+        if self.message_processor.is_alive():
+            self.message_processor.shutdown()
+        self.message_workers.shutdown()
+
+    def _on_message(self, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {debug_redacted_message_string(message)})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(message)
+
+    def _on_error(self, error: Exception):
+        error_message = (
+            f"on_error invoked (session id: {self.session_id()}, " f"error: {type(error).__name__}, message: {error})"
+        )
+        if self.trace_enabled:
+            self.logger.exception(error_message)
+        else:
+            self.logger.error(error_message)
+
+        for listener in self.on_error_listeners:
+            listener(error)
+
+    def _on_close(self, code: int, reason: Optional[str] = None):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked (session id: {self.session_id()})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Reconnecting... " f"(session id: {self.session_id()})")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(code, reason)
+
+    def _run_current_session(self):
+        if self.current_session is not None and self.current_session.is_active():
+            session_id = self.session_id()
+            try:
+                self.logger.info("Starting to receive messages from a new connection" f" (session id: {session_id})")
+                self.current_session_state.terminated = False
+                self.current_session.run_until_completion(self.current_session_state)
+                self.logger.info("Stopped receiving messages from a connection" f" (session id: {session_id})")
+            except Exception as e:
+                error_message = "Failed to start or stop the current session" f" (session id: {session_id}, error: {e})"
+                if self.trace_enabled:
+                    self.logger.exception(error_message)
+                else:
+                    self.logger.error(error_message)
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                self.current_session.check_state()
+
+                if self.auto_reconnect_enabled and (self.current_session is None or not self.current_session.is_active()):
+                    self.logger.info(
+                        "The session seems to be already closed. Reconnecting... " f"(session id: {self.session_id()})"
+                    )
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(session id: {self.session_id()}, error: {type(e).__name__}, message: {e})"
+                )
+
+

Socket Mode client

+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
trace_enabled
+
True if more detailed debug-logging is enabled (default: False)
+
all_message_trace_enabled
+
True if all message dump in debug logs is enabled (default: False)
+
ping_pong_trace_enabled
+
True if trace logging for all ping-pong communications is enabled (default: False)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
receive_buffer_size
+
the chunk size of a single socket recv operation (default: 1024)
+
concurrency
+
the size of thread pool (default: 10)
+
proxy
+
the HTTP proxy URL
+
proxy_headers
+
additional HTTP header for proxy connection
+
on_message_listeners
+
listener functions for on_message
+
on_error_listeners
+
listener functions for on_error
+
on_close_listeners
+
listener functions for on_close
+
+

Ancestors

+ +

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var current_app_monitor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_app_monitor_started :Β bool
+
+

The type of the None singleton.

+
+
var current_session :Β ConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_runner :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_session_state :Β ConnectionState
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[int,Β strΒ |Β None],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[str],Β None]]
+
+

The type of the None singleton.

+
+
var receive_buffer_size :Β int
+
+

The type of the None singleton.

+
+
var trace_enabled :Β bool
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) +
+
+
+ +Expand source code + +
def close(self):
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    self.disconnect()
+    if self.current_app_monitor.is_alive():
+        self.current_app_monitor.shutdown()
+    if self.message_processor.is_alive():
+        self.message_processor.shutdown()
+    self.message_workers.shutdown()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    old_session: Optional[Connection] = self.current_session
+    old_current_session_state: ConnectionState = self.current_session_state
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    current_session = Connection(
+        url=self.wss_uri,
+        logger=self.logger,
+        ping_interval=self.ping_interval,
+        trace_enabled=self.trace_enabled,
+        all_message_trace_enabled=self.all_message_trace_enabled,
+        ping_pong_trace_enabled=self.ping_pong_trace_enabled,
+        receive_buffer_size=self.receive_buffer_size,
+        proxy=self.proxy,
+        proxy_headers=self.proxy_headers,
+        on_message_listener=self._on_message,
+        on_error_listener=self._on_error,
+        on_close_listener=self._on_close,
+        ssl_context=self.web_client.ssl,
+    )
+    current_session.connect()
+
+    if old_current_session_state is not None:
+        old_current_session_state.terminated = True
+    if old_session is not None:
+        old_session.close()
+
+    self.current_session = current_session
+    self.current_session_state = ConnectionState()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    self.logger.info(f"A new session has been established (session id: {self.session_id()})")
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    if self.current_session is not None:
+        self.current_session.close()
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    return self.current_session is not None and self.current_session.is_active()
+
+
+
+
+def send_message(self, message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send_message(self, message: str) -> None:
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message (session id: {self.session_id()}, message: {message})")
+    try:
+        self.current_session.send(message)  # type: ignore[union-attr]
+    except SlackClientNotConnectedError as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (session id: {self.session_id()}, error: {e}, message: {message})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        with self.connect_operation_lock:
+            if self.is_connected():
+                self.current_session.send(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(
+                    f"The current session (session id: {self.session_id()}) is no longer active. "
+                    "Failed to send a message"
+                )
+                raise e
+
+
+
+
+def session_id(self) ‑>Β strΒ |Β None +
+
+
+ +Expand source code + +
def session_id(self) -> Optional[str]:
+    if self.current_session is not None:
+        return self.current_session.session_id
+    return None
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/interval_runner.html b/docs/reference/socket_mode/interval_runner.html new file mode 100644 index 000000000..54838d22f --- /dev/null +++ b/docs/reference/socket_mode/interval_runner.html @@ -0,0 +1,180 @@ + + + + + + +slack_sdk.socket_mode.interval_runner API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.interval_runner

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class IntervalRunner +(target:Β Callable[[],Β None], interval_seconds:Β floatΒ =Β 0.1) +
+
+
+ +Expand source code + +
class IntervalRunner:
+    event: Event
+    thread: Thread
+
+    def __init__(self, target: Callable[[], None], interval_seconds: float = 0.1):
+        self.event = threading.Event()
+        self.target = target
+        self.interval_seconds = interval_seconds
+        self.thread = threading.Thread(target=self._run)
+        self.thread.daemon = True
+
+    def _run(self) -> None:
+        while not self.event.is_set():
+            self.target()
+            self.event.wait(self.interval_seconds)
+
+    def start(self) -> "IntervalRunner":
+        self.thread.start()
+        return self
+
+    def is_alive(self) -> bool:
+        return self.thread is not None and self.thread.is_alive()
+
+    def shutdown(self):
+        if self.is_alive():
+            self.event.set()
+            self.thread.join()
+        self.thread = None
+
+
+

Class variables

+
+
var event :Β threading.Event
+
+

The type of the None singleton.

+
+
var thread :Β threading.Thread
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def is_alive(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_alive(self) -> bool:
+    return self.thread is not None and self.thread.is_alive()
+
+
+
+
+def shutdown(self) +
+
+
+ +Expand source code + +
def shutdown(self):
+    if self.is_alive():
+        self.event.set()
+        self.thread.join()
+    self.thread = None
+
+
+
+
+def start(self) ‑>Β IntervalRunner +
+
+
+ +Expand source code + +
def start(self) -> "IntervalRunner":
+    self.thread.start()
+    return self
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/listeners.html b/docs/reference/socket_mode/listeners.html new file mode 100644 index 000000000..daabff8fd --- /dev/null +++ b/docs/reference/socket_mode/listeners.html @@ -0,0 +1,111 @@ + + + + + + +slack_sdk.socket_mode.listeners API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.listeners

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeRequestListener +
+
+
+ +Expand source code + +
class SocketModeRequestListener:
+    def __call__(client: "BaseSocketModeClient", request: SocketModeRequest):  # type: ignore[name-defined]  # noqa: F821, F821, E501
+        raise NotImplementedError()
+
+
+
+
+class WebSocketMessageListener +
+
+
+ +Expand source code + +
class WebSocketMessageListener:
+    def __call__(
+        client: "BaseSocketModeClient",  # type: ignore[name-defined] # noqa: F821
+        message: dict,
+        raw_message: Optional[str] = None,
+    ):  # noqa: F821
+        raise NotImplementedError()
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/logger/index.html b/docs/reference/socket_mode/logger/index.html new file mode 100644 index 000000000..0d02b13f3 --- /dev/null +++ b/docs/reference/socket_mode/logger/index.html @@ -0,0 +1,78 @@ + + + + + + +slack_sdk.socket_mode.logger API documentation + + + + + + + + + + + +
+ + +
+ + + diff --git a/docs/reference/socket_mode/logger/messages.html b/docs/reference/socket_mode/logger/messages.html new file mode 100644 index 000000000..eb2a0dffe --- /dev/null +++ b/docs/reference/socket_mode/logger/messages.html @@ -0,0 +1,88 @@ + + + + + + +slack_sdk.socket_mode.logger.messages API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.logger.messages

+
+
+
+
+
+
+
+
+

Functions

+
+
+def debug_redacted_message_string(message:Β str) ‑>Β str +
+
+
+ +Expand source code + +
def debug_redacted_message_string(message: str) -> str:
+    xwfp_token_pattern = re.compile(r"\"xwfp-[A-Za-z0-9\-]+\"")  # ex: "xwfp-abc-ABC-1234"
+    return re.sub(xwfp_token_pattern, "[[REDACTED]]", message)
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/request.html b/docs/reference/socket_mode/request.html new file mode 100644 index 000000000..75945aa40 --- /dev/null +++ b/docs/reference/socket_mode/request.html @@ -0,0 +1,205 @@ + + + + + + +slack_sdk.socket_mode.request API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.request

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeRequest +(type:Β str,
envelope_id:Β str,
payload:Β dictΒ |Β JsonObjectΒ |Β str,
accepts_response_payload:Β boolΒ |Β NoneΒ =Β None,
retry_attempt:Β intΒ |Β NoneΒ =Β None,
retry_reason:Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeRequest:
+    type: str
+    envelope_id: str
+    payload: dict
+    accepts_response_payload: bool
+    retry_attempt: Optional[int]  # events_api
+    retry_reason: Optional[str]  # events_api
+
+    def __init__(
+        self,
+        type: str,
+        envelope_id: str,
+        payload: Union[dict, JsonObject, str],
+        accepts_response_payload: Optional[bool] = None,
+        retry_attempt: Optional[int] = None,
+        retry_reason: Optional[str] = None,
+    ):
+        self.type = type
+        self.envelope_id = envelope_id
+
+        if isinstance(payload, JsonObject):
+            self.payload = payload.to_dict()
+        elif isinstance(payload, dict):
+            self.payload = payload
+        elif isinstance(payload, str):
+            self.payload = {"text": payload}
+        else:
+            unexpected_payload_type = type(payload)
+            raise ValueError(f"Unsupported payload data type ({unexpected_payload_type})")
+
+        self.accepts_response_payload = accepts_response_payload or False
+        self.retry_attempt = retry_attempt
+        self.retry_reason = retry_reason
+
+    @classmethod
+    def from_dict(cls, message: dict) -> Optional["SocketModeRequest"]:
+        if all(k in message for k in ("type", "envelope_id", "payload")):
+            return SocketModeRequest(
+                type=message["type"],
+                envelope_id=message["envelope_id"],
+                payload=message["payload"],
+                accepts_response_payload=message.get("accepts_response_payload") or False,
+                retry_attempt=message.get("retry_attempt"),
+                retry_reason=message.get("retry_reason"),
+            )
+        return None
+
+    def to_dict(self) -> dict:
+        d = {"envelope_id": self.envelope_id}
+        if self.payload is not None:
+            d["payload"] = self.payload  # type: ignore[assignment]
+        return d
+
+
+

Class variables

+
+
var accepts_response_payload :Β bool
+
+

The type of the None singleton.

+
+
var envelope_id :Β str
+
+

The type of the None singleton.

+
+
var payload :Β dict
+
+

The type of the None singleton.

+
+
var retry_attempt :Β intΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_reason :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var type :Β str
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def from_dict(message:Β dict) ‑>Β SocketModeRequestΒ |Β None +
+
+
+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    d = {"envelope_id": self.envelope_id}
+    if self.payload is not None:
+        d["payload"] = self.payload  # type: ignore[assignment]
+    return d
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/response.html b/docs/reference/socket_mode/response.html new file mode 100644 index 000000000..0142f7c9e --- /dev/null +++ b/docs/reference/socket_mode/response.html @@ -0,0 +1,146 @@ + + + + + + +slack_sdk.socket_mode.response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.response

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeResponse +(envelope_id:Β str,
payload:Β dictΒ |Β JsonObjectΒ |Β strΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeResponse:
+    envelope_id: str
+    payload: Optional[dict]
+
+    def __init__(self, envelope_id: str, payload: Optional[Union[dict, JsonObject, str]] = None):
+        self.envelope_id = envelope_id
+
+        if payload is None:
+            self.payload = None
+        elif isinstance(payload, JsonObject):
+            self.payload = payload.to_dict()
+        elif isinstance(payload, dict):
+            self.payload = payload
+        elif isinstance(payload, str):
+            self.payload = {"text": payload}
+        else:
+            raise ValueError(f"Unsupported payload data type ({type(payload)})")
+
+    def to_dict(self) -> dict:
+        d = {"envelope_id": self.envelope_id}
+        if self.payload is not None:
+            d["payload"] = self.payload  # type: ignore[assignment]
+        return d
+
+
+

Class variables

+
+
var envelope_id :Β str
+
+

The type of the None singleton.

+
+
var payload :Β dictΒ |Β None
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def to_dict(self) ‑>Β dict +
+
+
+ +Expand source code + +
def to_dict(self) -> dict:
+    d = {"envelope_id": self.envelope_id}
+    if self.payload is not None:
+        d["payload"] = self.payload  # type: ignore[assignment]
+    return d
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/websocket_client/index.html b/docs/reference/socket_mode/websocket_client/index.html new file mode 100644 index 000000000..b90aa9137 --- /dev/null +++ b/docs/reference/socket_mode/websocket_client/index.html @@ -0,0 +1,588 @@ + + + + + + +slack_sdk.socket_mode.websocket_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.websocket_client

+
+
+

websocket-client bassd Socket Mode client

+ +
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β WebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
ping_interval:Β floatΒ =Β 10,
concurrency:Β intΒ =Β 10,
trace_enabled:Β boolΒ =Β False,
http_proxy_host:Β strΒ |Β NoneΒ =Β None,
http_proxy_port:Β intΒ |Β NoneΒ =Β None,
http_proxy_auth:Β Tuple[str,Β str]Β |Β NoneΒ =Β None,
proxy_type:Β strΒ |Β NoneΒ =Β None,
on_open_listeners:Β List[Callable[[websocket._app.WebSocketApp],Β None]]Β |Β NoneΒ =Β None,
on_message_listeners:Β List[Callable[[websocket._app.WebSocketApp,Β str],Β None]]Β |Β NoneΒ =Β None,
on_error_listeners:Β List[Callable[[websocket._app.WebSocketApp,Β Exception],Β None]]Β |Β NoneΒ =Β None,
on_close_listeners:Β List[Callable[[websocket._app.WebSocketApp],Β None]]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class SocketModeClient(BaseSocketModeClient):
+    logger: Logger
+    web_client: WebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            WebSocketMessageListener,
+            Callable[["BaseSocketModeClient", dict, Optional[str]], None],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            SocketModeRequestListener,
+            Callable[["BaseSocketModeClient", SocketModeRequest], None],
+        ]
+    ]
+
+    current_app_monitor: IntervalRunner
+    current_app_monitor_started: bool
+    message_processor: IntervalRunner
+    message_workers: ThreadPoolExecutor
+
+    current_session: Optional[WebSocketApp]
+    current_session_runner: IntervalRunner
+
+    auto_reconnect_enabled: bool
+    default_auto_reconnect_enabled: bool
+
+    closed: bool
+    connect_operation_lock: Lock
+
+    on_open_listeners: List[Callable[[WebSocketApp], None]]
+    on_message_listeners: List[Callable[[WebSocketApp, str], None]]
+    on_error_listeners: List[Callable[[WebSocketApp, Exception], None]]
+    on_close_listeners: List[Callable[[WebSocketApp], None]]
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[WebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        ping_interval: float = 10,
+        concurrency: int = 10,
+        trace_enabled: bool = False,
+        http_proxy_host: Optional[str] = None,
+        http_proxy_port: Optional[int] = None,
+        http_proxy_auth: Optional[Tuple[str, str]] = None,
+        proxy_type: Optional[str] = None,
+        on_open_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None,
+        on_message_listeners: Optional[List[Callable[[WebSocketApp, str], None]]] = None,
+        on_error_listeners: Optional[List[Callable[[WebSocketApp, Exception], None]]] = None,
+        on_close_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None,
+    ):
+        """
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            concurrency: the size of thread pool (default: 10)
+            http_proxy_host: the HTTP proxy host
+            http_proxy_port: the HTTP proxy port
+            http_proxy_auth: the HTTP proxy username & password
+            proxy_type: the HTTP proxy type
+            on_open_listeners: listener functions for on_open
+            on_message_listeners: listener functions for on_message
+            on_error_listeners: listener functions for on_error
+            on_close_listeners: listener functions for on_close
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or WebClient()
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.ping_interval = ping_interval
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+
+        self.current_session = None
+        self.current_session_runner = IntervalRunner(self._run_current_session, 0.5).start()
+
+        self.current_app_monitor_started = False
+        self.current_app_monitor = IntervalRunner(self._monitor_current_session, self.ping_interval)
+
+        self.closed = False
+        self.connect_operation_lock = Lock()
+
+        self.message_processor = IntervalRunner(self.process_messages, 0.001).start()
+        self.message_workers = ThreadPoolExecutor(max_workers=concurrency)
+
+        # NOTE: only global settings is provided by the library
+        websocket.enableTrace(trace_enabled)
+
+        self.http_proxy_host = http_proxy_host
+        self.http_proxy_port = http_proxy_port
+        self.http_proxy_auth = http_proxy_auth
+        self.proxy_type = proxy_type
+
+        self.on_open_listeners = on_open_listeners or []
+        self.on_message_listeners = on_message_listeners or []
+        self.on_error_listeners = on_error_listeners or []
+        self.on_close_listeners = on_close_listeners or []
+
+    def is_connected(self) -> bool:
+        return self.current_session is not None and self.current_session.sock is not None
+
+    def connect(self) -> None:
+        def on_open(ws: WebSocketApp):
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug("on_open invoked")
+            for listener in self.on_open_listeners:
+                listener(ws)
+
+        def on_message(ws: WebSocketApp, message: str):
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"on_message invoked: (message: {debug_redacted_message_string(message)})")
+            self.enqueue_message(message)
+            for listener in self.on_message_listeners:
+                listener(ws, message)
+
+        def on_error(ws: WebSocketApp, error: Exception):
+            self.logger.error(f"on_error invoked (error: {type(error).__name__}, message: {error})")
+            for listener in self.on_error_listeners:
+                listener(ws, error)
+
+        def on_close(
+            ws: WebSocketApp,
+            close_status_code: Optional[int] = None,
+            close_msg: Optional[str] = None,
+        ):
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"on_close invoked: (code: {close_status_code}, message: {close_msg})")
+            if self.auto_reconnect_enabled:
+                self.logger.info("Received CLOSE event. Reconnecting...")
+                self.connect_to_new_endpoint()
+            for listener in self.on_close_listeners:
+                listener(ws)
+
+        old_session: Optional[WebSocketApp] = self.current_session
+
+        if self.wss_uri is None:
+            self.wss_uri = self.issue_new_wss_url()
+
+        self.current_session = websocket.WebSocketApp(
+            self.wss_uri,
+            on_open=on_open,
+            on_message=on_message,
+            on_error=on_error,
+            on_close=on_close,
+        )
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+        if not self.current_app_monitor_started:
+            self.current_app_monitor_started = True
+            self.current_app_monitor.start()
+
+        if old_session is not None:
+            old_session.close()
+
+        self.logger.info("A new session has been established")
+
+    def disconnect(self) -> None:
+        if self.current_session is not None:
+            self.current_session.close()
+
+    def send_message(self, message: str) -> None:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message: {message}")
+        try:
+            self.current_session.send(message)  # type: ignore[union-attr]
+        except WebSocketException as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (error: {e}, message: {message})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            with self.connect_operation_lock:
+                if self.is_connected():
+                    self.current_session.send(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(
+                        f"The current session (session id: {self.session_id()}) is no longer active. "  # type: ignore[attr-defined] # noqa: E501
+                        "Failed to send a message"
+                    )
+                    raise e
+
+    def close(self) -> None:
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        self.disconnect()
+        self.current_app_monitor.shutdown()
+        self.message_processor.shutdown()
+        self.message_workers.shutdown()
+
+    def _run_current_session(self):
+        if self.current_session is not None:
+            try:
+                self.logger.info("Starting to receive messages from a new connection")
+                self.current_session.run_forever(
+                    ping_interval=self.ping_interval,
+                    http_proxy_host=self.http_proxy_host,
+                    http_proxy_port=self.http_proxy_port,
+                    http_proxy_auth=self.http_proxy_auth,
+                    proxy_type=self.proxy_type,
+                )
+                self.logger.info("Stopped receiving messages from a connection")
+            except Exception as e:
+                self.logger.exception(f"Failed to start or stop the current session: {e}")
+                # To let the monitoring job detect the connection issue, closing this session
+                if self.current_session is not None:
+                    self.current_session.close()
+
+    def _monitor_current_session(self):
+        if self.current_app_monitor_started:
+            try:
+                if self.auto_reconnect_enabled and (self.current_session is None or self.current_session.sock is None):
+                    self.logger.info("The session seems to be already closed. Reconnecting...")
+                    self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(error: {type(e).__name__}, message: {e})"
+                )
+
+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
concurrency
+
the size of thread pool (default: 10)
+
http_proxy_host
+
the HTTP proxy host
+
http_proxy_port
+
the HTTP proxy port
+
http_proxy_auth
+
the HTTP proxy username & password
+
proxy_type
+
the HTTP proxy type
+
on_open_listeners
+
listener functions for on_open
+
on_message_listeners
+
listener functions for on_message
+
on_error_listeners
+
listener functions for on_error
+
on_close_listeners
+
listener functions for on_close
+
+

Ancestors

+ +

Class variables

+
+
var auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var current_app_monitor :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var current_app_monitor_started :Β bool
+
+

The type of the None singleton.

+
+
var current_session :Β websocket._app.WebSocketAppΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_runner :Β IntervalRunner
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var on_close_listeners :Β List[Callable[[websocket._app.WebSocketApp],Β None]]
+
+

The type of the None singleton.

+
+
var on_error_listeners :Β List[Callable[[websocket._app.WebSocketApp,Β Exception],Β None]]
+
+

The type of the None singleton.

+
+
var on_message_listeners :Β List[Callable[[websocket._app.WebSocketApp,Β str],Β None]]
+
+

The type of the None singleton.

+
+
var on_open_listeners :Β List[Callable[[websocket._app.WebSocketApp],Β None]]
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def close(self) ‑>Β None +
+
+
+ +Expand source code + +
def close(self) -> None:
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    self.disconnect()
+    self.current_app_monitor.shutdown()
+    self.message_processor.shutdown()
+    self.message_workers.shutdown()
+
+
+
+
+def connect(self) ‑>Β None +
+
+
+ +Expand source code + +
def connect(self) -> None:
+    def on_open(ws: WebSocketApp):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug("on_open invoked")
+        for listener in self.on_open_listeners:
+            listener(ws)
+
+    def on_message(ws: WebSocketApp, message: str):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_message invoked: (message: {debug_redacted_message_string(message)})")
+        self.enqueue_message(message)
+        for listener in self.on_message_listeners:
+            listener(ws, message)
+
+    def on_error(ws: WebSocketApp, error: Exception):
+        self.logger.error(f"on_error invoked (error: {type(error).__name__}, message: {error})")
+        for listener in self.on_error_listeners:
+            listener(ws, error)
+
+    def on_close(
+        ws: WebSocketApp,
+        close_status_code: Optional[int] = None,
+        close_msg: Optional[str] = None,
+    ):
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"on_close invoked: (code: {close_status_code}, message: {close_msg})")
+        if self.auto_reconnect_enabled:
+            self.logger.info("Received CLOSE event. Reconnecting...")
+            self.connect_to_new_endpoint()
+        for listener in self.on_close_listeners:
+            listener(ws)
+
+    old_session: Optional[WebSocketApp] = self.current_session
+
+    if self.wss_uri is None:
+        self.wss_uri = self.issue_new_wss_url()
+
+    self.current_session = websocket.WebSocketApp(
+        self.wss_uri,
+        on_open=on_open,
+        on_message=on_message,
+        on_error=on_error,
+        on_close=on_close,
+    )
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+
+    if not self.current_app_monitor_started:
+        self.current_app_monitor_started = True
+        self.current_app_monitor.start()
+
+    if old_session is not None:
+        old_session.close()
+
+    self.logger.info("A new session has been established")
+
+
+
+
+def disconnect(self) ‑>Β None +
+
+
+ +Expand source code + +
def disconnect(self) -> None:
+    if self.current_session is not None:
+        self.current_session.close()
+
+
+
+
+def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
def is_connected(self) -> bool:
+    return self.current_session is not None and self.current_session.sock is not None
+
+
+
+
+def send_message(self, message:Β str) ‑>Β None +
+
+
+ +Expand source code + +
def send_message(self, message: str) -> None:
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message: {message}")
+    try:
+        self.current_session.send(message)  # type: ignore[union-attr]
+    except WebSocketException as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (error: {e}, message: {message})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        with self.connect_operation_lock:
+            if self.is_connected():
+                self.current_session.send(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(
+                    f"The current session (session id: {self.session_id()}) is no longer active. "  # type: ignore[attr-defined] # noqa: E501
+                    "Failed to send a message"
+                )
+                raise e
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/socket_mode/websockets/index.html b/docs/reference/socket_mode/websockets/index.html new file mode 100644 index 000000000..e38594eee --- /dev/null +++ b/docs/reference/socket_mode/websockets/index.html @@ -0,0 +1,639 @@ + + + + + + +slack_sdk.socket_mode.websockets API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.socket_mode.websockets

+
+
+

websockets bassd Socket Mode client

+ +
+
+
+
+
+
+
+
+

Classes

+
+
+class SocketModeClient +(app_token:Β str,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
web_client:Β AsyncWebClientΒ |Β NoneΒ =Β None,
auto_reconnect_enabled:Β boolΒ =Β True,
ping_interval:Β floatΒ =Β 10,
trace_enabled:Β boolΒ =Β False)
+
+
+
+ +Expand source code + +
class SocketModeClient(AsyncBaseSocketModeClient):
+    logger: Logger
+    web_client: AsyncWebClient
+    app_token: str
+    wss_uri: Optional[str]  # type: ignore[assignment]
+    auto_reconnect_enabled: bool
+    message_queue: Queue
+    message_listeners: List[
+        Union[
+            AsyncWebSocketMessageListener,
+            Callable[["AsyncBaseSocketModeClient", dict, Optional[str]], Awaitable[None]],
+        ]
+    ]
+    socket_mode_request_listeners: List[
+        Union[
+            AsyncSocketModeRequestListener,
+            Callable[["AsyncBaseSocketModeClient", SocketModeRequest], Awaitable[None]],
+        ]
+    ]
+
+    message_receiver: Optional[Future]
+    message_processor: Future
+
+    ping_interval: float
+    trace_enabled: bool
+
+    current_session: Optional[ClientConnection]
+    current_session_monitor: Optional[Future]
+
+    default_auto_reconnect_enabled: bool
+    closed: bool
+    connect_operation_lock: Lock
+
+    def __init__(
+        self,
+        app_token: str,
+        logger: Optional[Logger] = None,
+        web_client: Optional[AsyncWebClient] = None,
+        auto_reconnect_enabled: bool = True,
+        ping_interval: float = 10,
+        trace_enabled: bool = False,
+    ):
+        """Socket Mode client
+
+        Args:
+            app_token: App-level token
+            logger: Custom logger
+            web_client: Web API client
+            auto_reconnect_enabled: True if automatic reconnection is enabled (default: True)
+            ping_interval: interval for ping-pong with Slack servers (seconds)
+            trace_enabled: True if more verbose logs to see what's happening under the hood
+        """
+        self.app_token = app_token
+        self.logger = logger or logging.getLogger(__name__)
+        self.web_client = web_client or AsyncWebClient()
+        self.closed = False
+        self.connect_operation_lock = Lock()
+        self.default_auto_reconnect_enabled = auto_reconnect_enabled
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.ping_interval = ping_interval
+        self.trace_enabled = trace_enabled
+        self.wss_uri = None
+        self.message_queue = Queue()
+        self.message_listeners = []
+        self.socket_mode_request_listeners = []
+        self.current_session = None
+        self.current_session_monitor = None
+
+        self.message_receiver = None
+        self.message_processor = asyncio.ensure_future(self.process_messages())
+
+    async def monitor_current_session(self) -> None:
+        # In the asyncio runtime, accessing a shared object (self.current_session here) from
+        # multiple tasks can cause race conditions and errors.
+        # To avoid such, we access only the session that is active when this loop starts.
+        session: ClientConnection = self.current_session  # type: ignore[assignment]
+        session_id: str = await self.session_id()
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started")
+        try:
+            while not self.closed:
+                if session != self.current_session:
+                    if self.logger.level <= logging.DEBUG:
+                        self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+                    break
+                await asyncio.sleep(self.ping_interval)
+                try:
+                    if self.auto_reconnect_enabled and _session_closed(session=session):
+                        self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...")
+                        await self.connect_to_new_endpoint()
+                except Exception as e:
+                    self.logger.error(
+                        "Failed to check the current session or reconnect to the server "
+                        f"(error: {type(e).__name__}, message: {e}, session: {session_id})"
+                    )
+        except asyncio.CancelledError:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+            raise
+
+    async def receive_messages(self) -> None:
+        # In the asyncio runtime, accessing a shared object (self.current_session here) from
+        # multiple tasks can cause race conditions and errors.
+        # To avoid such, we access only the session that is active when this loop starts.
+        session: ClientConnection = self.current_session  # type: ignore[assignment]
+        session_id: str = await self.session_id()
+        consecutive_error_count = 0
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new receive_messages() execution loop with {session_id} started")
+        try:
+            while not self.closed:
+                if session != self.current_session:
+                    if self.logger.level <= logging.DEBUG:
+                        self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+                    break
+                try:
+                    message = await session.recv()
+                    if message is not None:
+                        if isinstance(message, bytes):
+                            message = message.decode("utf-8")
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.debug(
+                                f"Received message: {debug_redacted_message_string(message)}, session: {session_id}"
+                            )
+                        await self.enqueue_message(message)
+                    consecutive_error_count = 0
+                except Exception as e:
+                    consecutive_error_count += 1
+                    self.logger.error(
+                        f"Failed to receive or enqueue a message: {type(e).__name__}, error: {e}, session: {session_id}"
+                    )
+                    if isinstance(e, websockets.ConnectionClosedError):
+                        await asyncio.sleep(self.ping_interval)
+                    else:
+                        await asyncio.sleep(consecutive_error_count)
+        except asyncio.CancelledError:
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+            raise
+
+    async def is_connected(self) -> bool:
+        return not self.closed and not _session_closed(self.current_session)
+
+    async def session_id(self) -> str:
+        return self.build_session_id(self.current_session)  # type: ignore[arg-type]
+
+    async def connect(self):
+        if self.wss_uri is None:
+            self.wss_uri = await self.issue_new_wss_url()
+        old_session: Optional[ClientConnection] = None if self.current_session is None else self.current_session
+        # NOTE: websockets does not support proxy settings
+        self.current_session = await websockets.connect(
+            uri=self.wss_uri,
+            ping_interval=self.ping_interval,
+        )
+        session_id = await self.session_id()
+        self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+        self.logger.info(f"A new session ({session_id}) has been established")
+
+        if self.current_session_monitor is not None:
+            self.current_session_monitor.cancel()
+        self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session())
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}")
+
+        if self.message_receiver is not None:
+            self.message_receiver.cancel()
+        self.message_receiver = asyncio.ensure_future(self.receive_messages())
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}")
+
+        if old_session is not None:
+            await old_session.close()
+            old_session_id = self.build_session_id(old_session)
+            self.logger.info(f"The old session ({old_session_id}) has been abandoned")
+
+    async def disconnect(self):
+        if self.current_session is not None:
+            await self.current_session.close()
+
+    async def send_message(self, message: str):
+        session = self.current_session
+        session_id = self.build_session_id(session)  # type: ignore[arg-type]
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a message: {message}, session: {session_id}")
+        try:
+            await session.send(message)  # type: ignore[union-attr]
+        except WebSocketException as e:
+            # We rarely get this exception while replacing the underlying WebSocket connections.
+            # We can do one more try here as the self.current_session should be ready now.
+            if self.logger.level <= logging.DEBUG:
+                self.logger.debug(
+                    f"Failed to send a message (error: {e}, message: {message}, session: {session_id})"
+                    " as the underlying connection was replaced. Retrying the same request only one time..."
+                )
+            # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+            # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+            try:
+                if await self.is_connected():
+                    await self.current_session.send(message)  # type: ignore[union-attr]
+                else:
+                    self.logger.warning(f"The current session ({session_id}) is no longer active. Failed to send a message")
+                    raise e
+            finally:
+                if self.connect_operation_lock.locked() is True:
+                    self.connect_operation_lock.release()
+
+    async def close(self):
+        self.closed = True
+        self.auto_reconnect_enabled = False
+        await self.disconnect()
+        self.message_processor.cancel()
+        if self.current_session_monitor is not None:
+            self.current_session_monitor.cancel()
+        if self.message_receiver is not None:
+            self.message_receiver.cancel()
+
+    @classmethod
+    def build_session_id(cls, session: ClientConnection) -> str:
+        if session is None:
+            return ""
+        return "s_" + str(hash(session))
+
+

Socket Mode client

+

Args

+
+
app_token
+
App-level token
+
logger
+
Custom logger
+
web_client
+
Web API client
+
auto_reconnect_enabled
+
True if automatic reconnection is enabled (default: True)
+
ping_interval
+
interval for ping-pong with Slack servers (seconds)
+
trace_enabled
+
True if more verbose logs to see what's happening under the hood
+
+

Ancestors

+ +

Class variables

+
+
var current_session :Β websockets.asyncio.client.ClientConnectionΒ |Β None
+
+

The type of the None singleton.

+
+
var current_session_monitor :Β _asyncio.FutureΒ |Β None
+
+

The type of the None singleton.

+
+
var default_auto_reconnect_enabled :Β bool
+
+

The type of the None singleton.

+
+
var message_processor :Β _asyncio.Future
+
+

The type of the None singleton.

+
+
var message_receiver :Β _asyncio.FutureΒ |Β None
+
+

The type of the None singleton.

+
+
var ping_interval :Β float
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def build_session_id(session:Β websockets.asyncio.client.ClientConnection) ‑>Β str +
+
+
+
+
+

Methods

+
+
+async def close(self) +
+
+
+ +Expand source code + +
async def close(self):
+    self.closed = True
+    self.auto_reconnect_enabled = False
+    await self.disconnect()
+    self.message_processor.cancel()
+    if self.current_session_monitor is not None:
+        self.current_session_monitor.cancel()
+    if self.message_receiver is not None:
+        self.message_receiver.cancel()
+
+
+
+
+async def connect(self) +
+
+
+ +Expand source code + +
async def connect(self):
+    if self.wss_uri is None:
+        self.wss_uri = await self.issue_new_wss_url()
+    old_session: Optional[ClientConnection] = None if self.current_session is None else self.current_session
+    # NOTE: websockets does not support proxy settings
+    self.current_session = await websockets.connect(
+        uri=self.wss_uri,
+        ping_interval=self.ping_interval,
+    )
+    session_id = await self.session_id()
+    self.auto_reconnect_enabled = self.default_auto_reconnect_enabled
+    self.logger.info(f"A new session ({session_id}) has been established")
+
+    if self.current_session_monitor is not None:
+        self.current_session_monitor.cancel()
+    self.current_session_monitor = asyncio.ensure_future(self.monitor_current_session())
+
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new monitor_current_session() executor has been recreated for {session_id}")
+
+    if self.message_receiver is not None:
+        self.message_receiver.cancel()
+    self.message_receiver = asyncio.ensure_future(self.receive_messages())
+
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new receive_messages() executor has been recreated for {session_id}")
+
+    if old_session is not None:
+        await old_session.close()
+        old_session_id = self.build_session_id(old_session)
+        self.logger.info(f"The old session ({old_session_id}) has been abandoned")
+
+
+
+
+async def disconnect(self) +
+
+
+ +Expand source code + +
async def disconnect(self):
+    if self.current_session is not None:
+        await self.current_session.close()
+
+
+
+
+async def is_connected(self) ‑>Β bool +
+
+
+ +Expand source code + +
async def is_connected(self) -> bool:
+    return not self.closed and not _session_closed(self.current_session)
+
+
+
+
+async def monitor_current_session(self) ‑>Β None +
+
+
+ +Expand source code + +
async def monitor_current_session(self) -> None:
+    # In the asyncio runtime, accessing a shared object (self.current_session here) from
+    # multiple tasks can cause race conditions and errors.
+    # To avoid such, we access only the session that is active when this loop starts.
+    session: ClientConnection = self.current_session  # type: ignore[assignment]
+    session_id: str = await self.session_id()
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new monitor_current_session() execution loop for {session_id} started")
+    try:
+        while not self.closed:
+            if session != self.current_session:
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+                break
+            await asyncio.sleep(self.ping_interval)
+            try:
+                if self.auto_reconnect_enabled and _session_closed(session=session):
+                    self.logger.info(f"The session ({session_id}) seems to be already closed. Reconnecting...")
+                    await self.connect_to_new_endpoint()
+            except Exception as e:
+                self.logger.error(
+                    "Failed to check the current session or reconnect to the server "
+                    f"(error: {type(e).__name__}, message: {e}, session: {session_id})"
+                )
+    except asyncio.CancelledError:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"The monitor_current_session task for {session_id} is now cancelled")
+        raise
+
+
+
+
+async def receive_messages(self) ‑>Β None +
+
+
+ +Expand source code + +
async def receive_messages(self) -> None:
+    # In the asyncio runtime, accessing a shared object (self.current_session here) from
+    # multiple tasks can cause race conditions and errors.
+    # To avoid such, we access only the session that is active when this loop starts.
+    session: ClientConnection = self.current_session  # type: ignore[assignment]
+    session_id: str = await self.session_id()
+    consecutive_error_count = 0
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"A new receive_messages() execution loop with {session_id} started")
+    try:
+        while not self.closed:
+            if session != self.current_session:
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+                break
+            try:
+                message = await session.recv()
+                if message is not None:
+                    if isinstance(message, bytes):
+                        message = message.decode("utf-8")
+                    if self.logger.level <= logging.DEBUG:
+                        self.logger.debug(
+                            f"Received message: {debug_redacted_message_string(message)}, session: {session_id}"
+                        )
+                    await self.enqueue_message(message)
+                consecutive_error_count = 0
+            except Exception as e:
+                consecutive_error_count += 1
+                self.logger.error(
+                    f"Failed to receive or enqueue a message: {type(e).__name__}, error: {e}, session: {session_id}"
+                )
+                if isinstance(e, websockets.ConnectionClosedError):
+                    await asyncio.sleep(self.ping_interval)
+                else:
+                    await asyncio.sleep(consecutive_error_count)
+    except asyncio.CancelledError:
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"The running receive_messages task for {session_id} is now cancelled")
+        raise
+
+
+
+
+async def send_message(self, message:Β str) +
+
+
+ +Expand source code + +
async def send_message(self, message: str):
+    session = self.current_session
+    session_id = self.build_session_id(session)  # type: ignore[arg-type]
+    if self.logger.level <= logging.DEBUG:
+        self.logger.debug(f"Sending a message: {message}, session: {session_id}")
+    try:
+        await session.send(message)  # type: ignore[union-attr]
+    except WebSocketException as e:
+        # We rarely get this exception while replacing the underlying WebSocket connections.
+        # We can do one more try here as the self.current_session should be ready now.
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(
+                f"Failed to send a message (error: {e}, message: {message}, session: {session_id})"
+                " as the underlying connection was replaced. Retrying the same request only one time..."
+            )
+        # Although acquiring self.connect_operation_lock also for the first method call is the safest way,
+        # we avoid synchronizing a lot for better performance. That's why we are doing a retry here.
+        try:
+            if await self.is_connected():
+                await self.current_session.send(message)  # type: ignore[union-attr]
+            else:
+                self.logger.warning(f"The current session ({session_id}) is no longer active. Failed to send a message")
+                raise e
+        finally:
+            if self.connect_operation_lock.locked() is True:
+                self.connect_operation_lock.release()
+
+
+
+
+async def session_id(self) ‑>Β str +
+
+
+ +Expand source code + +
async def session_id(self) -> str:
+    return self.build_session_id(self.current_session)  # type: ignore[arg-type]
+
+
+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/version.html b/docs/reference/version.html new file mode 100644 index 000000000..9f8e3c5bb --- /dev/null +++ b/docs/reference/version.html @@ -0,0 +1,67 @@ + + + + + + +slack_sdk.version API documentation + + + + + + + + + + + +
+ + +
+ + + diff --git a/docs/reference/web/async_base_client.html b/docs/reference/web/async_base_client.html new file mode 100644 index 000000000..97615d924 --- /dev/null +++ b/docs/reference/web/async_base_client.html @@ -0,0 +1,535 @@ + + + + + + +slack_sdk.web.async_base_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.async_base_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncBaseClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncBaseClient:
+    BASE_URL = "https://slack.com/api/"
+
+    def __init__(
+        self,
+        token: Optional[str] = None,
+        base_url: str = BASE_URL,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        session: Optional[aiohttp.ClientSession] = None,
+        trust_env_in_session: bool = False,
+        headers: Optional[dict] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        # for Org-Wide App installation
+        team_id: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        self.token = None if token is None else token.strip()
+        """A string specifying an `xoxp-*` or `xoxb-*` token."""
+        if not base_url.endswith("/"):
+            base_url += "/"
+        self.base_url = base_url
+        """A string representing the Slack API base URL.
+        Default is `'https://slack.com/api/'`."""
+        self.timeout = timeout
+        """The maximum number of seconds the client will wait
+        to connect and receive a response from Slack.
+        Default is 30 seconds."""
+        self.ssl = ssl
+        """An [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
+        instance, helpful for specifying your own custom
+        certificate chain."""
+        self.proxy = proxy
+        """String representing a fully-qualified URL to a proxy through which
+        to route all requests to the Slack API. Even if this parameter
+        is not specified, if any of the following environment variables are
+        present, they will be loaded into this parameter: `HTTPS_PROXY`,
+        `https_proxy`, `HTTP_PROXY` or `http_proxy`."""
+        self.session = session
+        """An [`aiohttp.ClientSession`](https://docs.aiohttp.org/en/stable/client_reference.html#client-session)
+        to attach to all outgoing requests."""
+        # https://github.com/slackapi/python-slack-sdk/issues/738
+        self.trust_env_in_session = trust_env_in_session
+        """Boolean setting whether aiohttp outgoing requests
+        are allowed to read environment variables. Commonly used in conjunction
+        with proxy support via the `HTTPS_PROXY`, `https_proxy`, `HTTP_PROXY` and
+        `http_proxy` environment variables."""
+        self.headers = headers or {}
+        """`dict` representing additional request headers to attach to all requests."""
+        self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.default_params = {}
+        if team_id is not None:
+            self.default_params["team_id"] = team_id
+        self._logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self._logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # accessors
+
+    @property
+    def logger(self) -> logging.Logger:
+        """The logger this client uses."""
+        return self._logger
+
+    # -------------------------
+    # api call
+
+    async def api_call(
+        self,
+        api_method: str,
+        *,
+        http_verb: str = "POST",
+        files: Optional[dict] = None,
+        data: Optional[Union[dict, FormData]] = None,
+        params: Optional[dict] = None,
+        json: Optional[dict] = None,
+        headers: Optional[dict] = None,
+        auth: Optional[dict] = None,
+    ) -> AsyncSlackResponse:
+        """Create a request and execute the API call to Slack.
+
+        Args:
+            api_method (str): The target Slack API method.
+                e.g. 'chat.postMessage'
+            http_verb (str): HTTP Verb. e.g. 'POST'
+            files (dict): Files to multipart upload.
+                e.g. {image OR file: file_object OR file_path}
+            data: The body to attach to the request. If a dictionary is
+                provided, form-encoding will take place.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            params (dict): The URL parameters to append to the URL.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            json (dict): JSON for the body to attach to the request
+                (if files or data is not specified).
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            headers (dict): Additional request headers
+            auth (dict): A dictionary that consists of client_id and client_secret
+
+        Returns:
+            (AsyncSlackResponse)
+                The server's response to an HTTP request. Data
+                from the response can be accessed like a dict.
+                If the response included 'next_cursor' it can
+                be iterated on to execute subsequent requests.
+
+        Raises:
+            SlackApiError: The following Slack API call failed:
+                'chat.postMessage'.
+            SlackRequestError: Json data can only be submitted as
+                POST requests.
+        """
+
+        api_url = _get_url(self.base_url, api_method)
+        if auth is not None:
+            if isinstance(auth, Dict):
+                auth = BasicAuth(auth["client_id"], auth["client_secret"])  # type: ignore[assignment]
+            if isinstance(auth, BasicAuth):
+                if headers is None:
+                    headers = {}
+                headers["Authorization"] = auth.encode()
+                auth = None
+
+        headers = headers or {}
+        headers.update(self.headers)
+        req_args = _build_req_args(
+            token=self.token,
+            http_verb=http_verb,
+            files=files,  # type: ignore[arg-type]
+            data=data,  # type: ignore[arg-type]
+            default_params=self.default_params,
+            params=params,  # type: ignore[arg-type]
+            json=json,  # type: ignore[arg-type]
+            headers=headers,
+            auth=auth,  # type: ignore[arg-type]
+            ssl=self.ssl,
+            proxy=self.proxy,
+        )
+
+        show_deprecation_warning_if_any(api_method)
+
+        return await self._send(
+            http_verb=http_verb,
+            api_url=api_url,
+            req_args=req_args,
+        )
+
+    async def _send(self, http_verb: str, api_url: str, req_args: dict) -> AsyncSlackResponse:
+        """Sends the request out for transmission.
+
+        Args:
+            http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
+            api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
+            req_args (dict): The request arguments to be attached to the request.
+            e.g.
+            {
+                json: {
+                    'attachments': [{"pretext": "pre-hello", "text": "text-world"}],
+                    'channel': '#random'
+                }
+            }
+        Returns:
+            The response parsed into a AsyncSlackResponse object.
+        """
+        open_files = _files_to_data(req_args)
+        try:
+            if "params" in req_args:
+                # True/False -> "1"/"0"
+                req_args["params"] = convert_bool_to_0_or_1(req_args["params"])
+
+            res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args)
+        finally:
+            for f in open_files:
+                f.close()
+
+        data = {
+            "client": self,
+            "http_verb": http_verb,
+            "api_url": api_url,
+            "req_args": req_args,
+        }
+        return AsyncSlackResponse(**{**data, **res}).validate()
+
+    async def _request(self, *, http_verb, api_url, req_args) -> Dict[str, Any]:
+        """Submit the HTTP request with the running session or a new session.
+        Returns:
+            A dictionary of the response data.
+        """
+        return await _request_with_session(
+            current_session=self.session,
+            timeout=self.timeout,
+            logger=self._logger,
+            http_verb=http_verb,
+            api_url=api_url,
+            req_args=req_args,
+            retry_handlers=self.retry_handlers,
+        )
+
+    async def _upload_file(
+        self,
+        *,
+        url: str,
+        data: bytes,
+        logger: logging.Logger,
+        timeout: int,
+        proxy: Optional[str],
+        ssl: Optional[SSLContext],
+    ) -> FileUploadV2Result:
+        """Upload a file using the issued upload URL"""
+        result = await _request_with_session(
+            current_session=self.session,
+            timeout=timeout,
+            logger=logger,
+            http_verb="POST",
+            api_url=url,
+            req_args={"data": data, "proxy": proxy, "ssl": ssl},
+            retry_handlers=self.retry_handlers,
+        )
+        return FileUploadV2Result(
+            status=result.get("status_code"),  # type: ignore[arg-type]
+            body=result.get("body"),  # type: ignore[arg-type]
+        )
+
+
+

Subclasses

+ +

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
+

Instance variables

+
+
var base_url
+
+

A string representing the Slack API base URL. +Default is 'https://slack.com/api/'.

+
+
var headers
+
+

dict representing additional request headers to attach to all requests.

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> logging.Logger:
+    """The logger this client uses."""
+    return self._logger
+
+

The logger this client uses.

+
+
var proxy
+
+

String representing a fully-qualified URL to a proxy through which +to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.

+
+
var session
+
+

An aiohttp.ClientSession +to attach to all outgoing requests.

+
+
var ssl
+
+

An ssl.SSLContext +instance, helpful for specifying your own custom +certificate chain.

+
+
var timeout
+
+

The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.

+
+
var token
+
+

A string specifying an xoxp-* or xoxb-* token.

+
+
var trust_env_in_session
+
+

Boolean setting whether aiohttp outgoing requests +are allowed to read environment variables. Commonly used in conjunction +with proxy support via the HTTPS_PROXY, https_proxy, HTTP_PROXY and +http_proxy environment variables.

+
+
+

Methods

+
+
+async def api_call(self,
api_method:Β str,
*,
http_verb:Β strΒ =Β 'POST',
files:Β dictΒ |Β NoneΒ =Β None,
data:Β dictΒ |Β aiohttp.formdata.FormDataΒ |Β NoneΒ =Β None,
params:Β dictΒ |Β NoneΒ =Β None,
json:Β dictΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
auth:Β dictΒ |Β NoneΒ =Β None) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def api_call(
+    self,
+    api_method: str,
+    *,
+    http_verb: str = "POST",
+    files: Optional[dict] = None,
+    data: Optional[Union[dict, FormData]] = None,
+    params: Optional[dict] = None,
+    json: Optional[dict] = None,
+    headers: Optional[dict] = None,
+    auth: Optional[dict] = None,
+) -> AsyncSlackResponse:
+    """Create a request and execute the API call to Slack.
+
+    Args:
+        api_method (str): The target Slack API method.
+            e.g. 'chat.postMessage'
+        http_verb (str): HTTP Verb. e.g. 'POST'
+        files (dict): Files to multipart upload.
+            e.g. {image OR file: file_object OR file_path}
+        data: The body to attach to the request. If a dictionary is
+            provided, form-encoding will take place.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        params (dict): The URL parameters to append to the URL.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        json (dict): JSON for the body to attach to the request
+            (if files or data is not specified).
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        headers (dict): Additional request headers
+        auth (dict): A dictionary that consists of client_id and client_secret
+
+    Returns:
+        (AsyncSlackResponse)
+            The server's response to an HTTP request. Data
+            from the response can be accessed like a dict.
+            If the response included 'next_cursor' it can
+            be iterated on to execute subsequent requests.
+
+    Raises:
+        SlackApiError: The following Slack API call failed:
+            'chat.postMessage'.
+        SlackRequestError: Json data can only be submitted as
+            POST requests.
+    """
+
+    api_url = _get_url(self.base_url, api_method)
+    if auth is not None:
+        if isinstance(auth, Dict):
+            auth = BasicAuth(auth["client_id"], auth["client_secret"])  # type: ignore[assignment]
+        if isinstance(auth, BasicAuth):
+            if headers is None:
+                headers = {}
+            headers["Authorization"] = auth.encode()
+            auth = None
+
+    headers = headers or {}
+    headers.update(self.headers)
+    req_args = _build_req_args(
+        token=self.token,
+        http_verb=http_verb,
+        files=files,  # type: ignore[arg-type]
+        data=data,  # type: ignore[arg-type]
+        default_params=self.default_params,
+        params=params,  # type: ignore[arg-type]
+        json=json,  # type: ignore[arg-type]
+        headers=headers,
+        auth=auth,  # type: ignore[arg-type]
+        ssl=self.ssl,
+        proxy=self.proxy,
+    )
+
+    show_deprecation_warning_if_any(api_method)
+
+    return await self._send(
+        http_verb=http_verb,
+        api_url=api_url,
+        req_args=req_args,
+    )
+
+

Create a request and execute the API call to Slack.

+

Args

+
+
api_method : str
+
The target Slack API method. +e.g. 'chat.postMessage'
+
http_verb : str
+
HTTP Verb. e.g. 'POST'
+
files : dict
+
Files to multipart upload. +e.g. {image OR file: file_object OR file_path}
+
data
+
The body to attach to the request. If a dictionary is +provided, form-encoding will take place. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
params : dict
+
The URL parameters to append to the URL. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
json : dict
+
JSON for the body to attach to the request +(if files or data is not specified). +e.g. {'key1': 'value1', 'key2': 'value2'}
+
headers : dict
+
Additional request headers
+
auth : dict
+
A dictionary that consists of client_id and client_secret
+
+

Returns

+

(AsyncSlackResponse) +The server's response to an HTTP request. Data +from the response can be accessed like a dict. +If the response included 'next_cursor' it can +be iterated on to execute subsequent requests.

+

Raises

+
+
SlackApiError
+
The following Slack API call failed: +'chat.postMessage'.
+
SlackRequestError
+
Json data can only be submitted as +POST requests.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/async_chat_stream.html b/docs/reference/web/async_chat_stream.html new file mode 100644 index 000000000..ca7bf2506 --- /dev/null +++ b/docs/reference/web/async_chat_stream.html @@ -0,0 +1,506 @@ + + + + + + +slack_sdk.web.async_chat_stream API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.async_chat_stream

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncChatStream +(client:Β AsyncWebClient,
*,
channel:Β str,
logger:Β logging.Logger,
thread_ts:Β str,
buffer_size:Β int,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class AsyncChatStream:
+    """A helper class for streaming markdown text into a conversation using the chat streaming APIs.
+
+    This class provides a convenient interface for the chat.startStream, chat.appendStream, and chat.stopStream API
+    methods, with automatic buffering and state management.
+    """
+
+    def __init__(
+        self,
+        client: "AsyncWebClient",
+        *,
+        channel: str,
+        logger: logging.Logger,
+        thread_ts: str,
+        buffer_size: int,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ):
+        """Initialize a new ChatStream instance.
+
+        The __init__ method creates a unique ChatStream instance that keeps track of one chat stream.
+
+        Args:
+            client: The WebClient instance to use for API calls.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            logger: A logging channel for outputs.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            buffer_size: The length of markdown_text to buffer in-memory before calling a method. Increasing this value
+              decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
+            **kwargs: Additional arguments passed to the underlying API calls.
+        """
+        self._client = client
+        self._logger = logger
+        self._token: Optional[str] = kwargs.pop("token", None)
+        self._stream_args = {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+            **kwargs,
+        }
+        self._buffer = ""
+        self._state = "starting"
+        self._stream_ts: Optional[str] = None
+        self._buffer_size = buffer_size
+
+    async def append(
+        self,
+        *,
+        markdown_text: str,
+        **kwargs,
+    ) -> Optional[AsyncSlackResponse]:
+        """Append to the stream.
+
+        The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream
+        is stopped this method cannot be called.
+
+        Args:
+            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+              what will be appended to the message received so far.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            AsyncSlackResponse if the buffer was flushed, None if buffering.
+
+        Raises:
+            SlackRequestError: If the stream is already completed.
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        if self._state == "completed":
+            raise e.SlackRequestError(f"Cannot append to stream: stream state is {self._state}")
+        if kwargs.get("token"):
+            self._token = kwargs.pop("token")
+        self._buffer += markdown_text
+        if len(self._buffer) >= self._buffer_size:
+            return await self._flush_buffer(**kwargs)
+        details = {
+            "buffer_length": len(self._buffer),
+            "buffer_size": self._buffer_size,
+            "channel": self._stream_args.get("channel"),
+            "recipient_team_id": self._stream_args.get("recipient_team_id"),
+            "recipient_user_id": self._stream_args.get("recipient_user_id"),
+            "thread_ts": self._stream_args.get("thread_ts"),
+        }
+        self._logger.debug(f"ChatStream appended to buffer: {json.dumps(details)}")
+        return None
+
+    async def stop(
+        self,
+        *,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Stop the stream and finalize the message.
+
+        Args:
+            blocks: A list of blocks that will be rendered at the bottom of the finalized message.
+            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+              what will be appended to the message received so far.
+            metadata: JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you
+              post to Slack is accessible to any app or user who is a member of that workspace.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            AsyncSlackResponse from the chat.stopStream API call.
+
+        Raises:
+            SlackRequestError: If the stream is already completed.
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        if self._state == "completed":
+            raise e.SlackRequestError(f"Cannot stop stream: stream state is {self._state}")
+        if kwargs.get("token"):
+            self._token = kwargs.pop("token")
+        if markdown_text:
+            self._buffer += markdown_text
+        if not self._stream_ts:
+            response = await self._client.chat_startStream(
+                **self._stream_args,
+                token=self._token,
+            )
+            if not response.get("ts"):
+                raise e.SlackRequestError("Failed to stop stream: stream not started")
+            self._stream_ts = str(response["ts"])
+            self._state = "in_progress"
+        response = await self._client.chat_stopStream(
+            token=self._token,
+            channel=self._stream_args["channel"],
+            ts=self._stream_ts,
+            blocks=blocks,
+            markdown_text=self._buffer,
+            metadata=metadata,
+            **kwargs,
+        )
+        self._state = "completed"
+        return response
+
+    async def _flush_buffer(self, **kwargs) -> AsyncSlackResponse:
+        """Flush the internal buffer by making appropriate API calls."""
+        if not self._stream_ts:
+            response = await self._client.chat_startStream(
+                **self._stream_args,
+                token=self._token,
+                **kwargs,
+                markdown_text=self._buffer,
+            )
+            self._stream_ts = response.get("ts")
+            self._state = "in_progress"
+        else:
+            response = await self._client.chat_appendStream(
+                token=self._token,
+                channel=self._stream_args["channel"],
+                ts=self._stream_ts,
+                **kwargs,
+                markdown_text=self._buffer,
+            )
+        self._buffer = ""
+        return response
+
+

A helper class for streaming markdown text into a conversation using the chat streaming APIs.

+

This class provides a convenient interface for the chat.startStream, chat.appendStream, and chat.stopStream API +methods, with automatic buffering and state management.

+

Initialize a new ChatStream instance.

+

The init method creates a unique ChatStream instance that keeps track of one chat stream.

+

Args

+
+
client
+
The WebClient instance to use for API calls.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
logger
+
A logging channel for outputs.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a method. Increasing this value +decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Methods

+
+
+async def append(self, *, markdown_text:Β str, **kwargs) ‑>Β AsyncSlackResponseΒ |Β None +
+
+
+ +Expand source code + +
async def append(
+    self,
+    *,
+    markdown_text: str,
+    **kwargs,
+) -> Optional[AsyncSlackResponse]:
+    """Append to the stream.
+
+    The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream
+    is stopped this method cannot be called.
+
+    Args:
+        markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+          what will be appended to the message received so far.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        AsyncSlackResponse if the buffer was flushed, None if buffering.
+
+    Raises:
+        SlackRequestError: If the stream is already completed.
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    if self._state == "completed":
+        raise e.SlackRequestError(f"Cannot append to stream: stream state is {self._state}")
+    if kwargs.get("token"):
+        self._token = kwargs.pop("token")
+    self._buffer += markdown_text
+    if len(self._buffer) >= self._buffer_size:
+        return await self._flush_buffer(**kwargs)
+    details = {
+        "buffer_length": len(self._buffer),
+        "buffer_size": self._buffer_size,
+        "channel": self._stream_args.get("channel"),
+        "recipient_team_id": self._stream_args.get("recipient_team_id"),
+        "recipient_user_id": self._stream_args.get("recipient_user_id"),
+        "thread_ts": self._stream_args.get("thread_ts"),
+    }
+    self._logger.debug(f"ChatStream appended to buffer: {json.dumps(details)}")
+    return None
+
+

Append to the stream.

+

The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream +is stopped this method cannot be called.

+

Args

+
+
markdown_text
+
Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is +what will be appended to the message received so far.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

AsyncSlackResponse if the buffer was flushed, None if buffering.

+

Raises

+
+
SlackRequestError
+
If the stream is already completed.
+
+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+async def stop(self,
*,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def stop(
+    self,
+    *,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Stop the stream and finalize the message.
+
+    Args:
+        blocks: A list of blocks that will be rendered at the bottom of the finalized message.
+        markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+          what will be appended to the message received so far.
+        metadata: JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you
+          post to Slack is accessible to any app or user who is a member of that workspace.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        AsyncSlackResponse from the chat.stopStream API call.
+
+    Raises:
+        SlackRequestError: If the stream is already completed.
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    if self._state == "completed":
+        raise e.SlackRequestError(f"Cannot stop stream: stream state is {self._state}")
+    if kwargs.get("token"):
+        self._token = kwargs.pop("token")
+    if markdown_text:
+        self._buffer += markdown_text
+    if not self._stream_ts:
+        response = await self._client.chat_startStream(
+            **self._stream_args,
+            token=self._token,
+        )
+        if not response.get("ts"):
+            raise e.SlackRequestError("Failed to stop stream: stream not started")
+        self._stream_ts = str(response["ts"])
+        self._state = "in_progress"
+    response = await self._client.chat_stopStream(
+        token=self._token,
+        channel=self._stream_args["channel"],
+        ts=self._stream_ts,
+        blocks=blocks,
+        markdown_text=self._buffer,
+        metadata=metadata,
+        **kwargs,
+    )
+    self._state = "completed"
+    return response
+
+

Stop the stream and finalize the message.

+

Args

+
+
blocks
+
A list of blocks that will be rendered at the bottom of the finalized message.
+
markdown_text
+
Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is +what will be appended to the message received so far.
+
metadata
+
JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you +post to Slack is accessible to any app or user who is a member of that workspace.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

AsyncSlackResponse from the chat.stopStream API call.

+

Raises

+
+
SlackRequestError
+
If the stream is already completed.
+
+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/async_client.html b/docs/reference/web/async_client.html new file mode 100644 index 000000000..2ec1ba84a --- /dev/null +++ b/docs/reference/web/async_client.html @@ -0,0 +1,15788 @@ + + + + + + +slack_sdk.web.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.async_client

+
+
+

A Python module for interacting with Slack's Web API.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncWebClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncWebClient(AsyncBaseClient):
+    """A WebClient allows apps to communicate with the Slack Platform's Web API.
+
+    https://docs.slack.dev/reference/methods
+
+    The Slack Web API is an interface for querying information from
+    and enacting change in a Slack workspace.
+
+    This client handles constructing and sending HTTP requests to Slack
+    as well as parsing any responses received into a `SlackResponse`.
+
+    Attributes:
+        token (str): A string specifying an `xoxp-*` or `xoxb-*` token.
+        base_url (str): A string representing the Slack API base URL.
+            Default is `'https://slack.com/api/'`
+        timeout (int): The maximum number of seconds the client will wait
+            to connect and receive a response from Slack.
+            Default is 30 seconds.
+        ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying
+            your own custom certificate chain.
+        proxy (str): String representing a fully-qualified URL to a proxy through
+            which to route all requests to the Slack API. Even if this parameter
+            is not specified, if any of the following environment variables are
+            present, they will be loaded into this parameter: `HTTPS_PROXY`,
+            `https_proxy`, `HTTP_PROXY` or `http_proxy`.
+        headers (dict): Additional request headers to attach to all requests.
+
+    Methods:
+        `api_call`: Constructs a request and executes the API call to Slack.
+
+    Example of recommended usage:
+    ```python
+        import os
+        from slack_sdk.web.async_client import AsyncWebClient
+
+        client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.chat_postMessage(
+            channel='#random',
+            text="Hello world!")
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Example manually creating an API request:
+    ```python
+        import os
+        from slack_sdk.web.async_client import AsyncWebClient
+
+        client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.api_call(
+            api_method='chat.postMessage',
+            json={'channel': '#random','text': "Hello world!"}
+        )
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Note:
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+
+    [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
+    """
+
+    async def admin_analytics_getFile(
+        self,
+        *,
+        type: str,
+        date: Optional[str] = None,
+        metadata_only: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve analytics data for a given date, presented as a compressed JSON file
+        https://docs.slack.dev/reference/methods/admin.analytics.getFile
+        """
+        kwargs.update({"type": type})
+        if date is not None:
+            kwargs.update({"date": date})
+        if metadata_only is not None:
+            kwargs.update({"metadata_only": metadata_only})
+        return await self.api_call("admin.analytics.getFile", params=kwargs)
+
+    async def admin_apps_approve(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Approve an app for installation on a workspace.
+        Either app_id or request_id is required.
+        These IDs can be obtained either directly via the app_requested event,
+        or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.approve
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.approve", params=kwargs)
+
+    async def admin_apps_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List approved apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+    async def admin_apps_clearResolution(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Clear an app resolution
+        https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+    async def admin_apps_requests_cancel(
+        self,
+        *,
+        request_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+        """
+        kwargs.update(
+            {
+                "request_id": request_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+    async def admin_apps_requests_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+    async def admin_apps_restrict(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Restrict an app for installation on a workspace.
+        Exactly one of the team_id or enterprise_id arguments is required, not both.
+        Either app_id or request_id is required. These IDs can be obtained either directly
+        via the app_requested event, or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.restrict
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.restrict", params=kwargs)
+
+    async def admin_apps_restricted_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List restricted apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+    async def admin_apps_uninstall(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+        With an org-level token, enterprise_id or team_ids is required.
+        https://docs.slack.dev/reference/methods/admin.apps.uninstall
+        """
+        kwargs.update({"app_id": app_id})
+        if enterprise_id is not None:
+            kwargs.update({"enterprise_id": enterprise_id})
+        if team_ids is not None:
+            if isinstance(team_ids, (list, tuple)):
+                kwargs.update({"team_ids": ",".join(team_ids)})
+            else:
+                kwargs.update({"team_ids": team_ids})
+        return await self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+    async def admin_apps_activities_list(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        component_id: Optional[str] = None,
+        component_type: Optional[str] = None,
+        log_event_type: Optional[str] = None,
+        max_date_created: Optional[int] = None,
+        min_date_created: Optional[int] = None,
+        min_log_level: Optional[str] = None,
+        sort_direction: Optional[str] = None,
+        source: Optional[str] = None,
+        team_id: Optional[str] = None,
+        trace_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get logs for a specified team/org
+        https://docs.slack.dev/reference/methods/admin.apps.activities.list
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "component_id": component_id,
+                "component_type": component_type,
+                "log_event_type": log_event_type,
+                "max_date_created": max_date_created,
+                "min_date_created": min_date_created,
+                "min_log_level": min_log_level,
+                "sort_direction": sort_direction,
+                "source": source,
+                "team_id": team_id,
+                "trace_id": trace_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("admin.apps.activities.list", params=kwargs)
+
+    async def admin_apps_config_lookup(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Look up the app config for connectors by their IDs
+        https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        return await self.api_call("admin.apps.config.lookup", params=kwargs)
+
+    async def admin_apps_config_set(
+        self,
+        *,
+        app_id: str,
+        domain_restrictions: Optional[Dict[str, Any]] = None,
+        workflow_auth_strategy: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the app config for a connector
+        https://docs.slack.dev/reference/methods/admin.apps.config.set
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "workflow_auth_strategy": workflow_auth_strategy,
+            }
+        )
+        if domain_restrictions is not None:
+            kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+        return await self.api_call("admin.apps.config.set", params=kwargs)
+
+    async def admin_auth_policy_getEntities(
+        self,
+        *,
+        policy_name: str,
+        cursor: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetch all the entities assigned to a particular authentication policy by name.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+        """
+        kwargs.update({"policy_name": policy_name})
+        if cursor is not None:
+            kwargs.update({"cursor": cursor})
+        if entity_type is not None:
+            kwargs.update({"entity_type": entity_type})
+        if limit is not None:
+            kwargs.update({"limit": limit})
+        return await self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+    async def admin_auth_policy_assignEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Assign entities to a particular authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return await self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+    async def admin_auth_policy_removeEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove specified entities from a specified authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return await self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+    async def admin_conversations_createForObjects(
+        self,
+        *,
+        object_id: str,
+        salesforce_org_id: str,
+        invite_object_team: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create a Salesforce channel for the corresponding object provided.
+        https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+        """
+        kwargs.update(
+            {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+        )
+        return await self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+    async def admin_conversations_linkObjects(
+        self,
+        *,
+        channel: str,
+        record_id: str,
+        salesforce_org_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Link a Salesforce record to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "record_id": record_id,
+                "salesforce_org_id": salesforce_org_id,
+            }
+        )
+        return await self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+    async def admin_conversations_unlinkObjects(
+        self,
+        *,
+        channel: str,
+        new_name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Unlink a Salesforce record from a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "new_name": new_name,
+            }
+        )
+        return await self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+    async def admin_barriers_create(
+        self,
+        *,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create an Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.create
+        """
+        kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return await self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+    async def admin_barriers_delete(
+        self,
+        *,
+        barrier_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Delete an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.delete
+        """
+        kwargs.update({"barrier_id": barrier_id})
+        return await self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+    async def admin_barriers_update(
+        self,
+        *,
+        barrier_id: str,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.update
+        """
+        kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return await self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+    async def admin_barriers_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get all Information Barriers for your organization
+        https://docs.slack.dev/reference/methods/admin.barriers.list"""
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+    async def admin_conversations_create(
+        self,
+        *,
+        is_private: bool,
+        name: str,
+        description: Optional[str] = None,
+        org_wide: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create a public or private channel-based conversation.
+        https://docs.slack.dev/reference/methods/admin.conversations.create
+        """
+        kwargs.update(
+            {
+                "is_private": is_private,
+                "name": name,
+                "description": description,
+                "org_wide": org_wide,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.conversations.create", params=kwargs)
+
+    async def admin_conversations_delete(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Delete a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.delete
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.delete", params=kwargs)
+
+    async def admin_conversations_invite(
+        self,
+        *,
+        channel_id: str,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invite a user to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.invite
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+        return await self.api_call("admin.conversations.invite", params=kwargs)
+
+    async def admin_conversations_archive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Archive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.archive", params=kwargs)
+
+    async def admin_conversations_unarchive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Unarchive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.unarchive", params=kwargs)
+
+    async def admin_conversations_rename(
+        self,
+        *,
+        channel_id: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Rename a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.rename
+        """
+        kwargs.update({"channel_id": channel_id, "name": name})
+        return await self.api_call("admin.conversations.rename", params=kwargs)
+
+    async def admin_conversations_search(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        query: Optional[str] = None,
+        search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Search for public or private channels in an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.conversations.search
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+            }
+        )
+
+        if isinstance(search_channel_types, (list, tuple)):
+            kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+        else:
+            kwargs.update({"search_channel_types": search_channel_types})
+
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+
+        return await self.api_call("admin.conversations.search", params=kwargs)
+
+    async def admin_conversations_convertToPrivate(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Convert a public channel to a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+    async def admin_conversations_convertToPublic(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Convert a privte channel to a public channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+    async def admin_conversations_setConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        prefs: Union[str, Dict[str, str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the posting permissions for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(prefs, dict):
+            kwargs.update({"prefs": json.dumps(prefs)})
+        else:
+            kwargs.update({"prefs": prefs})
+        return await self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+    async def admin_conversations_getConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get conversation preferences for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+    async def admin_conversations_disconnectShared(
+        self,
+        *,
+        channel_id: str,
+        leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Disconnect a connected channel from one or more workspaces.
+        https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(leaving_team_ids, (list, tuple)):
+            kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+        else:
+            kwargs.update({"leaving_team_ids": leaving_team_ids})
+        return await self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+    async def admin_conversations_lookup(
+        self,
+        *,
+        last_message_activity_before: int,
+        team_ids: Union[str, Sequence[str]],
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        max_member_count: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Returns channels on the given team using the filters.
+        https://docs.slack.dev/reference/methods/admin.conversations.lookup
+        """
+        kwargs.update(
+            {
+                "last_message_activity_before": last_message_activity_before,
+                "cursor": cursor,
+                "limit": limit,
+                "max_member_count": max_member_count,
+            }
+        )
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return await self.api_call("admin.conversations.lookup", params=kwargs)
+
+    async def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+        self,
+        *,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all disconnected channelsβ€”i.e.,
+        channels that were once connected to other workspaces and then disconnectedβ€”and
+        the corresponding original channel IDs for key revocation with EKM.
+        https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return await self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+    async def admin_conversations_restrictAccess_addGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add an allowlist of IDP groups for accessing a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call(
+            "admin.conversations.restrictAccess.addGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    async def admin_conversations_restrictAccess_listGroups(
+        self,
+        *,
+        channel_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all IDP Groups linked to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call(
+            "admin.conversations.restrictAccess.listGroups",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    async def admin_conversations_restrictAccess_removeGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove a linked IDP group linked from a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call(
+            "admin.conversations.restrictAccess.removeGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    async def admin_conversations_setTeams(
+        self,
+        *,
+        channel_id: str,
+        org_channel: Optional[bool] = None,
+        target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "org_channel": org_channel,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(target_team_ids, (list, tuple)):
+            kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+        else:
+            kwargs.update({"target_team_ids": target_team_ids})
+        return await self.api_call("admin.conversations.setTeams", params=kwargs)
+
+    async def admin_conversations_getTeams(
+        self,
+        *,
+        channel_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("admin.conversations.getTeams", params=kwargs)
+
+    async def admin_conversations_getCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+    async def admin_conversations_removeCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+    async def admin_conversations_setCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        duration_days: int,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+        return await self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+    async def admin_conversations_bulkArchive(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Archive public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return await self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+    async def admin_conversations_bulkDelete(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Delete public or private channels in bulk.
+        https://slack.com/api/admin.conversations.bulkDelete
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return await self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+    async def admin_conversations_bulkMove(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        target_team_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Move public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+        """
+        kwargs.update(
+            {
+                "target_team_id": target_team_id,
+                "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+            }
+        )
+        return await self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+    async def admin_emoji_add(
+        self,
+        *,
+        name: str,
+        url: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.add
+        """
+        kwargs.update({"name": name, "url": url})
+        return await self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+    async def admin_emoji_addAlias(
+        self,
+        *,
+        alias_for: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add an emoji alias.
+        https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+        """
+        kwargs.update({"alias_for": alias_for, "name": name})
+        return await self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+    async def admin_emoji_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List emoji for an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return await self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+    async def admin_emoji_remove(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove an emoji across an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.remove
+        """
+        kwargs.update({"name": name})
+        return await self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+    async def admin_emoji_rename(
+        self,
+        *,
+        name: str,
+        new_name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Rename an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.rename
+        """
+        kwargs.update({"name": name, "new_name": new_name})
+        return await self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+    async def admin_functions_list(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Look up functions by a set of apps
+        https://docs.slack.dev/reference/methods/admin.functions.list
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("admin.functions.list", params=kwargs)
+
+    async def admin_functions_permissions_lookup(
+        self,
+        *,
+        function_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lookup the visibility of multiple Slack functions
+        and include the users if it is limited to particular named entities.
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+        """
+        if isinstance(function_ids, (list, tuple)):
+            kwargs.update({"function_ids": ",".join(function_ids)})
+        else:
+            kwargs.update({"function_ids": function_ids})
+        return await self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+    async def admin_functions_permissions_set(
+        self,
+        *,
+        function_id: str,
+        visibility: str,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the visibility of a Slack function
+        and define the users or workspaces if it is set to named_entities
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+        """
+        kwargs.update(
+            {
+                "function_id": function_id,
+                "visibility": visibility,
+            }
+        )
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return await self.api_call("admin.functions.permissions.set", params=kwargs)
+
+    async def admin_roles_addAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Adds members to the specified role with the specified scopes
+        https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return await self.api_call("admin.roles.addAssignments", params=kwargs)
+
+    async def admin_roles_listAssignments(
+        self,
+        *,
+        role_ids: Optional[Union[str, Sequence[str]]] = None,
+        entity_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[Union[str, int]] = None,
+        sort_dir: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists assignments for all roles across entities.
+            Options to scope results by any combination of roles or entities
+        https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(role_ids, (list, tuple)):
+            kwargs.update({"role_ids": ",".join(role_ids)})
+        else:
+            kwargs.update({"role_ids": role_ids})
+        return await self.api_call("admin.roles.listAssignments", params=kwargs)
+
+    async def admin_roles_removeAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a set of users from a role for the given scopes and entities
+        https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return await self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+    async def admin_users_session_reset(
+        self,
+        *,
+        user_id: str,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Wipes all valid sessions on all devices for a given user.
+        https://docs.slack.dev/reference/methods/admin.users.session.reset
+        """
+        kwargs.update(
+            {
+                "user_id": user_id,
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return await self.api_call("admin.users.session.reset", params=kwargs)
+
+    async def admin_users_session_resetBulk(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+        https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return await self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+    async def admin_users_session_invalidate(
+        self,
+        *,
+        session_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invalidate a single session for a user by session_id.
+        https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+        """
+        kwargs.update({"session_id": session_id, "team_id": team_id})
+        return await self.api_call("admin.users.session.invalidate", params=kwargs)
+
+    async def admin_users_session_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all active user sessions for an organization
+        https://docs.slack.dev/reference/methods/admin.users.session.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+                "user_id": user_id,
+            }
+        )
+        return await self.api_call("admin.users.session.list", params=kwargs)
+
+    async def admin_teams_settings_setDefaultChannels(
+        self,
+        *,
+        team_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the default channels of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+        """
+        kwargs.update({"team_id": team_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+    async def admin_users_session_getSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”given a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return await self.api_call("admin.users.session.getSettings", params=kwargs)
+
+    async def admin_users_session_setSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        desktop_app_browser_quit: Optional[bool] = None,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Configure the user-level session settingsβ€”the session duration
+        and what happens when the client closesβ€”for one or more users.
+        https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "desktop_app_browser_quit": desktop_app_browser_quit,
+                "duration": duration,
+            }
+        )
+        return await self.api_call("admin.users.session.setSettings", params=kwargs)
+
+    async def admin_users_session_clearSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Clear user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”for a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return await self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+    async def admin_users_unsupportedVersions_export(
+        self,
+        *,
+        date_end_of_support: Optional[Union[str, int]] = None,
+        date_sessions_started: Optional[Union[str, int]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+        presented as a zipped CSV file.
+        https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+        """
+        kwargs.update(
+            {
+                "date_end_of_support": date_end_of_support,
+                "date_sessions_started": date_sessions_started,
+            }
+        )
+        return await self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+    async def admin_inviteRequests_approve(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Approve a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return await self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+    async def admin_inviteRequests_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all approved workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+    async def admin_inviteRequests_denied_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all denied workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+    async def admin_inviteRequests_deny(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deny a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return await self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+    async def admin_inviteRequests_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all pending workspace invite requests."""
+        return await self.api_call("admin.inviteRequests.list", params=kwargs)
+
+    async def admin_teams_admins_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+    async def admin_teams_create(
+        self,
+        *,
+        team_domain: str,
+        team_name: str,
+        team_description: Optional[str] = None,
+        team_discoverability: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create an Enterprise team.
+        https://docs.slack.dev/reference/methods/admin.teams.create
+        """
+        kwargs.update(
+            {
+                "team_domain": team_domain,
+                "team_name": team_name,
+                "team_description": team_description,
+                "team_discoverability": team_discoverability,
+            }
+        )
+        return await self.api_call("admin.teams.create", params=kwargs)
+
+    async def admin_teams_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all teams on an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return await self.api_call("admin.teams.list", params=kwargs)
+
+    async def admin_teams_owners_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.owners.list
+        """
+        kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+        return await self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+    async def admin_teams_settings_info(
+        self,
+        *,
+        team_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetch information about settings in a workspace
+        https://docs.slack.dev/reference/methods/admin.teams.settings.info
+        """
+        kwargs.update({"team_id": team_id})
+        return await self.api_call("admin.teams.settings.info", params=kwargs)
+
+    async def admin_teams_settings_setDescription(
+        self,
+        *,
+        team_id: str,
+        description: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the description of a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+        """
+        kwargs.update({"team_id": team_id, "description": description})
+        return await self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+    async def admin_teams_settings_setDiscoverability(
+        self,
+        *,
+        team_id: str,
+        discoverability: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+        """
+        kwargs.update({"team_id": team_id, "discoverability": discoverability})
+        return await self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+    async def admin_teams_settings_setIcon(
+        self,
+        *,
+        team_id: str,
+        image_url: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+        """
+        kwargs.update({"team_id": team_id, "image_url": image_url})
+        return await self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+    async def admin_teams_settings_setName(
+        self,
+        *,
+        team_id: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+        """
+        kwargs.update({"team_id": team_id, "name": name})
+        return await self.api_call("admin.teams.settings.setName", params=kwargs)
+
+    async def admin_usergroups_addChannels(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        usergroup_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+        """
+        kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+    async def admin_usergroups_addTeams(
+        self,
+        *,
+        usergroup_id: str,
+        team_ids: Union[str, Sequence[str]],
+        auto_provision: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Associate one or more default workspaces with an organization-wide IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+        """
+        kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return await self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+    async def admin_usergroups_listChannels(
+        self,
+        *,
+        usergroup_id: str,
+        include_num_members: Optional[bool] = None,
+        team_id: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+        """
+        kwargs.update(
+            {
+                "usergroup_id": usergroup_id,
+                "include_num_members": include_num_members,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+    async def admin_usergroups_removeChannels(
+        self,
+        *,
+        usergroup_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+        """
+        kwargs.update({"usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+    async def admin_users_assign(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add an Enterprise user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.assign
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "user_id": user_id,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("admin.users.assign", params=kwargs)
+
+    async def admin_users_invite(
+        self,
+        *,
+        team_id: str,
+        email: str,
+        channel_ids: Union[str, Sequence[str]],
+        custom_message: Optional[str] = None,
+        email_password_policy_enabled: Optional[bool] = None,
+        guest_expiration_ts: Optional[Union[str, float]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        real_name: Optional[str] = None,
+        resend: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invite a user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.invite
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "email": email,
+                "custom_message": custom_message,
+                "email_password_policy_enabled": email_password_policy_enabled,
+                "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+                "real_name": real_name,
+                "resend": resend,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("admin.users.invite", params=kwargs)
+
+    async def admin_users_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        include_deactivated_user_workspaces: Optional[bool] = None,
+        is_active: Optional[bool] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List users on a workspace
+        https://docs.slack.dev/reference/methods/admin.users.list
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+                "is_active": is_active,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("admin.users.list", params=kwargs)
+
+    async def admin_users_remove(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove a user from a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.remove
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return await self.api_call("admin.users.remove", params=kwargs)
+
+    async def admin_users_setAdmin(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set an existing guest, regular user, or owner to be an admin user.
+        https://docs.slack.dev/reference/methods/admin.users.setAdmin
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return await self.api_call("admin.users.setAdmin", params=kwargs)
+
+    async def admin_users_setExpiration(
+        self,
+        *,
+        expiration_ts: int,
+        user_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set an expiration for a guest user.
+        https://docs.slack.dev/reference/methods/admin.users.setExpiration
+        """
+        kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+        return await self.api_call("admin.users.setExpiration", params=kwargs)
+
+    async def admin_users_setOwner(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set an existing guest, regular user, or admin user to be a workspace owner.
+        https://docs.slack.dev/reference/methods/admin.users.setOwner
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return await self.api_call("admin.users.setOwner", params=kwargs)
+
+    async def admin_users_setRegular(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set an existing guest user, admin user, or owner to be a regular user.
+        https://docs.slack.dev/reference/methods/admin.users.setRegular
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return await self.api_call("admin.users.setRegular", params=kwargs)
+
+    async def admin_workflows_search(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        no_collaborators: Optional[bool] = None,
+        num_trigger_ids: Optional[int] = None,
+        query: Optional[str] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        source: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Search workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.search
+        """
+        if collaborator_ids is not None:
+            if isinstance(collaborator_ids, (list, tuple)):
+                kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+            else:
+                kwargs.update({"collaborator_ids": collaborator_ids})
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "cursor": cursor,
+                "limit": limit,
+                "no_collaborators": no_collaborators,
+                "num_trigger_ids": num_trigger_ids,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "source": source,
+            }
+        )
+        return await self.api_call("admin.workflows.search", params=kwargs)
+
+    async def admin_workflows_permissions_lookup(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        max_workflow_triggers: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Look up the permissions for a set of workflows
+        https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        kwargs.update(
+            {
+                "max_workflow_triggers": max_workflow_triggers,
+            }
+        )
+        return await self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+    async def admin_workflows_collaborators_add(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add collaborators to workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return await self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+    async def admin_workflows_collaborators_remove(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove collaborators from workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return await self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+    async def admin_workflows_unpublish(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Unpublish workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return await self.api_call("admin.workflows.unpublish", params=kwargs)
+
+    async def api_test(
+        self,
+        *,
+        error: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Checks API calling code.
+        https://docs.slack.dev/reference/methods/api.test
+        """
+        kwargs.update({"error": error})
+        return await self.api_call("api.test", params=kwargs)
+
+    async def apps_connections_open(
+        self,
+        *,
+        app_token: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+        in order to receive events and interactive payloads
+        https://docs.slack.dev/reference/methods/apps.connections.open
+        """
+        kwargs.update({"token": app_token})
+        return await self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+    async def apps_event_authorizations_list(
+        self,
+        *,
+        event_context: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get a list of authorizations for the given event context.
+        Each authorization represents an app installation that the event is visible to.
+        https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+        """
+        kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+        return await self.api_call("apps.event.authorizations.list", params=kwargs)
+
+    async def apps_uninstall(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Uninstalls your app from a workspace.
+        https://docs.slack.dev/reference/methods/apps.uninstall
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret})
+        return await self.api_call("apps.uninstall", params=kwargs)
+
+    async def apps_manifest_create(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.create
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        return await self.api_call("apps.manifest.create", params=kwargs)
+
+    async def apps_manifest_delete(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Permanently deletes an app created through app manifests
+        https://docs.slack.dev/reference/methods/apps.manifest.delete
+        """
+        kwargs.update({"app_id": app_id})
+        return await self.api_call("apps.manifest.delete", params=kwargs)
+
+    async def apps_manifest_export(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Export an app manifest from an existing app
+        https://docs.slack.dev/reference/methods/apps.manifest.export
+        """
+        kwargs.update({"app_id": app_id})
+        return await self.api_call("apps.manifest.export", params=kwargs)
+
+    async def apps_manifest_update(
+        self,
+        *,
+        app_id: str,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.update
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return await self.api_call("apps.manifest.update", params=kwargs)
+
+    async def apps_manifest_validate(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        app_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Validate an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.validate
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return await self.api_call("apps.manifest.validate", params=kwargs)
+
+    async def tooling_tokens_rotate(
+        self,
+        *,
+        refresh_token: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Exchanges a refresh token for a new app configuration token
+        https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+        """
+        kwargs.update({"refresh_token": refresh_token})
+        return await self.api_call("tooling.tokens.rotate", params=kwargs)
+
+    async def assistant_threads_setStatus(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        status: str,
+        loading_messages: Optional[List[str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the status for an AI assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+        """
+        kwargs.update(
+            {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("assistant.threads.setStatus", json=kwargs)
+
+    async def assistant_threads_setTitle(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the title for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+        return await self.api_call("assistant.threads.setTitle", params=kwargs)
+
+    async def assistant_threads_setSuggestedPrompts(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: Optional[str] = None,
+        prompts: List[Dict[str, str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set suggested prompts for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+        if title is not None:
+            kwargs.update({"title": title})
+        return await self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+    async def auth_revoke(
+        self,
+        *,
+        test: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Revokes a token.
+        https://docs.slack.dev/reference/methods/auth.revoke
+        """
+        kwargs.update({"test": test})
+        return await self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+    async def auth_test(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Checks authentication & identity.
+        https://docs.slack.dev/reference/methods/auth.test
+        """
+        return await self.api_call("auth.test", params=kwargs)
+
+    async def auth_teams_list(
+        self,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        include_icon: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List the workspaces a token can access.
+        https://docs.slack.dev/reference/methods/auth.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+        return await self.api_call("auth.teams.list", params=kwargs)
+
+    async def bookmarks_add(
+        self,
+        *,
+        channel_id: str,
+        title: str,
+        type: str,
+        emoji: Optional[str] = None,
+        entity_id: Optional[str] = None,
+        link: Optional[str] = None,  # include when type is 'link'
+        parent_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add bookmark to a channel.
+        https://docs.slack.dev/reference/methods/bookmarks.add
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "title": title,
+                "type": type,
+                "emoji": emoji,
+                "entity_id": entity_id,
+                "link": link,
+                "parent_id": parent_id,
+            }
+        )
+        return await self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+    async def bookmarks_edit(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        emoji: Optional[str] = None,
+        link: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Edit bookmark.
+        https://docs.slack.dev/reference/methods/bookmarks.edit
+        """
+        kwargs.update(
+            {
+                "bookmark_id": bookmark_id,
+                "channel_id": channel_id,
+                "emoji": emoji,
+                "link": link,
+                "title": title,
+            }
+        )
+        return await self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+    async def bookmarks_list(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List bookmark for the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.list
+        """
+        kwargs.update({"channel_id": channel_id})
+        return await self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+    async def bookmarks_remove(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove bookmark from the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.remove
+        """
+        kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+        return await self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+    async def bots_info(
+        self,
+        *,
+        bot: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a bot user.
+        https://docs.slack.dev/reference/methods/bots.info
+        """
+        kwargs.update({"bot": bot, "team_id": team_id})
+        return await self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+    async def calls_add(
+        self,
+        *,
+        external_unique_id: str,
+        join_url: str,
+        created_by: Optional[str] = None,
+        date_start: Optional[int] = None,
+        desktop_app_join_url: Optional[str] = None,
+        external_display_id: Optional[str] = None,
+        title: Optional[str] = None,
+        users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Registers a new Call.
+        https://docs.slack.dev/reference/methods/calls.add
+        """
+        kwargs.update(
+            {
+                "external_unique_id": external_unique_id,
+                "join_url": join_url,
+                "created_by": created_by,
+                "date_start": date_start,
+                "desktop_app_join_url": desktop_app_join_url,
+                "external_display_id": external_display_id,
+                "title": title,
+            }
+        )
+        _update_call_participants(
+            kwargs,
+            users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+        )
+        return await self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+    async def calls_end(
+        self,
+        *,
+        id: str,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Ends a Call.
+        https://docs.slack.dev/reference/methods/calls.end
+        """
+        kwargs.update({"id": id, "duration": duration})
+        return await self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+    async def calls_info(
+        self,
+        *,
+        id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Returns information about a Call.
+        https://docs.slack.dev/reference/methods/calls.info
+        """
+        kwargs.update({"id": id})
+        return await self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+    async def calls_participants_add(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Registers new participants added to a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.add
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return await self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+    async def calls_participants_remove(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Registers participants removed from a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.remove
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return await self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+    async def calls_update(
+        self,
+        *,
+        id: str,
+        desktop_app_join_url: Optional[str] = None,
+        join_url: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Updates information about a Call.
+        https://docs.slack.dev/reference/methods/calls.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "desktop_app_join_url": desktop_app_join_url,
+                "join_url": join_url,
+                "title": title,
+            }
+        )
+        return await self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+    async def canvases_create(
+        self,
+        *,
+        title: Optional[str] = None,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create Canvas for a user
+        https://docs.slack.dev/reference/methods/canvases.create
+        """
+        kwargs.update({"title": title, "document_content": document_content})
+        return await self.api_call("canvases.create", json=kwargs)
+
+    async def canvases_edit(
+        self,
+        *,
+        canvas_id: str,
+        changes: Sequence[Dict[str, Any]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update an existing canvas
+        https://docs.slack.dev/reference/methods/canvases.edit
+        """
+        kwargs.update({"canvas_id": canvas_id, "changes": changes})
+        return await self.api_call("canvases.edit", json=kwargs)
+
+    async def canvases_delete(
+        self,
+        *,
+        canvas_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes a canvas
+        https://docs.slack.dev/reference/methods/canvases.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        return await self.api_call("canvases.delete", params=kwargs)
+
+    async def canvases_access_set(
+        self,
+        *,
+        canvas_id: str,
+        access_level: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the access level to a canvas for specified entities
+        https://docs.slack.dev/reference/methods/canvases.access.set
+        """
+        kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+
+        return await self.api_call("canvases.access.set", params=kwargs)
+
+    async def canvases_access_delete(
+        self,
+        *,
+        canvas_id: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/canvases.access.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return await self.api_call("canvases.access.delete", params=kwargs)
+
+    async def canvases_sections_lookup(
+        self,
+        *,
+        canvas_id: str,
+        criteria: Dict[str, Any],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Find sections matching the provided criteria
+        https://docs.slack.dev/reference/methods/canvases.sections.lookup
+        """
+        kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+        return await self.api_call("canvases.sections.lookup", params=kwargs)
+
+    # --------------------------
+    # Deprecated: channels.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    async def channels_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Archives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.archive", json=kwargs)
+
+    async def channels_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Creates a channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.create", json=kwargs)
+
+    async def channels_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetches history of messages and events from a channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+    async def channels_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+    async def channels_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invites a user to a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.invite", json=kwargs)
+
+    async def channels_join(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Joins a channel, creating it if needed."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.join", json=kwargs)
+
+    async def channels_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a user from a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.kick", json=kwargs)
+
+    async def channels_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Leaves a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.leave", json=kwargs)
+
+    async def channels_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all channels in a Slack team."""
+        return await self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+    async def channels_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the read cursor in a channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.mark", json=kwargs)
+
+    async def channels_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Renames a channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.rename", json=kwargs)
+
+    async def channels_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a thread of messages posted to a channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return await self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+    async def channels_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the purpose for a channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.setPurpose", json=kwargs)
+
+    async def channels_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the topic for a channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.setTopic", json=kwargs)
+
+    async def channels_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Unarchives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("channels.unarchive", json=kwargs)
+
+    # --------------------------
+
+    async def chat_appendStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Appends text to an existing streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.appendStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("chat.appendStream", json=kwargs)
+
+    async def chat_delete(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes a message.
+        https://docs.slack.dev/reference/methods/chat.delete
+        """
+        kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+        return await self.api_call("chat.delete", params=kwargs)
+
+    async def chat_deleteScheduledMessage(
+        self,
+        *,
+        channel: str,
+        scheduled_message_id: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes a scheduled message.
+        https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "scheduled_message_id": scheduled_message_id,
+                "as_user": as_user,
+            }
+        )
+        return await self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+    async def chat_getPermalink(
+        self,
+        *,
+        channel: str,
+        message_ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a permalink URL for a specific extant message
+        https://docs.slack.dev/reference/methods/chat.getPermalink
+        """
+        kwargs.update({"channel": channel, "message_ts": message_ts})
+        return await self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+    async def chat_meMessage(
+        self,
+        *,
+        channel: str,
+        text: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Share a me message into a channel.
+        https://docs.slack.dev/reference/methods/chat.meMessage
+        """
+        kwargs.update({"channel": channel, "text": text})
+        return await self.api_call("chat.meMessage", params=kwargs)
+
+    async def chat_postEphemeral(
+        self,
+        *,
+        channel: str,
+        user: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sends an ephemeral message to a user in a channel.
+        https://docs.slack.dev/reference/methods/chat.postEphemeral
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "user": user,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return await self.api_call("chat.postEphemeral", json=kwargs)
+
+    async def chat_postMessage(
+        self,
+        *,
+        channel: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        container_id: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        mrkdwn: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,  # none, full
+        metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sends a message to a channel.
+        https://docs.slack.dev/reference/methods/chat.postMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "container_id": container_id,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "mrkdwn": mrkdwn,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return await self.api_call("chat.postMessage", json=kwargs)
+
+    async def chat_scheduleMessage(
+        self,
+        *,
+        channel: str,
+        post_at: Union[str, int],
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        parse: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Schedules a message.
+        https://docs.slack.dev/reference/methods/chat.scheduleMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "post_at": post_at,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "parse": parse,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "link_names": link_names,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return await self.api_call("chat.scheduleMessage", json=kwargs)
+
+    async def chat_scheduledMessages_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all scheduled messages.
+        https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "latest": latest,
+                "limit": limit,
+                "oldest": oldest,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+    async def chat_startStream(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        markdown_text: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Starts a new streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.startStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "thread_ts": thread_ts,
+                "markdown_text": markdown_text,
+                "recipient_team_id": recipient_team_id,
+                "recipient_user_id": recipient_user_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("chat.startStream", json=kwargs)
+
+    async def chat_stopStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Stops a streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.stopStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+                "blocks": blocks,
+                "metadata": metadata,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("chat.stopStream", json=kwargs)
+
+    async def chat_stream(
+        self,
+        *,
+        buffer_size: int = 256,
+        channel: str,
+        thread_ts: str,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncChatStream:
+        """Stream markdown text into a conversation.
+
+        This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+        the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+        The following methods are used:
+
+        - chat.startStream: Starts a new streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+        - chat.appendStream: Appends text to an existing streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+        - chat.stopStream: Stops a streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+        Args:
+            buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+              value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+              limits. Default: 256.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            ChatStream instance for managing the stream
+
+        Example:
+            ```python
+            streamer = await client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            await streamer.append(markdown_text="**hello wo")
+            await streamer.append(markdown_text="rld!**")
+            await streamer.stop()
+            ```
+        """
+        return AsyncChatStream(
+            self,
+            logger=self._logger,
+            channel=channel,
+            thread_ts=thread_ts,
+            recipient_team_id=recipient_team_id,
+            recipient_user_id=recipient_user_id,
+            buffer_size=buffer_size,
+            **kwargs,
+        )
+
+    async def chat_unfurl(
+        self,
+        *,
+        channel: Optional[str] = None,
+        ts: Optional[str] = None,
+        source: Optional[str] = None,
+        unfurl_id: Optional[str] = None,
+        unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+        metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+        user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        user_auth_message: Optional[str] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Provide custom unfurl behavior for user-posted URLs.
+        https://docs.slack.dev/reference/methods/chat.unfurl
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "source": source,
+                "unfurl_id": unfurl_id,
+                "unfurls": unfurls,
+                "metadata": metadata,
+                "user_auth_blocks": user_auth_blocks,
+                "user_auth_message": user_auth_message,
+                "user_auth_required": user_auth_required,
+                "user_auth_url": user_auth_url,
+            }
+        )
+        _parse_web_class_objects(kwargs)  # for user_auth_blocks
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return await self.api_call("chat.unfurl", json=kwargs)
+
+    async def chat_update(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        text: Optional[str] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        as_user: Optional[bool] = None,
+        file_ids: Optional[Union[str, Sequence[str]]] = None,
+        link_names: Optional[bool] = None,
+        parse: Optional[str] = None,  # none, full
+        reply_broadcast: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Updates a message in a channel.
+        https://docs.slack.dev/reference/methods/chat.update
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "as_user": as_user,
+                "link_names": link_names,
+                "parse": parse,
+                "reply_broadcast": reply_broadcast,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        if isinstance(file_ids, (list, tuple)):
+            kwargs.update({"file_ids": ",".join(file_ids)})
+        else:
+            kwargs.update({"file_ids": file_ids})
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.update", kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return await self.api_call("chat.update", json=kwargs)
+
+    async def conversations_acceptSharedInvite(
+        self,
+        *,
+        channel_name: str,
+        channel_id: Optional[str] = None,
+        invite_id: Optional[str] = None,
+        free_trial_accepted: Optional[bool] = None,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Accepts an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+        """
+        if channel_id is None and invite_id is None:
+            raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+        kwargs.update(
+            {
+                "channel_name": channel_name,
+                "channel_id": channel_id,
+                "invite_id": invite_id,
+                "free_trial_accepted": free_trial_accepted,
+                "is_private": is_private,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+    async def conversations_approveSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Approves an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return await self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+    async def conversations_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Archives a conversation.
+        https://docs.slack.dev/reference/methods/conversations.archive
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("conversations.archive", params=kwargs)
+
+    async def conversations_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Closes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.close
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("conversations.close", params=kwargs)
+
+    async def conversations_create(
+        self,
+        *,
+        name: str,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Initiates a public or private channel-based conversation
+        https://docs.slack.dev/reference/methods/conversations.create
+        """
+        kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+        return await self.api_call("conversations.create", params=kwargs)
+
+    async def conversations_declineSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Declines a Slack Connect channel invite.
+        https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return await self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+    async def conversations_externalInvitePermissions_set(
+        self, *, action: str, channel: str, target_team: str, **kwargs
+    ) -> AsyncSlackResponse:
+        """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+        https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+        """
+        kwargs.update(
+            {
+                "action": action,
+                "channel": channel,
+                "target_team": target_team,
+            }
+        )
+        return await self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+    async def conversations_history(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetches a conversation's history of messages and events.
+        https://docs.slack.dev/reference/methods/conversations.history
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return await self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+    async def conversations_info(
+        self,
+        *,
+        channel: str,
+        include_locale: Optional[bool] = None,
+        include_num_members: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve information about a conversation.
+        https://docs.slack.dev/reference/methods/conversations.info
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "include_locale": include_locale,
+                "include_num_members": include_num_members,
+            }
+        )
+        return await self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+    async def conversations_invite(
+        self,
+        *,
+        channel: str,
+        users: Union[str, Sequence[str]],
+        force: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invites users to a channel.
+        https://docs.slack.dev/reference/methods/conversations.invite
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "force": force,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return await self.api_call("conversations.invite", params=kwargs)
+
+    async def conversations_inviteShared(
+        self,
+        *,
+        channel: str,
+        emails: Optional[Union[str, Sequence[str]]] = None,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sends an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.inviteShared
+        """
+        if emails is None and user_ids is None:
+            raise e.SlackRequestError("Either emails or user ids must be provided.")
+        kwargs.update({"channel": channel})
+        if isinstance(emails, (list, tuple)):
+            kwargs.update({"emails": ",".join(emails)})
+        else:
+            kwargs.update({"emails": emails})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return await self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+    async def conversations_join(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Joins an existing conversation.
+        https://docs.slack.dev/reference/methods/conversations.join
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("conversations.join", params=kwargs)
+
+    async def conversations_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a user from a conversation.
+        https://docs.slack.dev/reference/methods/conversations.kick
+        """
+        kwargs.update({"channel": channel, "user": user})
+        return await self.api_call("conversations.kick", params=kwargs)
+
+    async def conversations_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Leaves a conversation.
+        https://docs.slack.dev/reference/methods/conversations.leave
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("conversations.leave", params=kwargs)
+
+    async def conversations_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all channels in a Slack team.
+        https://docs.slack.dev/reference/methods/conversations.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return await self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+    async def conversations_listConnectInvites(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List shared channel invites that have been generated
+        or received but have not yet been approved by all parties.
+        https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+        """
+        kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+        return await self.api_call("conversations.listConnectInvites", params=kwargs)
+
+    async def conversations_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the read cursor in a channel.
+        https://docs.slack.dev/reference/methods/conversations.mark
+        """
+        kwargs.update({"channel": channel, "ts": ts})
+        return await self.api_call("conversations.mark", params=kwargs)
+
+    async def conversations_members(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve members of a conversation.
+        https://docs.slack.dev/reference/methods/conversations.members
+        """
+        kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+        return await self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+    async def conversations_open(
+        self,
+        *,
+        channel: Optional[str] = None,
+        return_im: Optional[bool] = None,
+        users: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Opens or resumes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.open
+        """
+        if channel is None and users is None:
+            raise e.SlackRequestError("Either channel or users must be provided.")
+        kwargs.update({"channel": channel, "return_im": return_im})
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return await self.api_call("conversations.open", params=kwargs)
+
+    async def conversations_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Renames a conversation.
+        https://docs.slack.dev/reference/methods/conversations.rename
+        """
+        kwargs.update({"channel": channel, "name": name})
+        return await self.api_call("conversations.rename", params=kwargs)
+
+    async def conversations_replies(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a thread of messages posted to a conversation
+        https://docs.slack.dev/reference/methods/conversations.replies
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return await self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+    async def conversations_requestSharedInvite_approve(
+        self,
+        *,
+        invite_id: str,
+        channel_id: Optional[str] = None,
+        is_external_limited: Optional[str] = None,
+        message: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+        """
+        kwargs.update(
+            {
+                "invite_id": invite_id,
+                "channel_id": channel_id,
+                "is_external_limited": is_external_limited,
+            }
+        )
+        if message is not None:
+            kwargs.update({"message": json.dumps(message)})
+        return await self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+    async def conversations_requestSharedInvite_deny(
+        self,
+        *,
+        invite_id: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deny a request to invite an external user to a channel.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+        """
+        kwargs.update({"invite_id": invite_id, "message": message})
+        return await self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+    async def conversations_requestSharedInvite_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_approved: Optional[bool] = None,
+        include_denied: Optional[bool] = None,
+        include_expired: Optional[bool] = None,
+        invite_ids: Optional[Union[str, Sequence[str]]] = None,
+        limit: Optional[int] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists requests to add external users to channels with ability to filter.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_approved": include_approved,
+                "include_denied": include_denied,
+                "include_expired": include_expired,
+                "limit": limit,
+                "user_id": user_id,
+            }
+        )
+        if invite_ids is not None:
+            if isinstance(invite_ids, (list, tuple)):
+                kwargs.update({"invite_ids": ",".join(invite_ids)})
+            else:
+                kwargs.update({"invite_ids": invite_ids})
+        return await self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+    async def conversations_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the purpose for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setPurpose
+        """
+        kwargs.update({"channel": channel, "purpose": purpose})
+        return await self.api_call("conversations.setPurpose", params=kwargs)
+
+    async def conversations_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the topic for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setTopic
+        """
+        kwargs.update({"channel": channel, "topic": topic})
+        return await self.api_call("conversations.setTopic", params=kwargs)
+
+    async def conversations_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Reverses conversation archival.
+        https://docs.slack.dev/reference/methods/conversations.unarchive
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("conversations.unarchive", params=kwargs)
+
+    async def conversations_canvases_create(
+        self,
+        *,
+        channel_id: str,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/conversations.canvases.create
+        """
+        kwargs.update({"channel_id": channel_id, "document_content": document_content})
+        return await self.api_call("conversations.canvases.create", json=kwargs)
+
+    async def dialog_open(
+        self,
+        *,
+        dialog: Dict[str, Any],
+        trigger_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Open a dialog with a user.
+        https://docs.slack.dev/reference/methods/dialog.open
+        """
+        kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: As the dialog can be a dict, this API call works only with json format.
+        return await self.api_call("dialog.open", json=kwargs)
+
+    async def dnd_endDnd(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Ends the current user's Do Not Disturb session immediately.
+        https://docs.slack.dev/reference/methods/dnd.endDnd
+        """
+        return await self.api_call("dnd.endDnd", params=kwargs)
+
+    async def dnd_endSnooze(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Ends the current user's snooze mode immediately.
+        https://docs.slack.dev/reference/methods/dnd.endSnooze
+        """
+        return await self.api_call("dnd.endSnooze", params=kwargs)
+
+    async def dnd_info(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieves a user's current Do Not Disturb status.
+        https://docs.slack.dev/reference/methods/dnd.info
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return await self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+    async def dnd_setSnooze(
+        self,
+        *,
+        num_minutes: Union[int, str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Turns on Do Not Disturb mode for the current user, or changes its duration.
+        https://docs.slack.dev/reference/methods/dnd.setSnooze
+        """
+        kwargs.update({"num_minutes": num_minutes})
+        return await self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+    async def dnd_teamInfo(
+        self,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieves the Do Not Disturb status for users on a team.
+        https://docs.slack.dev/reference/methods/dnd.teamInfo
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id})
+        return await self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+    async def emoji_list(
+        self,
+        include_categories: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists custom emoji for a team.
+        https://docs.slack.dev/reference/methods/emoji.list
+        """
+        kwargs.update({"include_categories": include_categories})
+        return await self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+    async def entity_presentDetails(
+        self,
+        trigger_id: str,
+        metadata: Optional[Union[Dict, EntityMetadata]] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        error: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Provides entity details for the flexpane.
+        https://docs.slack.dev/reference/methods/entity.presentDetails/
+        """
+        kwargs.update({"trigger_id": trigger_id})
+        if metadata is not None:
+            kwargs.update({"metadata": metadata})
+        if user_auth_required is not None:
+            kwargs.update({"user_auth_required": user_auth_required})
+        if user_auth_url is not None:
+            kwargs.update({"user_auth_url": user_auth_url})
+        if error is not None:
+            kwargs.update({"error": error})
+        _parse_web_class_objects(kwargs)
+        return await self.api_call("entity.presentDetails", json=kwargs)
+
+    async def files_comments_delete(
+        self,
+        *,
+        file: str,
+        id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes an existing comment on a file.
+        https://docs.slack.dev/reference/methods/files.comments.delete
+        """
+        kwargs.update({"file": file, "id": id})
+        return await self.api_call("files.comments.delete", params=kwargs)
+
+    async def files_delete(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes a file.
+        https://docs.slack.dev/reference/methods/files.delete
+        """
+        kwargs.update({"file": file})
+        return await self.api_call("files.delete", params=kwargs)
+
+    async def files_info(
+        self,
+        *,
+        file: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a team file.
+        https://docs.slack.dev/reference/methods/files.info
+        """
+        kwargs.update(
+            {
+                "file": file,
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+            }
+        )
+        return await self.api_call("files.info", http_verb="GET", params=kwargs)
+
+    async def files_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        count: Optional[int] = None,
+        page: Optional[int] = None,
+        show_files_hidden_by_limit: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists & filters team files.
+        https://docs.slack.dev/reference/methods/files.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "count": count,
+                "page": page,
+                "show_files_hidden_by_limit": show_files_hidden_by_limit,
+                "team_id": team_id,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return await self.api_call("files.list", http_verb="GET", params=kwargs)
+
+    async def files_remote_info(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.info
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return await self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+    async def files_remote_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "limit": limit,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+            }
+        )
+        return await self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+    async def files_remote_add(
+        self,
+        *,
+        external_id: str,
+        external_url: str,
+        title: str,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+        preview_image: Optional[Union[str, bytes, IOBase]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Adds a file from a remote service.
+        https://docs.slack.dev/reference/methods/files.remote.add
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return await self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.add",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    async def files_remote_update(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        external_url: Optional[str] = None,
+        file: Optional[str] = None,
+        title: Optional[str] = None,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[str] = None,
+        preview_image: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Updates an existing remote file.
+        https://docs.slack.dev/reference/methods/files.remote.update
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "file": file,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return await self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.update",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    async def files_remote_remove(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove a remote file.
+        https://docs.slack.dev/reference/methods/files.remote.remove
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return await self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+    async def files_remote_share(
+        self,
+        *,
+        channels: Union[str, Sequence[str]],
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Share a remote file into a channel.
+        https://docs.slack.dev/reference/methods/files.remote.share
+        """
+        if external_id is None and file is None:
+            raise e.SlackRequestError("Either external_id or file must be provided.")
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update({"external_id": external_id, "file": file})
+        return await self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+    async def files_revokePublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Revokes public/external sharing access for a file
+        https://docs.slack.dev/reference/methods/files.revokePublicURL
+        """
+        kwargs.update({"file": file})
+        return await self.api_call("files.revokePublicURL", params=kwargs)
+
+    async def files_sharedPublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Enables a file for public/external sharing.
+        https://docs.slack.dev/reference/methods/files.sharedPublicURL
+        """
+        kwargs.update({"file": file})
+        return await self.api_call("files.sharedPublicURL", params=kwargs)
+
+    async def files_upload(
+        self,
+        *,
+        file: Optional[Union[str, bytes, IOBase]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        filename: Optional[str] = None,
+        filetype: Optional[str] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        title: Optional[str] = None,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Uploads or creates a file.
+        https://docs.slack.dev/reference/methods/files.upload
+        """
+        _print_files_upload_v2_suggestion()
+
+        if file is None and content is None:
+            raise e.SlackRequestError("The file or content argument must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update(
+            {
+                "filename": filename,
+                "filetype": filetype,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+                "title": title,
+            }
+        )
+        if file:
+            if kwargs.get("filename") is None and isinstance(file, str):
+                # use the local filename if filename is missing
+                if kwargs.get("filename") is None:
+                    kwargs["filename"] = file.split(os.path.sep)[-1]
+            return await self.api_call("files.upload", files={"file": file}, data=kwargs)
+        else:
+            kwargs["content"] = content
+            return await self.api_call("files.upload", data=kwargs)
+
+    async def files_upload_v2(
+        self,
+        *,
+        # for sending a single file
+        filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+        file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        title: Optional[str] = None,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        # To upload multiple files at a time
+        file_uploads: Optional[List[Dict[str, Any]]] = None,
+        channel: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """This wrapper method provides an easy way to upload files using the following endpoints:
+
+        - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+        - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+        - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+            and https://docs.slack.dev/reference/methods/files.info
+
+        """
+        if file is None and content is None and file_uploads is None:
+            raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        # deprecated arguments:
+        filetype = kwargs.get("filetype")
+
+        if filetype is not None:
+            warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+        # step1: files.getUploadURLExternal per file
+        files: List[Dict[str, Any]] = []
+        if file_uploads is not None:
+            for f in file_uploads:
+                files.append(_to_v2_file_upload_item(f))
+        else:
+            f = _to_v2_file_upload_item(
+                {
+                    "filename": filename,
+                    "file": file,
+                    "content": content,
+                    "title": title,
+                    "alt_txt": alt_txt,
+                    "snippet_type": snippet_type,
+                }
+            )
+            files.append(f)
+
+        for f in files:
+            url_response = await self.files_getUploadURLExternal(
+                filename=f.get("filename"),  # type: ignore[arg-type]
+                length=f.get("length"),  # type: ignore[arg-type]
+                alt_txt=f.get("alt_txt"),
+                snippet_type=f.get("snippet_type"),
+                token=kwargs.get("token"),
+            )
+            _validate_for_legacy_client(url_response)
+            f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+            f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+        # step2: "https://files.slack.com/upload/v1/..." per file
+        for f in files:
+            upload_result = await self._upload_file(
+                url=f["upload_url"],
+                data=f["data"],
+                logger=self._logger,
+                timeout=self.timeout,
+                proxy=self.proxy,
+                ssl=self.ssl,
+            )
+            if upload_result.status != 200:
+                status = upload_result.status
+                body = upload_result.body
+                message = (
+                    "Failed to upload a file "
+                    f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+                )
+                raise e.SlackRequestError(message)
+
+        # step3: files.completeUploadExternal with all the sets of (file_id + title)
+        completion = await self.files_completeUploadExternal(
+            files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+            channel_id=channel,
+            channels=channels,
+            initial_comment=initial_comment,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+        if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+            completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+        return completion
+
+    async def files_getUploadURLExternal(
+        self,
+        *,
+        filename: str,
+        length: int,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets a URL for an edge external upload.
+        https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+        """
+        kwargs.update(
+            {
+                "filename": filename,
+                "length": length,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        return await self.api_call("files.getUploadURLExternal", params=kwargs)
+
+    async def files_completeUploadExternal(
+        self,
+        *,
+        files: List[Dict[str, str]],
+        channel_id: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Finishes an upload started with files.getUploadURLExternal.
+        https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        """
+        _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+        kwargs.update(
+            {
+                "files": json.dumps(_files),
+                "channel_id": channel_id,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+            }
+        )
+        if channels:
+            kwargs["channels"] = ",".join(channels)
+        return await self.api_call("files.completeUploadExternal", params=kwargs)
+
+    async def functions_completeSuccess(
+        self,
+        *,
+        function_execution_id: str,
+        outputs: Dict[str, Any],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Signal the successful completion of a function
+        https://docs.slack.dev/reference/methods/functions.completeSuccess
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+        return await self.api_call("functions.completeSuccess", params=kwargs)
+
+    async def functions_completeError(
+        self,
+        *,
+        function_execution_id: str,
+        error: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Signal the failure to execute a function
+        https://docs.slack.dev/reference/methods/functions.completeError
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "error": error})
+        return await self.api_call("functions.completeError", params=kwargs)
+
+    # --------------------------
+    # Deprecated: groups.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    async def groups_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Archives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.archive", json=kwargs)
+
+    async def groups_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Creates a private channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.create", json=kwargs)
+
+    async def groups_createChild(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Clones and archives a private channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+    async def groups_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetches history of messages and events from a private channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+    async def groups_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a private channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+    async def groups_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Invites a user to a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.invite", json=kwargs)
+
+    async def groups_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a user from a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.kick", json=kwargs)
+
+    async def groups_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Leaves a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.leave", json=kwargs)
+
+    async def groups_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists private channels that the calling user has access to."""
+        return await self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+    async def groups_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the read cursor in a private channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.mark", json=kwargs)
+
+    async def groups_open(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Opens a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.open", json=kwargs)
+
+    async def groups_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Renames a private channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.rename", json=kwargs)
+
+    async def groups_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a thread of messages posted to a private channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return await self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+    async def groups_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the purpose for a private channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.setPurpose", json=kwargs)
+
+    async def groups_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the topic for a private channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.setTopic", json=kwargs)
+
+    async def groups_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Unarchives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("groups.unarchive", json=kwargs)
+
+    # --------------------------
+    # Deprecated: im.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    async def im_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Close a direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("im.close", json=kwargs)
+
+    async def im_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetches history of messages and events from direct message channel."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("im.history", http_verb="GET", params=kwargs)
+
+    async def im_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists direct message channels for the calling user."""
+        return await self.api_call("im.list", http_verb="GET", params=kwargs)
+
+    async def im_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the read cursor in a direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("im.mark", json=kwargs)
+
+    async def im_open(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Opens a direct message channel."""
+        kwargs.update({"user": user})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("im.open", json=kwargs)
+
+    async def im_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return await self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    async def migration_exchange(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        to_old: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """For Enterprise Grid workspaces, map local user IDs to global user IDs
+        https://docs.slack.dev/reference/methods/migration.exchange
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id, "to_old": to_old})
+        return await self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+    # --------------------------
+    # Deprecated: mpim.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    async def mpim_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Closes a multiparty direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("mpim.close", json=kwargs)
+
+    async def mpim_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Fetches history of messages and events from a multiparty direct message."""
+        kwargs.update({"channel": channel})
+        return await self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+    async def mpim_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists multiparty direct message channels for the calling user."""
+        return await self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+    async def mpim_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Sets the read cursor in a multiparty direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("mpim.mark", json=kwargs)
+
+    async def mpim_open(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """This method opens a multiparty direct message."""
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return await self.api_call("mpim.open", params=kwargs)
+
+    async def mpim_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation from a
+        multiparty direct message.
+        """
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return await self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    async def oauth_v2_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        # This field is required when processing the OAuth redirect URL requests
+        # while it's absent for token rotation
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        # This field is required for token rotation
+        grant_type: Optional[str] = None,
+        # This field is required for token rotation
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.v2.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return await self.api_call(
+            "oauth.v2.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    async def oauth_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        code: str,
+        redirect_uri: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        kwargs.update({"code": code})
+        return await self.api_call(
+            "oauth.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    async def oauth_v2_exchange(
+        self,
+        *,
+        token: str,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Exchanges a legacy access token for a new expiring access token and refresh token
+        https://docs.slack.dev/reference/methods/oauth.v2.exchange
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+        return await self.api_call("oauth.v2.exchange", params=kwargs)
+
+    async def openid_connect_token(
+        self,
+        client_id: str,
+        client_secret: str,
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        grant_type: Optional[str] = None,
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.token
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return await self.api_call(
+            "openid.connect.token",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    async def openid_connect_userInfo(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get the identity of a user who has authorized Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.userInfo
+        """
+        return await self.api_call("openid.connect.userInfo", params=kwargs)
+
+    async def pins_add(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Pins an item to a channel.
+        https://docs.slack.dev/reference/methods/pins.add
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return await self.api_call("pins.add", params=kwargs)
+
+    async def pins_list(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists items pinned to a channel.
+        https://docs.slack.dev/reference/methods/pins.list
+        """
+        kwargs.update({"channel": channel})
+        return await self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+    async def pins_remove(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Un-pins an item from a channel.
+        https://docs.slack.dev/reference/methods/pins.remove
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return await self.api_call("pins.remove", params=kwargs)
+
+    async def reactions_add(
+        self,
+        *,
+        channel: str,
+        name: str,
+        timestamp: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Adds a reaction to an item.
+        https://docs.slack.dev/reference/methods/reactions.add
+        """
+        kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+        return await self.api_call("reactions.add", params=kwargs)
+
+    async def reactions_get(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        full: Optional[bool] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets reactions for an item.
+        https://docs.slack.dev/reference/methods/reactions.get
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "full": full,
+                "timestamp": timestamp,
+            }
+        )
+        return await self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+    async def reactions_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        full: Optional[bool] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists reactions made by a user.
+        https://docs.slack.dev/reference/methods/reactions.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "full": full,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return await self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+    async def reactions_remove(
+        self,
+        *,
+        name: str,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a reaction from an item.
+        https://docs.slack.dev/reference/methods/reactions.remove
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return await self.api_call("reactions.remove", params=kwargs)
+
+    async def reminders_add(
+        self,
+        *,
+        text: str,
+        time: str,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        recurrence: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Creates a reminder.
+        https://docs.slack.dev/reference/methods/reminders.add
+        """
+        kwargs.update(
+            {
+                "text": text,
+                "time": time,
+                "team_id": team_id,
+                "user": user,
+                "recurrence": recurrence,
+            }
+        )
+        return await self.api_call("reminders.add", params=kwargs)
+
+    async def reminders_complete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Marks a reminder as complete.
+        https://docs.slack.dev/reference/methods/reminders.complete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return await self.api_call("reminders.complete", params=kwargs)
+
+    async def reminders_delete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes a reminder.
+        https://docs.slack.dev/reference/methods/reminders.delete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return await self.api_call("reminders.delete", params=kwargs)
+
+    async def reminders_info(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a reminder.
+        https://docs.slack.dev/reference/methods/reminders.info
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return await self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+    async def reminders_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all reminders created by or for a given user.
+        https://docs.slack.dev/reference/methods/reminders.list
+        """
+        kwargs.update({"team_id": team_id})
+        return await self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+    async def rtm_connect(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.connect
+        """
+        kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+        return await self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+    async def rtm_start(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        include_locale: Optional[bool] = None,
+        mpim_aware: Optional[bool] = None,
+        no_latest: Optional[bool] = None,
+        no_unreads: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        simple_latest: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.start
+        """
+        kwargs.update(
+            {
+                "batch_presence_aware": batch_presence_aware,
+                "include_locale": include_locale,
+                "mpim_aware": mpim_aware,
+                "no_latest": no_latest,
+                "no_unreads": no_unreads,
+                "presence_sub": presence_sub,
+                "simple_latest": simple_latest,
+            }
+        )
+        return await self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+    async def search_all(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Searches for messages and files matching a query.
+        https://docs.slack.dev/reference/methods/search.all
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("search.all", http_verb="GET", params=kwargs)
+
+    async def search_files(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Searches for files matching a query.
+        https://docs.slack.dev/reference/methods/search.files
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("search.files", http_verb="GET", params=kwargs)
+
+    async def search_messages(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Searches for messages matching a query.
+        https://docs.slack.dev/reference/methods/search.messages
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "cursor": cursor,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+    async def slackLists_access_delete(
+        self,
+        *,
+        list_id: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Revoke access to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.delete
+        """
+        kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.access.delete", json=kwargs)
+
+    async def slackLists_access_set(
+        self,
+        *,
+        list_id: str,
+        access_level: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the access level to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.set
+        """
+        kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.access.set", json=kwargs)
+
+    async def slackLists_create(
+        self,
+        *,
+        name: str,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        schema: Optional[List[Dict[str, Any]]] = None,
+        copy_from_list_id: Optional[str] = None,
+        include_copied_list_records: Optional[bool] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Creates a List.
+        https://docs.slack.dev/reference/methods/slackLists.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description_blocks": description_blocks,
+                "schema": schema,
+                "copy_from_list_id": copy_from_list_id,
+                "include_copied_list_records": include_copied_list_records,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.create", json=kwargs)
+
+    async def slackLists_download_get(
+        self,
+        *,
+        list_id: str,
+        job_id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve List download URL from an export job to download List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.get
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "job_id": job_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.download.get", json=kwargs)
+
+    async def slackLists_download_start(
+        self,
+        *,
+        list_id: str,
+        include_archived: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Initiate a job to export List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.start
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "include_archived": include_archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.download.start", json=kwargs)
+
+    async def slackLists_items_create(
+        self,
+        *,
+        list_id: str,
+        duplicated_item_id: Optional[str] = None,
+        parent_item_id: Optional[str] = None,
+        initial_fields: Optional[List[Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add a new item to an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.create
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "duplicated_item_id": duplicated_item_id,
+                "parent_item_id": parent_item_id,
+                "initial_fields": initial_fields,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.create", json=kwargs)
+
+    async def slackLists_items_delete(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes an item from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.delete
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.delete", json=kwargs)
+
+    async def slackLists_items_deleteMultiple(
+        self,
+        *,
+        list_id: str,
+        ids: List[str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Deletes multiple items from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "ids": ids,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+    async def slackLists_items_info(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        include_is_subscribed: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get a row from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.info
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+                "include_is_subscribed": include_is_subscribed,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.info", json=kwargs)
+
+    async def slackLists_items_list(
+        self,
+        *,
+        list_id: str,
+        limit: Optional[int] = None,
+        cursor: Optional[str] = None,
+        archived: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get records from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.list
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "limit": limit,
+                "cursor": cursor,
+                "archived": archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.list", json=kwargs)
+
+    async def slackLists_items_update(
+        self,
+        *,
+        list_id: str,
+        cells: List[Dict[str, Any]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Updates cells in a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.update
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "cells": cells,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.items.update", json=kwargs)
+
+    async def slackLists_update(
+        self,
+        *,
+        id: str,
+        name: Optional[str] = None,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update a List.
+        https://docs.slack.dev/reference/methods/slackLists.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "name": name,
+                "description_blocks": description_blocks,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return await self.api_call("slackLists.update", json=kwargs)
+
+    async def stars_add(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Adds a star to an item.
+        https://docs.slack.dev/reference/methods/stars.add
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return await self.api_call("stars.add", params=kwargs)
+
+    async def stars_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists stars for a user.
+        https://docs.slack.dev/reference/methods/stars.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+    async def stars_remove(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Removes a star from an item.
+        https://docs.slack.dev/reference/methods/stars.remove
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return await self.api_call("stars.remove", params=kwargs)
+
+    async def team_accessLogs(
+        self,
+        *,
+        before: Optional[Union[int, str]] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets the access logs for the current team.
+        https://docs.slack.dev/reference/methods/team.accessLogs
+        """
+        kwargs.update(
+            {
+                "before": before,
+                "count": count,
+                "page": page,
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return await self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+    async def team_billableInfo(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets billable users information for the current team.
+        https://docs.slack.dev/reference/methods/team.billableInfo
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return await self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+    async def team_billing_info(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Reads a workspace's billing plan information.
+        https://docs.slack.dev/reference/methods/team.billing.info
+        """
+        return await self.api_call("team.billing.info", params=kwargs)
+
+    async def team_externalTeams_disconnect(
+        self,
+        *,
+        target_team: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Disconnects an external organization.
+        https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+        """
+        kwargs.update(
+            {
+                "target_team": target_team,
+            }
+        )
+        return await self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+    async def team_externalTeams_list(
+        self,
+        *,
+        connection_status_filter: Optional[str] = None,
+        slack_connect_pref_filter: Optional[Sequence[str]] = None,
+        sort_direction: Optional[str] = None,
+        sort_field: Optional[str] = None,
+        workspace_filter: Optional[Sequence[str]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Returns a list of all the external teams connected and details about the connection.
+        https://docs.slack.dev/reference/methods/team.externalTeams.list
+        """
+        kwargs.update(
+            {
+                "connection_status_filter": connection_status_filter,
+                "sort_direction": sort_direction,
+                "sort_field": sort_field,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if slack_connect_pref_filter is not None:
+            if isinstance(slack_connect_pref_filter, (list, tuple)):
+                kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+            else:
+                kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+        if workspace_filter is not None:
+            if isinstance(workspace_filter, (list, tuple)):
+                kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+            else:
+                kwargs.update({"workspace_filter": workspace_filter})
+        return await self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+    async def team_info(
+        self,
+        *,
+        team: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about the current team.
+        https://docs.slack.dev/reference/methods/team.info
+        """
+        kwargs.update({"team": team, "domain": domain})
+        return await self.api_call("team.info", http_verb="GET", params=kwargs)
+
+    async def team_integrationLogs(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        change_type: Optional[str] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        service_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets the integration logs for the current team.
+        https://docs.slack.dev/reference/methods/team.integrationLogs
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "change_type": change_type,
+                "count": count,
+                "page": page,
+                "service_id": service_id,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return await self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+    async def team_profile_get(
+        self,
+        *,
+        visibility: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a team's profile.
+        https://docs.slack.dev/reference/methods/team.profile.get
+        """
+        kwargs.update({"visibility": visibility})
+        return await self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+    async def team_preferences_list(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieve a list of a workspace's team preferences.
+        https://docs.slack.dev/reference/methods/team.preferences.list
+        """
+        return await self.api_call("team.preferences.list", params=kwargs)
+
+    async def usergroups_create(
+        self,
+        *,
+        name: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Create a User Group
+        https://docs.slack.dev/reference/methods/usergroups.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return await self.api_call("usergroups.create", params=kwargs)
+
+    async def usergroups_disable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Disable an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.disable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return await self.api_call("usergroups.disable", params=kwargs)
+
+    async def usergroups_enable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Enable a User Group
+        https://docs.slack.dev/reference/methods/usergroups.enable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return await self.api_call("usergroups.enable", params=kwargs)
+
+    async def usergroups_list(
+        self,
+        *,
+        include_count: Optional[bool] = None,
+        include_disabled: Optional[bool] = None,
+        include_users: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all User Groups for a team
+        https://docs.slack.dev/reference/methods/usergroups.list
+        """
+        kwargs.update(
+            {
+                "include_count": include_count,
+                "include_disabled": include_disabled,
+                "include_users": include_users,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+    async def usergroups_update(
+        self,
+        *,
+        usergroup: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "name": name,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return await self.api_call("usergroups.update", params=kwargs)
+
+    async def usergroups_users_list(
+        self,
+        *,
+        usergroup: str,
+        include_disabled: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List all users in a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.list
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_disabled": include_disabled,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+    async def usergroups_users_update(
+        self,
+        *,
+        usergroup: str,
+        users: Union[str, Sequence[str]],
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update the list of users for a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return await self.api_call("usergroups.users.update", params=kwargs)
+
+    async def users_conversations(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List conversations the calling user may access.
+        https://docs.slack.dev/reference/methods/users.conversations
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return await self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+    async def users_deletePhoto(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Delete the user profile photo
+        https://docs.slack.dev/reference/methods/users.deletePhoto
+        """
+        return await self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+    async def users_getPresence(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets user presence information.
+        https://docs.slack.dev/reference/methods/users.getPresence
+        """
+        kwargs.update({"user": user})
+        return await self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+    async def users_identity(
+        self,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Get a user's identity.
+        https://docs.slack.dev/reference/methods/users.identity
+        """
+        return await self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+    async def users_info(
+        self,
+        *,
+        user: str,
+        include_locale: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Gets information about a user.
+        https://docs.slack.dev/reference/methods/users.info
+        """
+        kwargs.update({"user": user, "include_locale": include_locale})
+        return await self.api_call("users.info", http_verb="GET", params=kwargs)
+
+    async def users_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_locale: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lists all users in a Slack team.
+        https://docs.slack.dev/reference/methods/users.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_locale": include_locale,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return await self.api_call("users.list", http_verb="GET", params=kwargs)
+
+    async def users_lookupByEmail(
+        self,
+        *,
+        email: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Find a user with an email address.
+        https://docs.slack.dev/reference/methods/users.lookupByEmail
+        """
+        kwargs.update({"email": email})
+        return await self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+    async def users_setPhoto(
+        self,
+        *,
+        image: Union[str, IOBase],
+        crop_w: Optional[Union[int, str]] = None,
+        crop_x: Optional[Union[int, str]] = None,
+        crop_y: Optional[Union[int, str]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the user profile photo
+        https://docs.slack.dev/reference/methods/users.setPhoto
+        """
+        kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+        return await self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+    async def users_setPresence(
+        self,
+        *,
+        presence: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Manually sets user presence.
+        https://docs.slack.dev/reference/methods/users.setPresence
+        """
+        kwargs.update({"presence": presence})
+        return await self.api_call("users.setPresence", params=kwargs)
+
+    async def users_discoverableContacts_lookup(
+        self,
+        email: str,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Lookup an email address to see if someone is on Slack
+        https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+        """
+        kwargs.update({"email": email})
+        return await self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+    async def users_profile_get(
+        self,
+        *,
+        user: Optional[str] = None,
+        include_labels: Optional[bool] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Retrieves a user's profile information.
+        https://docs.slack.dev/reference/methods/users.profile.get
+        """
+        kwargs.update({"user": user, "include_labels": include_labels})
+        return await self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+    async def users_profile_set(
+        self,
+        *,
+        name: Optional[str] = None,
+        value: Optional[str] = None,
+        user: Optional[str] = None,
+        profile: Optional[Dict] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set the profile information for a user.
+        https://docs.slack.dev/reference/methods/users.profile.set
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "profile": profile,
+                "user": user,
+                "value": value,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "profile" parameter
+        return await self.api_call("users.profile.set", json=kwargs)
+
+    async def views_open(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Open a view for a user.
+        https://docs.slack.dev/reference/methods/views.open
+        See https://docs.slack.dev/surfaces/modals/ for details.
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return await self.api_call("views.open", json=kwargs)
+
+    async def views_push(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Push a view onto the stack of a root view.
+        Push a new view onto the existing view stack by passing a view
+        payload and a valid trigger_id generated from an interaction
+        within the existing modal.
+        Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+        to learn more about the lifecycle and intricacies of views.
+        https://docs.slack.dev/reference/methods/views.push
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return await self.api_call("views.push", json=kwargs)
+
+    async def views_update(
+        self,
+        *,
+        view: Union[dict, View],
+        external_id: Optional[str] = None,
+        view_id: Optional[str] = None,
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update an existing view.
+        Update a view by passing a new view definition along with the
+        view_id returned in views.open or the external_id.
+        See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+        to learn more about updating views and avoiding race conditions with the hash argument.
+        https://docs.slack.dev/reference/methods/views.update
+        """
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        if external_id:
+            kwargs.update({"external_id": external_id})
+        elif view_id:
+            kwargs.update({"view_id": view_id})
+        else:
+            raise e.SlackRequestError("Either view_id or external_id is required.")
+        kwargs.update({"hash": hash})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return await self.api_call("views.update", json=kwargs)
+
+    async def views_publish(
+        self,
+        *,
+        user_id: str,
+        view: Union[dict, View],
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Publish a static view for a User.
+        Create or update the view that comprises an
+        app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+        https://docs.slack.dev/reference/methods/views.publish
+        """
+        kwargs.update({"user_id": user_id, "hash": hash})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return await self.api_call("views.publish", json=kwargs)
+
+    async def workflows_featured_add(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Add featured workflows to a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.add
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return await self.api_call("workflows.featured.add", params=kwargs)
+
+    async def workflows_featured_list(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """List the featured workflows for specified channels.
+        https://docs.slack.dev/reference/methods/workflows.featured.list
+        """
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return await self.api_call("workflows.featured.list", params=kwargs)
+
+    async def workflows_featured_remove(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Remove featured workflows from a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.remove
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return await self.api_call("workflows.featured.remove", params=kwargs)
+
+    async def workflows_featured_set(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Set featured workflows for a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.set
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return await self.api_call("workflows.featured.set", params=kwargs)
+
+    async def workflows_stepCompleted(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        outputs: Optional[dict] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Indicate a successful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepCompleted
+        """
+        kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "outputs" parameter
+        return await self.api_call("workflows.stepCompleted", json=kwargs)
+
+    async def workflows_stepFailed(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        error: Dict[str, str],
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Indicate an unsuccessful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepFailed
+        """
+        kwargs.update(
+            {
+                "workflow_step_execute_id": workflow_step_execute_id,
+                "error": error,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "error" parameter
+        return await self.api_call("workflows.stepFailed", json=kwargs)
+
+    async def workflows_updateStep(
+        self,
+        *,
+        workflow_step_edit_id: str,
+        inputs: Optional[Dict[str, Any]] = None,
+        outputs: Optional[List[Dict[str, str]]] = None,
+        **kwargs,
+    ) -> AsyncSlackResponse:
+        """Update the configuration for a workflow extension step.
+        https://docs.slack.dev/reference/methods/workflows.updateStep
+        """
+        kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+        if inputs is not None:
+            kwargs.update({"inputs": inputs})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+        return await self.api_call("workflows.updateStep", json=kwargs)
+
+

A WebClient allows apps to communicate with the Slack Platform's Web API.

+

https://docs.slack.dev/reference/methods

+

The Slack Web API is an interface for querying information from +and enacting change in a Slack workspace.

+

This client handles constructing and sending HTTP requests to Slack +as well as parsing any responses received into a SlackResponse.

+

Attributes

+
+
token : str
+
A string specifying an xoxp-* or xoxb-* token.
+
base_url : str
+
A string representing the Slack API base URL. +Default is 'https://slack.com/api/'
+
timeout : int
+
The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.
+
ssl : SSLContext
+
An ssl.SSLContext instance, helpful for specifying +your own custom certificate chain.
+
proxy : str
+
String representing a fully-qualified URL to a proxy through +which to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.
+
headers : dict
+
Additional request headers to attach to all requests.
+
+

Methods

+

api_call: Constructs a request and executes the API call to Slack.

+

Example of recommended usage:

+
    import os
+    from slack_sdk.web.async_client import AsyncWebClient
+
+    client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.chat_postMessage(
+        channel='#random',
+        text="Hello world!")
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Example manually creating an API request:

+
    import os
+    from slack_sdk.web.async_client import AsyncWebClient
+
+    client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.api_call(
+        api_method='chat.postMessage',
+        json={'channel': '#random','text': "Hello world!"}
+    )
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Note

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Ancestors

+ +

Methods

+
+
+async def admin_analytics_getFile(self,
*,
type:Β str,
date:Β strΒ |Β NoneΒ =Β None,
metadata_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_analytics_getFile(
+    self,
+    *,
+    type: str,
+    date: Optional[str] = None,
+    metadata_only: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve analytics data for a given date, presented as a compressed JSON file
+    https://docs.slack.dev/reference/methods/admin.analytics.getFile
+    """
+    kwargs.update({"type": type})
+    if date is not None:
+        kwargs.update({"date": date})
+    if metadata_only is not None:
+        kwargs.update({"metadata_only": metadata_only})
+    return await self.api_call("admin.analytics.getFile", params=kwargs)
+
+

Retrieve analytics data for a given date, presented as a compressed JSON file +https://docs.slack.dev/reference/methods/admin.analytics.getFile

+
+
+async def admin_apps_activities_list(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
component_id:Β strΒ |Β NoneΒ =Β None,
component_type:Β strΒ |Β NoneΒ =Β None,
log_event_type:Β strΒ |Β NoneΒ =Β None,
max_date_created:Β intΒ |Β NoneΒ =Β None,
min_date_created:Β intΒ |Β NoneΒ =Β None,
min_log_level:Β strΒ |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
trace_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_activities_list(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    component_id: Optional[str] = None,
+    component_type: Optional[str] = None,
+    log_event_type: Optional[str] = None,
+    max_date_created: Optional[int] = None,
+    min_date_created: Optional[int] = None,
+    min_log_level: Optional[str] = None,
+    sort_direction: Optional[str] = None,
+    source: Optional[str] = None,
+    team_id: Optional[str] = None,
+    trace_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get logs for a specified team/org
+    https://docs.slack.dev/reference/methods/admin.apps.activities.list
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "component_id": component_id,
+            "component_type": component_type,
+            "log_event_type": log_event_type,
+            "max_date_created": max_date_created,
+            "min_date_created": min_date_created,
+            "min_log_level": min_log_level,
+            "sort_direction": sort_direction,
+            "source": source,
+            "team_id": team_id,
+            "trace_id": trace_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("admin.apps.activities.list", params=kwargs)
+
+ +
+
+async def admin_apps_approve(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_approve(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Approve an app for installation on a workspace.
+    Either app_id or request_id is required.
+    These IDs can be obtained either directly via the app_requested event,
+    or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.approve
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.approve", params=kwargs)
+
+

Approve an app for installation on a workspace. +Either app_id or request_id is required. +These IDs can be obtained either directly via the app_requested event, +or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.approve

+
+
+async def admin_apps_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List approved apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+

List approved apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.approved.list

+
+
+async def admin_apps_clearResolution(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_clearResolution(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Clear an app resolution
+    https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+ +
+
+async def admin_apps_config_lookup(self, *, app_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_apps_config_lookup(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Look up the app config for connectors by their IDs
+    https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    return await self.api_call("admin.apps.config.lookup", params=kwargs)
+
+

Look up the app config for connectors by their IDs +https://docs.slack.dev/reference/methods/admin.apps.config.lookup

+
+
+async def admin_apps_config_set(self,
*,
app_id:Β str,
domain_restrictions:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_auth_strategy:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_config_set(
+    self,
+    *,
+    app_id: str,
+    domain_restrictions: Optional[Dict[str, Any]] = None,
+    workflow_auth_strategy: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the app config for a connector
+    https://docs.slack.dev/reference/methods/admin.apps.config.set
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "workflow_auth_strategy": workflow_auth_strategy,
+        }
+    )
+    if domain_restrictions is not None:
+        kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+    return await self.api_call("admin.apps.config.set", params=kwargs)
+
+ +
+
+async def admin_apps_requests_cancel(self,
*,
request_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_requests_cancel(
+    self,
+    *,
+    request_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+    """
+    kwargs.update(
+        {
+            "request_id": request_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+ +
+
+async def admin_apps_requests_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_requests_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_apps_restrict(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_restrict(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Restrict an app for installation on a workspace.
+    Exactly one of the team_id or enterprise_id arguments is required, not both.
+    Either app_id or request_id is required. These IDs can be obtained either directly
+    via the app_requested event, or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.restrict
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.restrict", params=kwargs)
+
+

Restrict an app for installation on a workspace. +Exactly one of the team_id or enterprise_id arguments is required, not both. +Either app_id or request_id is required. These IDs can be obtained either directly +via the app_requested event, or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.restrict

+
+
+async def admin_apps_restricted_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_restricted_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List restricted apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+

List restricted apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.restricted.list

+
+
+async def admin_apps_uninstall(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_apps_uninstall(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+    With an org-level token, enterprise_id or team_ids is required.
+    https://docs.slack.dev/reference/methods/admin.apps.uninstall
+    """
+    kwargs.update({"app_id": app_id})
+    if enterprise_id is not None:
+        kwargs.update({"enterprise_id": enterprise_id})
+    if team_ids is not None:
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+    return await self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+

Uninstall an app from one or many workspaces, or an entire enterprise organization. +With an org-level token, enterprise_id or team_ids is required. +https://docs.slack.dev/reference/methods/admin.apps.uninstall

+
+
+async def admin_auth_policy_assignEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_auth_policy_assignEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Assign entities to a particular authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return await self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+

Assign entities to a particular authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities

+
+
+async def admin_auth_policy_getEntities(self,
*,
policy_name:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_auth_policy_getEntities(
+    self,
+    *,
+    policy_name: str,
+    cursor: Optional[str] = None,
+    entity_type: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetch all the entities assigned to a particular authentication policy by name.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+    """
+    kwargs.update({"policy_name": policy_name})
+    if cursor is not None:
+        kwargs.update({"cursor": cursor})
+    if entity_type is not None:
+        kwargs.update({"entity_type": entity_type})
+    if limit is not None:
+        kwargs.update({"limit": limit})
+    return await self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+

Fetch all the entities assigned to a particular authentication policy by name. +https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities

+
+
+async def admin_auth_policy_removeEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_auth_policy_removeEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove specified entities from a specified authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return await self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+

Remove specified entities from a specified authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities

+
+
+async def admin_barriers_create(self,
*,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_barriers_create(
+    self,
+    *,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create an Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.create
+    """
+    kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return await self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+ +
+
+async def admin_barriers_delete(self, *, barrier_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_barriers_delete(
+    self,
+    *,
+    barrier_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Delete an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.delete
+    """
+    kwargs.update({"barrier_id": barrier_id})
+    return await self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+ +
+
+async def admin_barriers_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_barriers_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get all Information Barriers for your organization
+    https://docs.slack.dev/reference/methods/admin.barriers.list"""
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+

Get all Information Barriers for your organization +https://docs.slack.dev/reference/methods/admin.barriers.list

+
+
+async def admin_barriers_update(self,
*,
barrier_id:Β str,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_barriers_update(
+    self,
+    *,
+    barrier_id: str,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.update
+    """
+    kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return await self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+ +
+
+async def admin_conversations_archive(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_archive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Archive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.archive", params=kwargs)
+
+ +
+
+async def admin_conversations_bulkArchive(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_bulkArchive(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Archive public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return await self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+ +
+
+async def admin_conversations_bulkDelete(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_bulkDelete(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Delete public or private channels in bulk.
+    https://slack.com/api/admin.conversations.bulkDelete
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return await self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+

Delete public or private channels in bulk. +https://slack.com/api/admin.conversations.bulkDelete

+
+
+async def admin_conversations_bulkMove(self, *, channel_ids:Β strΒ |Β Sequence[str], target_team_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_bulkMove(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    target_team_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Move public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+    """
+    kwargs.update(
+        {
+            "target_team_id": target_team_id,
+            "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+        }
+    )
+    return await self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+ +
+
+async def admin_conversations_convertToPrivate(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_convertToPrivate(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Convert a public channel to a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+ +
+
+async def admin_conversations_convertToPublic(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_convertToPublic(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Convert a privte channel to a public channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+ +
+
+async def admin_conversations_create(self,
*,
is_private:Β bool,
name:Β str,
description:Β strΒ |Β NoneΒ =Β None,
org_wide:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_create(
+    self,
+    *,
+    is_private: bool,
+    name: str,
+    description: Optional[str] = None,
+    org_wide: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create a public or private channel-based conversation.
+    https://docs.slack.dev/reference/methods/admin.conversations.create
+    """
+    kwargs.update(
+        {
+            "is_private": is_private,
+            "name": name,
+            "description": description,
+            "org_wide": org_wide,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.conversations.create", params=kwargs)
+
+

Create a public or private channel-based conversation. +https://docs.slack.dev/reference/methods/admin.conversations.create

+
+
+async def admin_conversations_createForObjects(self,
*,
object_id:Β str,
salesforce_org_id:Β str,
invite_object_team:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_createForObjects(
+    self,
+    *,
+    object_id: str,
+    salesforce_org_id: str,
+    invite_object_team: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create a Salesforce channel for the corresponding object provided.
+    https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+    """
+    kwargs.update(
+        {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+    )
+    return await self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+

Create a Salesforce channel for the corresponding object provided. +https://docs.slack.dev/reference/methods/admin.conversations.createForObjects

+
+
+async def admin_conversations_delete(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_delete(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Delete a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.delete
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.delete", params=kwargs)
+
+ +
+
+async def admin_conversations_disconnectShared(self,
*,
channel_id:Β str,
leaving_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_disconnectShared(
+    self,
+    *,
+    channel_id: str,
+    leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Disconnect a connected channel from one or more workspaces.
+    https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(leaving_team_ids, (list, tuple)):
+        kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+    else:
+        kwargs.update({"leaving_team_ids": leaving_team_ids})
+    return await self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+

Disconnect a connected channel from one or more workspaces. +https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared

+
+
+async def admin_conversations_ekm_listOriginalConnectedChannelInfo(self,
*,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+    self,
+    *,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all disconnected channelsβ€”i.e.,
+    channels that were once connected to other workspaces and then disconnectedβ€”and
+    the corresponding original channel IDs for key revocation with EKM.
+    https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return await self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+

List all disconnected channelsβ€”i.e., +channels that were once connected to other workspaces and then disconnectedβ€”and +the corresponding original channel IDs for key revocation with EKM. +https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo

+
+
+async def admin_conversations_getConversationPrefs(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_getConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get conversation preferences for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+

Get conversation preferences for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs

+
+
+async def admin_conversations_getCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_getCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+ +
+
+async def admin_conversations_getTeams(self,
*,
channel_id:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_getTeams(
+    self,
+    *,
+    channel_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("admin.conversations.getTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a channel. +https://docs.slack.dev/reference/methods/admin.conversations.getTeams

+
+
+async def admin_conversations_invite(self, *, channel_id:Β str, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_invite(
+    self,
+    *,
+    channel_id: str,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invite a user to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.invite
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+    return await self.api_call("admin.conversations.invite", params=kwargs)
+
+

Invite a user to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.invite

+
+
+async def admin_conversations_linkObjects(self, *, channel:Β str, record_id:Β str, salesforce_org_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_linkObjects(
+    self,
+    *,
+    channel: str,
+    record_id: str,
+    salesforce_org_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Link a Salesforce record to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "record_id": record_id,
+            "salesforce_org_id": salesforce_org_id,
+        }
+    )
+    return await self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+ +
+
+async def admin_conversations_lookup(self,
*,
last_message_activity_before:Β int,
team_ids:Β strΒ |Β Sequence[str],
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
max_member_count:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_lookup(
+    self,
+    *,
+    last_message_activity_before: int,
+    team_ids: Union[str, Sequence[str]],
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    max_member_count: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Returns channels on the given team using the filters.
+    https://docs.slack.dev/reference/methods/admin.conversations.lookup
+    """
+    kwargs.update(
+        {
+            "last_message_activity_before": last_message_activity_before,
+            "cursor": cursor,
+            "limit": limit,
+            "max_member_count": max_member_count,
+        }
+    )
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return await self.api_call("admin.conversations.lookup", params=kwargs)
+
+

Returns channels on the given team using the filters. +https://docs.slack.dev/reference/methods/admin.conversations.lookup

+
+
+async def admin_conversations_removeCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_removeCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+ +
+
+async def admin_conversations_rename(self, *, channel_id:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_rename(
+    self,
+    *,
+    channel_id: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Rename a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.rename
+    """
+    kwargs.update({"channel_id": channel_id, "name": name})
+    return await self.api_call("admin.conversations.rename", params=kwargs)
+
+ +
+
+async def admin_conversations_restrictAccess_addGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_restrictAccess_addGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add an allowlist of IDP groups for accessing a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call(
+        "admin.conversations.restrictAccess.addGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Add an allowlist of IDP groups for accessing a channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup

+
+
+async def admin_conversations_restrictAccess_listGroups(self, *, channel_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_restrictAccess_listGroups(
+    self,
+    *,
+    channel_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all IDP Groups linked to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call(
+        "admin.conversations.restrictAccess.listGroups",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+ +
+
+async def admin_conversations_restrictAccess_removeGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_restrictAccess_removeGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove a linked IDP group linked from a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call(
+        "admin.conversations.restrictAccess.removeGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Remove a linked IDP group linked from a private channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup

+
+ +
+
+ +Expand source code + +
async def admin_conversations_search(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    query: Optional[str] = None,
+    search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Search for public or private channels in an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.conversations.search
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+        }
+    )
+
+    if isinstance(search_channel_types, (list, tuple)):
+        kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+    else:
+        kwargs.update({"search_channel_types": search_channel_types})
+
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+
+    return await self.api_call("admin.conversations.search", params=kwargs)
+
+

Search for public or private channels in an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.conversations.search

+
+
+async def admin_conversations_setConversationPrefs(self, *, channel_id:Β str, prefs:Β strΒ |Β Dict[str,Β str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_setConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    prefs: Union[str, Dict[str, str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the posting permissions for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(prefs, dict):
+        kwargs.update({"prefs": json.dumps(prefs)})
+    else:
+        kwargs.update({"prefs": prefs})
+    return await self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+

Set the posting permissions for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs

+
+
+async def admin_conversations_setCustomRetention(self, *, channel_id:Β str, duration_days:Β int, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_setCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    duration_days: int,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+    return await self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+ +
+
+async def admin_conversations_setTeams(self,
*,
channel_id:Β str,
org_channel:Β boolΒ |Β NoneΒ =Β None,
target_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_conversations_setTeams(
+    self,
+    *,
+    channel_id: str,
+    org_channel: Optional[bool] = None,
+    target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "org_channel": org_channel,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(target_team_ids, (list, tuple)):
+        kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+    else:
+        kwargs.update({"target_team_ids": target_team_ids})
+    return await self.api_call("admin.conversations.setTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setTeams

+
+
+async def admin_conversations_unarchive(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_unarchive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Unarchive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("admin.conversations.unarchive", params=kwargs)
+
+ +
+
+async def admin_conversations_unlinkObjects(self, *, channel:Β str, new_name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_conversations_unlinkObjects(
+    self,
+    *,
+    channel: str,
+    new_name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Unlink a Salesforce record from a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "new_name": new_name,
+        }
+    )
+    return await self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+ +
+
+async def admin_emoji_add(self, *, name:Β str, url:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_emoji_add(
+    self,
+    *,
+    name: str,
+    url: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.add
+    """
+    kwargs.update({"name": name, "url": url})
+    return await self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_emoji_addAlias(self, *, alias_for:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_emoji_addAlias(
+    self,
+    *,
+    alias_for: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add an emoji alias.
+    https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+    """
+    kwargs.update({"alias_for": alias_for, "name": name})
+    return await self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_emoji_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_emoji_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List emoji for an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return await self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+

List emoji for an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.list

+
+
+async def admin_emoji_remove(self, *, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_emoji_remove(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove an emoji across an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.remove
+    """
+    kwargs.update({"name": name})
+    return await self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+

Remove an emoji across an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.remove

+
+
+async def admin_emoji_rename(self, *, name:Β str, new_name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_emoji_rename(
+    self,
+    *,
+    name: str,
+    new_name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Rename an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.rename
+    """
+    kwargs.update({"name": name, "new_name": new_name})
+    return await self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_functions_list(self,
*,
app_ids:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_functions_list(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Look up functions by a set of apps
+    https://docs.slack.dev/reference/methods/admin.functions.list
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("admin.functions.list", params=kwargs)
+
+ +
+
+async def admin_functions_permissions_lookup(self, *, function_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_functions_permissions_lookup(
+    self,
+    *,
+    function_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lookup the visibility of multiple Slack functions
+    and include the users if it is limited to particular named entities.
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+    """
+    if isinstance(function_ids, (list, tuple)):
+        kwargs.update({"function_ids": ",".join(function_ids)})
+    else:
+        kwargs.update({"function_ids": function_ids})
+    return await self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+

Lookup the visibility of multiple Slack functions +and include the users if it is limited to particular named entities. +https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup

+
+
+async def admin_functions_permissions_set(self,
*,
function_id:Β str,
visibility:Β str,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_functions_permissions_set(
+    self,
+    *,
+    function_id: str,
+    visibility: str,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the visibility of a Slack function
+    and define the users or workspaces if it is set to named_entities
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+    """
+    kwargs.update(
+        {
+            "function_id": function_id,
+            "visibility": visibility,
+        }
+    )
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return await self.api_call("admin.functions.permissions.set", params=kwargs)
+
+

Set the visibility of a Slack function +and define the users or workspaces if it is set to named_entities +https://docs.slack.dev/reference/methods/admin.functions.permissions.set

+
+
+async def admin_inviteRequests_approve(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_inviteRequests_approve(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Approve a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return await self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+ +
+
+async def admin_inviteRequests_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_inviteRequests_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all approved workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+ +
+
+async def admin_inviteRequests_denied_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_inviteRequests_denied_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all denied workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+ +
+
+async def admin_inviteRequests_deny(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_inviteRequests_deny(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deny a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return await self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+ +
+
+async def admin_inviteRequests_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_inviteRequests_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all pending workspace invite requests."""
+    return await self.api_call("admin.inviteRequests.list", params=kwargs)
+
+

List all pending workspace invite requests.

+
+
+async def admin_roles_addAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_roles_addAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Adds members to the specified role with the specified scopes
+    https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return await self.api_call("admin.roles.addAssignments", params=kwargs)
+
+

Adds members to the specified role with the specified scopes +https://docs.slack.dev/reference/methods/admin.roles.addAssignments

+
+
+async def admin_roles_listAssignments(self,
*,
role_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
entity_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β strΒ |Β intΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_roles_listAssignments(
+    self,
+    *,
+    role_ids: Optional[Union[str, Sequence[str]]] = None,
+    entity_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[Union[str, int]] = None,
+    sort_dir: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists assignments for all roles across entities.
+        Options to scope results by any combination of roles or entities
+    https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(role_ids, (list, tuple)):
+        kwargs.update({"role_ids": ",".join(role_ids)})
+    else:
+        kwargs.update({"role_ids": role_ids})
+    return await self.api_call("admin.roles.listAssignments", params=kwargs)
+
+

Lists assignments for all roles across entities. +Options to scope results by any combination of roles or entities +https://docs.slack.dev/reference/methods/admin.roles.listAssignments

+
+
+async def admin_roles_removeAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_roles_removeAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a set of users from a role for the given scopes and entities
+    https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return await self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+

Removes a set of users from a role for the given scopes and entities +https://docs.slack.dev/reference/methods/admin.roles.removeAssignments

+
+
+async def admin_teams_admins_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_admins_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.inviteRequests.list

+
+
+async def admin_teams_create(self,
*,
team_domain:Β str,
team_name:Β str,
team_description:Β strΒ |Β NoneΒ =Β None,
team_discoverability:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_teams_create(
+    self,
+    *,
+    team_domain: str,
+    team_name: str,
+    team_description: Optional[str] = None,
+    team_discoverability: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create an Enterprise team.
+    https://docs.slack.dev/reference/methods/admin.teams.create
+    """
+    kwargs.update(
+        {
+            "team_domain": team_domain,
+            "team_name": team_name,
+            "team_description": team_description,
+            "team_discoverability": team_discoverability,
+        }
+    )
+    return await self.api_call("admin.teams.create", params=kwargs)
+
+ +
+
+async def admin_teams_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all teams on an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return await self.api_call("admin.teams.list", params=kwargs)
+
+

List all teams on an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.teams.list

+
+
+async def admin_teams_owners_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_owners_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.owners.list
+    """
+    kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+    return await self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.teams.owners.list

+
+
+async def admin_teams_settings_info(self, *, team_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_info(
+    self,
+    *,
+    team_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetch information about settings in a workspace
+    https://docs.slack.dev/reference/methods/admin.teams.settings.info
+    """
+    kwargs.update({"team_id": team_id})
+    return await self.api_call("admin.teams.settings.info", params=kwargs)
+
+

Fetch information about settings in a workspace +https://docs.slack.dev/reference/methods/admin.teams.settings.info

+
+
+async def admin_teams_settings_setDefaultChannels(self, *, team_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_setDefaultChannels(
+    self,
+    *,
+    team_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the default channels of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+    """
+    kwargs.update({"team_id": team_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_teams_settings_setDescription(self, *, team_id:Β str, description:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_setDescription(
+    self,
+    *,
+    team_id: str,
+    description: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the description of a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+    """
+    kwargs.update({"team_id": team_id, "description": description})
+    return await self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+ +
+
+async def admin_teams_settings_setDiscoverability(self, *, team_id:Β str, discoverability:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_setDiscoverability(
+    self,
+    *,
+    team_id: str,
+    discoverability: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+    """
+    kwargs.update({"team_id": team_id, "discoverability": discoverability})
+    return await self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+ +
+
+async def admin_teams_settings_setIcon(self, *, team_id:Β str, image_url:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_setIcon(
+    self,
+    *,
+    team_id: str,
+    image_url: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+    """
+    kwargs.update({"team_id": team_id, "image_url": image_url})
+    return await self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+ +
+
+async def admin_teams_settings_setName(self, *, team_id:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_teams_settings_setName(
+    self,
+    *,
+    team_id: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+    """
+    kwargs.update({"team_id": team_id, "name": name})
+    return await self.api_call("admin.teams.settings.setName", params=kwargs)
+
+ +
+
+async def admin_usergroups_addChannels(self,
*,
channel_ids:Β strΒ |Β Sequence[str],
usergroup_id:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_usergroups_addChannels(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    usergroup_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+    """
+    kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addChannels

+
+
+async def admin_usergroups_addTeams(self,
*,
usergroup_id:Β str,
team_ids:Β strΒ |Β Sequence[str],
auto_provision:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_usergroups_addTeams(
+    self,
+    *,
+    usergroup_id: str,
+    team_ids: Union[str, Sequence[str]],
+    auto_provision: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Associate one or more default workspaces with an organization-wide IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+    """
+    kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return await self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+

Associate one or more default workspaces with an organization-wide IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addTeams

+
+
+async def admin_usergroups_listChannels(self,
*,
usergroup_id:Β str,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
team_id:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_usergroups_listChannels(
+    self,
+    *,
+    usergroup_id: str,
+    include_num_members: Optional[bool] = None,
+    team_id: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+    """
+    kwargs.update(
+        {
+            "usergroup_id": usergroup_id,
+            "include_num_members": include_num_members,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.listChannels

+
+
+async def admin_usergroups_removeChannels(self, *, usergroup_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_usergroups_removeChannels(
+    self,
+    *,
+    usergroup_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+    """
+    kwargs.update({"usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels

+
+
+async def admin_users_assign(self,
*,
team_id:Β str,
user_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_assign(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add an Enterprise user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.assign
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "user_id": user_id,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("admin.users.assign", params=kwargs)
+
+

Add an Enterprise user to a workspace. +https://docs.slack.dev/reference/methods/admin.users.assign

+
+
+async def admin_users_invite(self,
*,
team_id:Β str,
email:Β str,
channel_ids:Β strΒ |Β Sequence[str],
custom_message:Β strΒ |Β NoneΒ =Β None,
email_password_policy_enabled:Β boolΒ |Β NoneΒ =Β None,
guest_expiration_ts:Β strΒ |Β floatΒ |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
real_name:Β strΒ |Β NoneΒ =Β None,
resend:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_invite(
+    self,
+    *,
+    team_id: str,
+    email: str,
+    channel_ids: Union[str, Sequence[str]],
+    custom_message: Optional[str] = None,
+    email_password_policy_enabled: Optional[bool] = None,
+    guest_expiration_ts: Optional[Union[str, float]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    real_name: Optional[str] = None,
+    resend: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invite a user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.invite
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "email": email,
+            "custom_message": custom_message,
+            "email_password_policy_enabled": email_password_policy_enabled,
+            "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+            "real_name": real_name,
+            "resend": resend,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("admin.users.invite", params=kwargs)
+
+ +
+
+async def admin_users_list(self,
*,
team_id:Β strΒ |Β NoneΒ =Β None,
include_deactivated_user_workspaces:Β boolΒ |Β NoneΒ =Β None,
is_active:Β boolΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    include_deactivated_user_workspaces: Optional[bool] = None,
+    is_active: Optional[bool] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List users on a workspace
+    https://docs.slack.dev/reference/methods/admin.users.list
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+            "is_active": is_active,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("admin.users.list", params=kwargs)
+
+ +
+
+async def admin_users_remove(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_remove(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove a user from a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.remove
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return await self.api_call("admin.users.remove", params=kwargs)
+
+ +
+
+async def admin_users_session_clearSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_session_clearSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Clear user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”for a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return await self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+

Clear user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”for a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.clearSettings

+
+
+async def admin_users_session_getSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_session_getSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”given a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return await self.api_call("admin.users.session.getSettings", params=kwargs)
+
+

Get user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”given a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.getSettings

+
+
+async def admin_users_session_invalidate(self, *, session_id:Β str, team_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_session_invalidate(
+    self,
+    *,
+    session_id: str,
+    team_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invalidate a single session for a user by session_id.
+    https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+    """
+    kwargs.update({"session_id": session_id, "team_id": team_id})
+    return await self.api_call("admin.users.session.invalidate", params=kwargs)
+
+

Invalidate a single session for a user by session_id. +https://docs.slack.dev/reference/methods/admin.users.session.invalidate

+
+
+async def admin_users_session_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_session_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all active user sessions for an organization
+    https://docs.slack.dev/reference/methods/admin.users.session.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+            "user_id": user_id,
+        }
+    )
+    return await self.api_call("admin.users.session.list", params=kwargs)
+
+

Lists all active user sessions for an organization +https://docs.slack.dev/reference/methods/admin.users.session.list

+
+
+async def admin_users_session_reset(self,
*,
user_id:Β str,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_session_reset(
+    self,
+    *,
+    user_id: str,
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Wipes all valid sessions on all devices for a given user.
+    https://docs.slack.dev/reference/methods/admin.users.session.reset
+    """
+    kwargs.update(
+        {
+            "user_id": user_id,
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return await self.api_call("admin.users.session.reset", params=kwargs)
+
+

Wipes all valid sessions on all devices for a given user. +https://docs.slack.dev/reference/methods/admin.users.session.reset

+
+
+async def admin_users_session_resetBulk(self,
*,
user_ids:Β strΒ |Β Sequence[str],
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_session_resetBulk(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+    https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return await self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+

Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users +https://docs.slack.dev/reference/methods/admin.users.session.resetBulk

+
+
+async def admin_users_session_setSettings(self,
*,
user_ids:Β strΒ |Β Sequence[str],
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_session_setSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    desktop_app_browser_quit: Optional[bool] = None,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Configure the user-level session settingsβ€”the session duration
+    and what happens when the client closesβ€”for one or more users.
+    https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "desktop_app_browser_quit": desktop_app_browser_quit,
+            "duration": duration,
+        }
+    )
+    return await self.api_call("admin.users.session.setSettings", params=kwargs)
+
+

Configure the user-level session settingsβ€”the session duration +and what happens when the client closesβ€”for one or more users. +https://docs.slack.dev/reference/methods/admin.users.session.setSettings

+
+
+async def admin_users_setAdmin(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_setAdmin(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set an existing guest, regular user, or owner to be an admin user.
+    https://docs.slack.dev/reference/methods/admin.users.setAdmin
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return await self.api_call("admin.users.setAdmin", params=kwargs)
+
+

Set an existing guest, regular user, or owner to be an admin user. +https://docs.slack.dev/reference/methods/admin.users.setAdmin

+
+
+async def admin_users_setExpiration(self, *, expiration_ts:Β int, user_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_setExpiration(
+    self,
+    *,
+    expiration_ts: int,
+    user_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set an expiration for a guest user.
+    https://docs.slack.dev/reference/methods/admin.users.setExpiration
+    """
+    kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+    return await self.api_call("admin.users.setExpiration", params=kwargs)
+
+ +
+
+async def admin_users_setOwner(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_setOwner(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set an existing guest, regular user, or admin user to be a workspace owner.
+    https://docs.slack.dev/reference/methods/admin.users.setOwner
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return await self.api_call("admin.users.setOwner", params=kwargs)
+
+

Set an existing guest, regular user, or admin user to be a workspace owner. +https://docs.slack.dev/reference/methods/admin.users.setOwner

+
+
+async def admin_users_setRegular(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_users_setRegular(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set an existing guest user, admin user, or owner to be a regular user.
+    https://docs.slack.dev/reference/methods/admin.users.setRegular
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return await self.api_call("admin.users.setRegular", params=kwargs)
+
+

Set an existing guest user, admin user, or owner to be a regular user. +https://docs.slack.dev/reference/methods/admin.users.setRegular

+
+
+async def admin_users_unsupportedVersions_export(self,
*,
date_end_of_support:Β strΒ |Β intΒ |Β NoneΒ =Β None,
date_sessions_started:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_users_unsupportedVersions_export(
+    self,
+    *,
+    date_end_of_support: Optional[Union[str, int]] = None,
+    date_sessions_started: Optional[Union[str, int]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+    presented as a zipped CSV file.
+    https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+    """
+    kwargs.update(
+        {
+            "date_end_of_support": date_end_of_support,
+            "date_sessions_started": date_sessions_started,
+        }
+    )
+    return await self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+

Ask Slackbot to send you an export listing all workspace members using unsupported software, +presented as a zipped CSV file. +https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export

+
+
+async def admin_workflows_collaborators_add(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_workflows_collaborators_add(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add collaborators to workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return await self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+

Add collaborators to workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add

+
+
+async def admin_workflows_collaborators_remove(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_workflows_collaborators_remove(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove collaborators from workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return await self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+

Remove collaborators from workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove

+
+
+async def admin_workflows_permissions_lookup(self,
*,
workflow_ids:Β strΒ |Β Sequence[str],
max_workflow_triggers:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def admin_workflows_permissions_lookup(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    max_workflow_triggers: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Look up the permissions for a set of workflows
+    https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    kwargs.update(
+        {
+            "max_workflow_triggers": max_workflow_triggers,
+        }
+    )
+    return await self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
async def admin_workflows_search(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    no_collaborators: Optional[bool] = None,
+    num_trigger_ids: Optional[int] = None,
+    query: Optional[str] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    source: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Search workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.search
+    """
+    if collaborator_ids is not None:
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "cursor": cursor,
+            "limit": limit,
+            "no_collaborators": no_collaborators,
+            "num_trigger_ids": num_trigger_ids,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "source": source,
+        }
+    )
+    return await self.api_call("admin.workflows.search", params=kwargs)
+
+

Search workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.search

+
+
+async def admin_workflows_unpublish(self, *, workflow_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def admin_workflows_unpublish(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Unpublish workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return await self.api_call("admin.workflows.unpublish", params=kwargs)
+
+

Unpublish workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.unpublish

+
+
+async def api_test(self, *, error:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def api_test(
+    self,
+    *,
+    error: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Checks API calling code.
+    https://docs.slack.dev/reference/methods/api.test
+    """
+    kwargs.update({"error": error})
+    return await self.api_call("api.test", params=kwargs)
+
+ +
+
+async def apps_connections_open(self, *, app_token:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_connections_open(
+    self,
+    *,
+    app_token: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+    in order to receive events and interactive payloads
+    https://docs.slack.dev/reference/methods/apps.connections.open
+    """
+    kwargs.update({"token": app_token})
+    return await self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+

Generate a temporary Socket Mode WebSocket URL that your app can connect to +in order to receive events and interactive payloads +https://docs.slack.dev/reference/methods/apps.connections.open

+
+
+async def apps_event_authorizations_list(self,
*,
event_context:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def apps_event_authorizations_list(
+    self,
+    *,
+    event_context: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get a list of authorizations for the given event context.
+    Each authorization represents an app installation that the event is visible to.
+    https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+    """
+    kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+    return await self.api_call("apps.event.authorizations.list", params=kwargs)
+
+

Get a list of authorizations for the given event context. +Each authorization represents an app installation that the event is visible to. +https://docs.slack.dev/reference/methods/apps.event.authorizations.list

+
+
+async def apps_manifest_create(self, *, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_manifest_create(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.create
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    return await self.api_call("apps.manifest.create", params=kwargs)
+
+ +
+
+async def apps_manifest_delete(self, *, app_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_manifest_delete(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Permanently deletes an app created through app manifests
+    https://docs.slack.dev/reference/methods/apps.manifest.delete
+    """
+    kwargs.update({"app_id": app_id})
+    return await self.api_call("apps.manifest.delete", params=kwargs)
+
+

Permanently deletes an app created through app manifests +https://docs.slack.dev/reference/methods/apps.manifest.delete

+
+
+async def apps_manifest_export(self, *, app_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_manifest_export(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Export an app manifest from an existing app
+    https://docs.slack.dev/reference/methods/apps.manifest.export
+    """
+    kwargs.update({"app_id": app_id})
+    return await self.api_call("apps.manifest.export", params=kwargs)
+
+

Export an app manifest from an existing app +https://docs.slack.dev/reference/methods/apps.manifest.export

+
+
+async def apps_manifest_update(self, *, app_id:Β str, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_manifest_update(
+    self,
+    *,
+    app_id: str,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.update
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return await self.api_call("apps.manifest.update", params=kwargs)
+
+ +
+
+async def apps_manifest_validate(self, *, manifest:Β strΒ |Β Dict[str,Β Any], app_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_manifest_validate(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    app_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Validate an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.validate
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return await self.api_call("apps.manifest.validate", params=kwargs)
+
+ +
+
+async def apps_uninstall(self, *, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def apps_uninstall(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Uninstalls your app from a workspace.
+    https://docs.slack.dev/reference/methods/apps.uninstall
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret})
+    return await self.api_call("apps.uninstall", params=kwargs)
+
+

Uninstalls your app from a workspace. +https://docs.slack.dev/reference/methods/apps.uninstall

+
+
+async def assistant_threads_setStatus(self,
*,
channel_id:Β str,
thread_ts:Β str,
status:Β str,
loading_messages:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def assistant_threads_setStatus(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    status: str,
+    loading_messages: Optional[List[str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the status for an AI assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+    """
+    kwargs.update(
+        {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("assistant.threads.setStatus", json=kwargs)
+
+ +
+
+async def assistant_threads_setSuggestedPrompts(self,
*,
channel_id:Β str,
thread_ts:Β str,
title:Β strΒ |Β NoneΒ =Β None,
prompts:Β List[Dict[str,Β str]],
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def assistant_threads_setSuggestedPrompts(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: Optional[str] = None,
+    prompts: List[Dict[str, str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set suggested prompts for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+    if title is not None:
+        kwargs.update({"title": title})
+    return await self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+

Set suggested prompts for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts

+
+
+async def assistant_threads_setTitle(self, *, channel_id:Β str, thread_ts:Β str, title:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def assistant_threads_setTitle(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the title for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+    return await self.api_call("assistant.threads.setTitle", params=kwargs)
+
+

Set the title for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setTitle

+
+
+async def auth_revoke(self, *, test:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def auth_revoke(
+    self,
+    *,
+    test: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Revokes a token.
+    https://docs.slack.dev/reference/methods/auth.revoke
+    """
+    kwargs.update({"test": test})
+    return await self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+ +
+
+async def auth_teams_list(self,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
include_icon:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def auth_teams_list(
+    self,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    include_icon: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List the workspaces a token can access.
+    https://docs.slack.dev/reference/methods/auth.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+    return await self.api_call("auth.teams.list", params=kwargs)
+
+

List the workspaces a token can access. +https://docs.slack.dev/reference/methods/auth.teams.list

+
+
+async def auth_test(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def auth_test(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Checks authentication & identity.
+    https://docs.slack.dev/reference/methods/auth.test
+    """
+    return await self.api_call("auth.test", params=kwargs)
+
+

Checks authentication & identity. +https://docs.slack.dev/reference/methods/auth.test

+
+
+async def bookmarks_add(self,
*,
channel_id:Β str,
title:Β str,
type:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
entity_id:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
parent_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def bookmarks_add(
+    self,
+    *,
+    channel_id: str,
+    title: str,
+    type: str,
+    emoji: Optional[str] = None,
+    entity_id: Optional[str] = None,
+    link: Optional[str] = None,  # include when type is 'link'
+    parent_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add bookmark to a channel.
+    https://docs.slack.dev/reference/methods/bookmarks.add
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "title": title,
+            "type": type,
+            "emoji": emoji,
+            "entity_id": entity_id,
+            "link": link,
+            "parent_id": parent_id,
+        }
+    )
+    return await self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+ +
+
+async def bookmarks_edit(self,
*,
bookmark_id:Β str,
channel_id:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def bookmarks_edit(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    emoji: Optional[str] = None,
+    link: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Edit bookmark.
+    https://docs.slack.dev/reference/methods/bookmarks.edit
+    """
+    kwargs.update(
+        {
+            "bookmark_id": bookmark_id,
+            "channel_id": channel_id,
+            "emoji": emoji,
+            "link": link,
+            "title": title,
+        }
+    )
+    return await self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+ +
+
+async def bookmarks_list(self, *, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def bookmarks_list(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List bookmark for the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.list
+    """
+    kwargs.update({"channel_id": channel_id})
+    return await self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+ +
+
+async def bookmarks_remove(self, *, bookmark_id:Β str, channel_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def bookmarks_remove(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove bookmark from the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.remove
+    """
+    kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+    return await self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+ +
+
+async def bots_info(self, *, bot:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def bots_info(
+    self,
+    *,
+    bot: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a bot user.
+    https://docs.slack.dev/reference/methods/bots.info
+    """
+    kwargs.update({"bot": bot, "team_id": team_id})
+    return await self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+

Gets information about a bot user. +https://docs.slack.dev/reference/methods/bots.info

+
+
+async def calls_add(self,
*,
external_unique_id:Β str,
join_url:Β str,
created_by:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
external_display_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def calls_add(
+    self,
+    *,
+    external_unique_id: str,
+    join_url: str,
+    created_by: Optional[str] = None,
+    date_start: Optional[int] = None,
+    desktop_app_join_url: Optional[str] = None,
+    external_display_id: Optional[str] = None,
+    title: Optional[str] = None,
+    users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Registers a new Call.
+    https://docs.slack.dev/reference/methods/calls.add
+    """
+    kwargs.update(
+        {
+            "external_unique_id": external_unique_id,
+            "join_url": join_url,
+            "created_by": created_by,
+            "date_start": date_start,
+            "desktop_app_join_url": desktop_app_join_url,
+            "external_display_id": external_display_id,
+            "title": title,
+        }
+    )
+    _update_call_participants(
+        kwargs,
+        users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+    )
+    return await self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+ +
+
+async def calls_end(self, *, id:Β str, duration:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def calls_end(
+    self,
+    *,
+    id: str,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Ends a Call.
+    https://docs.slack.dev/reference/methods/calls.end
+    """
+    kwargs.update({"id": id, "duration": duration})
+    return await self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+ +
+
+async def calls_info(self, *, id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def calls_info(
+    self,
+    *,
+    id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Returns information about a Call.
+    https://docs.slack.dev/reference/methods/calls.info
+    """
+    kwargs.update({"id": id})
+    return await self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+

Returns information about a Call. +https://docs.slack.dev/reference/methods/calls.info

+
+
+async def calls_participants_add(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def calls_participants_add(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Registers new participants added to a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.add
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return await self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+

Registers new participants added to a Call. +https://docs.slack.dev/reference/methods/calls.participants.add

+
+
+async def calls_participants_remove(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def calls_participants_remove(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Registers participants removed from a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.remove
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return await self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+

Registers participants removed from a Call. +https://docs.slack.dev/reference/methods/calls.participants.remove

+
+
+async def calls_update(self,
*,
id:Β str,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
join_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def calls_update(
+    self,
+    *,
+    id: str,
+    desktop_app_join_url: Optional[str] = None,
+    join_url: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Updates information about a Call.
+    https://docs.slack.dev/reference/methods/calls.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "desktop_app_join_url": desktop_app_join_url,
+            "join_url": join_url,
+            "title": title,
+        }
+    )
+    return await self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+ +
+
+async def canvases_access_delete(self,
*,
canvas_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def canvases_access_delete(
+    self,
+    *,
+    canvas_id: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/canvases.access.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return await self.api_call("canvases.access.delete", params=kwargs)
+
+ +
+
+async def canvases_access_set(self,
*,
canvas_id:Β str,
access_level:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def canvases_access_set(
+    self,
+    *,
+    canvas_id: str,
+    access_level: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the access level to a canvas for specified entities
+    https://docs.slack.dev/reference/methods/canvases.access.set
+    """
+    kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+
+    return await self.api_call("canvases.access.set", params=kwargs)
+
+

Sets the access level to a canvas for specified entities +https://docs.slack.dev/reference/methods/canvases.access.set

+
+
+async def canvases_create(self, *, title:Β strΒ |Β NoneΒ =Β None, document_content:Β Dict[str,Β str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def canvases_create(
+    self,
+    *,
+    title: Optional[str] = None,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create Canvas for a user
+    https://docs.slack.dev/reference/methods/canvases.create
+    """
+    kwargs.update({"title": title, "document_content": document_content})
+    return await self.api_call("canvases.create", json=kwargs)
+
+ +
+
+async def canvases_delete(self, *, canvas_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def canvases_delete(
+    self,
+    *,
+    canvas_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes a canvas
+    https://docs.slack.dev/reference/methods/canvases.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    return await self.api_call("canvases.delete", params=kwargs)
+
+ +
+
+async def canvases_edit(self, *, canvas_id:Β str, changes:Β Sequence[Dict[str,Β Any]], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def canvases_edit(
+    self,
+    *,
+    canvas_id: str,
+    changes: Sequence[Dict[str, Any]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update an existing canvas
+    https://docs.slack.dev/reference/methods/canvases.edit
+    """
+    kwargs.update({"canvas_id": canvas_id, "changes": changes})
+    return await self.api_call("canvases.edit", json=kwargs)
+
+ +
+
+async def canvases_sections_lookup(self, *, canvas_id:Β str, criteria:Β Dict[str,Β Any], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def canvases_sections_lookup(
+    self,
+    *,
+    canvas_id: str,
+    criteria: Dict[str, Any],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Find sections matching the provided criteria
+    https://docs.slack.dev/reference/methods/canvases.sections.lookup
+    """
+    kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+    return await self.api_call("canvases.sections.lookup", params=kwargs)
+
+

Find sections matching the provided criteria +https://docs.slack.dev/reference/methods/canvases.sections.lookup

+
+
+async def channels_archive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Archives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.archive", json=kwargs)
+
+

Archives a channel.

+
+
+async def channels_create(self, *, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Creates a channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.create", json=kwargs)
+
+

Creates a channel.

+
+
+async def channels_history(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetches history of messages and events from a channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a channel.

+
+
+async def channels_info(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+

Gets information about a channel.

+
+
+async def channels_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invites a user to a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.invite", json=kwargs)
+
+

Invites a user to a channel.

+
+
+async def channels_join(self, *, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_join(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Joins a channel, creating it if needed."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.join", json=kwargs)
+
+

Joins a channel, creating it if needed.

+
+
+async def channels_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a user from a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.kick", json=kwargs)
+
+

Removes a user from a channel.

+
+
+async def channels_leave(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Leaves a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.leave", json=kwargs)
+
+

Leaves a channel.

+
+
+async def channels_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all channels in a Slack team."""
+    return await self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+

Lists all channels in a Slack team.

+
+
+async def channels_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the read cursor in a channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.mark", json=kwargs)
+
+

Sets the read cursor in a channel.

+
+
+async def channels_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Renames a channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.rename", json=kwargs)
+
+

Renames a channel.

+
+
+async def channels_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a thread of messages posted to a channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return await self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a channel

+
+
+async def channels_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the purpose for a channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.setPurpose", json=kwargs)
+
+

Sets the purpose for a channel.

+
+
+async def channels_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the topic for a channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.setTopic", json=kwargs)
+
+

Sets the topic for a channel.

+
+
+async def channels_unarchive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def channels_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Unarchives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("channels.unarchive", json=kwargs)
+
+

Unarchives a channel.

+
+
+async def chat_appendStream(self, *, channel:Β str, ts:Β str, markdown_text:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def chat_appendStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Appends text to an existing streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.appendStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("chat.appendStream", json=kwargs)
+
+

Appends text to an existing streaming conversation. +https://docs.slack.dev/reference/methods/chat.appendStream

+
+
+async def chat_delete(self, *, channel:Β str, ts:Β str, as_user:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def chat_delete(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes a message.
+    https://docs.slack.dev/reference/methods/chat.delete
+    """
+    kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+    return await self.api_call("chat.delete", params=kwargs)
+
+ +
+
+async def chat_deleteScheduledMessage(self,
*,
channel:Β str,
scheduled_message_id:Β str,
as_user:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_deleteScheduledMessage(
+    self,
+    *,
+    channel: str,
+    scheduled_message_id: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes a scheduled message.
+    https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "scheduled_message_id": scheduled_message_id,
+            "as_user": as_user,
+        }
+    )
+    return await self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
async def chat_getPermalink(
+    self,
+    *,
+    channel: str,
+    message_ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a permalink URL for a specific extant message
+    https://docs.slack.dev/reference/methods/chat.getPermalink
+    """
+    kwargs.update({"channel": channel, "message_ts": message_ts})
+    return await self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+

Retrieve a permalink URL for a specific extant message +https://docs.slack.dev/reference/methods/chat.getPermalink

+
+
+async def chat_meMessage(self, *, channel:Β str, text:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def chat_meMessage(
+    self,
+    *,
+    channel: str,
+    text: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Share a me message into a channel.
+    https://docs.slack.dev/reference/methods/chat.meMessage
+    """
+    kwargs.update({"channel": channel, "text": text})
+    return await self.api_call("chat.meMessage", params=kwargs)
+
+ +
+
+async def chat_postEphemeral(self,
*,
channel:Β str,
user:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_postEphemeral(
+    self,
+    *,
+    channel: str,
+    user: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sends an ephemeral message to a user in a channel.
+    https://docs.slack.dev/reference/methods/chat.postEphemeral
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "user": user,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return await self.api_call("chat.postEphemeral", json=kwargs)
+
+

Sends an ephemeral message to a user in a channel. +https://docs.slack.dev/reference/methods/chat.postEphemeral

+
+
+async def chat_postMessage(self,
*,
channel:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
container_id:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
mrkdwn:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_postMessage(
+    self,
+    *,
+    channel: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    container_id: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    mrkdwn: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,  # none, full
+    metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sends a message to a channel.
+    https://docs.slack.dev/reference/methods/chat.postMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "container_id": container_id,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "mrkdwn": mrkdwn,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return await self.api_call("chat.postMessage", json=kwargs)
+
+ +
+
+async def chat_scheduleMessage(self,
*,
channel:Β str,
post_at:Β strΒ |Β int,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_scheduleMessage(
+    self,
+    *,
+    channel: str,
+    post_at: Union[str, int],
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    parse: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Schedules a message.
+    https://docs.slack.dev/reference/methods/chat.scheduleMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "post_at": post_at,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "parse": parse,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "link_names": link_names,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return await self.api_call("chat.scheduleMessage", json=kwargs)
+
+ +
+
+async def chat_scheduledMessages_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_scheduledMessages_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all scheduled messages.
+    https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "latest": latest,
+            "limit": limit,
+            "oldest": oldest,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+ +
+
+async def chat_startStream(self,
*,
channel:Β str,
thread_ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_startStream(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    markdown_text: Optional[str] = None,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Starts a new streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.startStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "markdown_text": markdown_text,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("chat.startStream", json=kwargs)
+
+

Starts a new streaming conversation. +https://docs.slack.dev/reference/methods/chat.startStream

+
+
+async def chat_stopStream(self,
*,
channel:Β str,
ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_stopStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Stops a streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.stopStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+            "blocks": blocks,
+            "metadata": metadata,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("chat.stopStream", json=kwargs)
+
+ +
+
+async def chat_stream(self,
*,
buffer_size:Β intΒ =Β 256,
channel:Β str,
thread_ts:Β str,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncChatStream
+
+
+
+ +Expand source code + +
async def chat_stream(
+    self,
+    *,
+    buffer_size: int = 256,
+    channel: str,
+    thread_ts: str,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncChatStream:
+    """Stream markdown text into a conversation.
+
+    This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+    the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+    The following methods are used:
+
+    - chat.startStream: Starts a new streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+    - chat.appendStream: Appends text to an existing streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+    - chat.stopStream: Stops a streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+    Args:
+        buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+          value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+          limits. Default: 256.
+        channel: An encoded ID that represents a channel, private group, or DM.
+        thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+          request.
+        recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+          streaming to channels.
+        recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        ChatStream instance for managing the stream
+
+    Example:
+        ```python
+        streamer = await client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        await streamer.append(markdown_text="**hello wo")
+        await streamer.append(markdown_text="rld!**")
+        await streamer.stop()
+        ```
+    """
+    return AsyncChatStream(
+        self,
+        logger=self._logger,
+        channel=channel,
+        thread_ts=thread_ts,
+        recipient_team_id=recipient_team_id,
+        recipient_user_id=recipient_user_id,
+        buffer_size=buffer_size,
+        **kwargs,
+    )
+
+

Stream markdown text into a conversation.

+

This method starts a new chat stream in a conversation that can be appended to. After appending an entire message, +the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.

+

The following methods are used:

+
    +
  • chat.startStream: Starts a new streaming conversation. +Reference.
  • +
  • chat.appendStream: Appends text to an existing streaming conversation. +Reference.
  • +
  • chat.stopStream: Stops a streaming conversation. +Reference.
  • +
+

Args

+
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a stream method. Increasing this +value decreases the number of method calls made for the same amount of text, which is useful to avoid rate +limits. Default: 256.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

ChatStream instance for managing the stream

+

Example

+
streamer = await client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+await streamer.append(markdown_text="**hello wo")
+await streamer.append(markdown_text="rld!**")
+await streamer.stop()
+
+
+
+async def chat_unfurl(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
ts:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
unfurl_id:Β strΒ |Β NoneΒ =Β None,
unfurls:Β Dict[str,Β Dict]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
user_auth_blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
user_auth_message:Β strΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_unfurl(
+    self,
+    *,
+    channel: Optional[str] = None,
+    ts: Optional[str] = None,
+    source: Optional[str] = None,
+    unfurl_id: Optional[str] = None,
+    unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+    metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+    user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    user_auth_message: Optional[str] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Provide custom unfurl behavior for user-posted URLs.
+    https://docs.slack.dev/reference/methods/chat.unfurl
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "source": source,
+            "unfurl_id": unfurl_id,
+            "unfurls": unfurls,
+            "metadata": metadata,
+            "user_auth_blocks": user_auth_blocks,
+            "user_auth_message": user_auth_message,
+            "user_auth_required": user_auth_required,
+            "user_auth_url": user_auth_url,
+        }
+    )
+    _parse_web_class_objects(kwargs)  # for user_auth_blocks
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return await self.api_call("chat.unfurl", json=kwargs)
+
+

Provide custom unfurl behavior for user-posted URLs. +https://docs.slack.dev/reference/methods/chat.unfurl

+
+
+async def chat_update(self,
*,
channel:Β str,
ts:Β str,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
file_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def chat_update(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    text: Optional[str] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    as_user: Optional[bool] = None,
+    file_ids: Optional[Union[str, Sequence[str]]] = None,
+    link_names: Optional[bool] = None,
+    parse: Optional[str] = None,  # none, full
+    reply_broadcast: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Updates a message in a channel.
+    https://docs.slack.dev/reference/methods/chat.update
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "as_user": as_user,
+            "link_names": link_names,
+            "parse": parse,
+            "reply_broadcast": reply_broadcast,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    if isinstance(file_ids, (list, tuple)):
+        kwargs.update({"file_ids": ",".join(file_ids)})
+    else:
+        kwargs.update({"file_ids": file_ids})
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.update", kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return await self.api_call("chat.update", json=kwargs)
+
+ +
+
+async def conversations_acceptSharedInvite(self,
*,
channel_name:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
free_trial_accepted:Β boolΒ |Β NoneΒ =Β None,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_acceptSharedInvite(
+    self,
+    *,
+    channel_name: str,
+    channel_id: Optional[str] = None,
+    invite_id: Optional[str] = None,
+    free_trial_accepted: Optional[bool] = None,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Accepts an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+    """
+    if channel_id is None and invite_id is None:
+        raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+    kwargs.update(
+        {
+            "channel_name": channel_name,
+            "channel_id": channel_id,
+            "invite_id": invite_id,
+            "free_trial_accepted": free_trial_accepted,
+            "is_private": is_private,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+

Accepts an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite

+
+
+async def conversations_approveSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_approveSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Approves an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return await self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+

Approves an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.approveSharedInvite

+
+
+async def conversations_archive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Archives a conversation.
+    https://docs.slack.dev/reference/methods/conversations.archive
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("conversations.archive", params=kwargs)
+
+ +
+
+async def conversations_canvases_create(self, *, channel_id:Β str, document_content:Β Dict[str,Β str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_canvases_create(
+    self,
+    *,
+    channel_id: str,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/conversations.canvases.create
+    """
+    kwargs.update({"channel_id": channel_id, "document_content": document_content})
+    return await self.api_call("conversations.canvases.create", json=kwargs)
+
+ +
+
+async def conversations_close(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Closes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.close
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("conversations.close", params=kwargs)
+
+

Closes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.close

+
+
+async def conversations_create(self,
*,
name:Β str,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_create(
+    self,
+    *,
+    name: str,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Initiates a public or private channel-based conversation
+    https://docs.slack.dev/reference/methods/conversations.create
+    """
+    kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+    return await self.api_call("conversations.create", params=kwargs)
+
+

Initiates a public or private channel-based conversation +https://docs.slack.dev/reference/methods/conversations.create

+
+
+async def conversations_declineSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_declineSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Declines a Slack Connect channel invite.
+    https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return await self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+ +
+
+async def conversations_externalInvitePermissions_set(self, *, action:Β str, channel:Β str, target_team:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_externalInvitePermissions_set(
+    self, *, action: str, channel: str, target_team: str, **kwargs
+) -> AsyncSlackResponse:
+    """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+    https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+    """
+    kwargs.update(
+        {
+            "action": action,
+            "channel": channel,
+            "target_team": target_team,
+        }
+    )
+    return await self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+

Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa. +https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set

+
+
+async def conversations_history(self,
*,
channel:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_history(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetches a conversation's history of messages and events.
+    https://docs.slack.dev/reference/methods/conversations.history
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return await self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+

Fetches a conversation's history of messages and events. +https://docs.slack.dev/reference/methods/conversations.history

+
+
+async def conversations_info(self,
*,
channel:Β str,
include_locale:Β boolΒ |Β NoneΒ =Β None,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_info(
+    self,
+    *,
+    channel: str,
+    include_locale: Optional[bool] = None,
+    include_num_members: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve information about a conversation.
+    https://docs.slack.dev/reference/methods/conversations.info
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "include_locale": include_locale,
+            "include_num_members": include_num_members,
+        }
+    )
+    return await self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a conversation. +https://docs.slack.dev/reference/methods/conversations.info

+
+
+async def conversations_invite(self,
*,
channel:Β str,
users:Β strΒ |Β Sequence[str],
force:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_invite(
+    self,
+    *,
+    channel: str,
+    users: Union[str, Sequence[str]],
+    force: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invites users to a channel.
+    https://docs.slack.dev/reference/methods/conversations.invite
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "force": force,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return await self.api_call("conversations.invite", params=kwargs)
+
+ +
+
+async def conversations_inviteShared(self,
*,
channel:Β str,
emails:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_inviteShared(
+    self,
+    *,
+    channel: str,
+    emails: Optional[Union[str, Sequence[str]]] = None,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sends an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.inviteShared
+    """
+    if emails is None and user_ids is None:
+        raise e.SlackRequestError("Either emails or user ids must be provided.")
+    kwargs.update({"channel": channel})
+    if isinstance(emails, (list, tuple)):
+        kwargs.update({"emails": ",".join(emails)})
+    else:
+        kwargs.update({"emails": emails})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return await self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+

Sends an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.inviteShared

+
+
+async def conversations_join(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_join(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Joins an existing conversation.
+    https://docs.slack.dev/reference/methods/conversations.join
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("conversations.join", params=kwargs)
+
+ +
+
+async def conversations_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a user from a conversation.
+    https://docs.slack.dev/reference/methods/conversations.kick
+    """
+    kwargs.update({"channel": channel, "user": user})
+    return await self.api_call("conversations.kick", params=kwargs)
+
+ +
+
+async def conversations_leave(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Leaves a conversation.
+    https://docs.slack.dev/reference/methods/conversations.leave
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("conversations.leave", params=kwargs)
+
+ +
+
+async def conversations_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all channels in a Slack team.
+    https://docs.slack.dev/reference/methods/conversations.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return await self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def conversations_listConnectInvites(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_listConnectInvites(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List shared channel invites that have been generated
+    or received but have not yet been approved by all parties.
+    https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+    """
+    kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+    return await self.api_call("conversations.listConnectInvites", params=kwargs)
+
+

List shared channel invites that have been generated +or received but have not yet been approved by all parties. +https://docs.slack.dev/reference/methods/conversations.listConnectInvites

+
+
+async def conversations_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the read cursor in a channel.
+    https://docs.slack.dev/reference/methods/conversations.mark
+    """
+    kwargs.update({"channel": channel, "ts": ts})
+    return await self.api_call("conversations.mark", params=kwargs)
+
+ +
+
+async def conversations_members(self, *, channel:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_members(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve members of a conversation.
+    https://docs.slack.dev/reference/methods/conversations.members
+    """
+    kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+    return await self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+ +
+
+async def conversations_open(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
return_im:Β boolΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_open(
+    self,
+    *,
+    channel: Optional[str] = None,
+    return_im: Optional[bool] = None,
+    users: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Opens or resumes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.open
+    """
+    if channel is None and users is None:
+        raise e.SlackRequestError("Either channel or users must be provided.")
+    kwargs.update({"channel": channel, "return_im": return_im})
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return await self.api_call("conversations.open", params=kwargs)
+
+

Opens or resumes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.open

+
+
+async def conversations_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Renames a conversation.
+    https://docs.slack.dev/reference/methods/conversations.rename
+    """
+    kwargs.update({"channel": channel, "name": name})
+    return await self.api_call("conversations.rename", params=kwargs)
+
+ +
+
+async def conversations_replies(self,
*,
channel:Β str,
ts:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_replies(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a thread of messages posted to a conversation
+    https://docs.slack.dev/reference/methods/conversations.replies
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return await self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a conversation +https://docs.slack.dev/reference/methods/conversations.replies

+
+
+async def conversations_requestSharedInvite_approve(self,
*,
invite_id:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
is_external_limited:Β strΒ |Β NoneΒ =Β None,
message:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_requestSharedInvite_approve(
+    self,
+    *,
+    invite_id: str,
+    channel_id: Optional[str] = None,
+    is_external_limited: Optional[str] = None,
+    message: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+    """
+    kwargs.update(
+        {
+            "invite_id": invite_id,
+            "channel_id": channel_id,
+            "is_external_limited": is_external_limited,
+        }
+    )
+    if message is not None:
+        kwargs.update({"message": json.dumps(message)})
+    return await self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+

Approve a request to add an external user to a channel. This also sends them a Slack Connect invite. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve

+
+
+async def conversations_requestSharedInvite_deny(self, *, invite_id:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_requestSharedInvite_deny(
+    self,
+    *,
+    invite_id: str,
+    message: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deny a request to invite an external user to a channel.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+    """
+    kwargs.update({"invite_id": invite_id, "message": message})
+    return await self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+

Deny a request to invite an external user to a channel. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny

+
+
+async def conversations_requestSharedInvite_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_approved:Β boolΒ |Β NoneΒ =Β None,
include_denied:Β boolΒ |Β NoneΒ =Β None,
include_expired:Β boolΒ |Β NoneΒ =Β None,
invite_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def conversations_requestSharedInvite_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_approved: Optional[bool] = None,
+    include_denied: Optional[bool] = None,
+    include_expired: Optional[bool] = None,
+    invite_ids: Optional[Union[str, Sequence[str]]] = None,
+    limit: Optional[int] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists requests to add external users to channels with ability to filter.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_approved": include_approved,
+            "include_denied": include_denied,
+            "include_expired": include_expired,
+            "limit": limit,
+            "user_id": user_id,
+        }
+    )
+    if invite_ids is not None:
+        if isinstance(invite_ids, (list, tuple)):
+            kwargs.update({"invite_ids": ",".join(invite_ids)})
+        else:
+            kwargs.update({"invite_ids": invite_ids})
+    return await self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+

Lists requests to add external users to channels with ability to filter. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list

+
+
+async def conversations_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the purpose for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setPurpose
+    """
+    kwargs.update({"channel": channel, "purpose": purpose})
+    return await self.api_call("conversations.setPurpose", params=kwargs)
+
+ +
+
+async def conversations_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the topic for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setTopic
+    """
+    kwargs.update({"channel": channel, "topic": topic})
+    return await self.api_call("conversations.setTopic", params=kwargs)
+
+ +
+
+async def conversations_unarchive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def conversations_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Reverses conversation archival.
+    https://docs.slack.dev/reference/methods/conversations.unarchive
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("conversations.unarchive", params=kwargs)
+
+ +
+
+async def dialog_open(self, *, dialog:Β Dict[str,Β Any], trigger_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dialog_open(
+    self,
+    *,
+    dialog: Dict[str, Any],
+    trigger_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Open a dialog with a user.
+    https://docs.slack.dev/reference/methods/dialog.open
+    """
+    kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: As the dialog can be a dict, this API call works only with json format.
+    return await self.api_call("dialog.open", json=kwargs)
+
+ +
+
+async def dnd_endDnd(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dnd_endDnd(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Ends the current user's Do Not Disturb session immediately.
+    https://docs.slack.dev/reference/methods/dnd.endDnd
+    """
+    return await self.api_call("dnd.endDnd", params=kwargs)
+
+

Ends the current user's Do Not Disturb session immediately. +https://docs.slack.dev/reference/methods/dnd.endDnd

+
+
+async def dnd_endSnooze(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dnd_endSnooze(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Ends the current user's snooze mode immediately.
+    https://docs.slack.dev/reference/methods/dnd.endSnooze
+    """
+    return await self.api_call("dnd.endSnooze", params=kwargs)
+
+

Ends the current user's snooze mode immediately. +https://docs.slack.dev/reference/methods/dnd.endSnooze

+
+
+async def dnd_info(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dnd_info(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieves a user's current Do Not Disturb status.
+    https://docs.slack.dev/reference/methods/dnd.info
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return await self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+

Retrieves a user's current Do Not Disturb status. +https://docs.slack.dev/reference/methods/dnd.info

+
+
+async def dnd_setSnooze(self, *, num_minutes:Β strΒ |Β int, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dnd_setSnooze(
+    self,
+    *,
+    num_minutes: Union[int, str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Turns on Do Not Disturb mode for the current user, or changes its duration.
+    https://docs.slack.dev/reference/methods/dnd.setSnooze
+    """
+    kwargs.update({"num_minutes": num_minutes})
+    return await self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+

Turns on Do Not Disturb mode for the current user, or changes its duration. +https://docs.slack.dev/reference/methods/dnd.setSnooze

+
+
+async def dnd_teamInfo(self, users:Β strΒ |Β Sequence[str], team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def dnd_teamInfo(
+    self,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieves the Do Not Disturb status for users on a team.
+    https://docs.slack.dev/reference/methods/dnd.teamInfo
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id})
+    return await self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+

Retrieves the Do Not Disturb status for users on a team. +https://docs.slack.dev/reference/methods/dnd.teamInfo

+
+
+async def emoji_list(self, include_categories:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def emoji_list(
+    self,
+    include_categories: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists custom emoji for a team.
+    https://docs.slack.dev/reference/methods/emoji.list
+    """
+    kwargs.update({"include_categories": include_categories})
+    return await self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def entity_presentDetails(self,
trigger_id:Β str,
metadata:Β DictΒ |Β EntityMetadataΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def entity_presentDetails(
+    self,
+    trigger_id: str,
+    metadata: Optional[Union[Dict, EntityMetadata]] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    error: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Provides entity details for the flexpane.
+    https://docs.slack.dev/reference/methods/entity.presentDetails/
+    """
+    kwargs.update({"trigger_id": trigger_id})
+    if metadata is not None:
+        kwargs.update({"metadata": metadata})
+    if user_auth_required is not None:
+        kwargs.update({"user_auth_required": user_auth_required})
+    if user_auth_url is not None:
+        kwargs.update({"user_auth_url": user_auth_url})
+    if error is not None:
+        kwargs.update({"error": error})
+    _parse_web_class_objects(kwargs)
+    return await self.api_call("entity.presentDetails", json=kwargs)
+
+

Provides entity details for the flexpane. +https://docs.slack.dev/reference/methods/entity.presentDetails/

+
+
+async def files_comments_delete(self, *, file:Β str, id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_comments_delete(
+    self,
+    *,
+    file: str,
+    id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes an existing comment on a file.
+    https://docs.slack.dev/reference/methods/files.comments.delete
+    """
+    kwargs.update({"file": file, "id": id})
+    return await self.api_call("files.comments.delete", params=kwargs)
+
+ +
+
+async def files_completeUploadExternal(self,
*,
files:Β List[Dict[str,Β str]],
channel_id:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_completeUploadExternal(
+    self,
+    *,
+    files: List[Dict[str, str]],
+    channel_id: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Finishes an upload started with files.getUploadURLExternal.
+    https://docs.slack.dev/reference/methods/files.completeUploadExternal
+    """
+    _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+    kwargs.update(
+        {
+            "files": json.dumps(_files),
+            "channel_id": channel_id,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+        }
+    )
+    if channels:
+        kwargs["channels"] = ",".join(channels)
+    return await self.api_call("files.completeUploadExternal", params=kwargs)
+
+

Finishes an upload started with files.getUploadURLExternal. +https://docs.slack.dev/reference/methods/files.completeUploadExternal

+
+
+async def files_delete(self, *, file:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_delete(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes a file.
+    https://docs.slack.dev/reference/methods/files.delete
+    """
+    kwargs.update({"file": file})
+    return await self.api_call("files.delete", params=kwargs)
+
+ +
+
+async def files_getUploadURLExternal(self,
*,
filename:Β str,
length:Β int,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_getUploadURLExternal(
+    self,
+    *,
+    filename: str,
+    length: int,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets a URL for an edge external upload.
+    https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+    """
+    kwargs.update(
+        {
+            "filename": filename,
+            "length": length,
+            "alt_txt": alt_txt,
+            "snippet_type": snippet_type,
+        }
+    )
+    return await self.api_call("files.getUploadURLExternal", params=kwargs)
+
+ +
+
+async def files_info(self,
*,
file:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_info(
+    self,
+    *,
+    file: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a team file.
+    https://docs.slack.dev/reference/methods/files.info
+    """
+    kwargs.update(
+        {
+            "file": file,
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+        }
+    )
+    return await self.api_call("files.info", http_verb="GET", params=kwargs)
+
+

Gets information about a team file. +https://docs.slack.dev/reference/methods/files.info

+
+
+async def files_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
count:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
show_files_hidden_by_limit:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    count: Optional[int] = None,
+    page: Optional[int] = None,
+    show_files_hidden_by_limit: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists & filters team files.
+    https://docs.slack.dev/reference/methods/files.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "count": count,
+            "page": page,
+            "show_files_hidden_by_limit": show_files_hidden_by_limit,
+            "team_id": team_id,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return await self.api_call("files.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def files_remote_add(self,
*,
external_id:Β str,
external_url:Β str,
title:Β str,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_remote_add(
+    self,
+    *,
+    external_id: str,
+    external_url: str,
+    title: str,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+    preview_image: Optional[Union[str, bytes, IOBase]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Adds a file from a remote service.
+    https://docs.slack.dev/reference/methods/files.remote.add
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return await self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.add",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+async def files_remote_info(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_remote_info(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.info
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return await self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.info

+
+
+async def files_remote_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_remote_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "limit": limit,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+        }
+    )
+    return await self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.list

+
+
+async def files_remote_remove(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_remote_remove(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove a remote file.
+    https://docs.slack.dev/reference/methods/files.remote.remove
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return await self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+ +
+
+async def files_remote_share(self,
*,
channels:Β strΒ |Β Sequence[str],
external_id:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_remote_share(
+    self,
+    *,
+    channels: Union[str, Sequence[str]],
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Share a remote file into a channel.
+    https://docs.slack.dev/reference/methods/files.remote.share
+    """
+    if external_id is None and file is None:
+        raise e.SlackRequestError("Either external_id or file must be provided.")
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update({"external_id": external_id, "file": file})
+    return await self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+ +
+
+async def files_remote_update(self,
*,
external_id:Β strΒ |Β NoneΒ =Β None,
external_url:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_remote_update(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    external_url: Optional[str] = None,
+    file: Optional[str] = None,
+    title: Optional[str] = None,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[str] = None,
+    preview_image: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Updates an existing remote file.
+    https://docs.slack.dev/reference/methods/files.remote.update
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "file": file,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return await self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.update",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+async def files_revokePublicURL(self, *, file:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_revokePublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Revokes public/external sharing access for a file
+    https://docs.slack.dev/reference/methods/files.revokePublicURL
+    """
+    kwargs.update({"file": file})
+    return await self.api_call("files.revokePublicURL", params=kwargs)
+
+

Revokes public/external sharing access for a file +https://docs.slack.dev/reference/methods/files.revokePublicURL

+
+
+async def files_sharedPublicURL(self, *, file:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def files_sharedPublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Enables a file for public/external sharing.
+    https://docs.slack.dev/reference/methods/files.sharedPublicURL
+    """
+    kwargs.update({"file": file})
+    return await self.api_call("files.sharedPublicURL", params=kwargs)
+
+

Enables a file for public/external sharing. +https://docs.slack.dev/reference/methods/files.sharedPublicURL

+
+
+async def files_upload(self,
*,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
filename:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_upload(
+    self,
+    *,
+    file: Optional[Union[str, bytes, IOBase]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    filename: Optional[str] = None,
+    filetype: Optional[str] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    title: Optional[str] = None,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Uploads or creates a file.
+    https://docs.slack.dev/reference/methods/files.upload
+    """
+    _print_files_upload_v2_suggestion()
+
+    if file is None and content is None:
+        raise e.SlackRequestError("The file or content argument must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update(
+        {
+            "filename": filename,
+            "filetype": filetype,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+            "title": title,
+        }
+    )
+    if file:
+        if kwargs.get("filename") is None and isinstance(file, str):
+            # use the local filename if filename is missing
+            if kwargs.get("filename") is None:
+                kwargs["filename"] = file.split(os.path.sep)[-1]
+        return await self.api_call("files.upload", files={"file": file}, data=kwargs)
+    else:
+        kwargs["content"] = content
+        return await self.api_call("files.upload", data=kwargs)
+
+ +
+
+async def files_upload_v2(self,
*,
filename:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β os.PathLikeΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
file_uploads:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
request_file_info:Β boolΒ =Β True,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def files_upload_v2(
+    self,
+    *,
+    # for sending a single file
+    filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+    file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    title: Optional[str] = None,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    # To upload multiple files at a time
+    file_uploads: Optional[List[Dict[str, Any]]] = None,
+    channel: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+    **kwargs,
+) -> AsyncSlackResponse:
+    """This wrapper method provides an easy way to upload files using the following endpoints:
+
+    - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+    - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+    - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        and https://docs.slack.dev/reference/methods/files.info
+
+    """
+    if file is None and content is None and file_uploads is None:
+        raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    # deprecated arguments:
+    filetype = kwargs.get("filetype")
+
+    if filetype is not None:
+        warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+    # step1: files.getUploadURLExternal per file
+    files: List[Dict[str, Any]] = []
+    if file_uploads is not None:
+        for f in file_uploads:
+            files.append(_to_v2_file_upload_item(f))
+    else:
+        f = _to_v2_file_upload_item(
+            {
+                "filename": filename,
+                "file": file,
+                "content": content,
+                "title": title,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        files.append(f)
+
+    for f in files:
+        url_response = await self.files_getUploadURLExternal(
+            filename=f.get("filename"),  # type: ignore[arg-type]
+            length=f.get("length"),  # type: ignore[arg-type]
+            alt_txt=f.get("alt_txt"),
+            snippet_type=f.get("snippet_type"),
+            token=kwargs.get("token"),
+        )
+        _validate_for_legacy_client(url_response)
+        f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+        f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+    # step2: "https://files.slack.com/upload/v1/..." per file
+    for f in files:
+        upload_result = await self._upload_file(
+            url=f["upload_url"],
+            data=f["data"],
+            logger=self._logger,
+            timeout=self.timeout,
+            proxy=self.proxy,
+            ssl=self.ssl,
+        )
+        if upload_result.status != 200:
+            status = upload_result.status
+            body = upload_result.body
+            message = (
+                "Failed to upload a file "
+                f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+            )
+            raise e.SlackRequestError(message)
+
+    # step3: files.completeUploadExternal with all the sets of (file_id + title)
+    completion = await self.files_completeUploadExternal(
+        files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+        channel_id=channel,
+        channels=channels,
+        initial_comment=initial_comment,
+        thread_ts=thread_ts,
+        **kwargs,
+    )
+    if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+        completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+    return completion
+
+

This wrapper method provides an easy way to upload files using the following endpoints:

+
+
+
+async def functions_completeError(self, *, function_execution_id:Β str, error:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def functions_completeError(
+    self,
+    *,
+    function_execution_id: str,
+    error: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Signal the failure to execute a function
+    https://docs.slack.dev/reference/methods/functions.completeError
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "error": error})
+    return await self.api_call("functions.completeError", params=kwargs)
+
+ +
+
+async def functions_completeSuccess(self, *, function_execution_id:Β str, outputs:Β Dict[str,Β Any], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def functions_completeSuccess(
+    self,
+    *,
+    function_execution_id: str,
+    outputs: Dict[str, Any],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Signal the successful completion of a function
+    https://docs.slack.dev/reference/methods/functions.completeSuccess
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+    return await self.api_call("functions.completeSuccess", params=kwargs)
+
+

Signal the successful completion of a function +https://docs.slack.dev/reference/methods/functions.completeSuccess

+
+
+async def groups_archive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Archives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.archive", json=kwargs)
+
+

Archives a private channel.

+
+
+async def groups_create(self, *, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Creates a private channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.create", json=kwargs)
+
+

Creates a private channel.

+
+
+async def groups_createChild(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_createChild(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Clones and archives a private channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+

Clones and archives a private channel.

+
+
+async def groups_history(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetches history of messages and events from a private channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a private channel.

+
+
+async def groups_info(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a private channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+

Gets information about a private channel.

+
+
+async def groups_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Invites a user to a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.invite", json=kwargs)
+
+

Invites a user to a private channel.

+
+
+async def groups_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a user from a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.kick", json=kwargs)
+
+

Removes a user from a private channel.

+
+
+async def groups_leave(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Leaves a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.leave", json=kwargs)
+
+

Leaves a private channel.

+
+
+async def groups_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists private channels that the calling user has access to."""
+    return await self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+

Lists private channels that the calling user has access to.

+
+
+async def groups_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the read cursor in a private channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.mark", json=kwargs)
+
+

Sets the read cursor in a private channel.

+
+
+async def groups_open(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_open(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Opens a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.open", json=kwargs)
+
+

Opens a private channel.

+
+
+async def groups_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Renames a private channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.rename", json=kwargs)
+
+

Renames a private channel.

+
+
+async def groups_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a thread of messages posted to a private channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return await self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a private channel

+
+
+async def groups_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the purpose for a private channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.setPurpose", json=kwargs)
+
+

Sets the purpose for a private channel.

+
+
+async def groups_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the topic for a private channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.setTopic", json=kwargs)
+
+

Sets the topic for a private channel.

+
+
+async def groups_unarchive(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def groups_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Unarchives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("groups.unarchive", json=kwargs)
+
+

Unarchives a private channel.

+
+
+async def im_close(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Close a direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("im.close", json=kwargs)
+
+

Close a direct message channel.

+
+
+async def im_history(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetches history of messages and events from direct message channel."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("im.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from direct message channel.

+
+
+async def im_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists direct message channels for the calling user."""
+    return await self.api_call("im.list", http_verb="GET", params=kwargs)
+
+

Lists direct message channels for the calling user.

+
+
+async def im_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the read cursor in a direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("im.mark", json=kwargs)
+
+

Sets the read cursor in a direct message channel.

+
+
+async def im_open(self, *, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_open(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Opens a direct message channel."""
+    kwargs.update({"user": user})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("im.open", json=kwargs)
+
+

Opens a direct message channel.

+
+
+async def im_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def im_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return await self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation

+
+
+async def migration_exchange(self,
*,
users:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
to_old:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def migration_exchange(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    to_old: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """For Enterprise Grid workspaces, map local user IDs to global user IDs
+    https://docs.slack.dev/reference/methods/migration.exchange
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id, "to_old": to_old})
+    return await self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+

For Enterprise Grid workspaces, map local user IDs to global user IDs +https://docs.slack.dev/reference/methods/migration.exchange

+
+
+async def mpim_close(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Closes a multiparty direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("mpim.close", json=kwargs)
+
+

Closes a multiparty direct message channel.

+
+
+async def mpim_history(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Fetches history of messages and events from a multiparty direct message."""
+    kwargs.update({"channel": channel})
+    return await self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a multiparty direct message.

+
+
+async def mpim_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists multiparty direct message channels for the calling user."""
+    return await self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+

Lists multiparty direct message channels for the calling user.

+
+
+async def mpim_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Sets the read cursor in a multiparty direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("mpim.mark", json=kwargs)
+
+

Sets the read cursor in a multiparty direct message channel.

+
+
+async def mpim_open(self, *, users:Β strΒ |Β Sequence[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_open(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """This method opens a multiparty direct message."""
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return await self.api_call("mpim.open", params=kwargs)
+
+

This method opens a multiparty direct message.

+
+
+async def mpim_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def mpim_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation from a
+    multiparty direct message.
+    """
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return await self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation from a +multiparty direct message.

+
+
+async def oauth_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def oauth_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    code: str,
+    redirect_uri: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    kwargs.update({"code": code})
+    return await self.api_call(
+        "oauth.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.access

+
+
+async def oauth_v2_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def oauth_v2_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    # This field is required when processing the OAuth redirect URL requests
+    # while it's absent for token rotation
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    # This field is required for token rotation
+    grant_type: Optional[str] = None,
+    # This field is required for token rotation
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.v2.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return await self.api_call(
+        "oauth.v2.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.v2.access

+
+
+async def oauth_v2_exchange(self, *, token:Β str, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def oauth_v2_exchange(
+    self,
+    *,
+    token: str,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Exchanges a legacy access token for a new expiring access token and refresh token
+    https://docs.slack.dev/reference/methods/oauth.v2.exchange
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+    return await self.api_call("oauth.v2.exchange", params=kwargs)
+
+

Exchanges a legacy access token for a new expiring access token and refresh token +https://docs.slack.dev/reference/methods/oauth.v2.exchange

+
+
+async def openid_connect_token(self,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def openid_connect_token(
+    self,
+    client_id: str,
+    client_secret: str,
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    grant_type: Optional[str] = None,
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.token
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return await self.api_call(
+        "openid.connect.token",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.token

+
+
+async def openid_connect_userInfo(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def openid_connect_userInfo(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get the identity of a user who has authorized Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.userInfo
+    """
+    return await self.api_call("openid.connect.userInfo", params=kwargs)
+
+

Get the identity of a user who has authorized Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.userInfo

+
+
+async def pins_add(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def pins_add(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Pins an item to a channel.
+    https://docs.slack.dev/reference/methods/pins.add
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return await self.api_call("pins.add", params=kwargs)
+
+ +
+
+async def pins_list(self, *, channel:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def pins_list(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists items pinned to a channel.
+    https://docs.slack.dev/reference/methods/pins.list
+    """
+    kwargs.update({"channel": channel})
+    return await self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+

Lists items pinned to a channel. +https://docs.slack.dev/reference/methods/pins.list

+
+
+async def pins_remove(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def pins_remove(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Un-pins an item from a channel.
+    https://docs.slack.dev/reference/methods/pins.remove
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return await self.api_call("pins.remove", params=kwargs)
+
+ +
+
+async def reactions_add(self, *, channel:Β str, name:Β str, timestamp:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def reactions_add(
+    self,
+    *,
+    channel: str,
+    name: str,
+    timestamp: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Adds a reaction to an item.
+    https://docs.slack.dev/reference/methods/reactions.add
+    """
+    kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+    return await self.api_call("reactions.add", params=kwargs)
+
+ +
+
+async def reactions_get(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def reactions_get(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    full: Optional[bool] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets reactions for an item.
+    https://docs.slack.dev/reference/methods/reactions.get
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "full": full,
+            "timestamp": timestamp,
+        }
+    )
+    return await self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+ +
+
+async def reactions_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def reactions_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    full: Optional[bool] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists reactions made by a user.
+    https://docs.slack.dev/reference/methods/reactions.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "full": full,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return await self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def reactions_remove(self,
*,
name:Β str,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def reactions_remove(
+    self,
+    *,
+    name: str,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a reaction from an item.
+    https://docs.slack.dev/reference/methods/reactions.remove
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return await self.api_call("reactions.remove", params=kwargs)
+
+ +
+
+async def reminders_add(self,
*,
text:Β str,
time:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
recurrence:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def reminders_add(
+    self,
+    *,
+    text: str,
+    time: str,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    recurrence: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Creates a reminder.
+    https://docs.slack.dev/reference/methods/reminders.add
+    """
+    kwargs.update(
+        {
+            "text": text,
+            "time": time,
+            "team_id": team_id,
+            "user": user,
+            "recurrence": recurrence,
+        }
+    )
+    return await self.api_call("reminders.add", params=kwargs)
+
+ +
+
+async def reminders_complete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def reminders_complete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Marks a reminder as complete.
+    https://docs.slack.dev/reference/methods/reminders.complete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return await self.api_call("reminders.complete", params=kwargs)
+
+ +
+
+async def reminders_delete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def reminders_delete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes a reminder.
+    https://docs.slack.dev/reference/methods/reminders.delete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return await self.api_call("reminders.delete", params=kwargs)
+
+ +
+
+async def reminders_info(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def reminders_info(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a reminder.
+    https://docs.slack.dev/reference/methods/reminders.info
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return await self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+ +
+
+async def reminders_list(self, *, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def reminders_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all reminders created by or for a given user.
+    https://docs.slack.dev/reference/methods/reminders.list
+    """
+    kwargs.update({"team_id": team_id})
+    return await self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+

Lists all reminders created by or for a given user. +https://docs.slack.dev/reference/methods/reminders.list

+
+
+async def rtm_connect(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def rtm_connect(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.connect
+    """
+    kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+    return await self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.connect

+
+
+async def rtm_start(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
mpim_aware:Β boolΒ |Β NoneΒ =Β None,
no_latest:Β boolΒ |Β NoneΒ =Β None,
no_unreads:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
simple_latest:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def rtm_start(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    include_locale: Optional[bool] = None,
+    mpim_aware: Optional[bool] = None,
+    no_latest: Optional[bool] = None,
+    no_unreads: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    simple_latest: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.start
+    """
+    kwargs.update(
+        {
+            "batch_presence_aware": batch_presence_aware,
+            "include_locale": include_locale,
+            "mpim_aware": mpim_aware,
+            "no_latest": no_latest,
+            "no_unreads": no_unreads,
+            "presence_sub": presence_sub,
+            "simple_latest": simple_latest,
+        }
+    )
+    return await self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.start

+
+
+async def search_all(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def search_all(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Searches for messages and files matching a query.
+    https://docs.slack.dev/reference/methods/search.all
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("search.all", http_verb="GET", params=kwargs)
+
+

Searches for messages and files matching a query. +https://docs.slack.dev/reference/methods/search.all

+
+
+async def search_files(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def search_files(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Searches for files matching a query.
+    https://docs.slack.dev/reference/methods/search.files
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("search.files", http_verb="GET", params=kwargs)
+
+

Searches for files matching a query. +https://docs.slack.dev/reference/methods/search.files

+
+
+async def search_messages(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def search_messages(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Searches for messages matching a query.
+    https://docs.slack.dev/reference/methods/search.messages
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "cursor": cursor,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+

Searches for messages matching a query. +https://docs.slack.dev/reference/methods/search.messages

+
+
+async def slackLists_access_delete(self,
*,
list_id:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_access_delete(
+    self,
+    *,
+    list_id: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Revoke access to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.delete
+    """
+    kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.access.delete", json=kwargs)
+
+

Revoke access to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.delete

+
+
+async def slackLists_access_set(self,
*,
list_id:Β str,
access_level:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_access_set(
+    self,
+    *,
+    list_id: str,
+    access_level: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the access level to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.set
+    """
+    kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.access.set", json=kwargs)
+
+

Set the access level to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.set

+
+
+async def slackLists_create(self,
*,
name:Β str,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
schema:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
copy_from_list_id:Β strΒ |Β NoneΒ =Β None,
include_copied_list_records:Β boolΒ |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_create(
+    self,
+    *,
+    name: str,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    schema: Optional[List[Dict[str, Any]]] = None,
+    copy_from_list_id: Optional[str] = None,
+    include_copied_list_records: Optional[bool] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Creates a List.
+    https://docs.slack.dev/reference/methods/slackLists.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description_blocks": description_blocks,
+            "schema": schema,
+            "copy_from_list_id": copy_from_list_id,
+            "include_copied_list_records": include_copied_list_records,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.create", json=kwargs)
+
+ +
+
+async def slackLists_download_get(self, *, list_id:Β str, job_id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_download_get(
+    self,
+    *,
+    list_id: str,
+    job_id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve List download URL from an export job to download List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.get
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "job_id": job_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.download.get", json=kwargs)
+
+

Retrieve List download URL from an export job to download List contents. +https://docs.slack.dev/reference/methods/slackLists.download.get

+
+
+async def slackLists_download_start(self, *, list_id:Β str, include_archived:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_download_start(
+    self,
+    *,
+    list_id: str,
+    include_archived: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Initiate a job to export List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.start
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "include_archived": include_archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.download.start", json=kwargs)
+
+ +
+
+async def slackLists_items_create(self,
*,
list_id:Β str,
duplicated_item_id:Β strΒ |Β NoneΒ =Β None,
parent_item_id:Β strΒ |Β NoneΒ =Β None,
initial_fields:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_items_create(
+    self,
+    *,
+    list_id: str,
+    duplicated_item_id: Optional[str] = None,
+    parent_item_id: Optional[str] = None,
+    initial_fields: Optional[List[Dict[str, Any]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add a new item to an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.create
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "duplicated_item_id": duplicated_item_id,
+            "parent_item_id": parent_item_id,
+            "initial_fields": initial_fields,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.create", json=kwargs)
+
+ +
+
+async def slackLists_items_delete(self, *, list_id:Β str, id:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_items_delete(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes an item from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.delete
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.delete", json=kwargs)
+
+ +
+
+async def slackLists_items_deleteMultiple(self, *, list_id:Β str, ids:Β List[str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_items_deleteMultiple(
+    self,
+    *,
+    list_id: str,
+    ids: List[str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Deletes multiple items from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "ids": ids,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+ +
+
+async def slackLists_items_info(self, *, list_id:Β str, id:Β str, include_is_subscribed:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_items_info(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    include_is_subscribed: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get a row from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.info
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+            "include_is_subscribed": include_is_subscribed,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.info", json=kwargs)
+
+ +
+
+async def slackLists_items_list(self,
*,
list_id:Β str,
limit:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
archived:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_items_list(
+    self,
+    *,
+    list_id: str,
+    limit: Optional[int] = None,
+    cursor: Optional[str] = None,
+    archived: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get records from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.list
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "limit": limit,
+            "cursor": cursor,
+            "archived": archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.list", json=kwargs)
+
+ +
+
+async def slackLists_items_update(self, *, list_id:Β str, cells:Β List[Dict[str,Β Any]], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def slackLists_items_update(
+    self,
+    *,
+    list_id: str,
+    cells: List[Dict[str, Any]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Updates cells in a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.update
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "cells": cells,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.items.update", json=kwargs)
+
+ +
+
+async def slackLists_update(self,
*,
id:Β str,
name:Β strΒ |Β NoneΒ =Β None,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def slackLists_update(
+    self,
+    *,
+    id: str,
+    name: Optional[str] = None,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update a List.
+    https://docs.slack.dev/reference/methods/slackLists.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "name": name,
+            "description_blocks": description_blocks,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return await self.api_call("slackLists.update", json=kwargs)
+
+ +
+
+async def stars_add(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def stars_add(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Adds a star to an item.
+    https://docs.slack.dev/reference/methods/stars.add
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return await self.api_call("stars.add", params=kwargs)
+
+ +
+
+async def stars_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def stars_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists stars for a user.
+    https://docs.slack.dev/reference/methods/stars.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def stars_remove(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def stars_remove(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Removes a star from an item.
+    https://docs.slack.dev/reference/methods/stars.remove
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return await self.api_call("stars.remove", params=kwargs)
+
+ +
+
+async def team_accessLogs(self,
*,
before:Β strΒ |Β intΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def team_accessLogs(
+    self,
+    *,
+    before: Optional[Union[int, str]] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets the access logs for the current team.
+    https://docs.slack.dev/reference/methods/team.accessLogs
+    """
+    kwargs.update(
+        {
+            "before": before,
+            "count": count,
+            "page": page,
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return await self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+

Gets the access logs for the current team. +https://docs.slack.dev/reference/methods/team.accessLogs

+
+
+async def team_billableInfo(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_billableInfo(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets billable users information for the current team.
+    https://docs.slack.dev/reference/methods/team.billableInfo
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return await self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+

Gets billable users information for the current team. +https://docs.slack.dev/reference/methods/team.billableInfo

+
+
+async def team_billing_info(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_billing_info(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Reads a workspace's billing plan information.
+    https://docs.slack.dev/reference/methods/team.billing.info
+    """
+    return await self.api_call("team.billing.info", params=kwargs)
+
+

Reads a workspace's billing plan information. +https://docs.slack.dev/reference/methods/team.billing.info

+
+
+async def team_externalTeams_disconnect(self, *, target_team:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_externalTeams_disconnect(
+    self,
+    *,
+    target_team: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Disconnects an external organization.
+    https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+    """
+    kwargs.update(
+        {
+            "target_team": target_team,
+        }
+    )
+    return await self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+ +
+
+async def team_externalTeams_list(self,
*,
connection_status_filter:Β strΒ |Β NoneΒ =Β None,
slack_connect_pref_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
sort_field:Β strΒ |Β NoneΒ =Β None,
workspace_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def team_externalTeams_list(
+    self,
+    *,
+    connection_status_filter: Optional[str] = None,
+    slack_connect_pref_filter: Optional[Sequence[str]] = None,
+    sort_direction: Optional[str] = None,
+    sort_field: Optional[str] = None,
+    workspace_filter: Optional[Sequence[str]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Returns a list of all the external teams connected and details about the connection.
+    https://docs.slack.dev/reference/methods/team.externalTeams.list
+    """
+    kwargs.update(
+        {
+            "connection_status_filter": connection_status_filter,
+            "sort_direction": sort_direction,
+            "sort_field": sort_field,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if slack_connect_pref_filter is not None:
+        if isinstance(slack_connect_pref_filter, (list, tuple)):
+            kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+        else:
+            kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+    if workspace_filter is not None:
+        if isinstance(workspace_filter, (list, tuple)):
+            kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+        else:
+            kwargs.update({"workspace_filter": workspace_filter})
+    return await self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+

Returns a list of all the external teams connected and details about the connection. +https://docs.slack.dev/reference/methods/team.externalTeams.list

+
+
+async def team_info(self, *, team:Β strΒ |Β NoneΒ =Β None, domain:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_info(
+    self,
+    *,
+    team: Optional[str] = None,
+    domain: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about the current team.
+    https://docs.slack.dev/reference/methods/team.info
+    """
+    kwargs.update({"team": team, "domain": domain})
+    return await self.api_call("team.info", http_verb="GET", params=kwargs)
+
+

Gets information about the current team. +https://docs.slack.dev/reference/methods/team.info

+
+
+async def team_integrationLogs(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
change_type:Β strΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
service_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def team_integrationLogs(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    change_type: Optional[str] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    service_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets the integration logs for the current team.
+    https://docs.slack.dev/reference/methods/team.integrationLogs
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "change_type": change_type,
+            "count": count,
+            "page": page,
+            "service_id": service_id,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return await self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+

Gets the integration logs for the current team. +https://docs.slack.dev/reference/methods/team.integrationLogs

+
+
+async def team_preferences_list(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_preferences_list(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a list of a workspace's team preferences.
+    https://docs.slack.dev/reference/methods/team.preferences.list
+    """
+    return await self.api_call("team.preferences.list", params=kwargs)
+
+

Retrieve a list of a workspace's team preferences. +https://docs.slack.dev/reference/methods/team.preferences.list

+
+
+async def team_profile_get(self, *, visibility:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def team_profile_get(
+    self,
+    *,
+    visibility: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieve a team's profile.
+    https://docs.slack.dev/reference/methods/team.profile.get
+    """
+    kwargs.update({"visibility": visibility})
+    return await self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+ +
+
+async def tooling_tokens_rotate(self, *, refresh_token:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def tooling_tokens_rotate(
+    self,
+    *,
+    refresh_token: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Exchanges a refresh token for a new app configuration token
+    https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+    """
+    kwargs.update({"refresh_token": refresh_token})
+    return await self.api_call("tooling.tokens.rotate", params=kwargs)
+
+

Exchanges a refresh token for a new app configuration token +https://docs.slack.dev/reference/methods/tooling.tokens.rotate

+
+
+async def usergroups_create(self,
*,
name:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_create(
+    self,
+    *,
+    name: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Create a User Group
+    https://docs.slack.dev/reference/methods/usergroups.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return await self.api_call("usergroups.create", params=kwargs)
+
+ +
+
+async def usergroups_disable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_disable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Disable an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.disable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return await self.api_call("usergroups.disable", params=kwargs)
+
+ +
+
+async def usergroups_enable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_enable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Enable a User Group
+    https://docs.slack.dev/reference/methods/usergroups.enable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return await self.api_call("usergroups.enable", params=kwargs)
+
+ +
+
+async def usergroups_list(self,
*,
include_count:Β boolΒ |Β NoneΒ =Β None,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
include_users:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_list(
+    self,
+    *,
+    include_count: Optional[bool] = None,
+    include_disabled: Optional[bool] = None,
+    include_users: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all User Groups for a team
+    https://docs.slack.dev/reference/methods/usergroups.list
+    """
+    kwargs.update(
+        {
+            "include_count": include_count,
+            "include_disabled": include_disabled,
+            "include_users": include_users,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def usergroups_update(self,
*,
usergroup:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_update(
+    self,
+    *,
+    usergroup: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    name: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "name": name,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return await self.api_call("usergroups.update", params=kwargs)
+
+ +
+
+async def usergroups_users_list(self,
*,
usergroup:Β str,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_users_list(
+    self,
+    *,
+    usergroup: str,
+    include_disabled: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List all users in a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.list
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_disabled": include_disabled,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+ +
+
+async def usergroups_users_update(self,
*,
usergroup:Β str,
users:Β strΒ |Β Sequence[str],
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def usergroups_users_update(
+    self,
+    *,
+    usergroup: str,
+    users: Union[str, Sequence[str]],
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update the list of users for a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return await self.api_call("usergroups.users.update", params=kwargs)
+
+

Update the list of users for a User Group +https://docs.slack.dev/reference/methods/usergroups.users.update

+
+
+async def users_conversations(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def users_conversations(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List conversations the calling user may access.
+    https://docs.slack.dev/reference/methods/users.conversations
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return await self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+

List conversations the calling user may access. +https://docs.slack.dev/reference/methods/users.conversations

+
+
+async def users_deletePhoto(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_deletePhoto(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Delete the user profile photo
+    https://docs.slack.dev/reference/methods/users.deletePhoto
+    """
+    return await self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+ +
+
+async def users_discoverableContacts_lookup(self, email:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_discoverableContacts_lookup(
+    self,
+    email: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lookup an email address to see if someone is on Slack
+    https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+    """
+    kwargs.update({"email": email})
+    return await self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+

Lookup an email address to see if someone is on Slack +https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup

+
+
+async def users_getPresence(self, *, user:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_getPresence(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets user presence information.
+    https://docs.slack.dev/reference/methods/users.getPresence
+    """
+    kwargs.update({"user": user})
+    return await self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+ +
+
+async def users_identity(self, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_identity(
+    self,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Get a user's identity.
+    https://docs.slack.dev/reference/methods/users.identity
+    """
+    return await self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+ +
+
+async def users_info(self, *, user:Β str, include_locale:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_info(
+    self,
+    *,
+    user: str,
+    include_locale: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Gets information about a user.
+    https://docs.slack.dev/reference/methods/users.info
+    """
+    kwargs.update({"user": user, "include_locale": include_locale})
+    return await self.api_call("users.info", http_verb="GET", params=kwargs)
+
+ +
+
+async def users_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def users_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_locale: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Lists all users in a Slack team.
+    https://docs.slack.dev/reference/methods/users.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_locale": include_locale,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return await self.api_call("users.list", http_verb="GET", params=kwargs)
+
+

Lists all users in a Slack team. +https://docs.slack.dev/reference/methods/users.list

+
+
+async def users_lookupByEmail(self, *, email:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_lookupByEmail(
+    self,
+    *,
+    email: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Find a user with an email address.
+    https://docs.slack.dev/reference/methods/users.lookupByEmail
+    """
+    kwargs.update({"email": email})
+    return await self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+ +
+
+async def users_profile_get(self, *, user:Β strΒ |Β NoneΒ =Β None, include_labels:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_profile_get(
+    self,
+    *,
+    user: Optional[str] = None,
+    include_labels: Optional[bool] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Retrieves a user's profile information.
+    https://docs.slack.dev/reference/methods/users.profile.get
+    """
+    kwargs.update({"user": user, "include_labels": include_labels})
+    return await self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+

Retrieves a user's profile information. +https://docs.slack.dev/reference/methods/users.profile.get

+
+
+async def users_profile_set(self,
*,
name:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
profile:Β DictΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def users_profile_set(
+    self,
+    *,
+    name: Optional[str] = None,
+    value: Optional[str] = None,
+    user: Optional[str] = None,
+    profile: Optional[Dict] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the profile information for a user.
+    https://docs.slack.dev/reference/methods/users.profile.set
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "profile": profile,
+            "user": user,
+            "value": value,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "profile" parameter
+    return await self.api_call("users.profile.set", json=kwargs)
+
+

Set the profile information for a user. +https://docs.slack.dev/reference/methods/users.profile.set

+
+
+async def users_setPhoto(self,
*,
image:Β strΒ |Β io.IOBase,
crop_w:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_x:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_y:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def users_setPhoto(
+    self,
+    *,
+    image: Union[str, IOBase],
+    crop_w: Optional[Union[int, str]] = None,
+    crop_x: Optional[Union[int, str]] = None,
+    crop_y: Optional[Union[int, str]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set the user profile photo
+    https://docs.slack.dev/reference/methods/users.setPhoto
+    """
+    kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+    return await self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+ +
+
+async def users_setPresence(self, *, presence:Β str, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def users_setPresence(
+    self,
+    *,
+    presence: str,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Manually sets user presence.
+    https://docs.slack.dev/reference/methods/users.setPresence
+    """
+    kwargs.update({"presence": presence})
+    return await self.api_call("users.setPresence", params=kwargs)
+
+ +
+
+async def views_open(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def views_open(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Open a view for a user.
+    https://docs.slack.dev/reference/methods/views.open
+    See https://docs.slack.dev/surfaces/modals/ for details.
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return await self.api_call("views.open", json=kwargs)
+
+ +
+
+async def views_publish(self,
*,
user_id:Β str,
view:Β dictΒ |Β View,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def views_publish(
+    self,
+    *,
+    user_id: str,
+    view: Union[dict, View],
+    hash: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Publish a static view for a User.
+    Create or update the view that comprises an
+    app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+    https://docs.slack.dev/reference/methods/views.publish
+    """
+    kwargs.update({"user_id": user_id, "hash": hash})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return await self.api_call("views.publish", json=kwargs)
+
+

Publish a static view for a User. +Create or update the view that comprises an +app's Home tab (https://docs.slack.dev/surfaces/app-home/) +https://docs.slack.dev/reference/methods/views.publish

+
+
+async def views_push(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def views_push(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Push a view onto the stack of a root view.
+    Push a new view onto the existing view stack by passing a view
+    payload and a valid trigger_id generated from an interaction
+    within the existing modal.
+    Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+    to learn more about the lifecycle and intricacies of views.
+    https://docs.slack.dev/reference/methods/views.push
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return await self.api_call("views.push", json=kwargs)
+
+

Push a view onto the stack of a root view. +Push a new view onto the existing view stack by passing a view +payload and a valid trigger_id generated from an interaction +within the existing modal. +Read the modals documentation (https://docs.slack.dev/surfaces/modals/) +to learn more about the lifecycle and intricacies of views. +https://docs.slack.dev/reference/methods/views.push

+
+
+async def views_update(self,
*,
view:Β dictΒ |Β View,
external_id:Β strΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def views_update(
+    self,
+    *,
+    view: Union[dict, View],
+    external_id: Optional[str] = None,
+    view_id: Optional[str] = None,
+    hash: Optional[str] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update an existing view.
+    Update a view by passing a new view definition along with the
+    view_id returned in views.open or the external_id.
+    See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+    to learn more about updating views and avoiding race conditions with the hash argument.
+    https://docs.slack.dev/reference/methods/views.update
+    """
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    if external_id:
+        kwargs.update({"external_id": external_id})
+    elif view_id:
+        kwargs.update({"view_id": view_id})
+    else:
+        raise e.SlackRequestError("Either view_id or external_id is required.")
+    kwargs.update({"hash": hash})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return await self.api_call("views.update", json=kwargs)
+
+

Update an existing view. +Update a view by passing a new view definition along with the +view_id returned in views.open or the external_id. +See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views) +to learn more about updating views and avoiding race conditions with the hash argument. +https://docs.slack.dev/reference/methods/views.update

+
+ +
+
+ +Expand source code + +
async def workflows_featured_add(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Add featured workflows to a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.add
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return await self.api_call("workflows.featured.add", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
async def workflows_featured_list(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """List the featured workflows for specified channels.
+    https://docs.slack.dev/reference/methods/workflows.featured.list
+    """
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return await self.api_call("workflows.featured.list", params=kwargs)
+
+

List the featured workflows for specified channels. +https://docs.slack.dev/reference/methods/workflows.featured.list

+
+ +
+
+ +Expand source code + +
async def workflows_featured_remove(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Remove featured workflows from a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.remove
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return await self.api_call("workflows.featured.remove", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
async def workflows_featured_set(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Set featured workflows for a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.set
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return await self.api_call("workflows.featured.set", params=kwargs)
+
+ +
+
+async def workflows_stepCompleted(self, *, workflow_step_execute_id:Β str, outputs:Β dictΒ |Β NoneΒ =Β None, **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def workflows_stepCompleted(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    outputs: Optional[dict] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Indicate a successful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepCompleted
+    """
+    kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "outputs" parameter
+    return await self.api_call("workflows.stepCompleted", json=kwargs)
+
+

Indicate a successful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepCompleted

+
+
+async def workflows_stepFailed(self, *, workflow_step_execute_id:Β str, error:Β Dict[str,Β str], **kwargs) ‑>Β AsyncSlackResponse +
+
+
+ +Expand source code + +
async def workflows_stepFailed(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    error: Dict[str, str],
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Indicate an unsuccessful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepFailed
+    """
+    kwargs.update(
+        {
+            "workflow_step_execute_id": workflow_step_execute_id,
+            "error": error,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "error" parameter
+    return await self.api_call("workflows.stepFailed", json=kwargs)
+
+

Indicate an unsuccessful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepFailed

+
+
+async def workflows_updateStep(self,
*,
workflow_step_edit_id:Β str,
inputs:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
outputs:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β AsyncSlackResponse
+
+
+
+ +Expand source code + +
async def workflows_updateStep(
+    self,
+    *,
+    workflow_step_edit_id: str,
+    inputs: Optional[Dict[str, Any]] = None,
+    outputs: Optional[List[Dict[str, str]]] = None,
+    **kwargs,
+) -> AsyncSlackResponse:
+    """Update the configuration for a workflow extension step.
+    https://docs.slack.dev/reference/methods/workflows.updateStep
+    """
+    kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+    if inputs is not None:
+        kwargs.update({"inputs": inputs})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+    return await self.api_call("workflows.updateStep", json=kwargs)
+
+

Update the configuration for a workflow extension step. +https://docs.slack.dev/reference/methods/workflows.updateStep

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/web/async_internal_utils.html b/docs/reference/web/async_internal_utils.html new file mode 100644 index 000000000..12eb2ba7f --- /dev/null +++ b/docs/reference/web/async_internal_utils.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.web.async_internal_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.async_internal_utils

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/async_slack_response.html b/docs/reference/web/async_slack_response.html new file mode 100644 index 000000000..e081b1ab8 --- /dev/null +++ b/docs/reference/web/async_slack_response.html @@ -0,0 +1,391 @@ + + + + + + +slack_sdk.web.async_slack_response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.async_slack_response

+
+
+

A Python module for interacting and consuming responses from Slack.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncSlackResponse +(*,
client,
http_verb:Β str,
api_url:Β str,
req_args:Β dict,
data:Β dictΒ |Β bytes,
headers:Β dict,
status_code:Β int)
+
+
+
+ +Expand source code + +
class AsyncSlackResponse:
+    """An iterable container of response data.
+
+    Attributes:
+        data (dict): The json-encoded content of the response. Along
+            with the headers and status code information.
+
+    Methods:
+        validate: Check if the response from Slack was successful.
+        get: Retrieves any key from the response data.
+        next: Retrieves the next portion of results,
+            if 'next_cursor' is present.
+
+    Example:
+    ```python
+    import os
+    import slack
+
+    client = slack.AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+
+    response1 = await client.auth_revoke(test='true')
+    assert not response1['revoked']
+
+    response2 = await client.auth_test()
+    assert response2.get('ok', False)
+
+    users = []
+    async for page in await client.users_list(limit=2):
+        users = users + page['members']
+    ```
+
+    Note:
+        Some responses return collections of information
+        like channel and user lists. If they do it's likely
+        that you'll only receive a portion of results. This
+        object allows you to iterate over the response which
+        makes subsequent API requests until your code hits
+        'break' or there are no more results to be found.
+
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+    """
+
+    def __init__(
+        self,
+        *,
+        client,  # AsyncWebClient
+        http_verb: str,
+        api_url: str,
+        req_args: dict,
+        data: Union[dict, bytes],  # data can be binary data
+        headers: dict,
+        status_code: int,
+    ):
+        self.http_verb = http_verb
+        self.api_url = api_url
+        self.req_args = req_args
+        self.data = data
+        self.headers = headers
+        self.status_code = status_code
+        self._initial_data = data
+        self._iteration = None  # for __iter__ & __next__
+        self._client = client
+        self._logger = logging.getLogger(__name__)
+
+    def __str__(self):
+        """Return the Response data if object is converted to a string."""
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return f"{self.data}"
+
+    def __contains__(self, key: str) -> bool:
+        return self.get(key) is not None
+
+    def __getitem__(self, key):
+        """Retrieves any key from the data store.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response["ok"]
+
+        Returns:
+            The value from data or None.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            raise ValueError("As the response.data is empty, this operation is unsupported")
+        return self.data.get(key, None)
+
+    def __aiter__(self):
+        """Enables the ability to iterate over the response.
+        It's required async-for the iterator protocol.
+
+        Note:
+            This enables Slack cursor-based pagination.
+
+        Returns:
+            (AsyncSlackResponse) self
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration = 0
+        self.data = self._initial_data
+        return self
+
+    async def __anext__(self):
+        """Retrieves the next portion of results, if 'next_cursor' is present.
+
+        Note:
+            Some responses return collections of information
+            like channel and user lists. If they do it's likely
+            that you'll only receive a portion of results. This
+            method allows you to iterate over the response until
+            your code hits 'break' or there are no more results
+            to be found.
+
+        Returns:
+            (AsyncSlackResponse) self
+                With the new response data now attached to this object.
+
+        Raises:
+            SlackApiError: If the request to the Slack API failed.
+            StopAsyncIteration: If 'next_cursor' is not present or empty.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration += 1
+        if self._iteration == 1:
+            return self
+        if _next_cursor_is_present(self.data):
+            params = self.req_args.get("params", {})
+            if params is None:
+                params = {}
+            next_cursor = self.data.get("response_metadata", {}).get("next_cursor") or self.data.get("next_cursor")
+            params.update({"cursor": next_cursor})
+            self.req_args.update({"params": params})
+
+            response = await self._client._request(
+                http_verb=self.http_verb,
+                api_url=self.api_url,
+                req_args=self.req_args,
+            )
+
+            self.data = response["data"]
+            self.headers = response["headers"]
+            self.status_code = response["status_code"]
+            return self.validate()
+        else:
+            raise StopAsyncIteration
+
+    @overload
+    def get(self, key: str, default: None = None) -> Optional[Any]:
+        ...
+
+    @overload
+    def get(self, key: str, default: T) -> T:
+        ...
+
+    def get(self, key, default=None):
+        """Retrieves any key from the response data.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response.get("ok", False)
+
+        Returns:
+            The value from data or the specified default.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            return None
+        return self.data.get(key, default)
+
+    def validate(self):
+        """Check if the response from Slack was successful.
+
+        Returns:
+            (AsyncSlackResponse)
+                This method returns it's own object. e.g. 'self'
+
+        Raises:
+            SlackApiError: The request to the Slack API failed.
+        """
+        if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+            return self
+        msg = f"The request to the Slack API failed. (url: {self.api_url}, status: {self.status_code})"
+        raise e.SlackApiError(message=msg, response=self)
+
+

An iterable container of response data.

+

Attributes

+
+
data : dict
+
The json-encoded content of the response. Along +with the headers and status code information.
+
+

Methods

+

validate: Check if the response from Slack was successful. +get: Retrieves any key from the response data. +next: Retrieves the next portion of results, +if 'next_cursor' is present.

+

Example:

+
import os
+import slack
+
+client = slack.AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
+
+response1 = await client.auth_revoke(test='true')
+assert not response1['revoked']
+
+response2 = await client.auth_test()
+assert response2.get('ok', False)
+
+users = []
+async for page in await client.users_list(limit=2):
+    users = users + page['members']
+
+

Note

+

Some responses return collections of information +like channel and user lists. If they do it's likely +that you'll only receive a portion of results. This +object allows you to iterate over the response which +makes subsequent API requests until your code hits +'break' or there are no more results to be found.

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Methods

+
+
+def get(self, key, default=None) +
+
+
+ +Expand source code + +
def get(self, key, default=None):
+    """Retrieves any key from the response data.
+
+    Note:
+        This is implemented so users can reference the
+        SlackResponse object like a dictionary.
+        e.g. response.get("ok", False)
+
+    Returns:
+        The value from data or the specified default.
+    """
+    if isinstance(self.data, bytes):
+        raise ValueError("As the response.data is binary data, this operation is unsupported")
+    if self.data is None:
+        return None
+    return self.data.get(key, default)
+
+

Retrieves any key from the response data.

+

Note

+

This is implemented so users can reference the +SlackResponse object like a dictionary. +e.g. response.get("ok", False)

+

Returns

+

The value from data or the specified default.

+
+
+def validate(self) +
+
+
+ +Expand source code + +
def validate(self):
+    """Check if the response from Slack was successful.
+
+    Returns:
+        (AsyncSlackResponse)
+            This method returns it's own object. e.g. 'self'
+
+    Raises:
+        SlackApiError: The request to the Slack API failed.
+    """
+    if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+        return self
+    msg = f"The request to the Slack API failed. (url: {self.api_url}, status: {self.status_code})"
+    raise e.SlackApiError(message=msg, response=self)
+
+

Check if the response from Slack was successful.

+

Returns

+

(AsyncSlackResponse) +This method returns it's own object. e.g. 'self'

+

Raises

+
+
SlackApiError
+
The request to the Slack API failed.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/base_client.html b/docs/reference/web/base_client.html new file mode 100644 index 000000000..affbba13c --- /dev/null +++ b/docs/reference/web/base_client.html @@ -0,0 +1,949 @@ + + + + + + +slack_sdk.web.base_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.base_client

+
+
+

A Python module for interacting with Slack's Web API.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class BaseClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class BaseClient:
+    BASE_URL = "https://slack.com/api/"
+
+    def __init__(
+        self,
+        token: Optional[str] = None,
+        base_url: str = BASE_URL,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        headers: Optional[dict] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        # for Org-Wide App installation
+        team_id: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        self.token = None if token is None else token.strip()
+        """A string specifying an `xoxp-*` or `xoxb-*` token."""
+        if not base_url.endswith("/"):
+            base_url += "/"
+        self.base_url = base_url
+        """A string representing the Slack API base URL.
+        Default is `'https://slack.com/api/'`."""
+        self.timeout = timeout
+        """The maximum number of seconds the client will wait
+        to connect and receive a response from Slack.
+        Default is 30 seconds."""
+        self.ssl = ssl
+        """An [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
+        instance, helpful for specifying your own custom
+        certificate chain."""
+        self.proxy = proxy
+        """String representing a fully-qualified URL to a proxy through which
+        to route all requests to the Slack API. Even if this parameter
+        is not specified, if any of the following environment variables are
+        present, they will be loaded into this parameter: `HTTPS_PROXY`,
+        `https_proxy`, `HTTP_PROXY` or `http_proxy`."""
+        self.headers = headers or {}
+        """`dict` representing additional request headers to attach to all requests."""
+        self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.default_params = {}
+        if team_id is not None:
+            self.default_params["team_id"] = team_id
+        self._logger = logger if logger is not None else logging.getLogger(__name__)
+
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self._logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    # -------------------------
+    # accessors
+
+    @property
+    def logger(self) -> logging.Logger:
+        """The logger this client uses."""
+        return self._logger
+
+    # -------------------------
+    # api call
+
+    def api_call(
+        self,
+        api_method: str,
+        *,
+        http_verb: str = "POST",
+        files: Optional[dict] = None,
+        data: Optional[dict] = None,
+        params: Optional[dict] = None,
+        json: Optional[dict] = None,
+        headers: Optional[dict] = None,
+        auth: Optional[dict] = None,
+    ) -> SlackResponse:
+        """Create a request and execute the API call to Slack.
+
+        Args:
+            api_method (str): The target Slack API method.
+                e.g. 'chat.postMessage'
+            http_verb (str): HTTP Verb. e.g. 'POST'
+            files (dict): Files to multipart upload.
+                e.g. {image OR file: file_object OR file_path}
+            data: The body to attach to the request. If a dictionary is
+                provided, form-encoding will take place.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            params (dict): The URL parameters to append to the URL.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            json (dict): JSON for the body to attach to the request
+                (if files or data is not specified).
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            headers (dict): Additional request headers
+            auth (dict): A dictionary that consists of client_id and client_secret
+
+        Returns:
+            (SlackResponse)
+                The server's response to an HTTP request. Data
+                from the response can be accessed like a dict.
+                If the response included 'next_cursor' it can
+                be iterated on to execute subsequent requests.
+
+        Raises:
+            SlackApiError: The following Slack API call failed:
+                'chat.postMessage'.
+            SlackRequestError: Json data can only be submitted as
+                POST requests.
+        """
+
+        api_url = _get_url(self.base_url, api_method)
+        headers = headers or {}
+        headers.update(self.headers)
+        req_args = _build_req_args(
+            token=self.token,
+            http_verb=http_verb,
+            files=files,  # type: ignore[arg-type]
+            data=data,  # type: ignore[arg-type]
+            default_params=self.default_params,
+            params=params,  # type: ignore[arg-type]
+            json=json,  # type: ignore[arg-type]
+            headers=headers,
+            auth=auth,  # type: ignore[arg-type]
+            ssl=self.ssl,
+            proxy=self.proxy,
+        )
+
+        show_deprecation_warning_if_any(api_method)
+        return self._sync_send(api_url=api_url, req_args=req_args)
+
+    # =================================================================
+    # urllib based WebClient
+    # =================================================================
+
+    def _sync_send(self, api_url, req_args) -> SlackResponse:
+        params = req_args["params"] if "params" in req_args else None
+        data = req_args["data"] if "data" in req_args else None
+        files = req_args["files"] if "files" in req_args else None
+        _json = req_args["json"] if "json" in req_args else None
+        headers = req_args["headers"] if "headers" in req_args else None
+        token = params.get("token") if params and "token" in params else None
+        auth = req_args["auth"] if "auth" in req_args else None  # Basic Auth for oauth.v2.access / oauth.access
+        if auth is not None:
+            headers = {}
+            if isinstance(auth, str):
+                headers["Authorization"] = auth
+            elif isinstance(auth, dict):
+                client_id, client_secret = auth["client_id"], auth["client_secret"]
+                value = b64encode(f"{client_id}:{client_secret}".encode("utf-8")).decode("ascii")
+                headers["Authorization"] = f"Basic {value}"
+            else:
+                self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped")
+
+        body_params = {}
+        if params:
+            body_params.update(params)
+        if data:
+            body_params.update(data)
+
+        return self._urllib_api_call(
+            token=token,
+            url=api_url,
+            query_params={},
+            body_params=body_params,
+            files=files,  # type: ignore[arg-type]
+            json_body=_json,  # type: ignore[arg-type]
+            additional_headers=headers,  # type: ignore[arg-type]
+        )
+
+    def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
+        """This method is supposed to be used only for SlackResponse pagination
+
+        You can paginate using Python's for iterator as below:
+
+          for response in client.conversations_list(limit=100):
+              # do something with each response here
+        """
+        response = self._perform_urllib_http_request(url=api_url, args=req_args)
+        return {
+            "status_code": int(response["status"]),
+            "headers": dict(response["headers"]),
+            "data": json.loads(response["body"]),
+        }
+
+    def _urllib_api_call(
+        self,
+        *,
+        token: Optional[str] = None,
+        url: str,
+        query_params: Dict[str, str],
+        json_body: Dict,
+        body_params: Dict[str, str],
+        files: Dict[str, io.BytesIO],
+        additional_headers: Dict[str, str],
+    ) -> SlackResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            token: Slack API Token (either bot token or user token)
+            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
+            query_params: Query string
+            json_body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            body_params: Form body params
+            files: Files to upload
+            additional_headers: Request headers to append
+
+        Returns:
+            API response
+        """
+        files_to_close: List[BinaryIO] = []
+        try:
+            # True/False -> "1"/"0"
+            query_params = convert_bool_to_0_or_1(query_params)  # type: ignore[assignment]
+            body_params = convert_bool_to_0_or_1(body_params)  # type: ignore[assignment]
+
+            if self._logger.level <= logging.DEBUG:
+
+                def convert_params(values: dict) -> dict:
+                    if not values or not isinstance(values, dict):
+                        return {}
+                    return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()}
+
+                headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()}
+                self._logger.debug(
+                    f"Sending a request - url: {url}, "
+                    f"query_params: {convert_params(query_params)}, "
+                    f"body_params: {convert_params(body_params)}, "
+                    f"files: {convert_params(files)}, "
+                    f"json_body: {json_body}, "
+                    f"headers: {headers}"
+                )
+
+            request_data = {}
+            if files is not None and isinstance(files, dict) and len(files) > 0:
+                if body_params:
+                    for k, v in body_params.items():
+                        request_data.update({k: v})
+
+                for k, v in files.items():  # type: ignore[assignment]
+                    if isinstance(v, str):
+                        f: BinaryIO = open(v.encode("utf-8", "ignore"), "rb")
+                        files_to_close.append(f)
+                        request_data.update({k: f})  # type: ignore[dict-item]
+                    elif isinstance(v, (bytearray, bytes)):
+                        request_data.update({k: io.BytesIO(v)})
+                    else:
+                        request_data.update({k: v})
+
+            request_headers = self._build_urllib_request_headers(
+                token=token or self.token,  # type: ignore[arg-type]
+                has_json=json is not None,
+                has_files=files is not None,
+                additional_headers=additional_headers,
+            )
+            request_args = {
+                "headers": request_headers,
+                "data": request_data,
+                "params": body_params,
+                "files": files,
+                "json": json_body,
+            }
+            if query_params:
+                q = urlencode(query_params)
+                url = f"{url}&{q}" if "?" in url else f"{url}?{q}"
+
+            response = self._perform_urllib_http_request(url=url, args=request_args)  # type: ignore[arg-type]
+            response_body = response.get("body", None)
+            response_body_data: Optional[Union[dict, bytes]] = response_body
+            if response_body is not None and not isinstance(response_body, bytes):
+                try:
+                    response_body_data = json.loads(response["body"])
+                except json.decoder.JSONDecodeError:
+                    message = _build_unexpected_body_error_message(response.get("body", ""))
+                    self._logger.error(f"Failed to decode Slack API response: {message}")
+                    response_body_data = {"ok": False, "error": message}
+
+            all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {}
+            if query_params:
+                all_params.update(query_params)
+            request_args["params"] = all_params  # for backward-compatibility
+
+            return SlackResponse(
+                client=self,
+                http_verb="POST",  # you can use POST method for all the Web APIs
+                api_url=url,
+                req_args=request_args,
+                data=response_body_data,  # type: ignore[arg-type]
+                headers=dict(response["headers"]),
+                status_code=response["status"],
+            ).validate()
+        finally:
+            for f in files_to_close:
+                if not f.closed:
+                    f.close()
+
+    def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
+        """Performs an HTTP request and parses the response.
+
+        Args:
+            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
+            args: args has "headers", "data", "params", and "json"
+                "headers": Dict[str, str]
+                "data": Dict[str, Any]
+                "params": Dict[str, str],
+                "json": Dict[str, Any],
+
+        Returns:
+            dict {status: int, headers: Headers, body: str}
+        """
+        headers = args["headers"]
+        body: Optional[Union[bytes, str]] = None
+        if args["json"]:
+            body = json.dumps(args["json"])
+            headers["Content-Type"] = "application/json;charset=utf-8"
+        elif args["data"]:
+            boundary = f"--------------{uuid.uuid4()}"
+            sep_boundary = b"\r\n--" + boundary.encode("ascii")
+            end_boundary = sep_boundary + b"--\r\n"
+            body_builder = io.BytesIO()
+            data = args["data"]
+            for key, value in data.items():
+                readable = getattr(value, "readable", None)
+                if readable and value.readable():
+                    filename = "Uploaded file"
+                    name_attr = getattr(value, "name", None)
+                    if name_attr:
+                        filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr
+                    if "filename" in data:
+                        filename = data["filename"]
+                    mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
+                    title = (
+                        f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n'
+                        + f"Content-Type: {mimetype}\r\n"
+                    )
+                    value = value.read()
+                else:
+                    title = f'\r\nContent-Disposition: form-data; name="{key}"\r\n'
+                    value = str(value).encode("utf-8")
+                body_builder.write(sep_boundary)
+                body_builder.write(title.encode("utf-8"))
+                body_builder.write(b"\r\n")
+                body_builder.write(value)
+
+            body_builder.write(end_boundary)
+            body = body_builder.getvalue()
+            headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
+            headers["Content-Length"] = len(body)
+        elif args["params"]:
+            body = urlencode(args["params"])
+            headers["Content-Type"] = "application/x-www-form-urlencoded"
+
+        if isinstance(body, str):
+            body = body.encode("utf-8")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(method="POST", url=url, data=body, headers=headers)
+        resp = None
+        last_error = None
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_urllib_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                if len(self.retry_handlers) > 0:
+                    retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                    body_string = resp["body"] if isinstance(resp["body"], str) else None
+                    body_bytes = body_string.encode("utf-8") if body_string is not None else resp["body"]
+                    if body_string is not None and body_string.startswith("{"):
+                        body = json.loads(body_string)
+                    else:
+                        body = {}  # type: ignore[assignment]
+                    retry_response = RetryHttpResponse(
+                        status_code=resp["status"],
+                        headers=resp["headers"],
+                        body=body,  # type: ignore[arg-type]
+                        data=body_bytes,
+                    )
+                    for handler in self.retry_handlers:
+                        if handler.can_retry(state=retry_state, request=retry_request, response=retry_response):
+                            if self._logger.level <= logging.DEBUG:
+                                self._logger.info(
+                                    f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url}"
+                                )
+                            handler.prepare_for_next_attempt(
+                                state=retry_state, request=retry_request, response=retry_response
+                            )
+                            break
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except HTTPError as e:
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = {"status": e.code, "headers": response_headers}
+                if e.code == 429:
+                    # for compatibility with aiohttp
+                    if "retry-after" not in response_headers and "Retry-After" in response_headers:
+                        response_headers["retry-after"] = response_headers["Retry-After"]
+                    if "Retry-After" not in response_headers and "retry-after" in response_headers:
+                        response_headers["Retry-After"] = response_headers["retry-after"]
+
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                resp["body"] = response_body
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in response_headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self._logger.level <= logging.DEBUG:
+                            self._logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self._logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self._logger.level <= logging.DEBUG:
+                            self._logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self._logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error  # type: ignore[misc]
+
+    def _perform_urllib_http_request_internal(
+        self,
+        url: str,
+        req: Request,
+    ) -> Dict[str, Any]:
+        # urllib not only opens http:// or https:// URLs, but also ftp:// and file://.
+        # With this it might be possible to open local files on the executing machine
+        # which might be a security risk if the URL to open can be manipulated by an external user.
+        # (BAN-B310)
+        if url.lower().startswith("http"):
+            opener: Optional[OpenerDirector] = None
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+
+            if opener:
+                resp = opener.open(req, timeout=self.timeout)
+            else:
+                resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+            if resp.headers.get_content_type() == "application/gzip":
+                # admin.analytics.getFile
+                body: bytes = resp.read()
+                if self._logger.level <= logging.DEBUG:
+                    self._logger.debug(
+                        "Received the following response - "
+                        f"status: {resp.code}, "
+                        f"headers: {dict(resp.headers)}, "
+                        f"body: (binary)"
+                    )
+                return {"status": resp.code, "headers": resp.headers, "body": body}
+
+            charset = resp.headers.get_content_charset() or "utf-8"
+            decoded_body: str = resp.read().decode(charset)  # read the response body here
+            if self._logger.level <= logging.DEBUG:
+                self._logger.debug(
+                    "Received the following response - "
+                    f"status: {resp.code}, "
+                    f"headers: {dict(resp.headers)}, "
+                    f"body: {decoded_body}"
+                )
+            return {"status": resp.code, "headers": resp.headers, "body": decoded_body}
+        raise SlackRequestError(f"Invalid URL detected: {url}")
+
+    def _build_urllib_request_headers(
+        self, token: str, has_json: bool, has_files: bool, additional_headers: dict
+    ) -> Dict[str, str]:
+        headers = {"Content-Type": "application/x-www-form-urlencoded"}
+        headers.update(self.headers)
+        if token:
+            headers.update({"Authorization": "Bearer {}".format(token)})
+        if additional_headers:
+            headers.update(additional_headers)
+        if has_json:
+            headers.update({"Content-Type": "application/json;charset=utf-8"})
+        if has_files:
+            # will be set afterward
+            headers.pop("Content-Type", None)
+        return headers
+
+    def _upload_file(
+        self,
+        *,
+        url: str,
+        data: bytes,
+        logger: logging.Logger,
+        timeout: int,
+        proxy: Optional[str],
+        ssl: Optional[SSLContext],
+    ) -> FileUploadV2Result:
+        """Upload a file using the issued upload URL"""
+        result = _upload_file_via_v2_url(
+            url=url,
+            data=data,
+            logger=logger,
+            timeout=timeout,
+            proxy=proxy,
+            ssl=ssl,
+        )
+        return FileUploadV2Result(
+            status=result.get("status"),  # type: ignore[arg-type]
+            body=result.get("body"),  # type: ignore[arg-type]
+        )
+
+    # =================================================================
+
+    @staticmethod
+    def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool:
+        """
+        Slack creates a unique string for your app and shares it with you. Verify
+        requests from Slack with confidence by verifying signatures using your
+        signing secret.
+
+        On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP
+        header. The signature is created by combining the signing secret with the
+        body of the request we're sending using a standard HMAC-SHA256 keyed hash.
+
+        https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview
+
+        Args:
+            signing_secret: Your application's signing secret, available in the
+                Slack API dashboard
+            data: The raw body of the incoming request - no headers, just the body.
+            timestamp: from the 'X-Slack-Request-Timestamp' header
+            signature: from the 'X-Slack-Signature' header - the calculated signature
+                should match this.
+
+        Returns:
+            True if signatures matches
+        """
+        warnings.warn(
+            "As this method is deprecated since slackclient 2.6.0, "
+            "use `from slack.signature import SignatureVerifier` instead",
+            DeprecationWarning,
+        )
+        format_req = str.encode(f"v0:{timestamp}:{data}")
+        encoded_secret = str.encode(signing_secret)
+        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+        calculated_signature = f"v0={request_hash}"
+        return hmac.compare_digest(calculated_signature, signature)
+
+
+

Subclasses

+ +

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def validate_slack_signature(*, signing_secret:Β str, data:Β str, timestamp:Β str, signature:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
@staticmethod
+def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool:
+    """
+    Slack creates a unique string for your app and shares it with you. Verify
+    requests from Slack with confidence by verifying signatures using your
+    signing secret.
+
+    On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP
+    header. The signature is created by combining the signing secret with the
+    body of the request we're sending using a standard HMAC-SHA256 keyed hash.
+
+    https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview
+
+    Args:
+        signing_secret: Your application's signing secret, available in the
+            Slack API dashboard
+        data: The raw body of the incoming request - no headers, just the body.
+        timestamp: from the 'X-Slack-Request-Timestamp' header
+        signature: from the 'X-Slack-Signature' header - the calculated signature
+            should match this.
+
+    Returns:
+        True if signatures matches
+    """
+    warnings.warn(
+        "As this method is deprecated since slackclient 2.6.0, "
+        "use `from slack.signature import SignatureVerifier` instead",
+        DeprecationWarning,
+    )
+    format_req = str.encode(f"v0:{timestamp}:{data}")
+    encoded_secret = str.encode(signing_secret)
+    request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+    calculated_signature = f"v0={request_hash}"
+    return hmac.compare_digest(calculated_signature, signature)
+
+

Slack creates a unique string for your app and shares it with you. Verify +requests from Slack with confidence by verifying signatures using your +signing secret.

+

On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP +header. The signature is created by combining the signing secret with the +body of the request we're sending using a standard HMAC-SHA256 keyed hash.

+

https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview

+

Args

+
+
signing_secret
+
Your application's signing secret, available in the +Slack API dashboard
+
data
+
The raw body of the incoming request - no headers, just the body.
+
timestamp
+
from the 'X-Slack-Request-Timestamp' header
+
signature
+
from the 'X-Slack-Signature' header - the calculated signature +should match this.
+
+

Returns

+

True if signatures matches

+
+
+

Instance variables

+
+
var base_url
+
+

A string representing the Slack API base URL. +Default is 'https://slack.com/api/'.

+
+
var headers
+
+

dict representing additional request headers to attach to all requests.

+
+
prop logger :Β logging.Logger
+
+
+ +Expand source code + +
@property
+def logger(self) -> logging.Logger:
+    """The logger this client uses."""
+    return self._logger
+
+

The logger this client uses.

+
+
var proxy
+
+

String representing a fully-qualified URL to a proxy through which +to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.

+
+
var ssl
+
+

An ssl.SSLContext +instance, helpful for specifying your own custom +certificate chain.

+
+
var timeout
+
+

The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.

+
+
var token
+
+

A string specifying an xoxp-* or xoxb-* token.

+
+
+

Methods

+
+
+def api_call(self,
api_method:Β str,
*,
http_verb:Β strΒ =Β 'POST',
files:Β dictΒ |Β NoneΒ =Β None,
data:Β dictΒ |Β NoneΒ =Β None,
params:Β dictΒ |Β NoneΒ =Β None,
json:Β dictΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
auth:Β dictΒ |Β NoneΒ =Β None) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    api_method: str,
+    *,
+    http_verb: str = "POST",
+    files: Optional[dict] = None,
+    data: Optional[dict] = None,
+    params: Optional[dict] = None,
+    json: Optional[dict] = None,
+    headers: Optional[dict] = None,
+    auth: Optional[dict] = None,
+) -> SlackResponse:
+    """Create a request and execute the API call to Slack.
+
+    Args:
+        api_method (str): The target Slack API method.
+            e.g. 'chat.postMessage'
+        http_verb (str): HTTP Verb. e.g. 'POST'
+        files (dict): Files to multipart upload.
+            e.g. {image OR file: file_object OR file_path}
+        data: The body to attach to the request. If a dictionary is
+            provided, form-encoding will take place.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        params (dict): The URL parameters to append to the URL.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        json (dict): JSON for the body to attach to the request
+            (if files or data is not specified).
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        headers (dict): Additional request headers
+        auth (dict): A dictionary that consists of client_id and client_secret
+
+    Returns:
+        (SlackResponse)
+            The server's response to an HTTP request. Data
+            from the response can be accessed like a dict.
+            If the response included 'next_cursor' it can
+            be iterated on to execute subsequent requests.
+
+    Raises:
+        SlackApiError: The following Slack API call failed:
+            'chat.postMessage'.
+        SlackRequestError: Json data can only be submitted as
+            POST requests.
+    """
+
+    api_url = _get_url(self.base_url, api_method)
+    headers = headers or {}
+    headers.update(self.headers)
+    req_args = _build_req_args(
+        token=self.token,
+        http_verb=http_verb,
+        files=files,  # type: ignore[arg-type]
+        data=data,  # type: ignore[arg-type]
+        default_params=self.default_params,
+        params=params,  # type: ignore[arg-type]
+        json=json,  # type: ignore[arg-type]
+        headers=headers,
+        auth=auth,  # type: ignore[arg-type]
+        ssl=self.ssl,
+        proxy=self.proxy,
+    )
+
+    show_deprecation_warning_if_any(api_method)
+    return self._sync_send(api_url=api_url, req_args=req_args)
+
+

Create a request and execute the API call to Slack.

+

Args

+
+
api_method : str
+
The target Slack API method. +e.g. 'chat.postMessage'
+
http_verb : str
+
HTTP Verb. e.g. 'POST'
+
files : dict
+
Files to multipart upload. +e.g. {image OR file: file_object OR file_path}
+
data
+
The body to attach to the request. If a dictionary is +provided, form-encoding will take place. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
params : dict
+
The URL parameters to append to the URL. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
json : dict
+
JSON for the body to attach to the request +(if files or data is not specified). +e.g. {'key1': 'value1', 'key2': 'value2'}
+
headers : dict
+
Additional request headers
+
auth : dict
+
A dictionary that consists of client_id and client_secret
+
+

Returns

+

(SlackResponse) +The server's response to an HTTP request. Data +from the response can be accessed like a dict. +If the response included 'next_cursor' it can +be iterated on to execute subsequent requests.

+

Raises

+
+
SlackApiError
+
The following Slack API call failed: +'chat.postMessage'.
+
SlackRequestError
+
Json data can only be submitted as +POST requests.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/chat_stream.html b/docs/reference/web/chat_stream.html new file mode 100644 index 000000000..94d96e5eb --- /dev/null +++ b/docs/reference/web/chat_stream.html @@ -0,0 +1,506 @@ + + + + + + +slack_sdk.web.chat_stream API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.chat_stream

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class ChatStream +(client:Β WebClient,
*,
channel:Β str,
logger:Β logging.Logger,
thread_ts:Β str,
buffer_size:Β int,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs)
+
+
+
+ +Expand source code + +
class ChatStream:
+    """A helper class for streaming markdown text into a conversation using the chat streaming APIs.
+
+    This class provides a convenient interface for the chat.startStream, chat.appendStream, and chat.stopStream API
+    methods, with automatic buffering and state management.
+    """
+
+    def __init__(
+        self,
+        client: "WebClient",
+        *,
+        channel: str,
+        logger: logging.Logger,
+        thread_ts: str,
+        buffer_size: int,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ):
+        """Initialize a new ChatStream instance.
+
+        The __init__ method creates a unique ChatStream instance that keeps track of one chat stream.
+
+        Args:
+            client: The WebClient instance to use for API calls.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            logger: A logging channel for outputs.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            buffer_size: The length of markdown_text to buffer in-memory before calling a method. Increasing this value
+              decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
+            **kwargs: Additional arguments passed to the underlying API calls.
+        """
+        self._client = client
+        self._logger = logger
+        self._token: Optional[str] = kwargs.pop("token", None)
+        self._stream_args = {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+            **kwargs,
+        }
+        self._buffer = ""
+        self._state = "starting"
+        self._stream_ts: Optional[str] = None
+        self._buffer_size = buffer_size
+
+    def append(
+        self,
+        *,
+        markdown_text: str,
+        **kwargs,
+    ) -> Optional[SlackResponse]:
+        """Append to the stream.
+
+        The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream
+        is stopped this method cannot be called.
+
+        Args:
+            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+              what will be appended to the message received so far.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            SlackResponse if the buffer was flushed, None if buffering.
+
+        Raises:
+            SlackRequestError: If the stream is already completed.
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        if self._state == "completed":
+            raise e.SlackRequestError(f"Cannot append to stream: stream state is {self._state}")
+        if kwargs.get("token"):
+            self._token = kwargs.pop("token")
+        self._buffer += markdown_text
+        if len(self._buffer) >= self._buffer_size:
+            return self._flush_buffer(**kwargs)
+        details = {
+            "buffer_length": len(self._buffer),
+            "buffer_size": self._buffer_size,
+            "channel": self._stream_args.get("channel"),
+            "recipient_team_id": self._stream_args.get("recipient_team_id"),
+            "recipient_user_id": self._stream_args.get("recipient_user_id"),
+            "thread_ts": self._stream_args.get("thread_ts"),
+        }
+        self._logger.debug(f"ChatStream appended to buffer: {json.dumps(details)}")
+        return None
+
+    def stop(
+        self,
+        *,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Stop the stream and finalize the message.
+
+        Args:
+            blocks: A list of blocks that will be rendered at the bottom of the finalized message.
+            markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+              what will be appended to the message received so far.
+            metadata: JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you
+              post to Slack is accessible to any app or user who is a member of that workspace.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            SlackResponse from the chat.stopStream API call.
+
+        Raises:
+            SlackRequestError: If the stream is already completed.
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        if self._state == "completed":
+            raise e.SlackRequestError(f"Cannot stop stream: stream state is {self._state}")
+        if kwargs.get("token"):
+            self._token = kwargs.pop("token")
+        if markdown_text:
+            self._buffer += markdown_text
+        if not self._stream_ts:
+            response = self._client.chat_startStream(
+                **self._stream_args,
+                token=self._token,
+            )
+            if not response.get("ts"):
+                raise e.SlackRequestError("Failed to stop stream: stream not started")
+            self._stream_ts = str(response["ts"])
+            self._state = "in_progress"
+        response = self._client.chat_stopStream(
+            token=self._token,
+            channel=self._stream_args["channel"],
+            ts=self._stream_ts,
+            blocks=blocks,
+            markdown_text=self._buffer,
+            metadata=metadata,
+            **kwargs,
+        )
+        self._state = "completed"
+        return response
+
+    def _flush_buffer(self, **kwargs) -> SlackResponse:
+        """Flush the internal buffer by making appropriate API calls."""
+        if not self._stream_ts:
+            response = self._client.chat_startStream(
+                **self._stream_args,
+                token=self._token,
+                **kwargs,
+                markdown_text=self._buffer,
+            )
+            self._stream_ts = response.get("ts")
+            self._state = "in_progress"
+        else:
+            response = self._client.chat_appendStream(
+                token=self._token,
+                channel=self._stream_args["channel"],
+                ts=self._stream_ts,
+                **kwargs,
+                markdown_text=self._buffer,
+            )
+        self._buffer = ""
+        return response
+
+

A helper class for streaming markdown text into a conversation using the chat streaming APIs.

+

This class provides a convenient interface for the chat.startStream, chat.appendStream, and chat.stopStream API +methods, with automatic buffering and state management.

+

Initialize a new ChatStream instance.

+

The init method creates a unique ChatStream instance that keeps track of one chat stream.

+

Args

+
+
client
+
The WebClient instance to use for API calls.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
logger
+
A logging channel for outputs.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a method. Increasing this value +decreases the number of method calls made for the same amount of text, which is useful to avoid rate limits.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Methods

+
+
+def append(self, *, markdown_text:Β str, **kwargs) ‑>Β SlackResponseΒ |Β None +
+
+
+ +Expand source code + +
def append(
+    self,
+    *,
+    markdown_text: str,
+    **kwargs,
+) -> Optional[SlackResponse]:
+    """Append to the stream.
+
+    The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream
+    is stopped this method cannot be called.
+
+    Args:
+        markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+          what will be appended to the message received so far.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        SlackResponse if the buffer was flushed, None if buffering.
+
+    Raises:
+        SlackRequestError: If the stream is already completed.
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    if self._state == "completed":
+        raise e.SlackRequestError(f"Cannot append to stream: stream state is {self._state}")
+    if kwargs.get("token"):
+        self._token = kwargs.pop("token")
+    self._buffer += markdown_text
+    if len(self._buffer) >= self._buffer_size:
+        return self._flush_buffer(**kwargs)
+    details = {
+        "buffer_length": len(self._buffer),
+        "buffer_size": self._buffer_size,
+        "channel": self._stream_args.get("channel"),
+        "recipient_team_id": self._stream_args.get("recipient_team_id"),
+        "recipient_user_id": self._stream_args.get("recipient_user_id"),
+        "thread_ts": self._stream_args.get("thread_ts"),
+    }
+    self._logger.debug(f"ChatStream appended to buffer: {json.dumps(details)}")
+    return None
+
+

Append to the stream.

+

The "append" method appends to the chat stream being used. This method can be called multiple times. After the stream +is stopped this method cannot be called.

+

Args

+
+
markdown_text
+
Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is +what will be appended to the message received so far.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

SlackResponse if the buffer was flushed, None if buffering.

+

Raises

+
+
SlackRequestError
+
If the stream is already completed.
+
+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+def stop(self,
*,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stop(
+    self,
+    *,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Stop the stream and finalize the message.
+
+    Args:
+        blocks: A list of blocks that will be rendered at the bottom of the finalized message.
+        markdown_text: Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is
+          what will be appended to the message received so far.
+        metadata: JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you
+          post to Slack is accessible to any app or user who is a member of that workspace.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        SlackResponse from the chat.stopStream API call.
+
+    Raises:
+        SlackRequestError: If the stream is already completed.
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    if self._state == "completed":
+        raise e.SlackRequestError(f"Cannot stop stream: stream state is {self._state}")
+    if kwargs.get("token"):
+        self._token = kwargs.pop("token")
+    if markdown_text:
+        self._buffer += markdown_text
+    if not self._stream_ts:
+        response = self._client.chat_startStream(
+            **self._stream_args,
+            token=self._token,
+        )
+        if not response.get("ts"):
+            raise e.SlackRequestError("Failed to stop stream: stream not started")
+        self._stream_ts = str(response["ts"])
+        self._state = "in_progress"
+    response = self._client.chat_stopStream(
+        token=self._token,
+        channel=self._stream_args["channel"],
+        ts=self._stream_ts,
+        blocks=blocks,
+        markdown_text=self._buffer,
+        metadata=metadata,
+        **kwargs,
+    )
+    self._state = "completed"
+    return response
+
+

Stop the stream and finalize the message.

+

Args

+
+
blocks
+
A list of blocks that will be rendered at the bottom of the finalized message.
+
markdown_text
+
Accepts message text formatted in markdown. Limit this field to 12,000 characters. This text is +what will be appended to the message received so far.
+
metadata
+
JSON object with event_type and event_payload fields, presented as a URL-encoded string. Metadata you +post to Slack is accessible to any app or user who is a member of that workspace.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

SlackResponse from the chat.stopStream API call.

+

Raises

+
+
SlackRequestError
+
If the stream is already completed.
+
+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/client.html b/docs/reference/web/client.html new file mode 100644 index 000000000..6fded11e1 --- /dev/null +++ b/docs/reference/web/client.html @@ -0,0 +1,15787 @@ + + + + + + +slack_sdk.web.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.client

+
+
+

A Python module for interacting with Slack's Web API.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class WebClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebClient(BaseClient):
+    """A WebClient allows apps to communicate with the Slack Platform's Web API.
+
+    https://docs.slack.dev/reference/methods
+
+    The Slack Web API is an interface for querying information from
+    and enacting change in a Slack workspace.
+
+    This client handles constructing and sending HTTP requests to Slack
+    as well as parsing any responses received into a `SlackResponse`.
+
+    Attributes:
+        token (str): A string specifying an `xoxp-*` or `xoxb-*` token.
+        base_url (str): A string representing the Slack API base URL.
+            Default is `'https://slack.com/api/'`
+        timeout (int): The maximum number of seconds the client will wait
+            to connect and receive a response from Slack.
+            Default is 30 seconds.
+        ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying
+            your own custom certificate chain.
+        proxy (str): String representing a fully-qualified URL to a proxy through
+            which to route all requests to the Slack API. Even if this parameter
+            is not specified, if any of the following environment variables are
+            present, they will be loaded into this parameter: `HTTPS_PROXY`,
+            `https_proxy`, `HTTP_PROXY` or `http_proxy`.
+        headers (dict): Additional request headers to attach to all requests.
+
+    Methods:
+        `api_call`: Constructs a request and executes the API call to Slack.
+
+    Example of recommended usage:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.chat_postMessage(
+            channel='#random',
+            text="Hello world!")
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Example manually creating an API request:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.api_call(
+            api_method='chat.postMessage',
+            json={'channel': '#random','text': "Hello world!"}
+        )
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Note:
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+
+    [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
+    """
+
+    def admin_analytics_getFile(
+        self,
+        *,
+        type: str,
+        date: Optional[str] = None,
+        metadata_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve analytics data for a given date, presented as a compressed JSON file
+        https://docs.slack.dev/reference/methods/admin.analytics.getFile
+        """
+        kwargs.update({"type": type})
+        if date is not None:
+            kwargs.update({"date": date})
+        if metadata_only is not None:
+            kwargs.update({"metadata_only": metadata_only})
+        return self.api_call("admin.analytics.getFile", params=kwargs)
+
+    def admin_apps_approve(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve an app for installation on a workspace.
+        Either app_id or request_id is required.
+        These IDs can be obtained either directly via the app_requested event,
+        or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.approve
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approve", params=kwargs)
+
+    def admin_apps_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List approved apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_clearResolution(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear an app resolution
+        https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_cancel(
+        self,
+        *,
+        request_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+        """
+        kwargs.update(
+            {
+                "request_id": request_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_restrict(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Restrict an app for installation on a workspace.
+        Exactly one of the team_id or enterprise_id arguments is required, not both.
+        Either app_id or request_id is required. These IDs can be obtained either directly
+        via the app_requested event, or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.restrict
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restrict", params=kwargs)
+
+    def admin_apps_restricted_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List restricted apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_uninstall(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+        With an org-level token, enterprise_id or team_ids is required.
+        https://docs.slack.dev/reference/methods/admin.apps.uninstall
+        """
+        kwargs.update({"app_id": app_id})
+        if enterprise_id is not None:
+            kwargs.update({"enterprise_id": enterprise_id})
+        if team_ids is not None:
+            if isinstance(team_ids, (list, tuple)):
+                kwargs.update({"team_ids": ",".join(team_ids)})
+            else:
+                kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+    def admin_apps_activities_list(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        component_id: Optional[str] = None,
+        component_type: Optional[str] = None,
+        log_event_type: Optional[str] = None,
+        max_date_created: Optional[int] = None,
+        min_date_created: Optional[int] = None,
+        min_log_level: Optional[str] = None,
+        sort_direction: Optional[str] = None,
+        source: Optional[str] = None,
+        team_id: Optional[str] = None,
+        trace_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get logs for a specified team/org
+        https://docs.slack.dev/reference/methods/admin.apps.activities.list
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "component_id": component_id,
+                "component_type": component_type,
+                "log_event_type": log_event_type,
+                "max_date_created": max_date_created,
+                "min_date_created": min_date_created,
+                "min_log_level": min_log_level,
+                "sort_direction": sort_direction,
+                "source": source,
+                "team_id": team_id,
+                "trace_id": trace_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.apps.activities.list", params=kwargs)
+
+    def admin_apps_config_lookup(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the app config for connectors by their IDs
+        https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+    def admin_apps_config_set(
+        self,
+        *,
+        app_id: str,
+        domain_restrictions: Optional[Dict[str, Any]] = None,
+        workflow_auth_strategy: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the app config for a connector
+        https://docs.slack.dev/reference/methods/admin.apps.config.set
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "workflow_auth_strategy": workflow_auth_strategy,
+            }
+        )
+        if domain_restrictions is not None:
+            kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+        return self.api_call("admin.apps.config.set", params=kwargs)
+
+    def admin_auth_policy_getEntities(
+        self,
+        *,
+        policy_name: str,
+        cursor: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch all the entities assigned to a particular authentication policy by name.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+        """
+        kwargs.update({"policy_name": policy_name})
+        if cursor is not None:
+            kwargs.update({"cursor": cursor})
+        if entity_type is not None:
+            kwargs.update({"entity_type": entity_type})
+        if limit is not None:
+            kwargs.update({"limit": limit})
+        return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_assignEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Assign entities to a particular authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_removeEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove specified entities from a specified authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+    def admin_conversations_createForObjects(
+        self,
+        *,
+        object_id: str,
+        salesforce_org_id: str,
+        invite_object_team: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Salesforce channel for the corresponding object provided.
+        https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+        """
+        kwargs.update(
+            {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+        )
+        return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+    def admin_conversations_linkObjects(
+        self,
+        *,
+        channel: str,
+        record_id: str,
+        salesforce_org_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Link a Salesforce record to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "record_id": record_id,
+                "salesforce_org_id": salesforce_org_id,
+            }
+        )
+        return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+    def admin_conversations_unlinkObjects(
+        self,
+        *,
+        channel: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unlink a Salesforce record from a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "new_name": new_name,
+            }
+        )
+        return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+    def admin_barriers_create(
+        self,
+        *,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.create
+        """
+        kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+    def admin_barriers_delete(
+        self,
+        *,
+        barrier_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.delete
+        """
+        kwargs.update({"barrier_id": barrier_id})
+        return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+    def admin_barriers_update(
+        self,
+        *,
+        barrier_id: str,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.update
+        """
+        kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+    def admin_barriers_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get all Information Barriers for your organization
+        https://docs.slack.dev/reference/methods/admin.barriers.list"""
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+    def admin_conversations_create(
+        self,
+        *,
+        is_private: bool,
+        name: str,
+        description: Optional[str] = None,
+        org_wide: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a public or private channel-based conversation.
+        https://docs.slack.dev/reference/methods/admin.conversations.create
+        """
+        kwargs.update(
+            {
+                "is_private": is_private,
+                "name": name,
+                "description": description,
+                "org_wide": org_wide,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.conversations.create", params=kwargs)
+
+    def admin_conversations_delete(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.delete
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.delete", params=kwargs)
+
+    def admin_conversations_invite(
+        self,
+        *,
+        channel_id: str,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.invite
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+        return self.api_call("admin.conversations.invite", params=kwargs)
+
+    def admin_conversations_archive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.archive", params=kwargs)
+
+    def admin_conversations_unarchive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+    def admin_conversations_rename(
+        self,
+        *,
+        channel_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.rename
+        """
+        kwargs.update({"channel_id": channel_id, "name": name})
+        return self.api_call("admin.conversations.rename", params=kwargs)
+
+    def admin_conversations_search(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        query: Optional[str] = None,
+        search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search for public or private channels in an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.conversations.search
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+            }
+        )
+
+        if isinstance(search_channel_types, (list, tuple)):
+            kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+        else:
+            kwargs.update({"search_channel_types": search_channel_types})
+
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+
+        return self.api_call("admin.conversations.search", params=kwargs)
+
+    def admin_conversations_convertToPrivate(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a public channel to a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+    def admin_conversations_convertToPublic(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a privte channel to a public channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+    def admin_conversations_setConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        prefs: Union[str, Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the posting permissions for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(prefs, dict):
+            kwargs.update({"prefs": json.dumps(prefs)})
+        else:
+            kwargs.update({"prefs": prefs})
+        return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+    def admin_conversations_getConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get conversation preferences for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+    def admin_conversations_disconnectShared(
+        self,
+        *,
+        channel_id: str,
+        leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnect a connected channel from one or more workspaces.
+        https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(leaving_team_ids, (list, tuple)):
+            kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+        else:
+            kwargs.update({"leaving_team_ids": leaving_team_ids})
+        return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+    def admin_conversations_lookup(
+        self,
+        *,
+        last_message_activity_before: int,
+        team_ids: Union[str, Sequence[str]],
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        max_member_count: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns channels on the given team using the filters.
+        https://docs.slack.dev/reference/methods/admin.conversations.lookup
+        """
+        kwargs.update(
+            {
+                "last_message_activity_before": last_message_activity_before,
+                "cursor": cursor,
+                "limit": limit,
+                "max_member_count": max_member_count,
+            }
+        )
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.lookup", params=kwargs)
+
+    def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+        self,
+        *,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all disconnected channelsβ€”i.e.,
+        channels that were once connected to other workspaces and then disconnectedβ€”and
+        the corresponding original channel IDs for key revocation with EKM.
+        https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+    def admin_conversations_restrictAccess_addGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an allowlist of IDP groups for accessing a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.addGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_listGroups(
+        self,
+        *,
+        channel_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all IDP Groups linked to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.listGroups",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_removeGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a linked IDP group linked from a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.removeGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_setTeams(
+        self,
+        *,
+        channel_id: str,
+        org_channel: Optional[bool] = None,
+        target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "org_channel": org_channel,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(target_team_ids, (list, tuple)):
+            kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+        else:
+            kwargs.update({"target_team_ids": target_team_ids})
+        return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+    def admin_conversations_getTeams(
+        self,
+        *,
+        channel_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+    def admin_conversations_getCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+    def admin_conversations_removeCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+    def admin_conversations_setCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        duration_days: int,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+        return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+    def admin_conversations_bulkArchive(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+    def admin_conversations_bulkDelete(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete public or private channels in bulk.
+        https://slack.com/api/admin.conversations.bulkDelete
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+    def admin_conversations_bulkMove(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        target_team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Move public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+        """
+        kwargs.update(
+            {
+                "target_team_id": target_team_id,
+                "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+            }
+        )
+        return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+    def admin_emoji_add(
+        self,
+        *,
+        name: str,
+        url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.add
+        """
+        kwargs.update({"name": name, "url": url})
+        return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+    def admin_emoji_addAlias(
+        self,
+        *,
+        alias_for: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji alias.
+        https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+        """
+        kwargs.update({"alias_for": alias_for, "name": name})
+        return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+    def admin_emoji_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List emoji for an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+    def admin_emoji_remove(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove an emoji across an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.remove
+        """
+        kwargs.update({"name": name})
+        return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+    def admin_emoji_rename(
+        self,
+        *,
+        name: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.rename
+        """
+        kwargs.update({"name": name, "new_name": new_name})
+        return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+    def admin_functions_list(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up functions by a set of apps
+        https://docs.slack.dev/reference/methods/admin.functions.list
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.functions.list", params=kwargs)
+
+    def admin_functions_permissions_lookup(
+        self,
+        *,
+        function_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup the visibility of multiple Slack functions
+        and include the users if it is limited to particular named entities.
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+        """
+        if isinstance(function_ids, (list, tuple)):
+            kwargs.update({"function_ids": ",".join(function_ids)})
+        else:
+            kwargs.update({"function_ids": function_ids})
+        return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+    def admin_functions_permissions_set(
+        self,
+        *,
+        function_id: str,
+        visibility: str,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the visibility of a Slack function
+        and define the users or workspaces if it is set to named_entities
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+        """
+        kwargs.update(
+            {
+                "function_id": function_id,
+                "visibility": visibility,
+            }
+        )
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+    def admin_roles_addAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds members to the specified role with the specified scopes
+        https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+    def admin_roles_listAssignments(
+        self,
+        *,
+        role_ids: Optional[Union[str, Sequence[str]]] = None,
+        entity_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[Union[str, int]] = None,
+        sort_dir: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists assignments for all roles across entities.
+            Options to scope results by any combination of roles or entities
+        https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(role_ids, (list, tuple)):
+            kwargs.update({"role_ids": ",".join(role_ids)})
+        else:
+            kwargs.update({"role_ids": role_ids})
+        return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+    def admin_roles_removeAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a set of users from a role for the given scopes and entities
+        https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+    def admin_users_session_reset(
+        self,
+        *,
+        user_id: str,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Wipes all valid sessions on all devices for a given user.
+        https://docs.slack.dev/reference/methods/admin.users.session.reset
+        """
+        kwargs.update(
+            {
+                "user_id": user_id,
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.reset", params=kwargs)
+
+    def admin_users_session_resetBulk(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+        https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+    def admin_users_session_invalidate(
+        self,
+        *,
+        session_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invalidate a single session for a user by session_id.
+        https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+        """
+        kwargs.update({"session_id": session_id, "team_id": team_id})
+        return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+    def admin_users_session_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all active user sessions for an organization
+        https://docs.slack.dev/reference/methods/admin.users.session.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+                "user_id": user_id,
+            }
+        )
+        return self.api_call("admin.users.session.list", params=kwargs)
+
+    def admin_teams_settings_setDefaultChannels(
+        self,
+        *,
+        team_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the default channels of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+        """
+        kwargs.update({"team_id": team_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+    def admin_users_session_getSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Get user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”given a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+    def admin_users_session_setSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        desktop_app_browser_quit: Optional[bool] = None,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Configure the user-level session settingsβ€”the session duration
+        and what happens when the client closesβ€”for one or more users.
+        https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "desktop_app_browser_quit": desktop_app_browser_quit,
+                "duration": duration,
+            }
+        )
+        return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+    def admin_users_session_clearSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”for a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+    def admin_users_unsupportedVersions_export(
+        self,
+        *,
+        date_end_of_support: Optional[Union[str, int]] = None,
+        date_sessions_started: Optional[Union[str, int]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+        presented as a zipped CSV file.
+        https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+        """
+        kwargs.update(
+            {
+                "date_end_of_support": date_end_of_support,
+                "date_sessions_started": date_sessions_started,
+            }
+        )
+        return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+    def admin_inviteRequests_approve(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+    def admin_inviteRequests_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all approved workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+    def admin_inviteRequests_denied_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all denied workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+    def admin_inviteRequests_deny(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+    def admin_inviteRequests_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all pending workspace invite requests."""
+        return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+    def admin_teams_admins_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_create(
+        self,
+        *,
+        team_domain: str,
+        team_name: str,
+        team_description: Optional[str] = None,
+        team_discoverability: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Enterprise team.
+        https://docs.slack.dev/reference/methods/admin.teams.create
+        """
+        kwargs.update(
+            {
+                "team_domain": team_domain,
+                "team_name": team_name,
+                "team_description": team_description,
+                "team_discoverability": team_discoverability,
+            }
+        )
+        return self.api_call("admin.teams.create", params=kwargs)
+
+    def admin_teams_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all teams on an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.list", params=kwargs)
+
+    def admin_teams_owners_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.owners.list
+        """
+        kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_info(
+        self,
+        *,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch information about settings in a workspace
+        https://docs.slack.dev/reference/methods/admin.teams.settings.info
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("admin.teams.settings.info", params=kwargs)
+
+    def admin_teams_settings_setDescription(
+        self,
+        *,
+        team_id: str,
+        description: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the description of a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+        """
+        kwargs.update({"team_id": team_id, "description": description})
+        return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+    def admin_teams_settings_setDiscoverability(
+        self,
+        *,
+        team_id: str,
+        discoverability: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+        """
+        kwargs.update({"team_id": team_id, "discoverability": discoverability})
+        return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+    def admin_teams_settings_setIcon(
+        self,
+        *,
+        team_id: str,
+        image_url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+        """
+        kwargs.update({"team_id": team_id, "image_url": image_url})
+        return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_setName(
+        self,
+        *,
+        team_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+        """
+        kwargs.update({"team_id": team_id, "name": name})
+        return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+    def admin_usergroups_addChannels(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        usergroup_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+        """
+        kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+    def admin_usergroups_addTeams(
+        self,
+        *,
+        usergroup_id: str,
+        team_ids: Union[str, Sequence[str]],
+        auto_provision: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Associate one or more default workspaces with an organization-wide IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+        """
+        kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+    def admin_usergroups_listChannels(
+        self,
+        *,
+        usergroup_id: str,
+        include_num_members: Optional[bool] = None,
+        team_id: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+        """
+        kwargs.update(
+            {
+                "usergroup_id": usergroup_id,
+                "include_num_members": include_num_members,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+    def admin_usergroups_removeChannels(
+        self,
+        *,
+        usergroup_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+        """
+        kwargs.update({"usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+    def admin_users_assign(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an Enterprise user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.assign
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "user_id": user_id,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.assign", params=kwargs)
+
+    def admin_users_invite(
+        self,
+        *,
+        team_id: str,
+        email: str,
+        channel_ids: Union[str, Sequence[str]],
+        custom_message: Optional[str] = None,
+        email_password_policy_enabled: Optional[bool] = None,
+        guest_expiration_ts: Optional[Union[str, float]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        real_name: Optional[str] = None,
+        resend: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.invite
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "email": email,
+                "custom_message": custom_message,
+                "email_password_policy_enabled": email_password_policy_enabled,
+                "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+                "real_name": real_name,
+                "resend": resend,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.invite", params=kwargs)
+
+    def admin_users_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        include_deactivated_user_workspaces: Optional[bool] = None,
+        is_active: Optional[bool] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List users on a workspace
+        https://docs.slack.dev/reference/methods/admin.users.list
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+                "is_active": is_active,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.users.list", params=kwargs)
+
+    def admin_users_remove(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a user from a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.remove
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.remove", params=kwargs)
+
+    def admin_users_setAdmin(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or owner to be an admin user.
+        https://docs.slack.dev/reference/methods/admin.users.setAdmin
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setAdmin", params=kwargs)
+
+    def admin_users_setExpiration(
+        self,
+        *,
+        expiration_ts: int,
+        user_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an expiration for a guest user.
+        https://docs.slack.dev/reference/methods/admin.users.setExpiration
+        """
+        kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setExpiration", params=kwargs)
+
+    def admin_users_setOwner(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or admin user to be a workspace owner.
+        https://docs.slack.dev/reference/methods/admin.users.setOwner
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setOwner", params=kwargs)
+
+    def admin_users_setRegular(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest user, admin user, or owner to be a regular user.
+        https://docs.slack.dev/reference/methods/admin.users.setRegular
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setRegular", params=kwargs)
+
+    def admin_workflows_search(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        no_collaborators: Optional[bool] = None,
+        num_trigger_ids: Optional[int] = None,
+        query: Optional[str] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        source: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.search
+        """
+        if collaborator_ids is not None:
+            if isinstance(collaborator_ids, (list, tuple)):
+                kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+            else:
+                kwargs.update({"collaborator_ids": collaborator_ids})
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "cursor": cursor,
+                "limit": limit,
+                "no_collaborators": no_collaborators,
+                "num_trigger_ids": num_trigger_ids,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "source": source,
+            }
+        )
+        return self.api_call("admin.workflows.search", params=kwargs)
+
+    def admin_workflows_permissions_lookup(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        max_workflow_triggers: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the permissions for a set of workflows
+        https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        kwargs.update(
+            {
+                "max_workflow_triggers": max_workflow_triggers,
+            }
+        )
+        return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+    def admin_workflows_collaborators_add(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add collaborators to workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+    def admin_workflows_collaborators_remove(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove collaborators from workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+    def admin_workflows_unpublish(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Unpublish workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+    def api_test(
+        self,
+        *,
+        error: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks API calling code.
+        https://docs.slack.dev/reference/methods/api.test
+        """
+        kwargs.update({"error": error})
+        return self.api_call("api.test", params=kwargs)
+
+    def apps_connections_open(
+        self,
+        *,
+        app_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+        in order to receive events and interactive payloads
+        https://docs.slack.dev/reference/methods/apps.connections.open
+        """
+        kwargs.update({"token": app_token})
+        return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+    def apps_event_authorizations_list(
+        self,
+        *,
+        event_context: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a list of authorizations for the given event context.
+        Each authorization represents an app installation that the event is visible to.
+        https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+        """
+        kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+        return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+    def apps_uninstall(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstalls your app from a workspace.
+        https://docs.slack.dev/reference/methods/apps.uninstall
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret})
+        return self.api_call("apps.uninstall", params=kwargs)
+
+    def apps_manifest_create(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.create
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        return self.api_call("apps.manifest.create", params=kwargs)
+
+    def apps_manifest_delete(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Permanently deletes an app created through app manifests
+        https://docs.slack.dev/reference/methods/apps.manifest.delete
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.delete", params=kwargs)
+
+    def apps_manifest_export(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Export an app manifest from an existing app
+        https://docs.slack.dev/reference/methods/apps.manifest.export
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.export", params=kwargs)
+
+    def apps_manifest_update(
+        self,
+        *,
+        app_id: str,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.update
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.update", params=kwargs)
+
+    def apps_manifest_validate(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        app_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Validate an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.validate
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.validate", params=kwargs)
+
+    def tooling_tokens_rotate(
+        self,
+        *,
+        refresh_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a refresh token for a new app configuration token
+        https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+        """
+        kwargs.update({"refresh_token": refresh_token})
+        return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+    def assistant_threads_setStatus(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        status: str,
+        loading_messages: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the status for an AI assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+        """
+        kwargs.update(
+            {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+    def assistant_threads_setTitle(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the title for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+        return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+    def assistant_threads_setSuggestedPrompts(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: Optional[str] = None,
+        prompts: List[Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set suggested prompts for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+        if title is not None:
+            kwargs.update({"title": title})
+        return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+    def auth_revoke(
+        self,
+        *,
+        test: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes a token.
+        https://docs.slack.dev/reference/methods/auth.revoke
+        """
+        kwargs.update({"test": test})
+        return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+    def auth_test(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks authentication & identity.
+        https://docs.slack.dev/reference/methods/auth.test
+        """
+        return self.api_call("auth.test", params=kwargs)
+
+    def auth_teams_list(
+        self,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        include_icon: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List the workspaces a token can access.
+        https://docs.slack.dev/reference/methods/auth.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+        return self.api_call("auth.teams.list", params=kwargs)
+
+    def bookmarks_add(
+        self,
+        *,
+        channel_id: str,
+        title: str,
+        type: str,
+        emoji: Optional[str] = None,
+        entity_id: Optional[str] = None,
+        link: Optional[str] = None,  # include when type is 'link'
+        parent_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add bookmark to a channel.
+        https://docs.slack.dev/reference/methods/bookmarks.add
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "title": title,
+                "type": type,
+                "emoji": emoji,
+                "entity_id": entity_id,
+                "link": link,
+                "parent_id": parent_id,
+            }
+        )
+        return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+    def bookmarks_edit(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        emoji: Optional[str] = None,
+        link: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Edit bookmark.
+        https://docs.slack.dev/reference/methods/bookmarks.edit
+        """
+        kwargs.update(
+            {
+                "bookmark_id": bookmark_id,
+                "channel_id": channel_id,
+                "emoji": emoji,
+                "link": link,
+                "title": title,
+            }
+        )
+        return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+    def bookmarks_list(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """List bookmark for the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.list
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+    def bookmarks_remove(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove bookmark from the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.remove
+        """
+        kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+        return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+    def bots_info(
+        self,
+        *,
+        bot: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a bot user.
+        https://docs.slack.dev/reference/methods/bots.info
+        """
+        kwargs.update({"bot": bot, "team_id": team_id})
+        return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+    def calls_add(
+        self,
+        *,
+        external_unique_id: str,
+        join_url: str,
+        created_by: Optional[str] = None,
+        date_start: Optional[int] = None,
+        desktop_app_join_url: Optional[str] = None,
+        external_display_id: Optional[str] = None,
+        title: Optional[str] = None,
+        users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers a new Call.
+        https://docs.slack.dev/reference/methods/calls.add
+        """
+        kwargs.update(
+            {
+                "external_unique_id": external_unique_id,
+                "join_url": join_url,
+                "created_by": created_by,
+                "date_start": date_start,
+                "desktop_app_join_url": desktop_app_join_url,
+                "external_display_id": external_display_id,
+                "title": title,
+            }
+        )
+        _update_call_participants(
+            kwargs,
+            users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+        )
+        return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+    def calls_end(
+        self,
+        *,
+        id: str,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends a Call.
+        https://docs.slack.dev/reference/methods/calls.end
+        """
+        kwargs.update({"id": id, "duration": duration})
+        return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+    def calls_info(
+        self,
+        *,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns information about a Call.
+        https://docs.slack.dev/reference/methods/calls.info
+        """
+        kwargs.update({"id": id})
+        return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+    def calls_participants_add(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers new participants added to a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.add
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+    def calls_participants_remove(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers participants removed from a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.remove
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+    def calls_update(
+        self,
+        *,
+        id: str,
+        desktop_app_join_url: Optional[str] = None,
+        join_url: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates information about a Call.
+        https://docs.slack.dev/reference/methods/calls.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "desktop_app_join_url": desktop_app_join_url,
+                "join_url": join_url,
+                "title": title,
+            }
+        )
+        return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+    def canvases_create(
+        self,
+        *,
+        title: Optional[str] = None,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create Canvas for a user
+        https://docs.slack.dev/reference/methods/canvases.create
+        """
+        kwargs.update({"title": title, "document_content": document_content})
+        return self.api_call("canvases.create", json=kwargs)
+
+    def canvases_edit(
+        self,
+        *,
+        canvas_id: str,
+        changes: Sequence[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing canvas
+        https://docs.slack.dev/reference/methods/canvases.edit
+        """
+        kwargs.update({"canvas_id": canvas_id, "changes": changes})
+        return self.api_call("canvases.edit", json=kwargs)
+
+    def canvases_delete(
+        self,
+        *,
+        canvas_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a canvas
+        https://docs.slack.dev/reference/methods/canvases.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        return self.api_call("canvases.delete", params=kwargs)
+
+    def canvases_access_set(
+        self,
+        *,
+        canvas_id: str,
+        access_level: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the access level to a canvas for specified entities
+        https://docs.slack.dev/reference/methods/canvases.access.set
+        """
+        kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+
+        return self.api_call("canvases.access.set", params=kwargs)
+
+    def canvases_access_delete(
+        self,
+        *,
+        canvas_id: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/canvases.access.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("canvases.access.delete", params=kwargs)
+
+    def canvases_sections_lookup(
+        self,
+        *,
+        canvas_id: str,
+        criteria: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Find sections matching the provided criteria
+        https://docs.slack.dev/reference/methods/canvases.sections.lookup
+        """
+        kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+        return self.api_call("canvases.sections.lookup", params=kwargs)
+
+    # --------------------------
+    # Deprecated: channels.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def channels_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.archive", json=kwargs)
+
+    def channels_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.create", json=kwargs)
+
+    def channels_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+    def channels_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+    def channels_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.invite", json=kwargs)
+
+    def channels_join(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins a channel, creating it if needed."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.join", json=kwargs)
+
+    def channels_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.kick", json=kwargs)
+
+    def channels_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.leave", json=kwargs)
+
+    def channels_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team."""
+        return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+    def channels_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.mark", json=kwargs)
+
+    def channels_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.rename", json=kwargs)
+
+    def channels_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+    def channels_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setPurpose", json=kwargs)
+
+    def channels_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setTopic", json=kwargs)
+
+    def channels_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.unarchive", json=kwargs)
+
+    # --------------------------
+
+    def chat_appendStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Appends text to an existing streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.appendStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.appendStream", json=kwargs)
+
+    def chat_delete(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a message.
+        https://docs.slack.dev/reference/methods/chat.delete
+        """
+        kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+        return self.api_call("chat.delete", params=kwargs)
+
+    def chat_deleteScheduledMessage(
+        self,
+        *,
+        channel: str,
+        scheduled_message_id: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a scheduled message.
+        https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "scheduled_message_id": scheduled_message_id,
+                "as_user": as_user,
+            }
+        )
+        return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+    def chat_getPermalink(
+        self,
+        *,
+        channel: str,
+        message_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a permalink URL for a specific extant message
+        https://docs.slack.dev/reference/methods/chat.getPermalink
+        """
+        kwargs.update({"channel": channel, "message_ts": message_ts})
+        return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+    def chat_meMessage(
+        self,
+        *,
+        channel: str,
+        text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a me message into a channel.
+        https://docs.slack.dev/reference/methods/chat.meMessage
+        """
+        kwargs.update({"channel": channel, "text": text})
+        return self.api_call("chat.meMessage", params=kwargs)
+
+    def chat_postEphemeral(
+        self,
+        *,
+        channel: str,
+        user: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an ephemeral message to a user in a channel.
+        https://docs.slack.dev/reference/methods/chat.postEphemeral
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "user": user,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postEphemeral", json=kwargs)
+
+    def chat_postMessage(
+        self,
+        *,
+        channel: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        container_id: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        mrkdwn: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,  # none, full
+        metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends a message to a channel.
+        https://docs.slack.dev/reference/methods/chat.postMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "container_id": container_id,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "mrkdwn": mrkdwn,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postMessage", json=kwargs)
+
+    def chat_scheduleMessage(
+        self,
+        *,
+        channel: str,
+        post_at: Union[str, int],
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        parse: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Schedules a message.
+        https://docs.slack.dev/reference/methods/chat.scheduleMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "post_at": post_at,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "parse": parse,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "link_names": link_names,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.scheduleMessage", json=kwargs)
+
+    def chat_scheduledMessages_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all scheduled messages.
+        https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "latest": latest,
+                "limit": limit,
+                "oldest": oldest,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+    def chat_startStream(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        markdown_text: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a new streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.startStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "thread_ts": thread_ts,
+                "markdown_text": markdown_text,
+                "recipient_team_id": recipient_team_id,
+                "recipient_user_id": recipient_user_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.startStream", json=kwargs)
+
+    def chat_stopStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Stops a streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.stopStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+                "blocks": blocks,
+                "metadata": metadata,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.stopStream", json=kwargs)
+
+    def chat_stream(
+        self,
+        *,
+        buffer_size: int = 256,
+        channel: str,
+        thread_ts: str,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> ChatStream:
+        """Stream markdown text into a conversation.
+
+        This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+        the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+        The following methods are used:
+
+        - chat.startStream: Starts a new streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+        - chat.appendStream: Appends text to an existing streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+        - chat.stopStream: Stops a streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+        Args:
+            buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+              value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+              limits. Default: 256.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            ChatStream instance for managing the stream
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        return ChatStream(
+            self,
+            logger=self._logger,
+            channel=channel,
+            thread_ts=thread_ts,
+            recipient_team_id=recipient_team_id,
+            recipient_user_id=recipient_user_id,
+            buffer_size=buffer_size,
+            **kwargs,
+        )
+
+    def chat_unfurl(
+        self,
+        *,
+        channel: Optional[str] = None,
+        ts: Optional[str] = None,
+        source: Optional[str] = None,
+        unfurl_id: Optional[str] = None,
+        unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+        metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+        user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        user_auth_message: Optional[str] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provide custom unfurl behavior for user-posted URLs.
+        https://docs.slack.dev/reference/methods/chat.unfurl
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "source": source,
+                "unfurl_id": unfurl_id,
+                "unfurls": unfurls,
+                "metadata": metadata,
+                "user_auth_blocks": user_auth_blocks,
+                "user_auth_message": user_auth_message,
+                "user_auth_required": user_auth_required,
+                "user_auth_url": user_auth_url,
+            }
+        )
+        _parse_web_class_objects(kwargs)  # for user_auth_blocks
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.unfurl", json=kwargs)
+
+    def chat_update(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        text: Optional[str] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        as_user: Optional[bool] = None,
+        file_ids: Optional[Union[str, Sequence[str]]] = None,
+        link_names: Optional[bool] = None,
+        parse: Optional[str] = None,  # none, full
+        reply_broadcast: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates a message in a channel.
+        https://docs.slack.dev/reference/methods/chat.update
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "as_user": as_user,
+                "link_names": link_names,
+                "parse": parse,
+                "reply_broadcast": reply_broadcast,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        if isinstance(file_ids, (list, tuple)):
+            kwargs.update({"file_ids": ",".join(file_ids)})
+        else:
+            kwargs.update({"file_ids": file_ids})
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.update", kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.update", json=kwargs)
+
+    def conversations_acceptSharedInvite(
+        self,
+        *,
+        channel_name: str,
+        channel_id: Optional[str] = None,
+        invite_id: Optional[str] = None,
+        free_trial_accepted: Optional[bool] = None,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Accepts an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+        """
+        if channel_id is None and invite_id is None:
+            raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+        kwargs.update(
+            {
+                "channel_name": channel_name,
+                "channel_id": channel_id,
+                "invite_id": invite_id,
+                "free_trial_accepted": free_trial_accepted,
+                "is_private": is_private,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_approveSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approves an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a conversation.
+        https://docs.slack.dev/reference/methods/conversations.archive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.archive", params=kwargs)
+
+    def conversations_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.close
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.close", params=kwargs)
+
+    def conversations_create(
+        self,
+        *,
+        name: str,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiates a public or private channel-based conversation
+        https://docs.slack.dev/reference/methods/conversations.create
+        """
+        kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+        return self.api_call("conversations.create", params=kwargs)
+
+    def conversations_declineSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Declines a Slack Connect channel invite.
+        https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+    def conversations_externalInvitePermissions_set(
+        self, *, action: str, channel: str, target_team: str, **kwargs
+    ) -> SlackResponse:
+        """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+        https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+        """
+        kwargs.update(
+            {
+                "action": action,
+                "channel": channel,
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+    def conversations_history(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches a conversation's history of messages and events.
+        https://docs.slack.dev/reference/methods/conversations.history
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+    def conversations_info(
+        self,
+        *,
+        channel: str,
+        include_locale: Optional[bool] = None,
+        include_num_members: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a conversation.
+        https://docs.slack.dev/reference/methods/conversations.info
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "include_locale": include_locale,
+                "include_num_members": include_num_members,
+            }
+        )
+        return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+    def conversations_invite(
+        self,
+        *,
+        channel: str,
+        users: Union[str, Sequence[str]],
+        force: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites users to a channel.
+        https://docs.slack.dev/reference/methods/conversations.invite
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "force": force,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.invite", params=kwargs)
+
+    def conversations_inviteShared(
+        self,
+        *,
+        channel: str,
+        emails: Optional[Union[str, Sequence[str]]] = None,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.inviteShared
+        """
+        if emails is None and user_ids is None:
+            raise e.SlackRequestError("Either emails or user ids must be provided.")
+        kwargs.update({"channel": channel})
+        if isinstance(emails, (list, tuple)):
+            kwargs.update({"emails": ",".join(emails)})
+        else:
+            kwargs.update({"emails": emails})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+    def conversations_join(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins an existing conversation.
+        https://docs.slack.dev/reference/methods/conversations.join
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.join", params=kwargs)
+
+    def conversations_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a conversation.
+        https://docs.slack.dev/reference/methods/conversations.kick
+        """
+        kwargs.update({"channel": channel, "user": user})
+        return self.api_call("conversations.kick", params=kwargs)
+
+    def conversations_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a conversation.
+        https://docs.slack.dev/reference/methods/conversations.leave
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.leave", params=kwargs)
+
+    def conversations_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team.
+        https://docs.slack.dev/reference/methods/conversations.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+    def conversations_listConnectInvites(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List shared channel invites that have been generated
+        or received but have not yet been approved by all parties.
+        https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+        """
+        kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+        return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+    def conversations_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel.
+        https://docs.slack.dev/reference/methods/conversations.mark
+        """
+        kwargs.update({"channel": channel, "ts": ts})
+        return self.api_call("conversations.mark", params=kwargs)
+
+    def conversations_members(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve members of a conversation.
+        https://docs.slack.dev/reference/methods/conversations.members
+        """
+        kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+        return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+    def conversations_open(
+        self,
+        *,
+        channel: Optional[str] = None,
+        return_im: Optional[bool] = None,
+        users: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens or resumes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.open
+        """
+        if channel is None and users is None:
+            raise e.SlackRequestError("Either channel or users must be provided.")
+        kwargs.update({"channel": channel, "return_im": return_im})
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.open", params=kwargs)
+
+    def conversations_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a conversation.
+        https://docs.slack.dev/reference/methods/conversations.rename
+        """
+        kwargs.update({"channel": channel, "name": name})
+        return self.api_call("conversations.rename", params=kwargs)
+
+    def conversations_replies(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a conversation
+        https://docs.slack.dev/reference/methods/conversations.replies
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+    def conversations_requestSharedInvite_approve(
+        self,
+        *,
+        invite_id: str,
+        channel_id: Optional[str] = None,
+        is_external_limited: Optional[str] = None,
+        message: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+        """
+        kwargs.update(
+            {
+                "invite_id": invite_id,
+                "channel_id": channel_id,
+                "is_external_limited": is_external_limited,
+            }
+        )
+        if message is not None:
+            kwargs.update({"message": json.dumps(message)})
+        return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+    def conversations_requestSharedInvite_deny(
+        self,
+        *,
+        invite_id: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a request to invite an external user to a channel.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+        """
+        kwargs.update({"invite_id": invite_id, "message": message})
+        return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+    def conversations_requestSharedInvite_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_approved: Optional[bool] = None,
+        include_denied: Optional[bool] = None,
+        include_expired: Optional[bool] = None,
+        invite_ids: Optional[Union[str, Sequence[str]]] = None,
+        limit: Optional[int] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists requests to add external users to channels with ability to filter.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_approved": include_approved,
+                "include_denied": include_denied,
+                "include_expired": include_expired,
+                "limit": limit,
+                "user_id": user_id,
+            }
+        )
+        if invite_ids is not None:
+            if isinstance(invite_ids, (list, tuple)):
+                kwargs.update({"invite_ids": ",".join(invite_ids)})
+            else:
+                kwargs.update({"invite_ids": invite_ids})
+        return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+    def conversations_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setPurpose
+        """
+        kwargs.update({"channel": channel, "purpose": purpose})
+        return self.api_call("conversations.setPurpose", params=kwargs)
+
+    def conversations_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setTopic
+        """
+        kwargs.update({"channel": channel, "topic": topic})
+        return self.api_call("conversations.setTopic", params=kwargs)
+
+    def conversations_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reverses conversation archival.
+        https://docs.slack.dev/reference/methods/conversations.unarchive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.unarchive", params=kwargs)
+
+    def conversations_canvases_create(
+        self,
+        *,
+        channel_id: str,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/conversations.canvases.create
+        """
+        kwargs.update({"channel_id": channel_id, "document_content": document_content})
+        return self.api_call("conversations.canvases.create", json=kwargs)
+
+    def dialog_open(
+        self,
+        *,
+        dialog: Dict[str, Any],
+        trigger_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a dialog with a user.
+        https://docs.slack.dev/reference/methods/dialog.open
+        """
+        kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: As the dialog can be a dict, this API call works only with json format.
+        return self.api_call("dialog.open", json=kwargs)
+
+    def dnd_endDnd(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's Do Not Disturb session immediately.
+        https://docs.slack.dev/reference/methods/dnd.endDnd
+        """
+        return self.api_call("dnd.endDnd", params=kwargs)
+
+    def dnd_endSnooze(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's snooze mode immediately.
+        https://docs.slack.dev/reference/methods/dnd.endSnooze
+        """
+        return self.api_call("dnd.endSnooze", params=kwargs)
+
+    def dnd_info(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's current Do Not Disturb status.
+        https://docs.slack.dev/reference/methods/dnd.info
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+    def dnd_setSnooze(
+        self,
+        *,
+        num_minutes: Union[int, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Turns on Do Not Disturb mode for the current user, or changes its duration.
+        https://docs.slack.dev/reference/methods/dnd.setSnooze
+        """
+        kwargs.update({"num_minutes": num_minutes})
+        return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+    def dnd_teamInfo(
+        self,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves the Do Not Disturb status for users on a team.
+        https://docs.slack.dev/reference/methods/dnd.teamInfo
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id})
+        return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+    def emoji_list(
+        self,
+        include_categories: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists custom emoji for a team.
+        https://docs.slack.dev/reference/methods/emoji.list
+        """
+        kwargs.update({"include_categories": include_categories})
+        return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+    def entity_presentDetails(
+        self,
+        trigger_id: str,
+        metadata: Optional[Union[Dict, EntityMetadata]] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        error: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provides entity details for the flexpane.
+        https://docs.slack.dev/reference/methods/entity.presentDetails/
+        """
+        kwargs.update({"trigger_id": trigger_id})
+        if metadata is not None:
+            kwargs.update({"metadata": metadata})
+        if user_auth_required is not None:
+            kwargs.update({"user_auth_required": user_auth_required})
+        if user_auth_url is not None:
+            kwargs.update({"user_auth_url": user_auth_url})
+        if error is not None:
+            kwargs.update({"error": error})
+        _parse_web_class_objects(kwargs)
+        return self.api_call("entity.presentDetails", json=kwargs)
+
+    def files_comments_delete(
+        self,
+        *,
+        file: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an existing comment on a file.
+        https://docs.slack.dev/reference/methods/files.comments.delete
+        """
+        kwargs.update({"file": file, "id": id})
+        return self.api_call("files.comments.delete", params=kwargs)
+
+    def files_delete(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a file.
+        https://docs.slack.dev/reference/methods/files.delete
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.delete", params=kwargs)
+
+    def files_info(
+        self,
+        *,
+        file: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a team file.
+        https://docs.slack.dev/reference/methods/files.info
+        """
+        kwargs.update(
+            {
+                "file": file,
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+            }
+        )
+        return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+    def files_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        count: Optional[int] = None,
+        page: Optional[int] = None,
+        show_files_hidden_by_limit: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists & filters team files.
+        https://docs.slack.dev/reference/methods/files.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "count": count,
+                "page": page,
+                "show_files_hidden_by_limit": show_files_hidden_by_limit,
+                "team_id": team_id,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+    def files_remote_info(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.info
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+    def files_remote_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "limit": limit,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+            }
+        )
+        return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+    def files_remote_add(
+        self,
+        *,
+        external_id: str,
+        external_url: str,
+        title: str,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+        preview_image: Optional[Union[str, bytes, IOBase]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a file from a remote service.
+        https://docs.slack.dev/reference/methods/files.remote.add
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.add",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_update(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        external_url: Optional[str] = None,
+        file: Optional[str] = None,
+        title: Optional[str] = None,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[str] = None,
+        preview_image: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates an existing remote file.
+        https://docs.slack.dev/reference/methods/files.remote.update
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "file": file,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.update",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_remove(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a remote file.
+        https://docs.slack.dev/reference/methods/files.remote.remove
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+    def files_remote_share(
+        self,
+        *,
+        channels: Union[str, Sequence[str]],
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a remote file into a channel.
+        https://docs.slack.dev/reference/methods/files.remote.share
+        """
+        if external_id is None and file is None:
+            raise e.SlackRequestError("Either external_id or file must be provided.")
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+    def files_revokePublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes public/external sharing access for a file
+        https://docs.slack.dev/reference/methods/files.revokePublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.revokePublicURL", params=kwargs)
+
+    def files_sharedPublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enables a file for public/external sharing.
+        https://docs.slack.dev/reference/methods/files.sharedPublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.sharedPublicURL", params=kwargs)
+
+    def files_upload(
+        self,
+        *,
+        file: Optional[Union[str, bytes, IOBase]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        filename: Optional[str] = None,
+        filetype: Optional[str] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        title: Optional[str] = None,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uploads or creates a file.
+        https://docs.slack.dev/reference/methods/files.upload
+        """
+        _print_files_upload_v2_suggestion()
+
+        if file is None and content is None:
+            raise e.SlackRequestError("The file or content argument must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update(
+            {
+                "filename": filename,
+                "filetype": filetype,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+                "title": title,
+            }
+        )
+        if file:
+            if kwargs.get("filename") is None and isinstance(file, str):
+                # use the local filename if filename is missing
+                if kwargs.get("filename") is None:
+                    kwargs["filename"] = file.split(os.path.sep)[-1]
+            return self.api_call("files.upload", files={"file": file}, data=kwargs)
+        else:
+            kwargs["content"] = content
+            return self.api_call("files.upload", data=kwargs)
+
+    def files_upload_v2(
+        self,
+        *,
+        # for sending a single file
+        filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+        file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        title: Optional[str] = None,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        # To upload multiple files at a time
+        file_uploads: Optional[List[Dict[str, Any]]] = None,
+        channel: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+        **kwargs,
+    ) -> SlackResponse:
+        """This wrapper method provides an easy way to upload files using the following endpoints:
+
+        - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+        - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+        - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+            and https://docs.slack.dev/reference/methods/files.info
+
+        """
+        if file is None and content is None and file_uploads is None:
+            raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        # deprecated arguments:
+        filetype = kwargs.get("filetype")
+
+        if filetype is not None:
+            warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+        # step1: files.getUploadURLExternal per file
+        files: List[Dict[str, Any]] = []
+        if file_uploads is not None:
+            for f in file_uploads:
+                files.append(_to_v2_file_upload_item(f))
+        else:
+            f = _to_v2_file_upload_item(
+                {
+                    "filename": filename,
+                    "file": file,
+                    "content": content,
+                    "title": title,
+                    "alt_txt": alt_txt,
+                    "snippet_type": snippet_type,
+                }
+            )
+            files.append(f)
+
+        for f in files:
+            url_response = self.files_getUploadURLExternal(
+                filename=f.get("filename"),  # type: ignore[arg-type]
+                length=f.get("length"),  # type: ignore[arg-type]
+                alt_txt=f.get("alt_txt"),
+                snippet_type=f.get("snippet_type"),
+                token=kwargs.get("token"),
+            )
+            _validate_for_legacy_client(url_response)
+            f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+            f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+        # step2: "https://files.slack.com/upload/v1/..." per file
+        for f in files:
+            upload_result = self._upload_file(
+                url=f["upload_url"],
+                data=f["data"],
+                logger=self._logger,
+                timeout=self.timeout,
+                proxy=self.proxy,
+                ssl=self.ssl,
+            )
+            if upload_result.status != 200:
+                status = upload_result.status
+                body = upload_result.body
+                message = (
+                    "Failed to upload a file "
+                    f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+                )
+                raise e.SlackRequestError(message)
+
+        # step3: files.completeUploadExternal with all the sets of (file_id + title)
+        completion = self.files_completeUploadExternal(
+            files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+            channel_id=channel,
+            channels=channels,
+            initial_comment=initial_comment,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+        if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+            completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+        return completion
+
+    def files_getUploadURLExternal(
+        self,
+        *,
+        filename: str,
+        length: int,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets a URL for an edge external upload.
+        https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+        """
+        kwargs.update(
+            {
+                "filename": filename,
+                "length": length,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+    def files_completeUploadExternal(
+        self,
+        *,
+        files: List[Dict[str, str]],
+        channel_id: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Finishes an upload started with files.getUploadURLExternal.
+        https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        """
+        _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+        kwargs.update(
+            {
+                "files": json.dumps(_files),
+                "channel_id": channel_id,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+            }
+        )
+        if channels:
+            kwargs["channels"] = ",".join(channels)
+        return self.api_call("files.completeUploadExternal", params=kwargs)
+
+    def functions_completeSuccess(
+        self,
+        *,
+        function_execution_id: str,
+        outputs: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the successful completion of a function
+        https://docs.slack.dev/reference/methods/functions.completeSuccess
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+        return self.api_call("functions.completeSuccess", params=kwargs)
+
+    def functions_completeError(
+        self,
+        *,
+        function_execution_id: str,
+        error: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the failure to execute a function
+        https://docs.slack.dev/reference/methods/functions.completeError
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "error": error})
+        return self.api_call("functions.completeError", params=kwargs)
+
+    # --------------------------
+    # Deprecated: groups.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def groups_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.archive", json=kwargs)
+
+    def groups_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a private channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.create", json=kwargs)
+
+    def groups_createChild(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clones and archives a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+    def groups_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+    def groups_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+    def groups_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.invite", json=kwargs)
+
+    def groups_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.kick", json=kwargs)
+
+    def groups_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.leave", json=kwargs)
+
+    def groups_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists private channels that the calling user has access to."""
+        return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+    def groups_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a private channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.mark", json=kwargs)
+
+    def groups_open(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.open", json=kwargs)
+
+    def groups_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a private channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.rename", json=kwargs)
+
+    def groups_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a private channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+    def groups_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a private channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setPurpose", json=kwargs)
+
+    def groups_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a private channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setTopic", json=kwargs)
+
+    def groups_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.unarchive", json=kwargs)
+
+    # --------------------------
+    # Deprecated: im.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def im_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Close a direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.close", json=kwargs)
+
+    def im_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from direct message channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+    def im_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists direct message channels for the calling user."""
+        return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+    def im_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.mark", json=kwargs)
+
+    def im_open(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a direct message channel."""
+        kwargs.update({"user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.open", json=kwargs)
+
+    def im_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def migration_exchange(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        to_old: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """For Enterprise Grid workspaces, map local user IDs to global user IDs
+        https://docs.slack.dev/reference/methods/migration.exchange
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id, "to_old": to_old})
+        return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+    # --------------------------
+    # Deprecated: mpim.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def mpim_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a multiparty direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.close", json=kwargs)
+
+    def mpim_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a multiparty direct message."""
+        kwargs.update({"channel": channel})
+        return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+    def mpim_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists multiparty direct message channels for the calling user."""
+        return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+    def mpim_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a multiparty direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.mark", json=kwargs)
+
+    def mpim_open(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """This method opens a multiparty direct message."""
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("mpim.open", params=kwargs)
+
+    def mpim_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation from a
+        multiparty direct message.
+        """
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def oauth_v2_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        # This field is required when processing the OAuth redirect URL requests
+        # while it's absent for token rotation
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        # This field is required for token rotation
+        grant_type: Optional[str] = None,
+        # This field is required for token rotation
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.v2.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "oauth.v2.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        code: str,
+        redirect_uri: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        kwargs.update({"code": code})
+        return self.api_call(
+            "oauth.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_v2_exchange(
+        self,
+        *,
+        token: str,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a legacy access token for a new expiring access token and refresh token
+        https://docs.slack.dev/reference/methods/oauth.v2.exchange
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+        return self.api_call("oauth.v2.exchange", params=kwargs)
+
+    def openid_connect_token(
+        self,
+        client_id: str,
+        client_secret: str,
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        grant_type: Optional[str] = None,
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.token
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "openid.connect.token",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def openid_connect_userInfo(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get the identity of a user who has authorized Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.userInfo
+        """
+        return self.api_call("openid.connect.userInfo", params=kwargs)
+
+    def pins_add(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Pins an item to a channel.
+        https://docs.slack.dev/reference/methods/pins.add
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.add", params=kwargs)
+
+    def pins_list(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists items pinned to a channel.
+        https://docs.slack.dev/reference/methods/pins.list
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+    def pins_remove(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Un-pins an item from a channel.
+        https://docs.slack.dev/reference/methods/pins.remove
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.remove", params=kwargs)
+
+    def reactions_add(
+        self,
+        *,
+        channel: str,
+        name: str,
+        timestamp: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a reaction to an item.
+        https://docs.slack.dev/reference/methods/reactions.add
+        """
+        kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+        return self.api_call("reactions.add", params=kwargs)
+
+    def reactions_get(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        full: Optional[bool] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets reactions for an item.
+        https://docs.slack.dev/reference/methods/reactions.get
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "full": full,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+    def reactions_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        full: Optional[bool] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists reactions made by a user.
+        https://docs.slack.dev/reference/methods/reactions.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "full": full,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+    def reactions_remove(
+        self,
+        *,
+        name: str,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a reaction from an item.
+        https://docs.slack.dev/reference/methods/reactions.remove
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.remove", params=kwargs)
+
+    def reminders_add(
+        self,
+        *,
+        text: str,
+        time: str,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        recurrence: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a reminder.
+        https://docs.slack.dev/reference/methods/reminders.add
+        """
+        kwargs.update(
+            {
+                "text": text,
+                "time": time,
+                "team_id": team_id,
+                "user": user,
+                "recurrence": recurrence,
+            }
+        )
+        return self.api_call("reminders.add", params=kwargs)
+
+    def reminders_complete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Marks a reminder as complete.
+        https://docs.slack.dev/reference/methods/reminders.complete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.complete", params=kwargs)
+
+    def reminders_delete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a reminder.
+        https://docs.slack.dev/reference/methods/reminders.delete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.delete", params=kwargs)
+
+    def reminders_info(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a reminder.
+        https://docs.slack.dev/reference/methods/reminders.info
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+    def reminders_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all reminders created by or for a given user.
+        https://docs.slack.dev/reference/methods/reminders.list
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+    def rtm_connect(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.connect
+        """
+        kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+        return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+    def rtm_start(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        include_locale: Optional[bool] = None,
+        mpim_aware: Optional[bool] = None,
+        no_latest: Optional[bool] = None,
+        no_unreads: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        simple_latest: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.start
+        """
+        kwargs.update(
+            {
+                "batch_presence_aware": batch_presence_aware,
+                "include_locale": include_locale,
+                "mpim_aware": mpim_aware,
+                "no_latest": no_latest,
+                "no_unreads": no_unreads,
+                "presence_sub": presence_sub,
+                "simple_latest": simple_latest,
+            }
+        )
+        return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+    def search_all(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages and files matching a query.
+        https://docs.slack.dev/reference/methods/search.all
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+    def search_files(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for files matching a query.
+        https://docs.slack.dev/reference/methods/search.files
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+    def search_messages(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages matching a query.
+        https://docs.slack.dev/reference/methods/search.messages
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "cursor": cursor,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+    def slackLists_access_delete(
+        self,
+        *,
+        list_id: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revoke access to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.delete
+        """
+        kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.delete", json=kwargs)
+
+    def slackLists_access_set(
+        self,
+        *,
+        list_id: str,
+        access_level: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the access level to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.set
+        """
+        kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.set", json=kwargs)
+
+    def slackLists_create(
+        self,
+        *,
+        name: str,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        schema: Optional[List[Dict[str, Any]]] = None,
+        copy_from_list_id: Optional[str] = None,
+        include_copied_list_records: Optional[bool] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a List.
+        https://docs.slack.dev/reference/methods/slackLists.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description_blocks": description_blocks,
+                "schema": schema,
+                "copy_from_list_id": copy_from_list_id,
+                "include_copied_list_records": include_copied_list_records,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.create", json=kwargs)
+
+    def slackLists_download_get(
+        self,
+        *,
+        list_id: str,
+        job_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve List download URL from an export job to download List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.get
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "job_id": job_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.get", json=kwargs)
+
+    def slackLists_download_start(
+        self,
+        *,
+        list_id: str,
+        include_archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiate a job to export List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.start
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "include_archived": include_archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.start", json=kwargs)
+
+    def slackLists_items_create(
+        self,
+        *,
+        list_id: str,
+        duplicated_item_id: Optional[str] = None,
+        parent_item_id: Optional[str] = None,
+        initial_fields: Optional[List[Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add a new item to an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.create
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "duplicated_item_id": duplicated_item_id,
+                "parent_item_id": parent_item_id,
+                "initial_fields": initial_fields,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.create", json=kwargs)
+
+    def slackLists_items_delete(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an item from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.delete
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.delete", json=kwargs)
+
+    def slackLists_items_deleteMultiple(
+        self,
+        *,
+        list_id: str,
+        ids: List[str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes multiple items from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "ids": ids,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+    def slackLists_items_info(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        include_is_subscribed: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a row from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.info
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+                "include_is_subscribed": include_is_subscribed,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.info", json=kwargs)
+
+    def slackLists_items_list(
+        self,
+        *,
+        list_id: str,
+        limit: Optional[int] = None,
+        cursor: Optional[str] = None,
+        archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get records from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.list
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "limit": limit,
+                "cursor": cursor,
+                "archived": archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.list", json=kwargs)
+
+    def slackLists_items_update(
+        self,
+        *,
+        list_id: str,
+        cells: List[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates cells in a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.update
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "cells": cells,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.update", json=kwargs)
+
+    def slackLists_update(
+        self,
+        *,
+        id: str,
+        name: Optional[str] = None,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update a List.
+        https://docs.slack.dev/reference/methods/slackLists.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "name": name,
+                "description_blocks": description_blocks,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.update", json=kwargs)
+
+    def stars_add(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a star to an item.
+        https://docs.slack.dev/reference/methods/stars.add
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.add", params=kwargs)
+
+    def stars_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists stars for a user.
+        https://docs.slack.dev/reference/methods/stars.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+    def stars_remove(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a star from an item.
+        https://docs.slack.dev/reference/methods/stars.remove
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.remove", params=kwargs)
+
+    def team_accessLogs(
+        self,
+        *,
+        before: Optional[Union[int, str]] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the access logs for the current team.
+        https://docs.slack.dev/reference/methods/team.accessLogs
+        """
+        kwargs.update(
+            {
+                "before": before,
+                "count": count,
+                "page": page,
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+    def team_billableInfo(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets billable users information for the current team.
+        https://docs.slack.dev/reference/methods/team.billableInfo
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+    def team_billing_info(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reads a workspace's billing plan information.
+        https://docs.slack.dev/reference/methods/team.billing.info
+        """
+        return self.api_call("team.billing.info", params=kwargs)
+
+    def team_externalTeams_disconnect(
+        self,
+        *,
+        target_team: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnects an external organization.
+        https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+        """
+        kwargs.update(
+            {
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+    def team_externalTeams_list(
+        self,
+        *,
+        connection_status_filter: Optional[str] = None,
+        slack_connect_pref_filter: Optional[Sequence[str]] = None,
+        sort_direction: Optional[str] = None,
+        sort_field: Optional[str] = None,
+        workspace_filter: Optional[Sequence[str]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns a list of all the external teams connected and details about the connection.
+        https://docs.slack.dev/reference/methods/team.externalTeams.list
+        """
+        kwargs.update(
+            {
+                "connection_status_filter": connection_status_filter,
+                "sort_direction": sort_direction,
+                "sort_field": sort_field,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if slack_connect_pref_filter is not None:
+            if isinstance(slack_connect_pref_filter, (list, tuple)):
+                kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+            else:
+                kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+        if workspace_filter is not None:
+            if isinstance(workspace_filter, (list, tuple)):
+                kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+            else:
+                kwargs.update({"workspace_filter": workspace_filter})
+        return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+    def team_info(
+        self,
+        *,
+        team: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about the current team.
+        https://docs.slack.dev/reference/methods/team.info
+        """
+        kwargs.update({"team": team, "domain": domain})
+        return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+    def team_integrationLogs(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        change_type: Optional[str] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        service_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the integration logs for the current team.
+        https://docs.slack.dev/reference/methods/team.integrationLogs
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "change_type": change_type,
+                "count": count,
+                "page": page,
+                "service_id": service_id,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+    def team_profile_get(
+        self,
+        *,
+        visibility: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a team's profile.
+        https://docs.slack.dev/reference/methods/team.profile.get
+        """
+        kwargs.update({"visibility": visibility})
+        return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+    def team_preferences_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a list of a workspace's team preferences.
+        https://docs.slack.dev/reference/methods/team.preferences.list
+        """
+        return self.api_call("team.preferences.list", params=kwargs)
+
+    def usergroups_create(
+        self,
+        *,
+        name: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a User Group
+        https://docs.slack.dev/reference/methods/usergroups.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.create", params=kwargs)
+
+    def usergroups_disable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disable an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.disable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.disable", params=kwargs)
+
+    def usergroups_enable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enable a User Group
+        https://docs.slack.dev/reference/methods/usergroups.enable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.enable", params=kwargs)
+
+    def usergroups_list(
+        self,
+        *,
+        include_count: Optional[bool] = None,
+        include_disabled: Optional[bool] = None,
+        include_users: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all User Groups for a team
+        https://docs.slack.dev/reference/methods/usergroups.list
+        """
+        kwargs.update(
+            {
+                "include_count": include_count,
+                "include_disabled": include_disabled,
+                "include_users": include_users,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+    def usergroups_update(
+        self,
+        *,
+        usergroup: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "name": name,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.update", params=kwargs)
+
+    def usergroups_users_list(
+        self,
+        *,
+        usergroup: str,
+        include_disabled: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all users in a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.list
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_disabled": include_disabled,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+    def usergroups_users_update(
+        self,
+        *,
+        usergroup: str,
+        users: Union[str, Sequence[str]],
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the list of users for a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("usergroups.users.update", params=kwargs)
+
+    def users_conversations(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List conversations the calling user may access.
+        https://docs.slack.dev/reference/methods/users.conversations
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+    def users_deletePhoto(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete the user profile photo
+        https://docs.slack.dev/reference/methods/users.deletePhoto
+        """
+        return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+    def users_getPresence(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets user presence information.
+        https://docs.slack.dev/reference/methods/users.getPresence
+        """
+        kwargs.update({"user": user})
+        return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+    def users_identity(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a user's identity.
+        https://docs.slack.dev/reference/methods/users.identity
+        """
+        return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+    def users_info(
+        self,
+        *,
+        user: str,
+        include_locale: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a user.
+        https://docs.slack.dev/reference/methods/users.info
+        """
+        kwargs.update({"user": user, "include_locale": include_locale})
+        return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+    def users_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_locale: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all users in a Slack team.
+        https://docs.slack.dev/reference/methods/users.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_locale": include_locale,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+    def users_lookupByEmail(
+        self,
+        *,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Find a user with an email address.
+        https://docs.slack.dev/reference/methods/users.lookupByEmail
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+    def users_setPhoto(
+        self,
+        *,
+        image: Union[str, IOBase],
+        crop_w: Optional[Union[int, str]] = None,
+        crop_x: Optional[Union[int, str]] = None,
+        crop_y: Optional[Union[int, str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the user profile photo
+        https://docs.slack.dev/reference/methods/users.setPhoto
+        """
+        kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+        return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+    def users_setPresence(
+        self,
+        *,
+        presence: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Manually sets user presence.
+        https://docs.slack.dev/reference/methods/users.setPresence
+        """
+        kwargs.update({"presence": presence})
+        return self.api_call("users.setPresence", params=kwargs)
+
+    def users_discoverableContacts_lookup(
+        self,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup an email address to see if someone is on Slack
+        https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+    def users_profile_get(
+        self,
+        *,
+        user: Optional[str] = None,
+        include_labels: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's profile information.
+        https://docs.slack.dev/reference/methods/users.profile.get
+        """
+        kwargs.update({"user": user, "include_labels": include_labels})
+        return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+    def users_profile_set(
+        self,
+        *,
+        name: Optional[str] = None,
+        value: Optional[str] = None,
+        user: Optional[str] = None,
+        profile: Optional[Dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the profile information for a user.
+        https://docs.slack.dev/reference/methods/users.profile.set
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "profile": profile,
+                "user": user,
+                "value": value,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "profile" parameter
+        return self.api_call("users.profile.set", json=kwargs)
+
+    def views_open(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a view for a user.
+        https://docs.slack.dev/reference/methods/views.open
+        See https://docs.slack.dev/surfaces/modals/ for details.
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.open", json=kwargs)
+
+    def views_push(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Push a view onto the stack of a root view.
+        Push a new view onto the existing view stack by passing a view
+        payload and a valid trigger_id generated from an interaction
+        within the existing modal.
+        Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+        to learn more about the lifecycle and intricacies of views.
+        https://docs.slack.dev/reference/methods/views.push
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.push", json=kwargs)
+
+    def views_update(
+        self,
+        *,
+        view: Union[dict, View],
+        external_id: Optional[str] = None,
+        view_id: Optional[str] = None,
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing view.
+        Update a view by passing a new view definition along with the
+        view_id returned in views.open or the external_id.
+        See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+        to learn more about updating views and avoiding race conditions with the hash argument.
+        https://docs.slack.dev/reference/methods/views.update
+        """
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        if external_id:
+            kwargs.update({"external_id": external_id})
+        elif view_id:
+            kwargs.update({"view_id": view_id})
+        else:
+            raise e.SlackRequestError("Either view_id or external_id is required.")
+        kwargs.update({"hash": hash})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.update", json=kwargs)
+
+    def views_publish(
+        self,
+        *,
+        user_id: str,
+        view: Union[dict, View],
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Publish a static view for a User.
+        Create or update the view that comprises an
+        app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+        https://docs.slack.dev/reference/methods/views.publish
+        """
+        kwargs.update({"user_id": user_id, "hash": hash})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.publish", json=kwargs)
+
+    def workflows_featured_add(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add featured workflows to a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.add
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.add", params=kwargs)
+
+    def workflows_featured_list(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """List the featured workflows for specified channels.
+        https://docs.slack.dev/reference/methods/workflows.featured.list
+        """
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("workflows.featured.list", params=kwargs)
+
+    def workflows_featured_remove(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove featured workflows from a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.remove
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.remove", params=kwargs)
+
+    def workflows_featured_set(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set featured workflows for a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.set
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.set", params=kwargs)
+
+    def workflows_stepCompleted(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        outputs: Optional[dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate a successful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepCompleted
+        """
+        kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "outputs" parameter
+        return self.api_call("workflows.stepCompleted", json=kwargs)
+
+    def workflows_stepFailed(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        error: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate an unsuccessful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepFailed
+        """
+        kwargs.update(
+            {
+                "workflow_step_execute_id": workflow_step_execute_id,
+                "error": error,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "error" parameter
+        return self.api_call("workflows.stepFailed", json=kwargs)
+
+    def workflows_updateStep(
+        self,
+        *,
+        workflow_step_edit_id: str,
+        inputs: Optional[Dict[str, Any]] = None,
+        outputs: Optional[List[Dict[str, str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the configuration for a workflow extension step.
+        https://docs.slack.dev/reference/methods/workflows.updateStep
+        """
+        kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+        if inputs is not None:
+            kwargs.update({"inputs": inputs})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+        return self.api_call("workflows.updateStep", json=kwargs)
+
+

A WebClient allows apps to communicate with the Slack Platform's Web API.

+

https://docs.slack.dev/reference/methods

+

The Slack Web API is an interface for querying information from +and enacting change in a Slack workspace.

+

This client handles constructing and sending HTTP requests to Slack +as well as parsing any responses received into a SlackResponse.

+

Attributes

+
+
token : str
+
A string specifying an xoxp-* or xoxb-* token.
+
base_url : str
+
A string representing the Slack API base URL. +Default is 'https://slack.com/api/'
+
timeout : int
+
The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.
+
ssl : SSLContext
+
An ssl.SSLContext instance, helpful for specifying +your own custom certificate chain.
+
proxy : str
+
String representing a fully-qualified URL to a proxy through +which to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.
+
headers : dict
+
Additional request headers to attach to all requests.
+
+

Methods

+

api_call: Constructs a request and executes the API call to Slack.

+

Example of recommended usage:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.chat_postMessage(
+        channel='#random',
+        text="Hello world!")
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Example manually creating an API request:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.api_call(
+        api_method='chat.postMessage',
+        json={'channel': '#random','text': "Hello world!"}
+    )
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Note

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Ancestors

+ +

Methods

+
+
+def admin_analytics_getFile(self,
*,
type:Β str,
date:Β strΒ |Β NoneΒ =Β None,
metadata_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_analytics_getFile(
+    self,
+    *,
+    type: str,
+    date: Optional[str] = None,
+    metadata_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve analytics data for a given date, presented as a compressed JSON file
+    https://docs.slack.dev/reference/methods/admin.analytics.getFile
+    """
+    kwargs.update({"type": type})
+    if date is not None:
+        kwargs.update({"date": date})
+    if metadata_only is not None:
+        kwargs.update({"metadata_only": metadata_only})
+    return self.api_call("admin.analytics.getFile", params=kwargs)
+
+

Retrieve analytics data for a given date, presented as a compressed JSON file +https://docs.slack.dev/reference/methods/admin.analytics.getFile

+
+
+def admin_apps_activities_list(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
component_id:Β strΒ |Β NoneΒ =Β None,
component_type:Β strΒ |Β NoneΒ =Β None,
log_event_type:Β strΒ |Β NoneΒ =Β None,
max_date_created:Β intΒ |Β NoneΒ =Β None,
min_date_created:Β intΒ |Β NoneΒ =Β None,
min_log_level:Β strΒ |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
trace_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_activities_list(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    component_id: Optional[str] = None,
+    component_type: Optional[str] = None,
+    log_event_type: Optional[str] = None,
+    max_date_created: Optional[int] = None,
+    min_date_created: Optional[int] = None,
+    min_log_level: Optional[str] = None,
+    sort_direction: Optional[str] = None,
+    source: Optional[str] = None,
+    team_id: Optional[str] = None,
+    trace_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get logs for a specified team/org
+    https://docs.slack.dev/reference/methods/admin.apps.activities.list
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "component_id": component_id,
+            "component_type": component_type,
+            "log_event_type": log_event_type,
+            "max_date_created": max_date_created,
+            "min_date_created": min_date_created,
+            "min_log_level": min_log_level,
+            "sort_direction": sort_direction,
+            "source": source,
+            "team_id": team_id,
+            "trace_id": trace_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.apps.activities.list", params=kwargs)
+
+ +
+
+def admin_apps_approve(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approve(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve an app for installation on a workspace.
+    Either app_id or request_id is required.
+    These IDs can be obtained either directly via the app_requested event,
+    or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.approve
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approve", params=kwargs)
+
+

Approve an app for installation on a workspace. +Either app_id or request_id is required. +These IDs can be obtained either directly via the app_requested event, +or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.approve

+
+
+def admin_apps_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List approved apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+

List approved apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.approved.list

+
+
+def admin_apps_clearResolution(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_clearResolution(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Clear an app resolution
+    https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_config_lookup(self, *, app_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_apps_config_lookup(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Look up the app config for connectors by their IDs
+    https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+

Look up the app config for connectors by their IDs +https://docs.slack.dev/reference/methods/admin.apps.config.lookup

+
+
+def admin_apps_config_set(self,
*,
app_id:Β str,
domain_restrictions:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_auth_strategy:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_config_set(
+    self,
+    *,
+    app_id: str,
+    domain_restrictions: Optional[Dict[str, Any]] = None,
+    workflow_auth_strategy: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the app config for a connector
+    https://docs.slack.dev/reference/methods/admin.apps.config.set
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "workflow_auth_strategy": workflow_auth_strategy,
+        }
+    )
+    if domain_restrictions is not None:
+        kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+    return self.api_call("admin.apps.config.set", params=kwargs)
+
+ +
+
+def admin_apps_requests_cancel(self,
*,
request_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_cancel(
+    self,
+    *,
+    request_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+    """
+    kwargs.update(
+        {
+            "request_id": request_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_requests_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_apps_restrict(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restrict(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Restrict an app for installation on a workspace.
+    Exactly one of the team_id or enterprise_id arguments is required, not both.
+    Either app_id or request_id is required. These IDs can be obtained either directly
+    via the app_requested event, or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.restrict
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restrict", params=kwargs)
+
+

Restrict an app for installation on a workspace. +Exactly one of the team_id or enterprise_id arguments is required, not both. +Either app_id or request_id is required. These IDs can be obtained either directly +via the app_requested event, or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.restrict

+
+
+def admin_apps_restricted_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restricted_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List restricted apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+

List restricted apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.restricted.list

+
+
+def admin_apps_uninstall(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_uninstall(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+    With an org-level token, enterprise_id or team_ids is required.
+    https://docs.slack.dev/reference/methods/admin.apps.uninstall
+    """
+    kwargs.update({"app_id": app_id})
+    if enterprise_id is not None:
+        kwargs.update({"enterprise_id": enterprise_id})
+    if team_ids is not None:
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+

Uninstall an app from one or many workspaces, or an entire enterprise organization. +With an org-level token, enterprise_id or team_ids is required. +https://docs.slack.dev/reference/methods/admin.apps.uninstall

+
+
+def admin_auth_policy_assignEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_assignEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Assign entities to a particular authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+

Assign entities to a particular authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities

+
+
+def admin_auth_policy_getEntities(self,
*,
policy_name:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_getEntities(
+    self,
+    *,
+    policy_name: str,
+    cursor: Optional[str] = None,
+    entity_type: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch all the entities assigned to a particular authentication policy by name.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+    """
+    kwargs.update({"policy_name": policy_name})
+    if cursor is not None:
+        kwargs.update({"cursor": cursor})
+    if entity_type is not None:
+        kwargs.update({"entity_type": entity_type})
+    if limit is not None:
+        kwargs.update({"limit": limit})
+    return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+

Fetch all the entities assigned to a particular authentication policy by name. +https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities

+
+
+def admin_auth_policy_removeEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_removeEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove specified entities from a specified authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+

Remove specified entities from a specified authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities

+
+
+def admin_barriers_create(self,
*,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_create(
+    self,
+    *,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.create
+    """
+    kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_delete(self, *, barrier_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_delete(
+    self,
+    *,
+    barrier_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.delete
+    """
+    kwargs.update({"barrier_id": barrier_id})
+    return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get all Information Barriers for your organization
+    https://docs.slack.dev/reference/methods/admin.barriers.list"""
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+

Get all Information Barriers for your organization +https://docs.slack.dev/reference/methods/admin.barriers.list

+
+
+def admin_barriers_update(self,
*,
barrier_id:Β str,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_update(
+    self,
+    *,
+    barrier_id: str,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.update
+    """
+    kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_conversations_archive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_archive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.archive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkArchive(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkArchive(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Archive public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkDelete(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkDelete(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Delete public or private channels in bulk.
+    https://slack.com/api/admin.conversations.bulkDelete
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+

Delete public or private channels in bulk. +https://slack.com/api/admin.conversations.bulkDelete

+
+
+def admin_conversations_bulkMove(self, *, channel_ids:Β strΒ |Β Sequence[str], target_team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkMove(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    target_team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Move public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+    """
+    kwargs.update(
+        {
+            "target_team_id": target_team_id,
+            "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+        }
+    )
+    return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPrivate(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPrivate(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a public channel to a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPublic(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPublic(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a privte channel to a public channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+ +
+
+def admin_conversations_create(self,
*,
is_private:Β bool,
name:Β str,
description:Β strΒ |Β NoneΒ =Β None,
org_wide:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_create(
+    self,
+    *,
+    is_private: bool,
+    name: str,
+    description: Optional[str] = None,
+    org_wide: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a public or private channel-based conversation.
+    https://docs.slack.dev/reference/methods/admin.conversations.create
+    """
+    kwargs.update(
+        {
+            "is_private": is_private,
+            "name": name,
+            "description": description,
+            "org_wide": org_wide,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.conversations.create", params=kwargs)
+
+

Create a public or private channel-based conversation. +https://docs.slack.dev/reference/methods/admin.conversations.create

+
+
+def admin_conversations_createForObjects(self,
*,
object_id:Β str,
salesforce_org_id:Β str,
invite_object_team:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_createForObjects(
+    self,
+    *,
+    object_id: str,
+    salesforce_org_id: str,
+    invite_object_team: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Salesforce channel for the corresponding object provided.
+    https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+    """
+    kwargs.update(
+        {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+    )
+    return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+

Create a Salesforce channel for the corresponding object provided. +https://docs.slack.dev/reference/methods/admin.conversations.createForObjects

+
+
+def admin_conversations_delete(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_delete(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.delete
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.delete", params=kwargs)
+
+ +
+
+def admin_conversations_disconnectShared(self,
*,
channel_id:Β str,
leaving_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_disconnectShared(
+    self,
+    *,
+    channel_id: str,
+    leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnect a connected channel from one or more workspaces.
+    https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(leaving_team_ids, (list, tuple)):
+        kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+    else:
+        kwargs.update({"leaving_team_ids": leaving_team_ids})
+    return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+

Disconnect a connected channel from one or more workspaces. +https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared

+
+
+def admin_conversations_ekm_listOriginalConnectedChannelInfo(self,
*,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+    self,
+    *,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all disconnected channelsβ€”i.e.,
+    channels that were once connected to other workspaces and then disconnectedβ€”and
+    the corresponding original channel IDs for key revocation with EKM.
+    https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+

List all disconnected channelsβ€”i.e., +channels that were once connected to other workspaces and then disconnectedβ€”and +the corresponding original channel IDs for key revocation with EKM. +https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo

+
+
+def admin_conversations_getConversationPrefs(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get conversation preferences for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+

Get conversation preferences for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs

+
+
+def admin_conversations_getCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_getTeams(self,
*,
channel_id:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_getTeams(
+    self,
+    *,
+    channel_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a channel. +https://docs.slack.dev/reference/methods/admin.conversations.getTeams

+
+
+def admin_conversations_invite(self, *, channel_id:Β str, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_invite(
+    self,
+    *,
+    channel_id: str,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.invite
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+    return self.api_call("admin.conversations.invite", params=kwargs)
+
+

Invite a user to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.invite

+
+
+def admin_conversations_linkObjects(self, *, channel:Β str, record_id:Β str, salesforce_org_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_linkObjects(
+    self,
+    *,
+    channel: str,
+    record_id: str,
+    salesforce_org_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Link a Salesforce record to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "record_id": record_id,
+            "salesforce_org_id": salesforce_org_id,
+        }
+    )
+    return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+ +
+
+def admin_conversations_lookup(self,
*,
last_message_activity_before:Β int,
team_ids:Β strΒ |Β Sequence[str],
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
max_member_count:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_lookup(
+    self,
+    *,
+    last_message_activity_before: int,
+    team_ids: Union[str, Sequence[str]],
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    max_member_count: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns channels on the given team using the filters.
+    https://docs.slack.dev/reference/methods/admin.conversations.lookup
+    """
+    kwargs.update(
+        {
+            "last_message_activity_before": last_message_activity_before,
+            "cursor": cursor,
+            "limit": limit,
+            "max_member_count": max_member_count,
+        }
+    )
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.lookup", params=kwargs)
+
+

Returns channels on the given team using the filters. +https://docs.slack.dev/reference/methods/admin.conversations.lookup

+
+
+def admin_conversations_removeCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_removeCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_rename(self, *, channel_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_rename(
+    self,
+    *,
+    channel_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.rename
+    """
+    kwargs.update({"channel_id": channel_id, "name": name})
+    return self.api_call("admin.conversations.rename", params=kwargs)
+
+ +
+
+def admin_conversations_restrictAccess_addGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_addGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an allowlist of IDP groups for accessing a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.addGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Add an allowlist of IDP groups for accessing a channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup

+
+
+def admin_conversations_restrictAccess_listGroups(self, *, channel_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_listGroups(
+    self,
+    *,
+    channel_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all IDP Groups linked to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.listGroups",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+ +
+
+def admin_conversations_restrictAccess_removeGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_removeGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a linked IDP group linked from a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.removeGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Remove a linked IDP group linked from a private channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup

+
+ +
+
+ +Expand source code + +
def admin_conversations_search(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    query: Optional[str] = None,
+    search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search for public or private channels in an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.conversations.search
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+        }
+    )
+
+    if isinstance(search_channel_types, (list, tuple)):
+        kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+    else:
+        kwargs.update({"search_channel_types": search_channel_types})
+
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+
+    return self.api_call("admin.conversations.search", params=kwargs)
+
+

Search for public or private channels in an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.conversations.search

+
+
+def admin_conversations_setConversationPrefs(self, *, channel_id:Β str, prefs:Β strΒ |Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    prefs: Union[str, Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the posting permissions for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(prefs, dict):
+        kwargs.update({"prefs": json.dumps(prefs)})
+    else:
+        kwargs.update({"prefs": prefs})
+    return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+

Set the posting permissions for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs

+
+
+def admin_conversations_setCustomRetention(self, *, channel_id:Β str, duration_days:Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    duration_days: int,
+    **kwargs,
+) -> SlackResponse:
+    """Set a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+    return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_setTeams(self,
*,
channel_id:Β str,
org_channel:Β boolΒ |Β NoneΒ =Β None,
target_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_setTeams(
+    self,
+    *,
+    channel_id: str,
+    org_channel: Optional[bool] = None,
+    target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "org_channel": org_channel,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(target_team_ids, (list, tuple)):
+        kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+    else:
+        kwargs.update({"target_team_ids": target_team_ids})
+    return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setTeams

+
+
+def admin_conversations_unarchive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unarchive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+ +
+
+def admin_conversations_unlinkObjects(self, *, channel:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unlinkObjects(
+    self,
+    *,
+    channel: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unlink a Salesforce record from a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "new_name": new_name,
+        }
+    )
+    return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+ +
+
+def admin_emoji_add(self, *, name:Β str, url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_add(
+    self,
+    *,
+    name: str,
+    url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.add
+    """
+    kwargs.update({"name": name, "url": url})
+    return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_addAlias(self, *, alias_for:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_addAlias(
+    self,
+    *,
+    alias_for: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji alias.
+    https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+    """
+    kwargs.update({"alias_for": alias_for, "name": name})
+    return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List emoji for an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+

List emoji for an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.list

+
+
+def admin_emoji_remove(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_remove(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove an emoji across an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.remove
+    """
+    kwargs.update({"name": name})
+    return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+

Remove an emoji across an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.remove

+
+
+def admin_emoji_rename(self, *, name:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_rename(
+    self,
+    *,
+    name: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.rename
+    """
+    kwargs.update({"name": name, "new_name": new_name})
+    return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_functions_list(self,
*,
app_ids:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_list(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up functions by a set of apps
+    https://docs.slack.dev/reference/methods/admin.functions.list
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.functions.list", params=kwargs)
+
+ +
+
+def admin_functions_permissions_lookup(self, *, function_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_functions_permissions_lookup(
+    self,
+    *,
+    function_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Lookup the visibility of multiple Slack functions
+    and include the users if it is limited to particular named entities.
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+    """
+    if isinstance(function_ids, (list, tuple)):
+        kwargs.update({"function_ids": ",".join(function_ids)})
+    else:
+        kwargs.update({"function_ids": function_ids})
+    return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+

Lookup the visibility of multiple Slack functions +and include the users if it is limited to particular named entities. +https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup

+
+
+def admin_functions_permissions_set(self,
*,
function_id:Β str,
visibility:Β str,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_permissions_set(
+    self,
+    *,
+    function_id: str,
+    visibility: str,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the visibility of a Slack function
+    and define the users or workspaces if it is set to named_entities
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+    """
+    kwargs.update(
+        {
+            "function_id": function_id,
+            "visibility": visibility,
+        }
+    )
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+

Set the visibility of a Slack function +and define the users or workspaces if it is set to named_entities +https://docs.slack.dev/reference/methods/admin.functions.permissions.set

+
+
+def admin_inviteRequests_approve(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_approve(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+ +
+
+def admin_inviteRequests_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all approved workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_denied_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_denied_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all denied workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_deny(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_deny(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+ +
+
+def admin_inviteRequests_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """List all pending workspace invite requests."""
+    return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+

List all pending workspace invite requests.

+
+
+def admin_roles_addAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_addAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Adds members to the specified role with the specified scopes
+    https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+

Adds members to the specified role with the specified scopes +https://docs.slack.dev/reference/methods/admin.roles.addAssignments

+
+
+def admin_roles_listAssignments(self,
*,
role_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
entity_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β strΒ |Β intΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_listAssignments(
+    self,
+    *,
+    role_ids: Optional[Union[str, Sequence[str]]] = None,
+    entity_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[Union[str, int]] = None,
+    sort_dir: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists assignments for all roles across entities.
+        Options to scope results by any combination of roles or entities
+    https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(role_ids, (list, tuple)):
+        kwargs.update({"role_ids": ",".join(role_ids)})
+    else:
+        kwargs.update({"role_ids": role_ids})
+    return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+

Lists assignments for all roles across entities. +Options to scope results by any combination of roles or entities +https://docs.slack.dev/reference/methods/admin.roles.listAssignments

+
+
+def admin_roles_removeAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_removeAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Removes a set of users from a role for the given scopes and entities
+    https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+

Removes a set of users from a role for the given scopes and entities +https://docs.slack.dev/reference/methods/admin.roles.removeAssignments

+
+
+def admin_teams_admins_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_admins_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.inviteRequests.list

+
+
+def admin_teams_create(self,
*,
team_domain:Β str,
team_name:Β str,
team_description:Β strΒ |Β NoneΒ =Β None,
team_discoverability:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_teams_create(
+    self,
+    *,
+    team_domain: str,
+    team_name: str,
+    team_description: Optional[str] = None,
+    team_discoverability: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create an Enterprise team.
+    https://docs.slack.dev/reference/methods/admin.teams.create
+    """
+    kwargs.update(
+        {
+            "team_domain": team_domain,
+            "team_name": team_name,
+            "team_description": team_description,
+            "team_discoverability": team_discoverability,
+        }
+    )
+    return self.api_call("admin.teams.create", params=kwargs)
+
+ +
+
+def admin_teams_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all teams on an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.list", params=kwargs)
+
+

List all teams on an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.teams.list

+
+
+def admin_teams_owners_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_owners_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.owners.list
+    """
+    kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.teams.owners.list

+
+
+def admin_teams_settings_info(self, *, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_info(
+    self,
+    *,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch information about settings in a workspace
+    https://docs.slack.dev/reference/methods/admin.teams.settings.info
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("admin.teams.settings.info", params=kwargs)
+
+

Fetch information about settings in a workspace +https://docs.slack.dev/reference/methods/admin.teams.settings.info

+
+
+def admin_teams_settings_setDefaultChannels(self, *, team_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDefaultChannels(
+    self,
+    *,
+    team_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the default channels of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+    """
+    kwargs.update({"team_id": team_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDescription(self, *, team_id:Β str, description:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDescription(
+    self,
+    *,
+    team_id: str,
+    description: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the description of a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+    """
+    kwargs.update({"team_id": team_id, "description": description})
+    return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDiscoverability(self, *, team_id:Β str, discoverability:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDiscoverability(
+    self,
+    *,
+    team_id: str,
+    discoverability: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+    """
+    kwargs.update({"team_id": team_id, "discoverability": discoverability})
+    return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+ +
+
+def admin_teams_settings_setIcon(self, *, team_id:Β str, image_url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setIcon(
+    self,
+    *,
+    team_id: str,
+    image_url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+    """
+    kwargs.update({"team_id": team_id, "image_url": image_url})
+    return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setName(self, *, team_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setName(
+    self,
+    *,
+    team_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+    """
+    kwargs.update({"team_id": team_id, "name": name})
+    return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+ +
+
+def admin_usergroups_addChannels(self,
*,
channel_ids:Β strΒ |Β Sequence[str],
usergroup_id:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addChannels(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    usergroup_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+    """
+    kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addChannels

+
+
+def admin_usergroups_addTeams(self,
*,
usergroup_id:Β str,
team_ids:Β strΒ |Β Sequence[str],
auto_provision:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addTeams(
+    self,
+    *,
+    usergroup_id: str,
+    team_ids: Union[str, Sequence[str]],
+    auto_provision: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Associate one or more default workspaces with an organization-wide IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+    """
+    kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+

Associate one or more default workspaces with an organization-wide IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addTeams

+
+
+def admin_usergroups_listChannels(self,
*,
usergroup_id:Β str,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
team_id:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_listChannels(
+    self,
+    *,
+    usergroup_id: str,
+    include_num_members: Optional[bool] = None,
+    team_id: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+    """
+    kwargs.update(
+        {
+            "usergroup_id": usergroup_id,
+            "include_num_members": include_num_members,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.listChannels

+
+
+def admin_usergroups_removeChannels(self, *, usergroup_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_usergroups_removeChannels(
+    self,
+    *,
+    usergroup_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+    """
+    kwargs.update({"usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels

+
+
+def admin_users_assign(self,
*,
team_id:Β str,
user_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_assign(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an Enterprise user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.assign
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "user_id": user_id,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.assign", params=kwargs)
+
+

Add an Enterprise user to a workspace. +https://docs.slack.dev/reference/methods/admin.users.assign

+
+
+def admin_users_invite(self,
*,
team_id:Β str,
email:Β str,
channel_ids:Β strΒ |Β Sequence[str],
custom_message:Β strΒ |Β NoneΒ =Β None,
email_password_policy_enabled:Β boolΒ |Β NoneΒ =Β None,
guest_expiration_ts:Β strΒ |Β floatΒ |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
real_name:Β strΒ |Β NoneΒ =Β None,
resend:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_invite(
+    self,
+    *,
+    team_id: str,
+    email: str,
+    channel_ids: Union[str, Sequence[str]],
+    custom_message: Optional[str] = None,
+    email_password_policy_enabled: Optional[bool] = None,
+    guest_expiration_ts: Optional[Union[str, float]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    real_name: Optional[str] = None,
+    resend: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.invite
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "email": email,
+            "custom_message": custom_message,
+            "email_password_policy_enabled": email_password_policy_enabled,
+            "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+            "real_name": real_name,
+            "resend": resend,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.invite", params=kwargs)
+
+ +
+
+def admin_users_list(self,
*,
team_id:Β strΒ |Β NoneΒ =Β None,
include_deactivated_user_workspaces:Β boolΒ |Β NoneΒ =Β None,
is_active:Β boolΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    include_deactivated_user_workspaces: Optional[bool] = None,
+    is_active: Optional[bool] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List users on a workspace
+    https://docs.slack.dev/reference/methods/admin.users.list
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+            "is_active": is_active,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.users.list", params=kwargs)
+
+ +
+
+def admin_users_remove(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_remove(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a user from a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.remove
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.remove", params=kwargs)
+
+ +
+
+def admin_users_session_clearSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_clearSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Clear user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”for a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+

Clear user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”for a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.clearSettings

+
+
+def admin_users_session_getSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_getSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Get user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”given a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+

Get user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”given a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.getSettings

+
+
+def admin_users_session_invalidate(self, *, session_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_invalidate(
+    self,
+    *,
+    session_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invalidate a single session for a user by session_id.
+    https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+    """
+    kwargs.update({"session_id": session_id, "team_id": team_id})
+    return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+

Invalidate a single session for a user by session_id. +https://docs.slack.dev/reference/methods/admin.users.session.invalidate

+
+
+def admin_users_session_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all active user sessions for an organization
+    https://docs.slack.dev/reference/methods/admin.users.session.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+            "user_id": user_id,
+        }
+    )
+    return self.api_call("admin.users.session.list", params=kwargs)
+
+

Lists all active user sessions for an organization +https://docs.slack.dev/reference/methods/admin.users.session.list

+
+
+def admin_users_session_reset(self,
*,
user_id:Β str,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_reset(
+    self,
+    *,
+    user_id: str,
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Wipes all valid sessions on all devices for a given user.
+    https://docs.slack.dev/reference/methods/admin.users.session.reset
+    """
+    kwargs.update(
+        {
+            "user_id": user_id,
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.reset", params=kwargs)
+
+

Wipes all valid sessions on all devices for a given user. +https://docs.slack.dev/reference/methods/admin.users.session.reset

+
+
+def admin_users_session_resetBulk(self,
*,
user_ids:Β strΒ |Β Sequence[str],
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_resetBulk(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+    https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+

Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users +https://docs.slack.dev/reference/methods/admin.users.session.resetBulk

+
+
+def admin_users_session_setSettings(self,
*,
user_ids:Β strΒ |Β Sequence[str],
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_setSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    desktop_app_browser_quit: Optional[bool] = None,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Configure the user-level session settingsβ€”the session duration
+    and what happens when the client closesβ€”for one or more users.
+    https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "desktop_app_browser_quit": desktop_app_browser_quit,
+            "duration": duration,
+        }
+    )
+    return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+

Configure the user-level session settingsβ€”the session duration +and what happens when the client closesβ€”for one or more users. +https://docs.slack.dev/reference/methods/admin.users.session.setSettings

+
+
+def admin_users_setAdmin(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setAdmin(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or owner to be an admin user.
+    https://docs.slack.dev/reference/methods/admin.users.setAdmin
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setAdmin", params=kwargs)
+
+

Set an existing guest, regular user, or owner to be an admin user. +https://docs.slack.dev/reference/methods/admin.users.setAdmin

+
+
+def admin_users_setExpiration(self, *, expiration_ts:Β int, user_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setExpiration(
+    self,
+    *,
+    expiration_ts: int,
+    user_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set an expiration for a guest user.
+    https://docs.slack.dev/reference/methods/admin.users.setExpiration
+    """
+    kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setExpiration", params=kwargs)
+
+ +
+
+def admin_users_setOwner(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setOwner(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or admin user to be a workspace owner.
+    https://docs.slack.dev/reference/methods/admin.users.setOwner
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setOwner", params=kwargs)
+
+

Set an existing guest, regular user, or admin user to be a workspace owner. +https://docs.slack.dev/reference/methods/admin.users.setOwner

+
+
+def admin_users_setRegular(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setRegular(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest user, admin user, or owner to be a regular user.
+    https://docs.slack.dev/reference/methods/admin.users.setRegular
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setRegular", params=kwargs)
+
+

Set an existing guest user, admin user, or owner to be a regular user. +https://docs.slack.dev/reference/methods/admin.users.setRegular

+
+
+def admin_users_unsupportedVersions_export(self,
*,
date_end_of_support:Β strΒ |Β intΒ |Β NoneΒ =Β None,
date_sessions_started:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_unsupportedVersions_export(
+    self,
+    *,
+    date_end_of_support: Optional[Union[str, int]] = None,
+    date_sessions_started: Optional[Union[str, int]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+    presented as a zipped CSV file.
+    https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+    """
+    kwargs.update(
+        {
+            "date_end_of_support": date_end_of_support,
+            "date_sessions_started": date_sessions_started,
+        }
+    )
+    return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+

Ask Slackbot to send you an export listing all workspace members using unsupported software, +presented as a zipped CSV file. +https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export

+
+
+def admin_workflows_collaborators_add(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_add(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add collaborators to workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+

Add collaborators to workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add

+
+
+def admin_workflows_collaborators_remove(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_remove(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove collaborators from workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+

Remove collaborators from workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove

+
+
+def admin_workflows_permissions_lookup(self,
*,
workflow_ids:Β strΒ |Β Sequence[str],
max_workflow_triggers:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_permissions_lookup(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    max_workflow_triggers: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up the permissions for a set of workflows
+    https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    kwargs.update(
+        {
+            "max_workflow_triggers": max_workflow_triggers,
+        }
+    )
+    return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def admin_workflows_search(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    no_collaborators: Optional[bool] = None,
+    num_trigger_ids: Optional[int] = None,
+    query: Optional[str] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    source: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.search
+    """
+    if collaborator_ids is not None:
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "cursor": cursor,
+            "limit": limit,
+            "no_collaborators": no_collaborators,
+            "num_trigger_ids": num_trigger_ids,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "source": source,
+        }
+    )
+    return self.api_call("admin.workflows.search", params=kwargs)
+
+

Search workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.search

+
+
+def admin_workflows_unpublish(self, *, workflow_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_workflows_unpublish(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Unpublish workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+

Unpublish workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.unpublish

+
+
+def api_test(self, *, error:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def api_test(
+    self,
+    *,
+    error: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Checks API calling code.
+    https://docs.slack.dev/reference/methods/api.test
+    """
+    kwargs.update({"error": error})
+    return self.api_call("api.test", params=kwargs)
+
+ +
+
+def apps_connections_open(self, *, app_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_connections_open(
+    self,
+    *,
+    app_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+    in order to receive events and interactive payloads
+    https://docs.slack.dev/reference/methods/apps.connections.open
+    """
+    kwargs.update({"token": app_token})
+    return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+

Generate a temporary Socket Mode WebSocket URL that your app can connect to +in order to receive events and interactive payloads +https://docs.slack.dev/reference/methods/apps.connections.open

+
+
+def apps_event_authorizations_list(self,
*,
event_context:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def apps_event_authorizations_list(
+    self,
+    *,
+    event_context: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a list of authorizations for the given event context.
+    Each authorization represents an app installation that the event is visible to.
+    https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+    """
+    kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+    return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+

Get a list of authorizations for the given event context. +Each authorization represents an app installation that the event is visible to. +https://docs.slack.dev/reference/methods/apps.event.authorizations.list

+
+
+def apps_manifest_create(self, *, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_create(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.create
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    return self.api_call("apps.manifest.create", params=kwargs)
+
+ +
+
+def apps_manifest_delete(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_delete(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Permanently deletes an app created through app manifests
+    https://docs.slack.dev/reference/methods/apps.manifest.delete
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.delete", params=kwargs)
+
+

Permanently deletes an app created through app manifests +https://docs.slack.dev/reference/methods/apps.manifest.delete

+
+
+def apps_manifest_export(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_export(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Export an app manifest from an existing app
+    https://docs.slack.dev/reference/methods/apps.manifest.export
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.export", params=kwargs)
+
+

Export an app manifest from an existing app +https://docs.slack.dev/reference/methods/apps.manifest.export

+
+
+def apps_manifest_update(self, *, app_id:Β str, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_update(
+    self,
+    *,
+    app_id: str,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.update
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.update", params=kwargs)
+
+ +
+
+def apps_manifest_validate(self, *, manifest:Β strΒ |Β Dict[str,Β Any], app_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_validate(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    app_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Validate an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.validate
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.validate", params=kwargs)
+
+ +
+
+def apps_uninstall(self, *, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_uninstall(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstalls your app from a workspace.
+    https://docs.slack.dev/reference/methods/apps.uninstall
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret})
+    return self.api_call("apps.uninstall", params=kwargs)
+
+

Uninstalls your app from a workspace. +https://docs.slack.dev/reference/methods/apps.uninstall

+
+
+def assistant_threads_setStatus(self,
*,
channel_id:Β str,
thread_ts:Β str,
status:Β str,
loading_messages:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setStatus(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    status: str,
+    loading_messages: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the status for an AI assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+    """
+    kwargs.update(
+        {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+ +
+
+def assistant_threads_setSuggestedPrompts(self,
*,
channel_id:Β str,
thread_ts:Β str,
title:Β strΒ |Β NoneΒ =Β None,
prompts:Β List[Dict[str,Β str]],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setSuggestedPrompts(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: Optional[str] = None,
+    prompts: List[Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set suggested prompts for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+    if title is not None:
+        kwargs.update({"title": title})
+    return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+

Set suggested prompts for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts

+
+
+def assistant_threads_setTitle(self, *, channel_id:Β str, thread_ts:Β str, title:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def assistant_threads_setTitle(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the title for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+    return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+

Set the title for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setTitle

+
+
+def auth_revoke(self, *, test:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_revoke(
+    self,
+    *,
+    test: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes a token.
+    https://docs.slack.dev/reference/methods/auth.revoke
+    """
+    kwargs.update({"test": test})
+    return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+ +
+
+def auth_teams_list(self,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
include_icon:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def auth_teams_list(
+    self,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    include_icon: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List the workspaces a token can access.
+    https://docs.slack.dev/reference/methods/auth.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+    return self.api_call("auth.teams.list", params=kwargs)
+
+

List the workspaces a token can access. +https://docs.slack.dev/reference/methods/auth.teams.list

+
+
+def auth_test(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_test(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Checks authentication & identity.
+    https://docs.slack.dev/reference/methods/auth.test
+    """
+    return self.api_call("auth.test", params=kwargs)
+
+

Checks authentication & identity. +https://docs.slack.dev/reference/methods/auth.test

+
+
+def bookmarks_add(self,
*,
channel_id:Β str,
title:Β str,
type:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
entity_id:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
parent_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_add(
+    self,
+    *,
+    channel_id: str,
+    title: str,
+    type: str,
+    emoji: Optional[str] = None,
+    entity_id: Optional[str] = None,
+    link: Optional[str] = None,  # include when type is 'link'
+    parent_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add bookmark to a channel.
+    https://docs.slack.dev/reference/methods/bookmarks.add
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "title": title,
+            "type": type,
+            "emoji": emoji,
+            "entity_id": entity_id,
+            "link": link,
+            "parent_id": parent_id,
+        }
+    )
+    return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_edit(self,
*,
bookmark_id:Β str,
channel_id:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_edit(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    emoji: Optional[str] = None,
+    link: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Edit bookmark.
+    https://docs.slack.dev/reference/methods/bookmarks.edit
+    """
+    kwargs.update(
+        {
+            "bookmark_id": bookmark_id,
+            "channel_id": channel_id,
+            "emoji": emoji,
+            "link": link,
+            "title": title,
+        }
+    )
+    return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_list(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_list(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """List bookmark for the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.list
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_remove(self, *, bookmark_id:Β str, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_remove(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove bookmark from the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.remove
+    """
+    kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+    return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def bots_info(self, *, bot:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bots_info(
+    self,
+    *,
+    bot: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a bot user.
+    https://docs.slack.dev/reference/methods/bots.info
+    """
+    kwargs.update({"bot": bot, "team_id": team_id})
+    return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+

Gets information about a bot user. +https://docs.slack.dev/reference/methods/bots.info

+
+
+def calls_add(self,
*,
external_unique_id:Β str,
join_url:Β str,
created_by:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
external_display_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_add(
+    self,
+    *,
+    external_unique_id: str,
+    join_url: str,
+    created_by: Optional[str] = None,
+    date_start: Optional[int] = None,
+    desktop_app_join_url: Optional[str] = None,
+    external_display_id: Optional[str] = None,
+    title: Optional[str] = None,
+    users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Registers a new Call.
+    https://docs.slack.dev/reference/methods/calls.add
+    """
+    kwargs.update(
+        {
+            "external_unique_id": external_unique_id,
+            "join_url": join_url,
+            "created_by": created_by,
+            "date_start": date_start,
+            "desktop_app_join_url": desktop_app_join_url,
+            "external_display_id": external_display_id,
+            "title": title,
+        }
+    )
+    _update_call_participants(
+        kwargs,
+        users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+    )
+    return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_end(self, *, id:Β str, duration:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_end(
+    self,
+    *,
+    id: str,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ends a Call.
+    https://docs.slack.dev/reference/methods/calls.end
+    """
+    kwargs.update({"id": id, "duration": duration})
+    return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_info(self, *, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_info(
+    self,
+    *,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Returns information about a Call.
+    https://docs.slack.dev/reference/methods/calls.info
+    """
+    kwargs.update({"id": id})
+    return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+

Returns information about a Call. +https://docs.slack.dev/reference/methods/calls.info

+
+
+def calls_participants_add(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_add(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers new participants added to a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.add
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+

Registers new participants added to a Call. +https://docs.slack.dev/reference/methods/calls.participants.add

+
+
+def calls_participants_remove(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_remove(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers participants removed from a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.remove
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+

Registers participants removed from a Call. +https://docs.slack.dev/reference/methods/calls.participants.remove

+
+
+def calls_update(self,
*,
id:Β str,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
join_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_update(
+    self,
+    *,
+    id: str,
+    desktop_app_join_url: Optional[str] = None,
+    join_url: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates information about a Call.
+    https://docs.slack.dev/reference/methods/calls.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "desktop_app_join_url": desktop_app_join_url,
+            "join_url": join_url,
+            "title": title,
+        }
+    )
+    return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+ +
+
+def canvases_access_delete(self,
*,
canvas_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_delete(
+    self,
+    *,
+    canvas_id: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/canvases.access.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("canvases.access.delete", params=kwargs)
+
+ +
+
+def canvases_access_set(self,
*,
canvas_id:Β str,
access_level:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_set(
+    self,
+    *,
+    canvas_id: str,
+    access_level: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the access level to a canvas for specified entities
+    https://docs.slack.dev/reference/methods/canvases.access.set
+    """
+    kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+
+    return self.api_call("canvases.access.set", params=kwargs)
+
+

Sets the access level to a canvas for specified entities +https://docs.slack.dev/reference/methods/canvases.access.set

+
+
+def canvases_create(self, *, title:Β strΒ |Β NoneΒ =Β None, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_create(
+    self,
+    *,
+    title: Optional[str] = None,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create Canvas for a user
+    https://docs.slack.dev/reference/methods/canvases.create
+    """
+    kwargs.update({"title": title, "document_content": document_content})
+    return self.api_call("canvases.create", json=kwargs)
+
+ +
+
+def canvases_delete(self, *, canvas_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_delete(
+    self,
+    *,
+    canvas_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a canvas
+    https://docs.slack.dev/reference/methods/canvases.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    return self.api_call("canvases.delete", params=kwargs)
+
+ +
+
+def canvases_edit(self, *, canvas_id:Β str, changes:Β Sequence[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_edit(
+    self,
+    *,
+    canvas_id: str,
+    changes: Sequence[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing canvas
+    https://docs.slack.dev/reference/methods/canvases.edit
+    """
+    kwargs.update({"canvas_id": canvas_id, "changes": changes})
+    return self.api_call("canvases.edit", json=kwargs)
+
+ +
+
+def canvases_sections_lookup(self, *, canvas_id:Β str, criteria:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_sections_lookup(
+    self,
+    *,
+    canvas_id: str,
+    criteria: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Find sections matching the provided criteria
+    https://docs.slack.dev/reference/methods/canvases.sections.lookup
+    """
+    kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+    return self.api_call("canvases.sections.lookup", params=kwargs)
+
+

Find sections matching the provided criteria +https://docs.slack.dev/reference/methods/canvases.sections.lookup

+
+
+def channels_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.archive", json=kwargs)
+
+

Archives a channel.

+
+
+def channels_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.create", json=kwargs)
+
+

Creates a channel.

+
+
+def channels_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a channel.

+
+
+def channels_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+

Gets information about a channel.

+
+
+def channels_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.invite", json=kwargs)
+
+

Invites a user to a channel.

+
+
+def channels_join(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_join(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins a channel, creating it if needed."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.join", json=kwargs)
+
+

Joins a channel, creating it if needed.

+
+
+def channels_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.kick", json=kwargs)
+
+

Removes a user from a channel.

+
+
+def channels_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.leave", json=kwargs)
+
+

Leaves a channel.

+
+
+def channels_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team."""
+    return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+

Lists all channels in a Slack team.

+
+
+def channels_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.mark", json=kwargs)
+
+

Sets the read cursor in a channel.

+
+
+def channels_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.rename", json=kwargs)
+
+

Renames a channel.

+
+
+def channels_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a channel

+
+
+def channels_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setPurpose", json=kwargs)
+
+

Sets the purpose for a channel.

+
+
+def channels_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setTopic", json=kwargs)
+
+

Sets the topic for a channel.

+
+
+def channels_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.unarchive", json=kwargs)
+
+

Unarchives a channel.

+
+
+def chat_appendStream(self, *, channel:Β str, ts:Β str, markdown_text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_appendStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Appends text to an existing streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.appendStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.appendStream", json=kwargs)
+
+

Appends text to an existing streaming conversation. +https://docs.slack.dev/reference/methods/chat.appendStream

+
+
+def chat_delete(self, *, channel:Β str, ts:Β str, as_user:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_delete(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a message.
+    https://docs.slack.dev/reference/methods/chat.delete
+    """
+    kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+    return self.api_call("chat.delete", params=kwargs)
+
+ +
+
+def chat_deleteScheduledMessage(self,
*,
channel:Β str,
scheduled_message_id:Β str,
as_user:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_deleteScheduledMessage(
+    self,
+    *,
+    channel: str,
+    scheduled_message_id: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a scheduled message.
+    https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "scheduled_message_id": scheduled_message_id,
+            "as_user": as_user,
+        }
+    )
+    return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def chat_getPermalink(
+    self,
+    *,
+    channel: str,
+    message_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a permalink URL for a specific extant message
+    https://docs.slack.dev/reference/methods/chat.getPermalink
+    """
+    kwargs.update({"channel": channel, "message_ts": message_ts})
+    return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+

Retrieve a permalink URL for a specific extant message +https://docs.slack.dev/reference/methods/chat.getPermalink

+
+
+def chat_meMessage(self, *, channel:Β str, text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_meMessage(
+    self,
+    *,
+    channel: str,
+    text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Share a me message into a channel.
+    https://docs.slack.dev/reference/methods/chat.meMessage
+    """
+    kwargs.update({"channel": channel, "text": text})
+    return self.api_call("chat.meMessage", params=kwargs)
+
+ +
+
+def chat_postEphemeral(self,
*,
channel:Β str,
user:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postEphemeral(
+    self,
+    *,
+    channel: str,
+    user: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an ephemeral message to a user in a channel.
+    https://docs.slack.dev/reference/methods/chat.postEphemeral
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "user": user,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postEphemeral", json=kwargs)
+
+

Sends an ephemeral message to a user in a channel. +https://docs.slack.dev/reference/methods/chat.postEphemeral

+
+
+def chat_postMessage(self,
*,
channel:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
container_id:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
mrkdwn:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postMessage(
+    self,
+    *,
+    channel: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    container_id: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    mrkdwn: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,  # none, full
+    metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends a message to a channel.
+    https://docs.slack.dev/reference/methods/chat.postMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "container_id": container_id,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "mrkdwn": mrkdwn,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postMessage", json=kwargs)
+
+ +
+
+def chat_scheduleMessage(self,
*,
channel:Β str,
post_at:Β strΒ |Β int,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduleMessage(
+    self,
+    *,
+    channel: str,
+    post_at: Union[str, int],
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    parse: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Schedules a message.
+    https://docs.slack.dev/reference/methods/chat.scheduleMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "post_at": post_at,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "parse": parse,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "link_names": link_names,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.scheduleMessage", json=kwargs)
+
+ +
+
+def chat_scheduledMessages_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduledMessages_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all scheduled messages.
+    https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "latest": latest,
+            "limit": limit,
+            "oldest": oldest,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+ +
+
+def chat_startStream(self,
*,
channel:Β str,
thread_ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_startStream(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    markdown_text: Optional[str] = None,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a new streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.startStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "markdown_text": markdown_text,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.startStream", json=kwargs)
+
+

Starts a new streaming conversation. +https://docs.slack.dev/reference/methods/chat.startStream

+
+
+def chat_stopStream(self,
*,
channel:Β str,
ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_stopStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Stops a streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.stopStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+            "blocks": blocks,
+            "metadata": metadata,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.stopStream", json=kwargs)
+
+ +
+
+def chat_stream(self,
*,
buffer_size:Β intΒ =Β 256,
channel:Β str,
thread_ts:Β str,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β ChatStream
+
+
+
+ +Expand source code + +
def chat_stream(
+    self,
+    *,
+    buffer_size: int = 256,
+    channel: str,
+    thread_ts: str,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> ChatStream:
+    """Stream markdown text into a conversation.
+
+    This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+    the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+    The following methods are used:
+
+    - chat.startStream: Starts a new streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+    - chat.appendStream: Appends text to an existing streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+    - chat.stopStream: Stops a streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+    Args:
+        buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+          value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+          limits. Default: 256.
+        channel: An encoded ID that represents a channel, private group, or DM.
+        thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+          request.
+        recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+          streaming to channels.
+        recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        ChatStream instance for managing the stream
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    return ChatStream(
+        self,
+        logger=self._logger,
+        channel=channel,
+        thread_ts=thread_ts,
+        recipient_team_id=recipient_team_id,
+        recipient_user_id=recipient_user_id,
+        buffer_size=buffer_size,
+        **kwargs,
+    )
+
+

Stream markdown text into a conversation.

+

This method starts a new chat stream in a conversation that can be appended to. After appending an entire message, +the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.

+

The following methods are used:

+
    +
  • chat.startStream: Starts a new streaming conversation. +Reference.
  • +
  • chat.appendStream: Appends text to an existing streaming conversation. +Reference.
  • +
  • chat.stopStream: Stops a streaming conversation. +Reference.
  • +
+

Args

+
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a stream method. Increasing this +value decreases the number of method calls made for the same amount of text, which is useful to avoid rate +limits. Default: 256.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

ChatStream instance for managing the stream

+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+def chat_unfurl(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
ts:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
unfurl_id:Β strΒ |Β NoneΒ =Β None,
unfurls:Β Dict[str,Β Dict]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
user_auth_blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
user_auth_message:Β strΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_unfurl(
+    self,
+    *,
+    channel: Optional[str] = None,
+    ts: Optional[str] = None,
+    source: Optional[str] = None,
+    unfurl_id: Optional[str] = None,
+    unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+    metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+    user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    user_auth_message: Optional[str] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provide custom unfurl behavior for user-posted URLs.
+    https://docs.slack.dev/reference/methods/chat.unfurl
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "source": source,
+            "unfurl_id": unfurl_id,
+            "unfurls": unfurls,
+            "metadata": metadata,
+            "user_auth_blocks": user_auth_blocks,
+            "user_auth_message": user_auth_message,
+            "user_auth_required": user_auth_required,
+            "user_auth_url": user_auth_url,
+        }
+    )
+    _parse_web_class_objects(kwargs)  # for user_auth_blocks
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.unfurl", json=kwargs)
+
+

Provide custom unfurl behavior for user-posted URLs. +https://docs.slack.dev/reference/methods/chat.unfurl

+
+
+def chat_update(self,
*,
channel:Β str,
ts:Β str,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
file_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_update(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    text: Optional[str] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    as_user: Optional[bool] = None,
+    file_ids: Optional[Union[str, Sequence[str]]] = None,
+    link_names: Optional[bool] = None,
+    parse: Optional[str] = None,  # none, full
+    reply_broadcast: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates a message in a channel.
+    https://docs.slack.dev/reference/methods/chat.update
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "as_user": as_user,
+            "link_names": link_names,
+            "parse": parse,
+            "reply_broadcast": reply_broadcast,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    if isinstance(file_ids, (list, tuple)):
+        kwargs.update({"file_ids": ",".join(file_ids)})
+    else:
+        kwargs.update({"file_ids": file_ids})
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.update", kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.update", json=kwargs)
+
+ +
+
+def conversations_acceptSharedInvite(self,
*,
channel_name:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
free_trial_accepted:Β boolΒ |Β NoneΒ =Β None,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_acceptSharedInvite(
+    self,
+    *,
+    channel_name: str,
+    channel_id: Optional[str] = None,
+    invite_id: Optional[str] = None,
+    free_trial_accepted: Optional[bool] = None,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Accepts an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+    """
+    if channel_id is None and invite_id is None:
+        raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+    kwargs.update(
+        {
+            "channel_name": channel_name,
+            "channel_id": channel_id,
+            "invite_id": invite_id,
+            "free_trial_accepted": free_trial_accepted,
+            "is_private": is_private,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+

Accepts an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite

+
+
+def conversations_approveSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_approveSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approves an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+

Approves an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.approveSharedInvite

+
+
+def conversations_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a conversation.
+    https://docs.slack.dev/reference/methods/conversations.archive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.archive", params=kwargs)
+
+ +
+
+def conversations_canvases_create(self, *, channel_id:Β str, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_canvases_create(
+    self,
+    *,
+    channel_id: str,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/conversations.canvases.create
+    """
+    kwargs.update({"channel_id": channel_id, "document_content": document_content})
+    return self.api_call("conversations.canvases.create", json=kwargs)
+
+ +
+
+def conversations_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.close
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.close", params=kwargs)
+
+

Closes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.close

+
+
+def conversations_create(self,
*,
name:Β str,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_create(
+    self,
+    *,
+    name: str,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiates a public or private channel-based conversation
+    https://docs.slack.dev/reference/methods/conversations.create
+    """
+    kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+    return self.api_call("conversations.create", params=kwargs)
+
+

Initiates a public or private channel-based conversation +https://docs.slack.dev/reference/methods/conversations.create

+
+
+def conversations_declineSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_declineSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Declines a Slack Connect channel invite.
+    https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_externalInvitePermissions_set(self, *, action:Β str, channel:Β str, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_externalInvitePermissions_set(
+    self, *, action: str, channel: str, target_team: str, **kwargs
+) -> SlackResponse:
+    """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+    https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+    """
+    kwargs.update(
+        {
+            "action": action,
+            "channel": channel,
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+

Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa. +https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set

+
+
+def conversations_history(self,
*,
channel:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_history(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches a conversation's history of messages and events.
+    https://docs.slack.dev/reference/methods/conversations.history
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+

Fetches a conversation's history of messages and events. +https://docs.slack.dev/reference/methods/conversations.history

+
+
+def conversations_info(self,
*,
channel:Β str,
include_locale:Β boolΒ |Β NoneΒ =Β None,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_info(
+    self,
+    *,
+    channel: str,
+    include_locale: Optional[bool] = None,
+    include_num_members: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a conversation.
+    https://docs.slack.dev/reference/methods/conversations.info
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "include_locale": include_locale,
+            "include_num_members": include_num_members,
+        }
+    )
+    return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a conversation. +https://docs.slack.dev/reference/methods/conversations.info

+
+
+def conversations_invite(self,
*,
channel:Β str,
users:Β strΒ |Β Sequence[str],
force:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_invite(
+    self,
+    *,
+    channel: str,
+    users: Union[str, Sequence[str]],
+    force: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invites users to a channel.
+    https://docs.slack.dev/reference/methods/conversations.invite
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "force": force,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.invite", params=kwargs)
+
+ +
+
+def conversations_inviteShared(self,
*,
channel:Β str,
emails:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_inviteShared(
+    self,
+    *,
+    channel: str,
+    emails: Optional[Union[str, Sequence[str]]] = None,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.inviteShared
+    """
+    if emails is None and user_ids is None:
+        raise e.SlackRequestError("Either emails or user ids must be provided.")
+    kwargs.update({"channel": channel})
+    if isinstance(emails, (list, tuple)):
+        kwargs.update({"emails": ",".join(emails)})
+    else:
+        kwargs.update({"emails": emails})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+

Sends an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.inviteShared

+
+
+def conversations_join(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_join(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins an existing conversation.
+    https://docs.slack.dev/reference/methods/conversations.join
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.join", params=kwargs)
+
+ +
+
+def conversations_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a conversation.
+    https://docs.slack.dev/reference/methods/conversations.kick
+    """
+    kwargs.update({"channel": channel, "user": user})
+    return self.api_call("conversations.kick", params=kwargs)
+
+ +
+
+def conversations_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a conversation.
+    https://docs.slack.dev/reference/methods/conversations.leave
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.leave", params=kwargs)
+
+ +
+
+def conversations_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team.
+    https://docs.slack.dev/reference/methods/conversations.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_listConnectInvites(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_listConnectInvites(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List shared channel invites that have been generated
+    or received but have not yet been approved by all parties.
+    https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+    """
+    kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+    return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+

List shared channel invites that have been generated +or received but have not yet been approved by all parties. +https://docs.slack.dev/reference/methods/conversations.listConnectInvites

+
+
+def conversations_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel.
+    https://docs.slack.dev/reference/methods/conversations.mark
+    """
+    kwargs.update({"channel": channel, "ts": ts})
+    return self.api_call("conversations.mark", params=kwargs)
+
+ +
+
+def conversations_members(self, *, channel:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_members(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve members of a conversation.
+    https://docs.slack.dev/reference/methods/conversations.members
+    """
+    kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+    return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_open(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
return_im:Β boolΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_open(
+    self,
+    *,
+    channel: Optional[str] = None,
+    return_im: Optional[bool] = None,
+    users: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Opens or resumes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.open
+    """
+    if channel is None and users is None:
+        raise e.SlackRequestError("Either channel or users must be provided.")
+    kwargs.update({"channel": channel, "return_im": return_im})
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.open", params=kwargs)
+
+

Opens or resumes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.open

+
+
+def conversations_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a conversation.
+    https://docs.slack.dev/reference/methods/conversations.rename
+    """
+    kwargs.update({"channel": channel, "name": name})
+    return self.api_call("conversations.rename", params=kwargs)
+
+ +
+
+def conversations_replies(self,
*,
channel:Β str,
ts:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_replies(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a conversation
+    https://docs.slack.dev/reference/methods/conversations.replies
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a conversation +https://docs.slack.dev/reference/methods/conversations.replies

+
+
+def conversations_requestSharedInvite_approve(self,
*,
invite_id:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
is_external_limited:Β strΒ |Β NoneΒ =Β None,
message:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_approve(
+    self,
+    *,
+    invite_id: str,
+    channel_id: Optional[str] = None,
+    is_external_limited: Optional[str] = None,
+    message: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+    """
+    kwargs.update(
+        {
+            "invite_id": invite_id,
+            "channel_id": channel_id,
+            "is_external_limited": is_external_limited,
+        }
+    )
+    if message is not None:
+        kwargs.update({"message": json.dumps(message)})
+    return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+

Approve a request to add an external user to a channel. This also sends them a Slack Connect invite. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve

+
+
+def conversations_requestSharedInvite_deny(self, *, invite_id:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_deny(
+    self,
+    *,
+    invite_id: str,
+    message: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a request to invite an external user to a channel.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+    """
+    kwargs.update({"invite_id": invite_id, "message": message})
+    return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+

Deny a request to invite an external user to a channel. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny

+
+
+def conversations_requestSharedInvite_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_approved:Β boolΒ |Β NoneΒ =Β None,
include_denied:Β boolΒ |Β NoneΒ =Β None,
include_expired:Β boolΒ |Β NoneΒ =Β None,
invite_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_approved: Optional[bool] = None,
+    include_denied: Optional[bool] = None,
+    include_expired: Optional[bool] = None,
+    invite_ids: Optional[Union[str, Sequence[str]]] = None,
+    limit: Optional[int] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists requests to add external users to channels with ability to filter.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_approved": include_approved,
+            "include_denied": include_denied,
+            "include_expired": include_expired,
+            "limit": limit,
+            "user_id": user_id,
+        }
+    )
+    if invite_ids is not None:
+        if isinstance(invite_ids, (list, tuple)):
+            kwargs.update({"invite_ids": ",".join(invite_ids)})
+        else:
+            kwargs.update({"invite_ids": invite_ids})
+    return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+

Lists requests to add external users to channels with ability to filter. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list

+
+
+def conversations_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setPurpose
+    """
+    kwargs.update({"channel": channel, "purpose": purpose})
+    return self.api_call("conversations.setPurpose", params=kwargs)
+
+ +
+
+def conversations_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setTopic
+    """
+    kwargs.update({"channel": channel, "topic": topic})
+    return self.api_call("conversations.setTopic", params=kwargs)
+
+ +
+
+def conversations_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Reverses conversation archival.
+    https://docs.slack.dev/reference/methods/conversations.unarchive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.unarchive", params=kwargs)
+
+ +
+
+def dialog_open(self, *, dialog:Β Dict[str,Β Any], trigger_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dialog_open(
+    self,
+    *,
+    dialog: Dict[str, Any],
+    trigger_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Open a dialog with a user.
+    https://docs.slack.dev/reference/methods/dialog.open
+    """
+    kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: As the dialog can be a dict, this API call works only with json format.
+    return self.api_call("dialog.open", json=kwargs)
+
+ +
+
+def dnd_endDnd(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endDnd(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's Do Not Disturb session immediately.
+    https://docs.slack.dev/reference/methods/dnd.endDnd
+    """
+    return self.api_call("dnd.endDnd", params=kwargs)
+
+

Ends the current user's Do Not Disturb session immediately. +https://docs.slack.dev/reference/methods/dnd.endDnd

+
+
+def dnd_endSnooze(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endSnooze(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's snooze mode immediately.
+    https://docs.slack.dev/reference/methods/dnd.endSnooze
+    """
+    return self.api_call("dnd.endSnooze", params=kwargs)
+
+

Ends the current user's snooze mode immediately. +https://docs.slack.dev/reference/methods/dnd.endSnooze

+
+
+def dnd_info(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_info(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's current Do Not Disturb status.
+    https://docs.slack.dev/reference/methods/dnd.info
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+

Retrieves a user's current Do Not Disturb status. +https://docs.slack.dev/reference/methods/dnd.info

+
+
+def dnd_setSnooze(self, *, num_minutes:Β strΒ |Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_setSnooze(
+    self,
+    *,
+    num_minutes: Union[int, str],
+    **kwargs,
+) -> SlackResponse:
+    """Turns on Do Not Disturb mode for the current user, or changes its duration.
+    https://docs.slack.dev/reference/methods/dnd.setSnooze
+    """
+    kwargs.update({"num_minutes": num_minutes})
+    return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+

Turns on Do Not Disturb mode for the current user, or changes its duration. +https://docs.slack.dev/reference/methods/dnd.setSnooze

+
+
+def dnd_teamInfo(self, users:Β strΒ |Β Sequence[str], team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_teamInfo(
+    self,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves the Do Not Disturb status for users on a team.
+    https://docs.slack.dev/reference/methods/dnd.teamInfo
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id})
+    return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+

Retrieves the Do Not Disturb status for users on a team. +https://docs.slack.dev/reference/methods/dnd.teamInfo

+
+
+def emoji_list(self, include_categories:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def emoji_list(
+    self,
+    include_categories: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists custom emoji for a team.
+    https://docs.slack.dev/reference/methods/emoji.list
+    """
+    kwargs.update({"include_categories": include_categories})
+    return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+ +
+
+def entity_presentDetails(self,
trigger_id:Β str,
metadata:Β DictΒ |Β EntityMetadataΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def entity_presentDetails(
+    self,
+    trigger_id: str,
+    metadata: Optional[Union[Dict, EntityMetadata]] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    error: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provides entity details for the flexpane.
+    https://docs.slack.dev/reference/methods/entity.presentDetails/
+    """
+    kwargs.update({"trigger_id": trigger_id})
+    if metadata is not None:
+        kwargs.update({"metadata": metadata})
+    if user_auth_required is not None:
+        kwargs.update({"user_auth_required": user_auth_required})
+    if user_auth_url is not None:
+        kwargs.update({"user_auth_url": user_auth_url})
+    if error is not None:
+        kwargs.update({"error": error})
+    _parse_web_class_objects(kwargs)
+    return self.api_call("entity.presentDetails", json=kwargs)
+
+

Provides entity details for the flexpane. +https://docs.slack.dev/reference/methods/entity.presentDetails/

+
+
+def files_comments_delete(self, *, file:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_comments_delete(
+    self,
+    *,
+    file: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an existing comment on a file.
+    https://docs.slack.dev/reference/methods/files.comments.delete
+    """
+    kwargs.update({"file": file, "id": id})
+    return self.api_call("files.comments.delete", params=kwargs)
+
+ +
+
+def files_completeUploadExternal(self,
*,
files:Β List[Dict[str,Β str]],
channel_id:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_completeUploadExternal(
+    self,
+    *,
+    files: List[Dict[str, str]],
+    channel_id: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Finishes an upload started with files.getUploadURLExternal.
+    https://docs.slack.dev/reference/methods/files.completeUploadExternal
+    """
+    _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+    kwargs.update(
+        {
+            "files": json.dumps(_files),
+            "channel_id": channel_id,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+        }
+    )
+    if channels:
+        kwargs["channels"] = ",".join(channels)
+    return self.api_call("files.completeUploadExternal", params=kwargs)
+
+

Finishes an upload started with files.getUploadURLExternal. +https://docs.slack.dev/reference/methods/files.completeUploadExternal

+
+
+def files_delete(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_delete(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a file.
+    https://docs.slack.dev/reference/methods/files.delete
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.delete", params=kwargs)
+
+ +
+
+def files_getUploadURLExternal(self,
*,
filename:Β str,
length:Β int,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_getUploadURLExternal(
+    self,
+    *,
+    filename: str,
+    length: int,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets a URL for an edge external upload.
+    https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+    """
+    kwargs.update(
+        {
+            "filename": filename,
+            "length": length,
+            "alt_txt": alt_txt,
+            "snippet_type": snippet_type,
+        }
+    )
+    return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+ +
+
+def files_info(self,
*,
file:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_info(
+    self,
+    *,
+    file: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a team file.
+    https://docs.slack.dev/reference/methods/files.info
+    """
+    kwargs.update(
+        {
+            "file": file,
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+        }
+    )
+    return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+

Gets information about a team file. +https://docs.slack.dev/reference/methods/files.info

+
+
+def files_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
count:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
show_files_hidden_by_limit:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    count: Optional[int] = None,
+    page: Optional[int] = None,
+    show_files_hidden_by_limit: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists & filters team files.
+    https://docs.slack.dev/reference/methods/files.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "count": count,
+            "page": page,
+            "show_files_hidden_by_limit": show_files_hidden_by_limit,
+            "team_id": team_id,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_add(self,
*,
external_id:Β str,
external_url:Β str,
title:Β str,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_add(
+    self,
+    *,
+    external_id: str,
+    external_url: str,
+    title: str,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+    preview_image: Optional[Union[str, bytes, IOBase]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a file from a remote service.
+    https://docs.slack.dev/reference/methods/files.remote.add
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.add",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_remote_info(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_info(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.info
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.info

+
+
+def files_remote_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "limit": limit,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+        }
+    )
+    return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.list

+
+
+def files_remote_remove(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_remove(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a remote file.
+    https://docs.slack.dev/reference/methods/files.remote.remove
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def files_remote_share(self,
*,
channels:Β strΒ |Β Sequence[str],
external_id:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_share(
+    self,
+    *,
+    channels: Union[str, Sequence[str]],
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Share a remote file into a channel.
+    https://docs.slack.dev/reference/methods/files.remote.share
+    """
+    if external_id is None and file is None:
+        raise e.SlackRequestError("Either external_id or file must be provided.")
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_update(self,
*,
external_id:Β strΒ |Β NoneΒ =Β None,
external_url:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_update(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    external_url: Optional[str] = None,
+    file: Optional[str] = None,
+    title: Optional[str] = None,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[str] = None,
+    preview_image: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates an existing remote file.
+    https://docs.slack.dev/reference/methods/files.remote.update
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "file": file,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.update",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_revokePublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_revokePublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes public/external sharing access for a file
+    https://docs.slack.dev/reference/methods/files.revokePublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.revokePublicURL", params=kwargs)
+
+

Revokes public/external sharing access for a file +https://docs.slack.dev/reference/methods/files.revokePublicURL

+
+
+def files_sharedPublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_sharedPublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Enables a file for public/external sharing.
+    https://docs.slack.dev/reference/methods/files.sharedPublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.sharedPublicURL", params=kwargs)
+
+

Enables a file for public/external sharing. +https://docs.slack.dev/reference/methods/files.sharedPublicURL

+
+
+def files_upload(self,
*,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
filename:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload(
+    self,
+    *,
+    file: Optional[Union[str, bytes, IOBase]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    filename: Optional[str] = None,
+    filetype: Optional[str] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    title: Optional[str] = None,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uploads or creates a file.
+    https://docs.slack.dev/reference/methods/files.upload
+    """
+    _print_files_upload_v2_suggestion()
+
+    if file is None and content is None:
+        raise e.SlackRequestError("The file or content argument must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update(
+        {
+            "filename": filename,
+            "filetype": filetype,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+            "title": title,
+        }
+    )
+    if file:
+        if kwargs.get("filename") is None and isinstance(file, str):
+            # use the local filename if filename is missing
+            if kwargs.get("filename") is None:
+                kwargs["filename"] = file.split(os.path.sep)[-1]
+        return self.api_call("files.upload", files={"file": file}, data=kwargs)
+    else:
+        kwargs["content"] = content
+        return self.api_call("files.upload", data=kwargs)
+
+ +
+
+def files_upload_v2(self,
*,
filename:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β os.PathLikeΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
file_uploads:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
request_file_info:Β boolΒ =Β True,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload_v2(
+    self,
+    *,
+    # for sending a single file
+    filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+    file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    title: Optional[str] = None,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    # To upload multiple files at a time
+    file_uploads: Optional[List[Dict[str, Any]]] = None,
+    channel: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+    **kwargs,
+) -> SlackResponse:
+    """This wrapper method provides an easy way to upload files using the following endpoints:
+
+    - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+    - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+    - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        and https://docs.slack.dev/reference/methods/files.info
+
+    """
+    if file is None and content is None and file_uploads is None:
+        raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    # deprecated arguments:
+    filetype = kwargs.get("filetype")
+
+    if filetype is not None:
+        warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+    # step1: files.getUploadURLExternal per file
+    files: List[Dict[str, Any]] = []
+    if file_uploads is not None:
+        for f in file_uploads:
+            files.append(_to_v2_file_upload_item(f))
+    else:
+        f = _to_v2_file_upload_item(
+            {
+                "filename": filename,
+                "file": file,
+                "content": content,
+                "title": title,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        files.append(f)
+
+    for f in files:
+        url_response = self.files_getUploadURLExternal(
+            filename=f.get("filename"),  # type: ignore[arg-type]
+            length=f.get("length"),  # type: ignore[arg-type]
+            alt_txt=f.get("alt_txt"),
+            snippet_type=f.get("snippet_type"),
+            token=kwargs.get("token"),
+        )
+        _validate_for_legacy_client(url_response)
+        f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+        f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+    # step2: "https://files.slack.com/upload/v1/..." per file
+    for f in files:
+        upload_result = self._upload_file(
+            url=f["upload_url"],
+            data=f["data"],
+            logger=self._logger,
+            timeout=self.timeout,
+            proxy=self.proxy,
+            ssl=self.ssl,
+        )
+        if upload_result.status != 200:
+            status = upload_result.status
+            body = upload_result.body
+            message = (
+                "Failed to upload a file "
+                f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+            )
+            raise e.SlackRequestError(message)
+
+    # step3: files.completeUploadExternal with all the sets of (file_id + title)
+    completion = self.files_completeUploadExternal(
+        files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+        channel_id=channel,
+        channels=channels,
+        initial_comment=initial_comment,
+        thread_ts=thread_ts,
+        **kwargs,
+    )
+    if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+        completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+    return completion
+
+

This wrapper method provides an easy way to upload files using the following endpoints:

+
+
+
+def functions_completeError(self, *, function_execution_id:Β str, error:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeError(
+    self,
+    *,
+    function_execution_id: str,
+    error: str,
+    **kwargs,
+) -> SlackResponse:
+    """Signal the failure to execute a function
+    https://docs.slack.dev/reference/methods/functions.completeError
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "error": error})
+    return self.api_call("functions.completeError", params=kwargs)
+
+ +
+
+def functions_completeSuccess(self, *, function_execution_id:Β str, outputs:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeSuccess(
+    self,
+    *,
+    function_execution_id: str,
+    outputs: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Signal the successful completion of a function
+    https://docs.slack.dev/reference/methods/functions.completeSuccess
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+    return self.api_call("functions.completeSuccess", params=kwargs)
+
+

Signal the successful completion of a function +https://docs.slack.dev/reference/methods/functions.completeSuccess

+
+
+def groups_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.archive", json=kwargs)
+
+

Archives a private channel.

+
+
+def groups_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a private channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.create", json=kwargs)
+
+

Creates a private channel.

+
+
+def groups_createChild(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_createChild(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Clones and archives a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+

Clones and archives a private channel.

+
+
+def groups_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a private channel.

+
+
+def groups_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+

Gets information about a private channel.

+
+
+def groups_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.invite", json=kwargs)
+
+

Invites a user to a private channel.

+
+
+def groups_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.kick", json=kwargs)
+
+

Removes a user from a private channel.

+
+
+def groups_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.leave", json=kwargs)
+
+

Leaves a private channel.

+
+
+def groups_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists private channels that the calling user has access to."""
+    return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+

Lists private channels that the calling user has access to.

+
+
+def groups_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a private channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.mark", json=kwargs)
+
+

Sets the read cursor in a private channel.

+
+
+def groups_open(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_open(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.open", json=kwargs)
+
+

Opens a private channel.

+
+
+def groups_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a private channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.rename", json=kwargs)
+
+

Renames a private channel.

+
+
+def groups_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a private channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a private channel

+
+
+def groups_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a private channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setPurpose", json=kwargs)
+
+

Sets the purpose for a private channel.

+
+
+def groups_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a private channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setTopic", json=kwargs)
+
+

Sets the topic for a private channel.

+
+
+def groups_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.unarchive", json=kwargs)
+
+

Unarchives a private channel.

+
+
+def im_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Close a direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.close", json=kwargs)
+
+

Close a direct message channel.

+
+
+def im_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from direct message channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from direct message channel.

+
+
+def im_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists direct message channels for the calling user."""
+    return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+

Lists direct message channels for the calling user.

+
+
+def im_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.mark", json=kwargs)
+
+

Sets the read cursor in a direct message channel.

+
+
+def im_open(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_open(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a direct message channel."""
+    kwargs.update({"user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.open", json=kwargs)
+
+

Opens a direct message channel.

+
+
+def im_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation

+
+
+def migration_exchange(self,
*,
users:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
to_old:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def migration_exchange(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    to_old: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """For Enterprise Grid workspaces, map local user IDs to global user IDs
+    https://docs.slack.dev/reference/methods/migration.exchange
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id, "to_old": to_old})
+    return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+

For Enterprise Grid workspaces, map local user IDs to global user IDs +https://docs.slack.dev/reference/methods/migration.exchange

+
+
+def mpim_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a multiparty direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.close", json=kwargs)
+
+

Closes a multiparty direct message channel.

+
+
+def mpim_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a multiparty direct message."""
+    kwargs.update({"channel": channel})
+    return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a multiparty direct message.

+
+
+def mpim_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists multiparty direct message channels for the calling user."""
+    return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+

Lists multiparty direct message channels for the calling user.

+
+
+def mpim_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a multiparty direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.mark", json=kwargs)
+
+

Sets the read cursor in a multiparty direct message channel.

+
+
+def mpim_open(self, *, users:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_open(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """This method opens a multiparty direct message."""
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("mpim.open", params=kwargs)
+
+

This method opens a multiparty direct message.

+
+
+def mpim_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation from a
+    multiparty direct message.
+    """
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation from a +multiparty direct message.

+
+
+def oauth_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    code: str,
+    redirect_uri: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    kwargs.update({"code": code})
+    return self.api_call(
+        "oauth.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.access

+
+
+def oauth_v2_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_v2_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    # This field is required when processing the OAuth redirect URL requests
+    # while it's absent for token rotation
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    # This field is required for token rotation
+    grant_type: Optional[str] = None,
+    # This field is required for token rotation
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.v2.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "oauth.v2.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.v2.access

+
+
+def oauth_v2_exchange(self, *, token:Β str, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def oauth_v2_exchange(
+    self,
+    *,
+    token: str,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a legacy access token for a new expiring access token and refresh token
+    https://docs.slack.dev/reference/methods/oauth.v2.exchange
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+    return self.api_call("oauth.v2.exchange", params=kwargs)
+
+

Exchanges a legacy access token for a new expiring access token and refresh token +https://docs.slack.dev/reference/methods/oauth.v2.exchange

+
+
+def openid_connect_token(self,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def openid_connect_token(
+    self,
+    client_id: str,
+    client_secret: str,
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    grant_type: Optional[str] = None,
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.token
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "openid.connect.token",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.token

+
+
+def openid_connect_userInfo(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def openid_connect_userInfo(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get the identity of a user who has authorized Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.userInfo
+    """
+    return self.api_call("openid.connect.userInfo", params=kwargs)
+
+

Get the identity of a user who has authorized Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.userInfo

+
+
+def pins_add(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_add(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Pins an item to a channel.
+    https://docs.slack.dev/reference/methods/pins.add
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.add", params=kwargs)
+
+ +
+
+def pins_list(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_list(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lists items pinned to a channel.
+    https://docs.slack.dev/reference/methods/pins.list
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+

Lists items pinned to a channel. +https://docs.slack.dev/reference/methods/pins.list

+
+
+def pins_remove(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_remove(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Un-pins an item from a channel.
+    https://docs.slack.dev/reference/methods/pins.remove
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.remove", params=kwargs)
+
+ +
+
+def reactions_add(self, *, channel:Β str, name:Β str, timestamp:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reactions_add(
+    self,
+    *,
+    channel: str,
+    name: str,
+    timestamp: str,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a reaction to an item.
+    https://docs.slack.dev/reference/methods/reactions.add
+    """
+    kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+    return self.api_call("reactions.add", params=kwargs)
+
+ +
+
+def reactions_get(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_get(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    full: Optional[bool] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets reactions for an item.
+    https://docs.slack.dev/reference/methods/reactions.get
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "full": full,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    full: Optional[bool] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists reactions made by a user.
+    https://docs.slack.dev/reference/methods/reactions.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "full": full,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_remove(self,
*,
name:Β str,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_remove(
+    self,
+    *,
+    name: str,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a reaction from an item.
+    https://docs.slack.dev/reference/methods/reactions.remove
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.remove", params=kwargs)
+
+ +
+
+def reminders_add(self,
*,
text:Β str,
time:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
recurrence:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reminders_add(
+    self,
+    *,
+    text: str,
+    time: str,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    recurrence: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a reminder.
+    https://docs.slack.dev/reference/methods/reminders.add
+    """
+    kwargs.update(
+        {
+            "text": text,
+            "time": time,
+            "team_id": team_id,
+            "user": user,
+            "recurrence": recurrence,
+        }
+    )
+    return self.api_call("reminders.add", params=kwargs)
+
+ +
+
+def reminders_complete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_complete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Marks a reminder as complete.
+    https://docs.slack.dev/reference/methods/reminders.complete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.complete", params=kwargs)
+
+ +
+
+def reminders_delete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_delete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a reminder.
+    https://docs.slack.dev/reference/methods/reminders.delete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.delete", params=kwargs)
+
+ +
+
+def reminders_info(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_info(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a reminder.
+    https://docs.slack.dev/reference/methods/reminders.info
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+ +
+
+def reminders_list(self, *, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all reminders created by or for a given user.
+    https://docs.slack.dev/reference/methods/reminders.list
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+

Lists all reminders created by or for a given user. +https://docs.slack.dev/reference/methods/reminders.list

+
+
+def rtm_connect(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_connect(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.connect
+    """
+    kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+    return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.connect

+
+
+def rtm_start(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
mpim_aware:Β boolΒ |Β NoneΒ =Β None,
no_latest:Β boolΒ |Β NoneΒ =Β None,
no_unreads:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
simple_latest:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_start(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    include_locale: Optional[bool] = None,
+    mpim_aware: Optional[bool] = None,
+    no_latest: Optional[bool] = None,
+    no_unreads: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    simple_latest: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.start
+    """
+    kwargs.update(
+        {
+            "batch_presence_aware": batch_presence_aware,
+            "include_locale": include_locale,
+            "mpim_aware": mpim_aware,
+            "no_latest": no_latest,
+            "no_unreads": no_unreads,
+            "presence_sub": presence_sub,
+            "simple_latest": simple_latest,
+        }
+    )
+    return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.start

+
+
+def search_all(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_all(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages and files matching a query.
+    https://docs.slack.dev/reference/methods/search.all
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+

Searches for messages and files matching a query. +https://docs.slack.dev/reference/methods/search.all

+
+
+def search_files(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_files(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for files matching a query.
+    https://docs.slack.dev/reference/methods/search.files
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+

Searches for files matching a query. +https://docs.slack.dev/reference/methods/search.files

+
+
+def search_messages(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_messages(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages matching a query.
+    https://docs.slack.dev/reference/methods/search.messages
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "cursor": cursor,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+

Searches for messages matching a query. +https://docs.slack.dev/reference/methods/search.messages

+
+
+def slackLists_access_delete(self,
*,
list_id:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_delete(
+    self,
+    *,
+    list_id: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revoke access to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.delete
+    """
+    kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.delete", json=kwargs)
+
+

Revoke access to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.delete

+
+
+def slackLists_access_set(self,
*,
list_id:Β str,
access_level:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_set(
+    self,
+    *,
+    list_id: str,
+    access_level: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the access level to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.set
+    """
+    kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.set", json=kwargs)
+
+

Set the access level to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.set

+
+
+def slackLists_create(self,
*,
name:Β str,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
schema:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
copy_from_list_id:Β strΒ |Β NoneΒ =Β None,
include_copied_list_records:Β boolΒ |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_create(
+    self,
+    *,
+    name: str,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    schema: Optional[List[Dict[str, Any]]] = None,
+    copy_from_list_id: Optional[str] = None,
+    include_copied_list_records: Optional[bool] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a List.
+    https://docs.slack.dev/reference/methods/slackLists.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description_blocks": description_blocks,
+            "schema": schema,
+            "copy_from_list_id": copy_from_list_id,
+            "include_copied_list_records": include_copied_list_records,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.create", json=kwargs)
+
+ +
+
+def slackLists_download_get(self, *, list_id:Β str, job_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_get(
+    self,
+    *,
+    list_id: str,
+    job_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve List download URL from an export job to download List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.get
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "job_id": job_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.get", json=kwargs)
+
+

Retrieve List download URL from an export job to download List contents. +https://docs.slack.dev/reference/methods/slackLists.download.get

+
+
+def slackLists_download_start(self, *, list_id:Β str, include_archived:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_start(
+    self,
+    *,
+    list_id: str,
+    include_archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiate a job to export List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.start
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "include_archived": include_archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.start", json=kwargs)
+
+ +
+
+def slackLists_items_create(self,
*,
list_id:Β str,
duplicated_item_id:Β strΒ |Β NoneΒ =Β None,
parent_item_id:Β strΒ |Β NoneΒ =Β None,
initial_fields:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_create(
+    self,
+    *,
+    list_id: str,
+    duplicated_item_id: Optional[str] = None,
+    parent_item_id: Optional[str] = None,
+    initial_fields: Optional[List[Dict[str, Any]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add a new item to an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.create
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "duplicated_item_id": duplicated_item_id,
+            "parent_item_id": parent_item_id,
+            "initial_fields": initial_fields,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.create", json=kwargs)
+
+ +
+
+def slackLists_items_delete(self, *, list_id:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_delete(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an item from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.delete
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.delete", json=kwargs)
+
+ +
+
+def slackLists_items_deleteMultiple(self, *, list_id:Β str, ids:Β List[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_deleteMultiple(
+    self,
+    *,
+    list_id: str,
+    ids: List[str],
+    **kwargs,
+) -> SlackResponse:
+    """Deletes multiple items from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "ids": ids,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+ +
+
+def slackLists_items_info(self, *, list_id:Β str, id:Β str, include_is_subscribed:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_info(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    include_is_subscribed: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a row from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.info
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+            "include_is_subscribed": include_is_subscribed,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.info", json=kwargs)
+
+ +
+
+def slackLists_items_list(self,
*,
list_id:Β str,
limit:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
archived:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_list(
+    self,
+    *,
+    list_id: str,
+    limit: Optional[int] = None,
+    cursor: Optional[str] = None,
+    archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get records from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.list
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "limit": limit,
+            "cursor": cursor,
+            "archived": archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.list", json=kwargs)
+
+ +
+
+def slackLists_items_update(self, *, list_id:Β str, cells:Β List[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_update(
+    self,
+    *,
+    list_id: str,
+    cells: List[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Updates cells in a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.update
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "cells": cells,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.update", json=kwargs)
+
+ +
+
+def slackLists_update(self,
*,
id:Β str,
name:Β strΒ |Β NoneΒ =Β None,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_update(
+    self,
+    *,
+    id: str,
+    name: Optional[str] = None,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update a List.
+    https://docs.slack.dev/reference/methods/slackLists.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "name": name,
+            "description_blocks": description_blocks,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.update", json=kwargs)
+
+ +
+
+def stars_add(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_add(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a star to an item.
+    https://docs.slack.dev/reference/methods/stars.add
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.add", params=kwargs)
+
+ +
+
+def stars_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists stars for a user.
+    https://docs.slack.dev/reference/methods/stars.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+ +
+
+def stars_remove(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_remove(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a star from an item.
+    https://docs.slack.dev/reference/methods/stars.remove
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.remove", params=kwargs)
+
+ +
+
+def team_accessLogs(self,
*,
before:Β strΒ |Β intΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_accessLogs(
+    self,
+    *,
+    before: Optional[Union[int, str]] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the access logs for the current team.
+    https://docs.slack.dev/reference/methods/team.accessLogs
+    """
+    kwargs.update(
+        {
+            "before": before,
+            "count": count,
+            "page": page,
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+

Gets the access logs for the current team. +https://docs.slack.dev/reference/methods/team.accessLogs

+
+
+def team_billableInfo(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billableInfo(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets billable users information for the current team.
+    https://docs.slack.dev/reference/methods/team.billableInfo
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+

Gets billable users information for the current team. +https://docs.slack.dev/reference/methods/team.billableInfo

+
+
+def team_billing_info(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billing_info(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Reads a workspace's billing plan information.
+    https://docs.slack.dev/reference/methods/team.billing.info
+    """
+    return self.api_call("team.billing.info", params=kwargs)
+
+

Reads a workspace's billing plan information. +https://docs.slack.dev/reference/methods/team.billing.info

+
+
+def team_externalTeams_disconnect(self, *, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_externalTeams_disconnect(
+    self,
+    *,
+    target_team: str,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnects an external organization.
+    https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+    """
+    kwargs.update(
+        {
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+ +
+
+def team_externalTeams_list(self,
*,
connection_status_filter:Β strΒ |Β NoneΒ =Β None,
slack_connect_pref_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
sort_field:Β strΒ |Β NoneΒ =Β None,
workspace_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_externalTeams_list(
+    self,
+    *,
+    connection_status_filter: Optional[str] = None,
+    slack_connect_pref_filter: Optional[Sequence[str]] = None,
+    sort_direction: Optional[str] = None,
+    sort_field: Optional[str] = None,
+    workspace_filter: Optional[Sequence[str]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns a list of all the external teams connected and details about the connection.
+    https://docs.slack.dev/reference/methods/team.externalTeams.list
+    """
+    kwargs.update(
+        {
+            "connection_status_filter": connection_status_filter,
+            "sort_direction": sort_direction,
+            "sort_field": sort_field,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if slack_connect_pref_filter is not None:
+        if isinstance(slack_connect_pref_filter, (list, tuple)):
+            kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+        else:
+            kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+    if workspace_filter is not None:
+        if isinstance(workspace_filter, (list, tuple)):
+            kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+        else:
+            kwargs.update({"workspace_filter": workspace_filter})
+    return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+

Returns a list of all the external teams connected and details about the connection. +https://docs.slack.dev/reference/methods/team.externalTeams.list

+
+
+def team_info(self, *, team:Β strΒ |Β NoneΒ =Β None, domain:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_info(
+    self,
+    *,
+    team: Optional[str] = None,
+    domain: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about the current team.
+    https://docs.slack.dev/reference/methods/team.info
+    """
+    kwargs.update({"team": team, "domain": domain})
+    return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+

Gets information about the current team. +https://docs.slack.dev/reference/methods/team.info

+
+
+def team_integrationLogs(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
change_type:Β strΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
service_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_integrationLogs(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    change_type: Optional[str] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    service_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the integration logs for the current team.
+    https://docs.slack.dev/reference/methods/team.integrationLogs
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "change_type": change_type,
+            "count": count,
+            "page": page,
+            "service_id": service_id,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+

Gets the integration logs for the current team. +https://docs.slack.dev/reference/methods/team.integrationLogs

+
+
+def team_preferences_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_preferences_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a list of a workspace's team preferences.
+    https://docs.slack.dev/reference/methods/team.preferences.list
+    """
+    return self.api_call("team.preferences.list", params=kwargs)
+
+

Retrieve a list of a workspace's team preferences. +https://docs.slack.dev/reference/methods/team.preferences.list

+
+
+def team_profile_get(self, *, visibility:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_profile_get(
+    self,
+    *,
+    visibility: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a team's profile.
+    https://docs.slack.dev/reference/methods/team.profile.get
+    """
+    kwargs.update({"visibility": visibility})
+    return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+ +
+
+def tooling_tokens_rotate(self, *, refresh_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def tooling_tokens_rotate(
+    self,
+    *,
+    refresh_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a refresh token for a new app configuration token
+    https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+    """
+    kwargs.update({"refresh_token": refresh_token})
+    return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+

Exchanges a refresh token for a new app configuration token +https://docs.slack.dev/reference/methods/tooling.tokens.rotate

+
+
+def usergroups_create(self,
*,
name:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_create(
+    self,
+    *,
+    name: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a User Group
+    https://docs.slack.dev/reference/methods/usergroups.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.create", params=kwargs)
+
+ +
+
+def usergroups_disable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_disable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disable an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.disable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.disable", params=kwargs)
+
+ +
+
+def usergroups_enable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_enable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enable a User Group
+    https://docs.slack.dev/reference/methods/usergroups.enable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.enable", params=kwargs)
+
+ +
+
+def usergroups_list(self,
*,
include_count:Β boolΒ |Β NoneΒ =Β None,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
include_users:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_list(
+    self,
+    *,
+    include_count: Optional[bool] = None,
+    include_disabled: Optional[bool] = None,
+    include_users: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all User Groups for a team
+    https://docs.slack.dev/reference/methods/usergroups.list
+    """
+    kwargs.update(
+        {
+            "include_count": include_count,
+            "include_disabled": include_disabled,
+            "include_users": include_users,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_update(self,
*,
usergroup:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_update(
+    self,
+    *,
+    usergroup: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    name: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "name": name,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.update", params=kwargs)
+
+ +
+
+def usergroups_users_list(self,
*,
usergroup:Β str,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_list(
+    self,
+    *,
+    usergroup: str,
+    include_disabled: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all users in a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.list
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_disabled": include_disabled,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_users_update(self,
*,
usergroup:Β str,
users:Β strΒ |Β Sequence[str],
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_update(
+    self,
+    *,
+    usergroup: str,
+    users: Union[str, Sequence[str]],
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the list of users for a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("usergroups.users.update", params=kwargs)
+
+

Update the list of users for a User Group +https://docs.slack.dev/reference/methods/usergroups.users.update

+
+
+def users_conversations(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_conversations(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List conversations the calling user may access.
+    https://docs.slack.dev/reference/methods/users.conversations
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+

List conversations the calling user may access. +https://docs.slack.dev/reference/methods/users.conversations

+
+
+def users_deletePhoto(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_deletePhoto(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Delete the user profile photo
+    https://docs.slack.dev/reference/methods/users.deletePhoto
+    """
+    return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+ +
+
+def users_discoverableContacts_lookup(self, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_discoverableContacts_lookup(
+    self,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lookup an email address to see if someone is on Slack
+    https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+

Lookup an email address to see if someone is on Slack +https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup

+
+
+def users_getPresence(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_getPresence(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets user presence information.
+    https://docs.slack.dev/reference/methods/users.getPresence
+    """
+    kwargs.update({"user": user})
+    return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+ +
+
+def users_identity(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_identity(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get a user's identity.
+    https://docs.slack.dev/reference/methods/users.identity
+    """
+    return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+ +
+
+def users_info(self, *, user:Β str, include_locale:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_info(
+    self,
+    *,
+    user: str,
+    include_locale: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a user.
+    https://docs.slack.dev/reference/methods/users.info
+    """
+    kwargs.update({"user": user, "include_locale": include_locale})
+    return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+ +
+
+def users_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_locale: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all users in a Slack team.
+    https://docs.slack.dev/reference/methods/users.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_locale": include_locale,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+

Lists all users in a Slack team. +https://docs.slack.dev/reference/methods/users.list

+
+
+def users_lookupByEmail(self, *, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_lookupByEmail(
+    self,
+    *,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Find a user with an email address.
+    https://docs.slack.dev/reference/methods/users.lookupByEmail
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+ +
+
+def users_profile_get(self, *, user:Β strΒ |Β NoneΒ =Β None, include_labels:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_profile_get(
+    self,
+    *,
+    user: Optional[str] = None,
+    include_labels: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's profile information.
+    https://docs.slack.dev/reference/methods/users.profile.get
+    """
+    kwargs.update({"user": user, "include_labels": include_labels})
+    return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+

Retrieves a user's profile information. +https://docs.slack.dev/reference/methods/users.profile.get

+
+
+def users_profile_set(self,
*,
name:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
profile:Β DictΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_profile_set(
+    self,
+    *,
+    name: Optional[str] = None,
+    value: Optional[str] = None,
+    user: Optional[str] = None,
+    profile: Optional[Dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the profile information for a user.
+    https://docs.slack.dev/reference/methods/users.profile.set
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "profile": profile,
+            "user": user,
+            "value": value,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "profile" parameter
+    return self.api_call("users.profile.set", json=kwargs)
+
+

Set the profile information for a user. +https://docs.slack.dev/reference/methods/users.profile.set

+
+
+def users_setPhoto(self,
*,
image:Β strΒ |Β io.IOBase,
crop_w:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_x:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_y:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_setPhoto(
+    self,
+    *,
+    image: Union[str, IOBase],
+    crop_w: Optional[Union[int, str]] = None,
+    crop_x: Optional[Union[int, str]] = None,
+    crop_y: Optional[Union[int, str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the user profile photo
+    https://docs.slack.dev/reference/methods/users.setPhoto
+    """
+    kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+    return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+ +
+
+def users_setPresence(self, *, presence:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_setPresence(
+    self,
+    *,
+    presence: str,
+    **kwargs,
+) -> SlackResponse:
+    """Manually sets user presence.
+    https://docs.slack.dev/reference/methods/users.setPresence
+    """
+    kwargs.update({"presence": presence})
+    return self.api_call("users.setPresence", params=kwargs)
+
+ +
+
+def views_open(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_open(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Open a view for a user.
+    https://docs.slack.dev/reference/methods/views.open
+    See https://docs.slack.dev/surfaces/modals/ for details.
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.open", json=kwargs)
+
+ +
+
+def views_publish(self,
*,
user_id:Β str,
view:Β dictΒ |Β View,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_publish(
+    self,
+    *,
+    user_id: str,
+    view: Union[dict, View],
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Publish a static view for a User.
+    Create or update the view that comprises an
+    app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+    https://docs.slack.dev/reference/methods/views.publish
+    """
+    kwargs.update({"user_id": user_id, "hash": hash})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.publish", json=kwargs)
+
+

Publish a static view for a User. +Create or update the view that comprises an +app's Home tab (https://docs.slack.dev/surfaces/app-home/) +https://docs.slack.dev/reference/methods/views.publish

+
+
+def views_push(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_push(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Push a view onto the stack of a root view.
+    Push a new view onto the existing view stack by passing a view
+    payload and a valid trigger_id generated from an interaction
+    within the existing modal.
+    Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+    to learn more about the lifecycle and intricacies of views.
+    https://docs.slack.dev/reference/methods/views.push
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.push", json=kwargs)
+
+

Push a view onto the stack of a root view. +Push a new view onto the existing view stack by passing a view +payload and a valid trigger_id generated from an interaction +within the existing modal. +Read the modals documentation (https://docs.slack.dev/surfaces/modals/) +to learn more about the lifecycle and intricacies of views. +https://docs.slack.dev/reference/methods/views.push

+
+
+def views_update(self,
*,
view:Β dictΒ |Β View,
external_id:Β strΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_update(
+    self,
+    *,
+    view: Union[dict, View],
+    external_id: Optional[str] = None,
+    view_id: Optional[str] = None,
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing view.
+    Update a view by passing a new view definition along with the
+    view_id returned in views.open or the external_id.
+    See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+    to learn more about updating views and avoiding race conditions with the hash argument.
+    https://docs.slack.dev/reference/methods/views.update
+    """
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    if external_id:
+        kwargs.update({"external_id": external_id})
+    elif view_id:
+        kwargs.update({"view_id": view_id})
+    else:
+        raise e.SlackRequestError("Either view_id or external_id is required.")
+    kwargs.update({"hash": hash})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.update", json=kwargs)
+
+

Update an existing view. +Update a view by passing a new view definition along with the +view_id returned in views.open or the external_id. +See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views) +to learn more about updating views and avoiding race conditions with the hash argument. +https://docs.slack.dev/reference/methods/views.update

+
+ +
+
+ +Expand source code + +
def workflows_featured_add(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add featured workflows to a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.add
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.add", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_list(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """List the featured workflows for specified channels.
+    https://docs.slack.dev/reference/methods/workflows.featured.list
+    """
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("workflows.featured.list", params=kwargs)
+
+

List the featured workflows for specified channels. +https://docs.slack.dev/reference/methods/workflows.featured.list

+
+ +
+
+ +Expand source code + +
def workflows_featured_remove(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove featured workflows from a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.remove
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.remove", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_set(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set featured workflows for a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.set
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.set", params=kwargs)
+
+ +
+
+def workflows_stepCompleted(self, *, workflow_step_execute_id:Β str, outputs:Β dictΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepCompleted(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    outputs: Optional[dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Indicate a successful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepCompleted
+    """
+    kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "outputs" parameter
+    return self.api_call("workflows.stepCompleted", json=kwargs)
+
+

Indicate a successful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepCompleted

+
+
+def workflows_stepFailed(self, *, workflow_step_execute_id:Β str, error:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepFailed(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    error: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Indicate an unsuccessful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepFailed
+    """
+    kwargs.update(
+        {
+            "workflow_step_execute_id": workflow_step_execute_id,
+            "error": error,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "error" parameter
+    return self.api_call("workflows.stepFailed", json=kwargs)
+
+

Indicate an unsuccessful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepFailed

+
+
+def workflows_updateStep(self,
*,
workflow_step_edit_id:Β str,
inputs:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
outputs:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def workflows_updateStep(
+    self,
+    *,
+    workflow_step_edit_id: str,
+    inputs: Optional[Dict[str, Any]] = None,
+    outputs: Optional[List[Dict[str, str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the configuration for a workflow extension step.
+    https://docs.slack.dev/reference/methods/workflows.updateStep
+    """
+    kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+    if inputs is not None:
+        kwargs.update({"inputs": inputs})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+    return self.api_call("workflows.updateStep", json=kwargs)
+
+

Update the configuration for a workflow extension step. +https://docs.slack.dev/reference/methods/workflows.updateStep

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/web/deprecation.html b/docs/reference/web/deprecation.html new file mode 100644 index 000000000..0b68d0c84 --- /dev/null +++ b/docs/reference/web/deprecation.html @@ -0,0 +1,121 @@ + + + + + + +slack_sdk.web.deprecation API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.deprecation

+
+
+
+
+
+
+
+
+

Functions

+
+
+def show_deprecation_warning_if_any(method_name:Β str) +
+
+
+ +Expand source code + +
def show_deprecation_warning_if_any(method_name: str):
+    """Prints a warning if the given method is deprecated"""
+
+    skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION")  # for unit tests etc.
+    if skip_deprecation:
+        return
+    if not method_name:
+        return
+
+    # 2020/01 conversations API deprecation
+    matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2020_01 if method_name.startswith(prefix)]
+    if len(matched_prefixes) > 0:
+        message = (
+            f"{method_name} is deprecated. Please use the Conversations API instead. "
+            "For more info, go to "
+            "https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/"
+        )
+        warnings.warn(message)
+
+    # 2023/07 stars API deprecation
+    matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2023_07 if method_name.startswith(prefix)]
+    if len(matched_prefixes) > 0:
+        message = (
+            f"{method_name} is deprecated. For more info, go to "
+            "https://docs.slack.dev/changelog/2023-07-its-later-already-for-stars-and-reminders/"
+        )
+        warnings.warn(message)
+
+    # 2024/09 workflow steps API deprecation
+    matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2024_09 if method_name.startswith(prefix)]
+    if len(matched_prefixes) > 0:
+        message = (
+            f"{method_name} is deprecated. For more info, go to "
+            "https://docs.slack.dev/changelog/2023-08-workflow-steps-from-apps-step-back/"
+        )
+        warnings.warn(message)
+
+

Prints a warning if the given method is deprecated

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/file_upload_v2_result.html b/docs/reference/web/file_upload_v2_result.html new file mode 100644 index 000000000..6cd74fcb3 --- /dev/null +++ b/docs/reference/web/file_upload_v2_result.html @@ -0,0 +1,110 @@ + + + + + + +slack_sdk.web.file_upload_v2_result API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.file_upload_v2_result

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class FileUploadV2Result +(status:Β int, body:Β str) +
+
+
+ +Expand source code + +
class FileUploadV2Result:
+    status: int
+    body: str
+
+    def __init__(self, status: int, body: str):
+        self.status = status
+        self.body = body
+
+
+

Class variables

+
+
var body :Β str
+
+

The type of the None singleton.

+
+
var status :Β int
+
+

The type of the None singleton.

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/index.html b/docs/reference/web/index.html new file mode 100644 index 000000000..611a26b3b --- /dev/null +++ b/docs/reference/web/index.html @@ -0,0 +1,16182 @@ + + + + + + +slack_sdk.web API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web

+
+
+

The Slack Web API allows you to build applications that interact with Slack +in more complex ways than the integrations we provide out of the box.

+
+
+

Sub-modules

+
+
slack_sdk.web.async_base_client
+
+
+
+
slack_sdk.web.async_chat_stream
+
+
+
+
slack_sdk.web.async_client
+
+

A Python module for interacting with Slack's Web API.

+
+
slack_sdk.web.async_internal_utils
+
+
+
+
slack_sdk.web.async_slack_response
+
+

A Python module for interacting and consuming responses from Slack.

+
+
slack_sdk.web.base_client
+
+

A Python module for interacting with Slack's Web API.

+
+
slack_sdk.web.chat_stream
+
+
+
+
slack_sdk.web.client
+
+

A Python module for interacting with Slack's Web API.

+
+
slack_sdk.web.deprecation
+
+
+
+
slack_sdk.web.file_upload_v2_result
+
+
+
+
slack_sdk.web.internal_utils
+
+
+
+
slack_sdk.web.legacy_base_client
+
+

A Python module for interacting with Slack's Web API.

+
+
slack_sdk.web.legacy_client
+
+
+
+
slack_sdk.web.legacy_slack_response
+
+

A Python module for interacting and consuming responses from Slack.

+
+
slack_sdk.web.slack_response
+
+

A Python module for interacting and consuming responses from Slack.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class SlackResponse +(*,
client,
http_verb:Β str,
api_url:Β str,
req_args:Β dict,
data:Β dictΒ |Β bytes,
headers:Β dict,
status_code:Β int)
+
+
+
+ +Expand source code + +
class SlackResponse:
+    """An iterable container of response data.
+
+    Attributes:
+        data (dict): The json-encoded content of the response. Along
+            with the headers and status code information.
+
+    Methods:
+        validate: Check if the response from Slack was successful.
+        get: Retrieves any key from the response data.
+        next: Retrieves the next portion of results,
+            if 'next_cursor' is present.
+
+    Example:
+    ```python
+    import os
+    import slack
+
+    client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+    response1 = client.auth_revoke(test='true')
+    assert not response1['revoked']
+
+    response2 = client.auth_test()
+    assert response2.get('ok', False)
+
+    users = []
+    for page in client.users_list(limit=2):
+        users = users + page['members']
+    ```
+
+    Note:
+        Some responses return collections of information
+        like channel and user lists. If they do it's likely
+        that you'll only receive a portion of results. This
+        object allows you to iterate over the response which
+        makes subsequent API requests until your code hits
+        'break' or there are no more results to be found.
+
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+    """
+
+    def __init__(
+        self,
+        *,
+        client,
+        http_verb: str,
+        api_url: str,
+        req_args: dict,
+        data: Union[dict, bytes],  # data can be binary data
+        headers: dict,
+        status_code: int,
+    ):
+        self.http_verb = http_verb
+        self.api_url = api_url
+        self.req_args = req_args
+        self.data = data
+        self.headers = headers
+        self.status_code = status_code
+        self._initial_data = data
+        self._iteration = None  # for __iter__ & __next__
+        self._client = client
+        self._logger = logging.getLogger(__name__)
+
+    def __str__(self):
+        """Return the Response data if object is converted to a string."""
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return f"{self.data}"
+
+    def __contains__(self, key: str) -> bool:
+        return self.get(key) is not None
+
+    def __getitem__(self, key):
+        """Retrieves any key from the data store.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response["ok"]
+
+        Returns:
+            The value from data or None.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            raise ValueError("As the response.data is empty, this operation is unsupported")
+        return self.data.get(key, None)
+
+    def __iter__(self):
+        """Enables the ability to iterate over the response.
+        It's required for the iterator protocol.
+
+        Note:
+            This enables Slack cursor-based pagination.
+
+        Returns:
+            (SlackResponse) self
+        """
+        self._iteration = 0
+        self.data = self._initial_data
+        return self
+
+    def __next__(self):
+        """Retrieves the next portion of results, if 'next_cursor' is present.
+
+        Note:
+            Some responses return collections of information
+            like channel and user lists. If they do it's likely
+            that you'll only receive a portion of results. This
+            method allows you to iterate over the response until
+            your code hits 'break' or there are no more results
+            to be found.
+
+        Returns:
+            (SlackResponse) self
+                With the new response data now attached to this object.
+
+        Raises:
+            SlackApiError: If the request to the Slack API failed.
+            StopIteration: If 'next_cursor' is not present or empty.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration += 1
+        if self._iteration == 1:
+            return self
+        if _next_cursor_is_present(self.data):
+            params = self.req_args.get("params", {})
+            if params is None:
+                params = {}
+            next_cursor = self.data.get("response_metadata", {}).get("next_cursor") or self.data.get("next_cursor")
+            params.update({"cursor": next_cursor})
+            self.req_args.update({"params": params})
+
+            # This method sends a request in a synchronous way
+            response = self._client._request_for_pagination(api_url=self.api_url, req_args=self.req_args)
+            self.data = response["data"]
+            self.headers = response["headers"]
+            self.status_code = response["status_code"]
+            return self.validate()
+        else:
+            raise StopIteration
+
+    @overload
+    def get(self, key: str, default: None = None) -> Optional[Any]:
+        ...
+
+    @overload
+    def get(self, key: str, default: T) -> T:
+        ...
+
+    def get(self, key, default=None):
+        """Retrieves any key from the response data.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response.get("ok", False)
+
+        Returns:
+            The value from data or the specified default.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            return None
+        return self.data.get(key, default)
+
+    def validate(self):
+        """Check if the response from Slack was successful.
+
+        Returns:
+            (SlackResponse)
+                This method returns it's own object. e.g. 'self'
+
+        Raises:
+            SlackApiError: The request to the Slack API failed.
+        """
+        if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+            return self
+        msg = f"The request to the Slack API failed. (url: {self.api_url})"
+        raise e.SlackApiError(message=msg, response=self)
+
+

An iterable container of response data.

+

Attributes

+
+
data : dict
+
The json-encoded content of the response. Along +with the headers and status code information.
+
+

Methods

+

validate: Check if the response from Slack was successful. +get: Retrieves any key from the response data. +next: Retrieves the next portion of results, +if 'next_cursor' is present.

+

Example:

+
import os
+import slack
+
+client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+response1 = client.auth_revoke(test='true')
+assert not response1['revoked']
+
+response2 = client.auth_test()
+assert response2.get('ok', False)
+
+users = []
+for page in client.users_list(limit=2):
+    users = users + page['members']
+
+

Note

+

Some responses return collections of information +like channel and user lists. If they do it's likely +that you'll only receive a portion of results. This +object allows you to iterate over the response which +makes subsequent API requests until your code hits +'break' or there are no more results to be found.

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Methods

+
+
+def get(self, key, default=None) +
+
+
+ +Expand source code + +
def get(self, key, default=None):
+    """Retrieves any key from the response data.
+
+    Note:
+        This is implemented so users can reference the
+        SlackResponse object like a dictionary.
+        e.g. response.get("ok", False)
+
+    Returns:
+        The value from data or the specified default.
+    """
+    if isinstance(self.data, bytes):
+        raise ValueError("As the response.data is binary data, this operation is unsupported")
+    if self.data is None:
+        return None
+    return self.data.get(key, default)
+
+

Retrieves any key from the response data.

+

Note

+

This is implemented so users can reference the +SlackResponse object like a dictionary. +e.g. response.get("ok", False)

+

Returns

+

The value from data or the specified default.

+
+
+def validate(self) +
+
+
+ +Expand source code + +
def validate(self):
+    """Check if the response from Slack was successful.
+
+    Returns:
+        (SlackResponse)
+            This method returns it's own object. e.g. 'self'
+
+    Raises:
+        SlackApiError: The request to the Slack API failed.
+    """
+    if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+        return self
+    msg = f"The request to the Slack API failed. (url: {self.api_url})"
+    raise e.SlackApiError(message=msg, response=self)
+
+

Check if the response from Slack was successful.

+

Returns

+

(SlackResponse) +This method returns it's own object. e.g. 'self'

+

Raises

+
+
SlackApiError
+
The request to the Slack API failed.
+
+
+
+
+
+class WebClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebClient(BaseClient):
+    """A WebClient allows apps to communicate with the Slack Platform's Web API.
+
+    https://docs.slack.dev/reference/methods
+
+    The Slack Web API is an interface for querying information from
+    and enacting change in a Slack workspace.
+
+    This client handles constructing and sending HTTP requests to Slack
+    as well as parsing any responses received into a `SlackResponse`.
+
+    Attributes:
+        token (str): A string specifying an `xoxp-*` or `xoxb-*` token.
+        base_url (str): A string representing the Slack API base URL.
+            Default is `'https://slack.com/api/'`
+        timeout (int): The maximum number of seconds the client will wait
+            to connect and receive a response from Slack.
+            Default is 30 seconds.
+        ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying
+            your own custom certificate chain.
+        proxy (str): String representing a fully-qualified URL to a proxy through
+            which to route all requests to the Slack API. Even if this parameter
+            is not specified, if any of the following environment variables are
+            present, they will be loaded into this parameter: `HTTPS_PROXY`,
+            `https_proxy`, `HTTP_PROXY` or `http_proxy`.
+        headers (dict): Additional request headers to attach to all requests.
+
+    Methods:
+        `api_call`: Constructs a request and executes the API call to Slack.
+
+    Example of recommended usage:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.chat_postMessage(
+            channel='#random',
+            text="Hello world!")
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Example manually creating an API request:
+    ```python
+        import os
+        from slack_sdk import WebClient
+
+        client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.api_call(
+            api_method='chat.postMessage',
+            json={'channel': '#random','text': "Hello world!"}
+        )
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Note:
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+
+    [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
+    """
+
+    def admin_analytics_getFile(
+        self,
+        *,
+        type: str,
+        date: Optional[str] = None,
+        metadata_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve analytics data for a given date, presented as a compressed JSON file
+        https://docs.slack.dev/reference/methods/admin.analytics.getFile
+        """
+        kwargs.update({"type": type})
+        if date is not None:
+            kwargs.update({"date": date})
+        if metadata_only is not None:
+            kwargs.update({"metadata_only": metadata_only})
+        return self.api_call("admin.analytics.getFile", params=kwargs)
+
+    def admin_apps_approve(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve an app for installation on a workspace.
+        Either app_id or request_id is required.
+        These IDs can be obtained either directly via the app_requested event,
+        or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.approve
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approve", params=kwargs)
+
+    def admin_apps_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List approved apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_clearResolution(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear an app resolution
+        https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_cancel(
+        self,
+        *,
+        request_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+        """
+        kwargs.update(
+            {
+                "request_id": request_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_restrict(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Restrict an app for installation on a workspace.
+        Exactly one of the team_id or enterprise_id arguments is required, not both.
+        Either app_id or request_id is required. These IDs can be obtained either directly
+        via the app_requested event, or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.restrict
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restrict", params=kwargs)
+
+    def admin_apps_restricted_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List restricted apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_uninstall(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+        With an org-level token, enterprise_id or team_ids is required.
+        https://docs.slack.dev/reference/methods/admin.apps.uninstall
+        """
+        kwargs.update({"app_id": app_id})
+        if enterprise_id is not None:
+            kwargs.update({"enterprise_id": enterprise_id})
+        if team_ids is not None:
+            if isinstance(team_ids, (list, tuple)):
+                kwargs.update({"team_ids": ",".join(team_ids)})
+            else:
+                kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+    def admin_apps_activities_list(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        component_id: Optional[str] = None,
+        component_type: Optional[str] = None,
+        log_event_type: Optional[str] = None,
+        max_date_created: Optional[int] = None,
+        min_date_created: Optional[int] = None,
+        min_log_level: Optional[str] = None,
+        sort_direction: Optional[str] = None,
+        source: Optional[str] = None,
+        team_id: Optional[str] = None,
+        trace_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get logs for a specified team/org
+        https://docs.slack.dev/reference/methods/admin.apps.activities.list
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "component_id": component_id,
+                "component_type": component_type,
+                "log_event_type": log_event_type,
+                "max_date_created": max_date_created,
+                "min_date_created": min_date_created,
+                "min_log_level": min_log_level,
+                "sort_direction": sort_direction,
+                "source": source,
+                "team_id": team_id,
+                "trace_id": trace_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.apps.activities.list", params=kwargs)
+
+    def admin_apps_config_lookup(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the app config for connectors by their IDs
+        https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+    def admin_apps_config_set(
+        self,
+        *,
+        app_id: str,
+        domain_restrictions: Optional[Dict[str, Any]] = None,
+        workflow_auth_strategy: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the app config for a connector
+        https://docs.slack.dev/reference/methods/admin.apps.config.set
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "workflow_auth_strategy": workflow_auth_strategy,
+            }
+        )
+        if domain_restrictions is not None:
+            kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+        return self.api_call("admin.apps.config.set", params=kwargs)
+
+    def admin_auth_policy_getEntities(
+        self,
+        *,
+        policy_name: str,
+        cursor: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch all the entities assigned to a particular authentication policy by name.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+        """
+        kwargs.update({"policy_name": policy_name})
+        if cursor is not None:
+            kwargs.update({"cursor": cursor})
+        if entity_type is not None:
+            kwargs.update({"entity_type": entity_type})
+        if limit is not None:
+            kwargs.update({"limit": limit})
+        return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_assignEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Assign entities to a particular authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_removeEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove specified entities from a specified authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+    def admin_conversations_createForObjects(
+        self,
+        *,
+        object_id: str,
+        salesforce_org_id: str,
+        invite_object_team: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Salesforce channel for the corresponding object provided.
+        https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+        """
+        kwargs.update(
+            {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+        )
+        return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+    def admin_conversations_linkObjects(
+        self,
+        *,
+        channel: str,
+        record_id: str,
+        salesforce_org_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Link a Salesforce record to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "record_id": record_id,
+                "salesforce_org_id": salesforce_org_id,
+            }
+        )
+        return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+    def admin_conversations_unlinkObjects(
+        self,
+        *,
+        channel: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unlink a Salesforce record from a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "new_name": new_name,
+            }
+        )
+        return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+    def admin_barriers_create(
+        self,
+        *,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.create
+        """
+        kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+    def admin_barriers_delete(
+        self,
+        *,
+        barrier_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.delete
+        """
+        kwargs.update({"barrier_id": barrier_id})
+        return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+    def admin_barriers_update(
+        self,
+        *,
+        barrier_id: str,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.update
+        """
+        kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+    def admin_barriers_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get all Information Barriers for your organization
+        https://docs.slack.dev/reference/methods/admin.barriers.list"""
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+    def admin_conversations_create(
+        self,
+        *,
+        is_private: bool,
+        name: str,
+        description: Optional[str] = None,
+        org_wide: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a public or private channel-based conversation.
+        https://docs.slack.dev/reference/methods/admin.conversations.create
+        """
+        kwargs.update(
+            {
+                "is_private": is_private,
+                "name": name,
+                "description": description,
+                "org_wide": org_wide,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.conversations.create", params=kwargs)
+
+    def admin_conversations_delete(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.delete
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.delete", params=kwargs)
+
+    def admin_conversations_invite(
+        self,
+        *,
+        channel_id: str,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.invite
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+        return self.api_call("admin.conversations.invite", params=kwargs)
+
+    def admin_conversations_archive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.archive", params=kwargs)
+
+    def admin_conversations_unarchive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+    def admin_conversations_rename(
+        self,
+        *,
+        channel_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.rename
+        """
+        kwargs.update({"channel_id": channel_id, "name": name})
+        return self.api_call("admin.conversations.rename", params=kwargs)
+
+    def admin_conversations_search(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        query: Optional[str] = None,
+        search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search for public or private channels in an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.conversations.search
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+            }
+        )
+
+        if isinstance(search_channel_types, (list, tuple)):
+            kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+        else:
+            kwargs.update({"search_channel_types": search_channel_types})
+
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+
+        return self.api_call("admin.conversations.search", params=kwargs)
+
+    def admin_conversations_convertToPrivate(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a public channel to a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+    def admin_conversations_convertToPublic(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Convert a privte channel to a public channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+    def admin_conversations_setConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        prefs: Union[str, Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the posting permissions for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(prefs, dict):
+            kwargs.update({"prefs": json.dumps(prefs)})
+        else:
+            kwargs.update({"prefs": prefs})
+        return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+    def admin_conversations_getConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get conversation preferences for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+    def admin_conversations_disconnectShared(
+        self,
+        *,
+        channel_id: str,
+        leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnect a connected channel from one or more workspaces.
+        https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(leaving_team_ids, (list, tuple)):
+            kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+        else:
+            kwargs.update({"leaving_team_ids": leaving_team_ids})
+        return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+    def admin_conversations_lookup(
+        self,
+        *,
+        last_message_activity_before: int,
+        team_ids: Union[str, Sequence[str]],
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        max_member_count: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns channels on the given team using the filters.
+        https://docs.slack.dev/reference/methods/admin.conversations.lookup
+        """
+        kwargs.update(
+            {
+                "last_message_activity_before": last_message_activity_before,
+                "cursor": cursor,
+                "limit": limit,
+                "max_member_count": max_member_count,
+            }
+        )
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.lookup", params=kwargs)
+
+    def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+        self,
+        *,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all disconnected channelsβ€”i.e.,
+        channels that were once connected to other workspaces and then disconnectedβ€”and
+        the corresponding original channel IDs for key revocation with EKM.
+        https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+    def admin_conversations_restrictAccess_addGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an allowlist of IDP groups for accessing a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.addGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_listGroups(
+        self,
+        *,
+        channel_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all IDP Groups linked to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.listGroups",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_removeGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a linked IDP group linked from a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.removeGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_setTeams(
+        self,
+        *,
+        channel_id: str,
+        org_channel: Optional[bool] = None,
+        target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "org_channel": org_channel,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(target_team_ids, (list, tuple)):
+            kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+        else:
+            kwargs.update({"target_team_ids": target_team_ids})
+        return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+    def admin_conversations_getTeams(
+        self,
+        *,
+        channel_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the workspaces in an Enterprise grid org that connect to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+    def admin_conversations_getCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+    def admin_conversations_removeCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+    def admin_conversations_setCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        duration_days: int,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+        return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+    def admin_conversations_bulkArchive(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Archive public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+    def admin_conversations_bulkDelete(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete public or private channels in bulk.
+        https://slack.com/api/admin.conversations.bulkDelete
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+    def admin_conversations_bulkMove(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        target_team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Move public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+        """
+        kwargs.update(
+            {
+                "target_team_id": target_team_id,
+                "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+            }
+        )
+        return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+    def admin_emoji_add(
+        self,
+        *,
+        name: str,
+        url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.add
+        """
+        kwargs.update({"name": name, "url": url})
+        return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+    def admin_emoji_addAlias(
+        self,
+        *,
+        alias_for: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an emoji alias.
+        https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+        """
+        kwargs.update({"alias_for": alias_for, "name": name})
+        return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+    def admin_emoji_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List emoji for an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+    def admin_emoji_remove(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove an emoji across an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.remove
+        """
+        kwargs.update({"name": name})
+        return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+    def admin_emoji_rename(
+        self,
+        *,
+        name: str,
+        new_name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Rename an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.rename
+        """
+        kwargs.update({"name": name, "new_name": new_name})
+        return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+    def admin_functions_list(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up functions by a set of apps
+        https://docs.slack.dev/reference/methods/admin.functions.list
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.functions.list", params=kwargs)
+
+    def admin_functions_permissions_lookup(
+        self,
+        *,
+        function_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup the visibility of multiple Slack functions
+        and include the users if it is limited to particular named entities.
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+        """
+        if isinstance(function_ids, (list, tuple)):
+            kwargs.update({"function_ids": ",".join(function_ids)})
+        else:
+            kwargs.update({"function_ids": function_ids})
+        return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+    def admin_functions_permissions_set(
+        self,
+        *,
+        function_id: str,
+        visibility: str,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the visibility of a Slack function
+        and define the users or workspaces if it is set to named_entities
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+        """
+        kwargs.update(
+            {
+                "function_id": function_id,
+                "visibility": visibility,
+            }
+        )
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+    def admin_roles_addAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds members to the specified role with the specified scopes
+        https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+    def admin_roles_listAssignments(
+        self,
+        *,
+        role_ids: Optional[Union[str, Sequence[str]]] = None,
+        entity_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[Union[str, int]] = None,
+        sort_dir: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists assignments for all roles across entities.
+            Options to scope results by any combination of roles or entities
+        https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(role_ids, (list, tuple)):
+            kwargs.update({"role_ids": ",".join(role_ids)})
+        else:
+            kwargs.update({"role_ids": role_ids})
+        return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+    def admin_roles_removeAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a set of users from a role for the given scopes and entities
+        https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+    def admin_users_session_reset(
+        self,
+        *,
+        user_id: str,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Wipes all valid sessions on all devices for a given user.
+        https://docs.slack.dev/reference/methods/admin.users.session.reset
+        """
+        kwargs.update(
+            {
+                "user_id": user_id,
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.reset", params=kwargs)
+
+    def admin_users_session_resetBulk(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+        https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+    def admin_users_session_invalidate(
+        self,
+        *,
+        session_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invalidate a single session for a user by session_id.
+        https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+        """
+        kwargs.update({"session_id": session_id, "team_id": team_id})
+        return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+    def admin_users_session_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all active user sessions for an organization
+        https://docs.slack.dev/reference/methods/admin.users.session.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+                "user_id": user_id,
+            }
+        )
+        return self.api_call("admin.users.session.list", params=kwargs)
+
+    def admin_teams_settings_setDefaultChannels(
+        self,
+        *,
+        team_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the default channels of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+        """
+        kwargs.update({"team_id": team_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+    def admin_users_session_getSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Get user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”given a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+    def admin_users_session_setSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        desktop_app_browser_quit: Optional[bool] = None,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Configure the user-level session settingsβ€”the session duration
+        and what happens when the client closesβ€”for one or more users.
+        https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "desktop_app_browser_quit": desktop_app_browser_quit,
+                "duration": duration,
+            }
+        )
+        return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+    def admin_users_session_clearSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Clear user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”for a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+    def admin_users_unsupportedVersions_export(
+        self,
+        *,
+        date_end_of_support: Optional[Union[str, int]] = None,
+        date_sessions_started: Optional[Union[str, int]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+        presented as a zipped CSV file.
+        https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+        """
+        kwargs.update(
+            {
+                "date_end_of_support": date_end_of_support,
+                "date_sessions_started": date_sessions_started,
+            }
+        )
+        return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+    def admin_inviteRequests_approve(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+    def admin_inviteRequests_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all approved workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+    def admin_inviteRequests_denied_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all denied workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+    def admin_inviteRequests_deny(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+    def admin_inviteRequests_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all pending workspace invite requests."""
+        return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+    def admin_teams_admins_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_create(
+        self,
+        *,
+        team_domain: str,
+        team_name: str,
+        team_description: Optional[str] = None,
+        team_discoverability: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an Enterprise team.
+        https://docs.slack.dev/reference/methods/admin.teams.create
+        """
+        kwargs.update(
+            {
+                "team_domain": team_domain,
+                "team_name": team_name,
+                "team_description": team_description,
+                "team_discoverability": team_discoverability,
+            }
+        )
+        return self.api_call("admin.teams.create", params=kwargs)
+
+    def admin_teams_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all teams on an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.list", params=kwargs)
+
+    def admin_teams_owners_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.owners.list
+        """
+        kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_info(
+        self,
+        *,
+        team_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetch information about settings in a workspace
+        https://docs.slack.dev/reference/methods/admin.teams.settings.info
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("admin.teams.settings.info", params=kwargs)
+
+    def admin_teams_settings_setDescription(
+        self,
+        *,
+        team_id: str,
+        description: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the description of a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+        """
+        kwargs.update({"team_id": team_id, "description": description})
+        return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+    def admin_teams_settings_setDiscoverability(
+        self,
+        *,
+        team_id: str,
+        discoverability: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+        """
+        kwargs.update({"team_id": team_id, "discoverability": discoverability})
+        return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+    def admin_teams_settings_setIcon(
+        self,
+        *,
+        team_id: str,
+        image_url: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+        """
+        kwargs.update({"team_id": team_id, "image_url": image_url})
+        return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_setName(
+        self,
+        *,
+        team_id: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+        """
+        kwargs.update({"team_id": team_id, "name": name})
+        return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+    def admin_usergroups_addChannels(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        usergroup_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+        """
+        kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+    def admin_usergroups_addTeams(
+        self,
+        *,
+        usergroup_id: str,
+        team_ids: Union[str, Sequence[str]],
+        auto_provision: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Associate one or more default workspaces with an organization-wide IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+        """
+        kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+    def admin_usergroups_listChannels(
+        self,
+        *,
+        usergroup_id: str,
+        include_num_members: Optional[bool] = None,
+        team_id: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+        """
+        kwargs.update(
+            {
+                "usergroup_id": usergroup_id,
+                "include_num_members": include_num_members,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+    def admin_usergroups_removeChannels(
+        self,
+        *,
+        usergroup_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+        """
+        kwargs.update({"usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+    def admin_users_assign(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add an Enterprise user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.assign
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "user_id": user_id,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.assign", params=kwargs)
+
+    def admin_users_invite(
+        self,
+        *,
+        team_id: str,
+        email: str,
+        channel_ids: Union[str, Sequence[str]],
+        custom_message: Optional[str] = None,
+        email_password_policy_enabled: Optional[bool] = None,
+        guest_expiration_ts: Optional[Union[str, float]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        real_name: Optional[str] = None,
+        resend: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invite a user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.invite
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "email": email,
+                "custom_message": custom_message,
+                "email_password_policy_enabled": email_password_policy_enabled,
+                "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+                "real_name": real_name,
+                "resend": resend,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.invite", params=kwargs)
+
+    def admin_users_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        include_deactivated_user_workspaces: Optional[bool] = None,
+        is_active: Optional[bool] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List users on a workspace
+        https://docs.slack.dev/reference/methods/admin.users.list
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+                "is_active": is_active,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.users.list", params=kwargs)
+
+    def admin_users_remove(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a user from a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.remove
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.remove", params=kwargs)
+
+    def admin_users_setAdmin(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or owner to be an admin user.
+        https://docs.slack.dev/reference/methods/admin.users.setAdmin
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setAdmin", params=kwargs)
+
+    def admin_users_setExpiration(
+        self,
+        *,
+        expiration_ts: int,
+        user_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an expiration for a guest user.
+        https://docs.slack.dev/reference/methods/admin.users.setExpiration
+        """
+        kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setExpiration", params=kwargs)
+
+    def admin_users_setOwner(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest, regular user, or admin user to be a workspace owner.
+        https://docs.slack.dev/reference/methods/admin.users.setOwner
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setOwner", params=kwargs)
+
+    def admin_users_setRegular(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set an existing guest user, admin user, or owner to be a regular user.
+        https://docs.slack.dev/reference/methods/admin.users.setRegular
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setRegular", params=kwargs)
+
+    def admin_workflows_search(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        no_collaborators: Optional[bool] = None,
+        num_trigger_ids: Optional[int] = None,
+        query: Optional[str] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        source: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Search workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.search
+        """
+        if collaborator_ids is not None:
+            if isinstance(collaborator_ids, (list, tuple)):
+                kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+            else:
+                kwargs.update({"collaborator_ids": collaborator_ids})
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "cursor": cursor,
+                "limit": limit,
+                "no_collaborators": no_collaborators,
+                "num_trigger_ids": num_trigger_ids,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "source": source,
+            }
+        )
+        return self.api_call("admin.workflows.search", params=kwargs)
+
+    def admin_workflows_permissions_lookup(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        max_workflow_triggers: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Look up the permissions for a set of workflows
+        https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        kwargs.update(
+            {
+                "max_workflow_triggers": max_workflow_triggers,
+            }
+        )
+        return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+    def admin_workflows_collaborators_add(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add collaborators to workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+    def admin_workflows_collaborators_remove(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove collaborators from workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+    def admin_workflows_unpublish(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Unpublish workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+    def api_test(
+        self,
+        *,
+        error: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks API calling code.
+        https://docs.slack.dev/reference/methods/api.test
+        """
+        kwargs.update({"error": error})
+        return self.api_call("api.test", params=kwargs)
+
+    def apps_connections_open(
+        self,
+        *,
+        app_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+        in order to receive events and interactive payloads
+        https://docs.slack.dev/reference/methods/apps.connections.open
+        """
+        kwargs.update({"token": app_token})
+        return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+    def apps_event_authorizations_list(
+        self,
+        *,
+        event_context: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a list of authorizations for the given event context.
+        Each authorization represents an app installation that the event is visible to.
+        https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+        """
+        kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+        return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+    def apps_uninstall(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uninstalls your app from a workspace.
+        https://docs.slack.dev/reference/methods/apps.uninstall
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret})
+        return self.api_call("apps.uninstall", params=kwargs)
+
+    def apps_manifest_create(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.create
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        return self.api_call("apps.manifest.create", params=kwargs)
+
+    def apps_manifest_delete(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Permanently deletes an app created through app manifests
+        https://docs.slack.dev/reference/methods/apps.manifest.delete
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.delete", params=kwargs)
+
+    def apps_manifest_export(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Export an app manifest from an existing app
+        https://docs.slack.dev/reference/methods/apps.manifest.export
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.export", params=kwargs)
+
+    def apps_manifest_update(
+        self,
+        *,
+        app_id: str,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.update
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.update", params=kwargs)
+
+    def apps_manifest_validate(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        app_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Validate an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.validate
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.validate", params=kwargs)
+
+    def tooling_tokens_rotate(
+        self,
+        *,
+        refresh_token: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a refresh token for a new app configuration token
+        https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+        """
+        kwargs.update({"refresh_token": refresh_token})
+        return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+    def assistant_threads_setStatus(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        status: str,
+        loading_messages: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the status for an AI assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+        """
+        kwargs.update(
+            {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+    def assistant_threads_setTitle(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the title for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+        return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+    def assistant_threads_setSuggestedPrompts(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: Optional[str] = None,
+        prompts: List[Dict[str, str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set suggested prompts for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+        if title is not None:
+            kwargs.update({"title": title})
+        return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+    def auth_revoke(
+        self,
+        *,
+        test: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes a token.
+        https://docs.slack.dev/reference/methods/auth.revoke
+        """
+        kwargs.update({"test": test})
+        return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+    def auth_test(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Checks authentication & identity.
+        https://docs.slack.dev/reference/methods/auth.test
+        """
+        return self.api_call("auth.test", params=kwargs)
+
+    def auth_teams_list(
+        self,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        include_icon: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List the workspaces a token can access.
+        https://docs.slack.dev/reference/methods/auth.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+        return self.api_call("auth.teams.list", params=kwargs)
+
+    def bookmarks_add(
+        self,
+        *,
+        channel_id: str,
+        title: str,
+        type: str,
+        emoji: Optional[str] = None,
+        entity_id: Optional[str] = None,
+        link: Optional[str] = None,  # include when type is 'link'
+        parent_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add bookmark to a channel.
+        https://docs.slack.dev/reference/methods/bookmarks.add
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "title": title,
+                "type": type,
+                "emoji": emoji,
+                "entity_id": entity_id,
+                "link": link,
+                "parent_id": parent_id,
+            }
+        )
+        return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+    def bookmarks_edit(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        emoji: Optional[str] = None,
+        link: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Edit bookmark.
+        https://docs.slack.dev/reference/methods/bookmarks.edit
+        """
+        kwargs.update(
+            {
+                "bookmark_id": bookmark_id,
+                "channel_id": channel_id,
+                "emoji": emoji,
+                "link": link,
+                "title": title,
+            }
+        )
+        return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+    def bookmarks_list(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """List bookmark for the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.list
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+    def bookmarks_remove(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove bookmark from the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.remove
+        """
+        kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+        return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+    def bots_info(
+        self,
+        *,
+        bot: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a bot user.
+        https://docs.slack.dev/reference/methods/bots.info
+        """
+        kwargs.update({"bot": bot, "team_id": team_id})
+        return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+    def calls_add(
+        self,
+        *,
+        external_unique_id: str,
+        join_url: str,
+        created_by: Optional[str] = None,
+        date_start: Optional[int] = None,
+        desktop_app_join_url: Optional[str] = None,
+        external_display_id: Optional[str] = None,
+        title: Optional[str] = None,
+        users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers a new Call.
+        https://docs.slack.dev/reference/methods/calls.add
+        """
+        kwargs.update(
+            {
+                "external_unique_id": external_unique_id,
+                "join_url": join_url,
+                "created_by": created_by,
+                "date_start": date_start,
+                "desktop_app_join_url": desktop_app_join_url,
+                "external_display_id": external_display_id,
+                "title": title,
+            }
+        )
+        _update_call_participants(
+            kwargs,
+            users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+        )
+        return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+    def calls_end(
+        self,
+        *,
+        id: str,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends a Call.
+        https://docs.slack.dev/reference/methods/calls.end
+        """
+        kwargs.update({"id": id, "duration": duration})
+        return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+    def calls_info(
+        self,
+        *,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns information about a Call.
+        https://docs.slack.dev/reference/methods/calls.info
+        """
+        kwargs.update({"id": id})
+        return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+    def calls_participants_add(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers new participants added to a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.add
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+    def calls_participants_remove(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Registers participants removed from a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.remove
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+    def calls_update(
+        self,
+        *,
+        id: str,
+        desktop_app_join_url: Optional[str] = None,
+        join_url: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates information about a Call.
+        https://docs.slack.dev/reference/methods/calls.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "desktop_app_join_url": desktop_app_join_url,
+                "join_url": join_url,
+                "title": title,
+            }
+        )
+        return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+    def canvases_create(
+        self,
+        *,
+        title: Optional[str] = None,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create Canvas for a user
+        https://docs.slack.dev/reference/methods/canvases.create
+        """
+        kwargs.update({"title": title, "document_content": document_content})
+        return self.api_call("canvases.create", json=kwargs)
+
+    def canvases_edit(
+        self,
+        *,
+        canvas_id: str,
+        changes: Sequence[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing canvas
+        https://docs.slack.dev/reference/methods/canvases.edit
+        """
+        kwargs.update({"canvas_id": canvas_id, "changes": changes})
+        return self.api_call("canvases.edit", json=kwargs)
+
+    def canvases_delete(
+        self,
+        *,
+        canvas_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a canvas
+        https://docs.slack.dev/reference/methods/canvases.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        return self.api_call("canvases.delete", params=kwargs)
+
+    def canvases_access_set(
+        self,
+        *,
+        canvas_id: str,
+        access_level: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the access level to a canvas for specified entities
+        https://docs.slack.dev/reference/methods/canvases.access.set
+        """
+        kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+
+        return self.api_call("canvases.access.set", params=kwargs)
+
+    def canvases_access_delete(
+        self,
+        *,
+        canvas_id: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/canvases.access.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("canvases.access.delete", params=kwargs)
+
+    def canvases_sections_lookup(
+        self,
+        *,
+        canvas_id: str,
+        criteria: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Find sections matching the provided criteria
+        https://docs.slack.dev/reference/methods/canvases.sections.lookup
+        """
+        kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+        return self.api_call("canvases.sections.lookup", params=kwargs)
+
+    # --------------------------
+    # Deprecated: channels.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def channels_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.archive", json=kwargs)
+
+    def channels_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.create", json=kwargs)
+
+    def channels_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+    def channels_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+    def channels_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.invite", json=kwargs)
+
+    def channels_join(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins a channel, creating it if needed."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.join", json=kwargs)
+
+    def channels_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.kick", json=kwargs)
+
+    def channels_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.leave", json=kwargs)
+
+    def channels_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team."""
+        return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+    def channels_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.mark", json=kwargs)
+
+    def channels_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.rename", json=kwargs)
+
+    def channels_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+    def channels_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setPurpose", json=kwargs)
+
+    def channels_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setTopic", json=kwargs)
+
+    def channels_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.unarchive", json=kwargs)
+
+    # --------------------------
+
+    def chat_appendStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Appends text to an existing streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.appendStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.appendStream", json=kwargs)
+
+    def chat_delete(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a message.
+        https://docs.slack.dev/reference/methods/chat.delete
+        """
+        kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+        return self.api_call("chat.delete", params=kwargs)
+
+    def chat_deleteScheduledMessage(
+        self,
+        *,
+        channel: str,
+        scheduled_message_id: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a scheduled message.
+        https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "scheduled_message_id": scheduled_message_id,
+                "as_user": as_user,
+            }
+        )
+        return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+    def chat_getPermalink(
+        self,
+        *,
+        channel: str,
+        message_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a permalink URL for a specific extant message
+        https://docs.slack.dev/reference/methods/chat.getPermalink
+        """
+        kwargs.update({"channel": channel, "message_ts": message_ts})
+        return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+    def chat_meMessage(
+        self,
+        *,
+        channel: str,
+        text: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a me message into a channel.
+        https://docs.slack.dev/reference/methods/chat.meMessage
+        """
+        kwargs.update({"channel": channel, "text": text})
+        return self.api_call("chat.meMessage", params=kwargs)
+
+    def chat_postEphemeral(
+        self,
+        *,
+        channel: str,
+        user: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an ephemeral message to a user in a channel.
+        https://docs.slack.dev/reference/methods/chat.postEphemeral
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "user": user,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postEphemeral", json=kwargs)
+
+    def chat_postMessage(
+        self,
+        *,
+        channel: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        container_id: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        mrkdwn: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,  # none, full
+        metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends a message to a channel.
+        https://docs.slack.dev/reference/methods/chat.postMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "container_id": container_id,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "mrkdwn": mrkdwn,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postMessage", json=kwargs)
+
+    def chat_scheduleMessage(
+        self,
+        *,
+        channel: str,
+        post_at: Union[str, int],
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        parse: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Schedules a message.
+        https://docs.slack.dev/reference/methods/chat.scheduleMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "post_at": post_at,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "parse": parse,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "link_names": link_names,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.scheduleMessage", json=kwargs)
+
+    def chat_scheduledMessages_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all scheduled messages.
+        https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "latest": latest,
+                "limit": limit,
+                "oldest": oldest,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+    def chat_startStream(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        markdown_text: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a new streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.startStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "thread_ts": thread_ts,
+                "markdown_text": markdown_text,
+                "recipient_team_id": recipient_team_id,
+                "recipient_user_id": recipient_user_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.startStream", json=kwargs)
+
+    def chat_stopStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Stops a streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.stopStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+                "blocks": blocks,
+                "metadata": metadata,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.stopStream", json=kwargs)
+
+    def chat_stream(
+        self,
+        *,
+        buffer_size: int = 256,
+        channel: str,
+        thread_ts: str,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> ChatStream:
+        """Stream markdown text into a conversation.
+
+        This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+        the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+        The following methods are used:
+
+        - chat.startStream: Starts a new streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+        - chat.appendStream: Appends text to an existing streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+        - chat.stopStream: Stops a streaming conversation.
+          [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+        Args:
+            buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+              value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+              limits. Default: 256.
+            channel: An encoded ID that represents a channel, private group, or DM.
+            thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+              request.
+            recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+              streaming to channels.
+            recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+            **kwargs: Additional arguments passed to the underlying API calls.
+
+        Returns:
+            ChatStream instance for managing the stream
+
+        Example:
+            ```python
+            streamer = client.chat_stream(
+                channel="C0123456789",
+                thread_ts="1700000001.123456",
+                recipient_team_id="T0123456789",
+                recipient_user_id="U0123456789",
+            )
+            streamer.append(markdown_text="**hello wo")
+            streamer.append(markdown_text="rld!**")
+            streamer.stop()
+            ```
+        """
+        return ChatStream(
+            self,
+            logger=self._logger,
+            channel=channel,
+            thread_ts=thread_ts,
+            recipient_team_id=recipient_team_id,
+            recipient_user_id=recipient_user_id,
+            buffer_size=buffer_size,
+            **kwargs,
+        )
+
+    def chat_unfurl(
+        self,
+        *,
+        channel: Optional[str] = None,
+        ts: Optional[str] = None,
+        source: Optional[str] = None,
+        unfurl_id: Optional[str] = None,
+        unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+        metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+        user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        user_auth_message: Optional[str] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provide custom unfurl behavior for user-posted URLs.
+        https://docs.slack.dev/reference/methods/chat.unfurl
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "source": source,
+                "unfurl_id": unfurl_id,
+                "unfurls": unfurls,
+                "metadata": metadata,
+                "user_auth_blocks": user_auth_blocks,
+                "user_auth_message": user_auth_message,
+                "user_auth_required": user_auth_required,
+                "user_auth_url": user_auth_url,
+            }
+        )
+        _parse_web_class_objects(kwargs)  # for user_auth_blocks
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.unfurl", json=kwargs)
+
+    def chat_update(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        text: Optional[str] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        as_user: Optional[bool] = None,
+        file_ids: Optional[Union[str, Sequence[str]]] = None,
+        link_names: Optional[bool] = None,
+        parse: Optional[str] = None,  # none, full
+        reply_broadcast: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates a message in a channel.
+        https://docs.slack.dev/reference/methods/chat.update
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "as_user": as_user,
+                "link_names": link_names,
+                "parse": parse,
+                "reply_broadcast": reply_broadcast,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        if isinstance(file_ids, (list, tuple)):
+            kwargs.update({"file_ids": ",".join(file_ids)})
+        else:
+            kwargs.update({"file_ids": file_ids})
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.update", kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.update", json=kwargs)
+
+    def conversations_acceptSharedInvite(
+        self,
+        *,
+        channel_name: str,
+        channel_id: Optional[str] = None,
+        invite_id: Optional[str] = None,
+        free_trial_accepted: Optional[bool] = None,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Accepts an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+        """
+        if channel_id is None and invite_id is None:
+            raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+        kwargs.update(
+            {
+                "channel_name": channel_name,
+                "channel_id": channel_id,
+                "invite_id": invite_id,
+                "free_trial_accepted": free_trial_accepted,
+                "is_private": is_private,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_approveSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approves an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a conversation.
+        https://docs.slack.dev/reference/methods/conversations.archive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.archive", params=kwargs)
+
+    def conversations_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.close
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.close", params=kwargs)
+
+    def conversations_create(
+        self,
+        *,
+        name: str,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiates a public or private channel-based conversation
+        https://docs.slack.dev/reference/methods/conversations.create
+        """
+        kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+        return self.api_call("conversations.create", params=kwargs)
+
+    def conversations_declineSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Declines a Slack Connect channel invite.
+        https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+    def conversations_externalInvitePermissions_set(
+        self, *, action: str, channel: str, target_team: str, **kwargs
+    ) -> SlackResponse:
+        """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+        https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+        """
+        kwargs.update(
+            {
+                "action": action,
+                "channel": channel,
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+    def conversations_history(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches a conversation's history of messages and events.
+        https://docs.slack.dev/reference/methods/conversations.history
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+    def conversations_info(
+        self,
+        *,
+        channel: str,
+        include_locale: Optional[bool] = None,
+        include_num_members: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a conversation.
+        https://docs.slack.dev/reference/methods/conversations.info
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "include_locale": include_locale,
+                "include_num_members": include_num_members,
+            }
+        )
+        return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+    def conversations_invite(
+        self,
+        *,
+        channel: str,
+        users: Union[str, Sequence[str]],
+        force: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites users to a channel.
+        https://docs.slack.dev/reference/methods/conversations.invite
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "force": force,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.invite", params=kwargs)
+
+    def conversations_inviteShared(
+        self,
+        *,
+        channel: str,
+        emails: Optional[Union[str, Sequence[str]]] = None,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sends an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.inviteShared
+        """
+        if emails is None and user_ids is None:
+            raise e.SlackRequestError("Either emails or user ids must be provided.")
+        kwargs.update({"channel": channel})
+        if isinstance(emails, (list, tuple)):
+            kwargs.update({"emails": ",".join(emails)})
+        else:
+            kwargs.update({"emails": emails})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+    def conversations_join(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Joins an existing conversation.
+        https://docs.slack.dev/reference/methods/conversations.join
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.join", params=kwargs)
+
+    def conversations_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a conversation.
+        https://docs.slack.dev/reference/methods/conversations.kick
+        """
+        kwargs.update({"channel": channel, "user": user})
+        return self.api_call("conversations.kick", params=kwargs)
+
+    def conversations_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a conversation.
+        https://docs.slack.dev/reference/methods/conversations.leave
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.leave", params=kwargs)
+
+    def conversations_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all channels in a Slack team.
+        https://docs.slack.dev/reference/methods/conversations.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+    def conversations_listConnectInvites(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List shared channel invites that have been generated
+        or received but have not yet been approved by all parties.
+        https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+        """
+        kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+        return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+    def conversations_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a channel.
+        https://docs.slack.dev/reference/methods/conversations.mark
+        """
+        kwargs.update({"channel": channel, "ts": ts})
+        return self.api_call("conversations.mark", params=kwargs)
+
+    def conversations_members(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve members of a conversation.
+        https://docs.slack.dev/reference/methods/conversations.members
+        """
+        kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+        return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+    def conversations_open(
+        self,
+        *,
+        channel: Optional[str] = None,
+        return_im: Optional[bool] = None,
+        users: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens or resumes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.open
+        """
+        if channel is None and users is None:
+            raise e.SlackRequestError("Either channel or users must be provided.")
+        kwargs.update({"channel": channel, "return_im": return_im})
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.open", params=kwargs)
+
+    def conversations_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a conversation.
+        https://docs.slack.dev/reference/methods/conversations.rename
+        """
+        kwargs.update({"channel": channel, "name": name})
+        return self.api_call("conversations.rename", params=kwargs)
+
+    def conversations_replies(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a conversation
+        https://docs.slack.dev/reference/methods/conversations.replies
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+    def conversations_requestSharedInvite_approve(
+        self,
+        *,
+        invite_id: str,
+        channel_id: Optional[str] = None,
+        is_external_limited: Optional[str] = None,
+        message: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+        """
+        kwargs.update(
+            {
+                "invite_id": invite_id,
+                "channel_id": channel_id,
+                "is_external_limited": is_external_limited,
+            }
+        )
+        if message is not None:
+            kwargs.update({"message": json.dumps(message)})
+        return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+    def conversations_requestSharedInvite_deny(
+        self,
+        *,
+        invite_id: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deny a request to invite an external user to a channel.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+        """
+        kwargs.update({"invite_id": invite_id, "message": message})
+        return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+    def conversations_requestSharedInvite_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_approved: Optional[bool] = None,
+        include_denied: Optional[bool] = None,
+        include_expired: Optional[bool] = None,
+        invite_ids: Optional[Union[str, Sequence[str]]] = None,
+        limit: Optional[int] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists requests to add external users to channels with ability to filter.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_approved": include_approved,
+                "include_denied": include_denied,
+                "include_expired": include_expired,
+                "limit": limit,
+                "user_id": user_id,
+            }
+        )
+        if invite_ids is not None:
+            if isinstance(invite_ids, (list, tuple)):
+                kwargs.update({"invite_ids": ",".join(invite_ids)})
+            else:
+                kwargs.update({"invite_ids": invite_ids})
+        return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+    def conversations_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setPurpose
+        """
+        kwargs.update({"channel": channel, "purpose": purpose})
+        return self.api_call("conversations.setPurpose", params=kwargs)
+
+    def conversations_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setTopic
+        """
+        kwargs.update({"channel": channel, "topic": topic})
+        return self.api_call("conversations.setTopic", params=kwargs)
+
+    def conversations_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reverses conversation archival.
+        https://docs.slack.dev/reference/methods/conversations.unarchive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.unarchive", params=kwargs)
+
+    def conversations_canvases_create(
+        self,
+        *,
+        channel_id: str,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/conversations.canvases.create
+        """
+        kwargs.update({"channel_id": channel_id, "document_content": document_content})
+        return self.api_call("conversations.canvases.create", json=kwargs)
+
+    def dialog_open(
+        self,
+        *,
+        dialog: Dict[str, Any],
+        trigger_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a dialog with a user.
+        https://docs.slack.dev/reference/methods/dialog.open
+        """
+        kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: As the dialog can be a dict, this API call works only with json format.
+        return self.api_call("dialog.open", json=kwargs)
+
+    def dnd_endDnd(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's Do Not Disturb session immediately.
+        https://docs.slack.dev/reference/methods/dnd.endDnd
+        """
+        return self.api_call("dnd.endDnd", params=kwargs)
+
+    def dnd_endSnooze(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Ends the current user's snooze mode immediately.
+        https://docs.slack.dev/reference/methods/dnd.endSnooze
+        """
+        return self.api_call("dnd.endSnooze", params=kwargs)
+
+    def dnd_info(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's current Do Not Disturb status.
+        https://docs.slack.dev/reference/methods/dnd.info
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+    def dnd_setSnooze(
+        self,
+        *,
+        num_minutes: Union[int, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Turns on Do Not Disturb mode for the current user, or changes its duration.
+        https://docs.slack.dev/reference/methods/dnd.setSnooze
+        """
+        kwargs.update({"num_minutes": num_minutes})
+        return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+    def dnd_teamInfo(
+        self,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves the Do Not Disturb status for users on a team.
+        https://docs.slack.dev/reference/methods/dnd.teamInfo
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id})
+        return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+    def emoji_list(
+        self,
+        include_categories: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists custom emoji for a team.
+        https://docs.slack.dev/reference/methods/emoji.list
+        """
+        kwargs.update({"include_categories": include_categories})
+        return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+    def entity_presentDetails(
+        self,
+        trigger_id: str,
+        metadata: Optional[Union[Dict, EntityMetadata]] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        error: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Provides entity details for the flexpane.
+        https://docs.slack.dev/reference/methods/entity.presentDetails/
+        """
+        kwargs.update({"trigger_id": trigger_id})
+        if metadata is not None:
+            kwargs.update({"metadata": metadata})
+        if user_auth_required is not None:
+            kwargs.update({"user_auth_required": user_auth_required})
+        if user_auth_url is not None:
+            kwargs.update({"user_auth_url": user_auth_url})
+        if error is not None:
+            kwargs.update({"error": error})
+        _parse_web_class_objects(kwargs)
+        return self.api_call("entity.presentDetails", json=kwargs)
+
+    def files_comments_delete(
+        self,
+        *,
+        file: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an existing comment on a file.
+        https://docs.slack.dev/reference/methods/files.comments.delete
+        """
+        kwargs.update({"file": file, "id": id})
+        return self.api_call("files.comments.delete", params=kwargs)
+
+    def files_delete(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a file.
+        https://docs.slack.dev/reference/methods/files.delete
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.delete", params=kwargs)
+
+    def files_info(
+        self,
+        *,
+        file: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a team file.
+        https://docs.slack.dev/reference/methods/files.info
+        """
+        kwargs.update(
+            {
+                "file": file,
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+            }
+        )
+        return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+    def files_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        count: Optional[int] = None,
+        page: Optional[int] = None,
+        show_files_hidden_by_limit: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists & filters team files.
+        https://docs.slack.dev/reference/methods/files.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "count": count,
+                "page": page,
+                "show_files_hidden_by_limit": show_files_hidden_by_limit,
+                "team_id": team_id,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+    def files_remote_info(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.info
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+    def files_remote_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "limit": limit,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+            }
+        )
+        return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+    def files_remote_add(
+        self,
+        *,
+        external_id: str,
+        external_url: str,
+        title: str,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+        preview_image: Optional[Union[str, bytes, IOBase]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a file from a remote service.
+        https://docs.slack.dev/reference/methods/files.remote.add
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.add",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_update(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        external_url: Optional[str] = None,
+        file: Optional[str] = None,
+        title: Optional[str] = None,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[str] = None,
+        preview_image: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates an existing remote file.
+        https://docs.slack.dev/reference/methods/files.remote.update
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "file": file,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.update",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_remove(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove a remote file.
+        https://docs.slack.dev/reference/methods/files.remote.remove
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+    def files_remote_share(
+        self,
+        *,
+        channels: Union[str, Sequence[str]],
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Share a remote file into a channel.
+        https://docs.slack.dev/reference/methods/files.remote.share
+        """
+        if external_id is None and file is None:
+            raise e.SlackRequestError("Either external_id or file must be provided.")
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+    def files_revokePublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revokes public/external sharing access for a file
+        https://docs.slack.dev/reference/methods/files.revokePublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.revokePublicURL", params=kwargs)
+
+    def files_sharedPublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enables a file for public/external sharing.
+        https://docs.slack.dev/reference/methods/files.sharedPublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.sharedPublicURL", params=kwargs)
+
+    def files_upload(
+        self,
+        *,
+        file: Optional[Union[str, bytes, IOBase]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        filename: Optional[str] = None,
+        filetype: Optional[str] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        title: Optional[str] = None,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Uploads or creates a file.
+        https://docs.slack.dev/reference/methods/files.upload
+        """
+        _print_files_upload_v2_suggestion()
+
+        if file is None and content is None:
+            raise e.SlackRequestError("The file or content argument must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update(
+            {
+                "filename": filename,
+                "filetype": filetype,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+                "title": title,
+            }
+        )
+        if file:
+            if kwargs.get("filename") is None and isinstance(file, str):
+                # use the local filename if filename is missing
+                if kwargs.get("filename") is None:
+                    kwargs["filename"] = file.split(os.path.sep)[-1]
+            return self.api_call("files.upload", files={"file": file}, data=kwargs)
+        else:
+            kwargs["content"] = content
+            return self.api_call("files.upload", data=kwargs)
+
+    def files_upload_v2(
+        self,
+        *,
+        # for sending a single file
+        filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+        file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        title: Optional[str] = None,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        # To upload multiple files at a time
+        file_uploads: Optional[List[Dict[str, Any]]] = None,
+        channel: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+        **kwargs,
+    ) -> SlackResponse:
+        """This wrapper method provides an easy way to upload files using the following endpoints:
+
+        - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+        - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+        - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+            and https://docs.slack.dev/reference/methods/files.info
+
+        """
+        if file is None and content is None and file_uploads is None:
+            raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        # deprecated arguments:
+        filetype = kwargs.get("filetype")
+
+        if filetype is not None:
+            warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+        # step1: files.getUploadURLExternal per file
+        files: List[Dict[str, Any]] = []
+        if file_uploads is not None:
+            for f in file_uploads:
+                files.append(_to_v2_file_upload_item(f))
+        else:
+            f = _to_v2_file_upload_item(
+                {
+                    "filename": filename,
+                    "file": file,
+                    "content": content,
+                    "title": title,
+                    "alt_txt": alt_txt,
+                    "snippet_type": snippet_type,
+                }
+            )
+            files.append(f)
+
+        for f in files:
+            url_response = self.files_getUploadURLExternal(
+                filename=f.get("filename"),  # type: ignore[arg-type]
+                length=f.get("length"),  # type: ignore[arg-type]
+                alt_txt=f.get("alt_txt"),
+                snippet_type=f.get("snippet_type"),
+                token=kwargs.get("token"),
+            )
+            _validate_for_legacy_client(url_response)
+            f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+            f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+        # step2: "https://files.slack.com/upload/v1/..." per file
+        for f in files:
+            upload_result = self._upload_file(
+                url=f["upload_url"],
+                data=f["data"],
+                logger=self._logger,
+                timeout=self.timeout,
+                proxy=self.proxy,
+                ssl=self.ssl,
+            )
+            if upload_result.status != 200:
+                status = upload_result.status
+                body = upload_result.body
+                message = (
+                    "Failed to upload a file "
+                    f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+                )
+                raise e.SlackRequestError(message)
+
+        # step3: files.completeUploadExternal with all the sets of (file_id + title)
+        completion = self.files_completeUploadExternal(
+            files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+            channel_id=channel,
+            channels=channels,
+            initial_comment=initial_comment,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+        if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+            completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+        return completion
+
+    def files_getUploadURLExternal(
+        self,
+        *,
+        filename: str,
+        length: int,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets a URL for an edge external upload.
+        https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+        """
+        kwargs.update(
+            {
+                "filename": filename,
+                "length": length,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+    def files_completeUploadExternal(
+        self,
+        *,
+        files: List[Dict[str, str]],
+        channel_id: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Finishes an upload started with files.getUploadURLExternal.
+        https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        """
+        _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+        kwargs.update(
+            {
+                "files": json.dumps(_files),
+                "channel_id": channel_id,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+            }
+        )
+        if channels:
+            kwargs["channels"] = ",".join(channels)
+        return self.api_call("files.completeUploadExternal", params=kwargs)
+
+    def functions_completeSuccess(
+        self,
+        *,
+        function_execution_id: str,
+        outputs: Dict[str, Any],
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the successful completion of a function
+        https://docs.slack.dev/reference/methods/functions.completeSuccess
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+        return self.api_call("functions.completeSuccess", params=kwargs)
+
+    def functions_completeError(
+        self,
+        *,
+        function_execution_id: str,
+        error: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Signal the failure to execute a function
+        https://docs.slack.dev/reference/methods/functions.completeError
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "error": error})
+        return self.api_call("functions.completeError", params=kwargs)
+
+    # --------------------------
+    # Deprecated: groups.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def groups_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Archives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.archive", json=kwargs)
+
+    def groups_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a private channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.create", json=kwargs)
+
+    def groups_createChild(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Clones and archives a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+    def groups_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+    def groups_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+    def groups_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Invites a user to a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.invite", json=kwargs)
+
+    def groups_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a user from a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.kick", json=kwargs)
+
+    def groups_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Leaves a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.leave", json=kwargs)
+
+    def groups_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists private channels that the calling user has access to."""
+        return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+    def groups_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a private channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.mark", json=kwargs)
+
+    def groups_open(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.open", json=kwargs)
+
+    def groups_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Renames a private channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.rename", json=kwargs)
+
+    def groups_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a private channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+    def groups_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the purpose for a private channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setPurpose", json=kwargs)
+
+    def groups_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the topic for a private channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setTopic", json=kwargs)
+
+    def groups_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Unarchives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.unarchive", json=kwargs)
+
+    # --------------------------
+    # Deprecated: im.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def im_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Close a direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.close", json=kwargs)
+
+    def im_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from direct message channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+    def im_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists direct message channels for the calling user."""
+        return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+    def im_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.mark", json=kwargs)
+
+    def im_open(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Opens a direct message channel."""
+        kwargs.update({"user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.open", json=kwargs)
+
+    def im_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def migration_exchange(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        to_old: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """For Enterprise Grid workspaces, map local user IDs to global user IDs
+        https://docs.slack.dev/reference/methods/migration.exchange
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id, "to_old": to_old})
+        return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+    # --------------------------
+    # Deprecated: mpim.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def mpim_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Closes a multiparty direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.close", json=kwargs)
+
+    def mpim_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Fetches history of messages and events from a multiparty direct message."""
+        kwargs.update({"channel": channel})
+        return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+    def mpim_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists multiparty direct message channels for the calling user."""
+        return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+    def mpim_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Sets the read cursor in a multiparty direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.mark", json=kwargs)
+
+    def mpim_open(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """This method opens a multiparty direct message."""
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("mpim.open", params=kwargs)
+
+    def mpim_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a thread of messages posted to a direct message conversation from a
+        multiparty direct message.
+        """
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def oauth_v2_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        # This field is required when processing the OAuth redirect URL requests
+        # while it's absent for token rotation
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        # This field is required for token rotation
+        grant_type: Optional[str] = None,
+        # This field is required for token rotation
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.v2.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "oauth.v2.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        code: str,
+        redirect_uri: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        kwargs.update({"code": code})
+        return self.api_call(
+            "oauth.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_v2_exchange(
+        self,
+        *,
+        token: str,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a legacy access token for a new expiring access token and refresh token
+        https://docs.slack.dev/reference/methods/oauth.v2.exchange
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+        return self.api_call("oauth.v2.exchange", params=kwargs)
+
+    def openid_connect_token(
+        self,
+        client_id: str,
+        client_secret: str,
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        grant_type: Optional[str] = None,
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.token
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "openid.connect.token",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def openid_connect_userInfo(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get the identity of a user who has authorized Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.userInfo
+        """
+        return self.api_call("openid.connect.userInfo", params=kwargs)
+
+    def pins_add(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Pins an item to a channel.
+        https://docs.slack.dev/reference/methods/pins.add
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.add", params=kwargs)
+
+    def pins_list(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists items pinned to a channel.
+        https://docs.slack.dev/reference/methods/pins.list
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+    def pins_remove(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Un-pins an item from a channel.
+        https://docs.slack.dev/reference/methods/pins.remove
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.remove", params=kwargs)
+
+    def reactions_add(
+        self,
+        *,
+        channel: str,
+        name: str,
+        timestamp: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a reaction to an item.
+        https://docs.slack.dev/reference/methods/reactions.add
+        """
+        kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+        return self.api_call("reactions.add", params=kwargs)
+
+    def reactions_get(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        full: Optional[bool] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets reactions for an item.
+        https://docs.slack.dev/reference/methods/reactions.get
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "full": full,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+    def reactions_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        full: Optional[bool] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists reactions made by a user.
+        https://docs.slack.dev/reference/methods/reactions.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "full": full,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+    def reactions_remove(
+        self,
+        *,
+        name: str,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a reaction from an item.
+        https://docs.slack.dev/reference/methods/reactions.remove
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.remove", params=kwargs)
+
+    def reminders_add(
+        self,
+        *,
+        text: str,
+        time: str,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        recurrence: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a reminder.
+        https://docs.slack.dev/reference/methods/reminders.add
+        """
+        kwargs.update(
+            {
+                "text": text,
+                "time": time,
+                "team_id": team_id,
+                "user": user,
+                "recurrence": recurrence,
+            }
+        )
+        return self.api_call("reminders.add", params=kwargs)
+
+    def reminders_complete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Marks a reminder as complete.
+        https://docs.slack.dev/reference/methods/reminders.complete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.complete", params=kwargs)
+
+    def reminders_delete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes a reminder.
+        https://docs.slack.dev/reference/methods/reminders.delete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.delete", params=kwargs)
+
+    def reminders_info(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a reminder.
+        https://docs.slack.dev/reference/methods/reminders.info
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+    def reminders_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all reminders created by or for a given user.
+        https://docs.slack.dev/reference/methods/reminders.list
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+    def rtm_connect(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.connect
+        """
+        kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+        return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+    def rtm_start(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        include_locale: Optional[bool] = None,
+        mpim_aware: Optional[bool] = None,
+        no_latest: Optional[bool] = None,
+        no_unreads: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        simple_latest: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.start
+        """
+        kwargs.update(
+            {
+                "batch_presence_aware": batch_presence_aware,
+                "include_locale": include_locale,
+                "mpim_aware": mpim_aware,
+                "no_latest": no_latest,
+                "no_unreads": no_unreads,
+                "presence_sub": presence_sub,
+                "simple_latest": simple_latest,
+            }
+        )
+        return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+    def search_all(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages and files matching a query.
+        https://docs.slack.dev/reference/methods/search.all
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+    def search_files(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for files matching a query.
+        https://docs.slack.dev/reference/methods/search.files
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+    def search_messages(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Searches for messages matching a query.
+        https://docs.slack.dev/reference/methods/search.messages
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "cursor": cursor,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+    def slackLists_access_delete(
+        self,
+        *,
+        list_id: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Revoke access to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.delete
+        """
+        kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.delete", json=kwargs)
+
+    def slackLists_access_set(
+        self,
+        *,
+        list_id: str,
+        access_level: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the access level to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.set
+        """
+        kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.set", json=kwargs)
+
+    def slackLists_create(
+        self,
+        *,
+        name: str,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        schema: Optional[List[Dict[str, Any]]] = None,
+        copy_from_list_id: Optional[str] = None,
+        include_copied_list_records: Optional[bool] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Creates a List.
+        https://docs.slack.dev/reference/methods/slackLists.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description_blocks": description_blocks,
+                "schema": schema,
+                "copy_from_list_id": copy_from_list_id,
+                "include_copied_list_records": include_copied_list_records,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.create", json=kwargs)
+
+    def slackLists_download_get(
+        self,
+        *,
+        list_id: str,
+        job_id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve List download URL from an export job to download List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.get
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "job_id": job_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.get", json=kwargs)
+
+    def slackLists_download_start(
+        self,
+        *,
+        list_id: str,
+        include_archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Initiate a job to export List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.start
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "include_archived": include_archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.start", json=kwargs)
+
+    def slackLists_items_create(
+        self,
+        *,
+        list_id: str,
+        duplicated_item_id: Optional[str] = None,
+        parent_item_id: Optional[str] = None,
+        initial_fields: Optional[List[Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Add a new item to an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.create
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "duplicated_item_id": duplicated_item_id,
+                "parent_item_id": parent_item_id,
+                "initial_fields": initial_fields,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.create", json=kwargs)
+
+    def slackLists_items_delete(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes an item from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.delete
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.delete", json=kwargs)
+
+    def slackLists_items_deleteMultiple(
+        self,
+        *,
+        list_id: str,
+        ids: List[str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Deletes multiple items from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "ids": ids,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+    def slackLists_items_info(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        include_is_subscribed: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a row from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.info
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+                "include_is_subscribed": include_is_subscribed,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.info", json=kwargs)
+
+    def slackLists_items_list(
+        self,
+        *,
+        list_id: str,
+        limit: Optional[int] = None,
+        cursor: Optional[str] = None,
+        archived: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get records from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.list
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "limit": limit,
+                "cursor": cursor,
+                "archived": archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.list", json=kwargs)
+
+    def slackLists_items_update(
+        self,
+        *,
+        list_id: str,
+        cells: List[Dict[str, Any]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Updates cells in a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.update
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "cells": cells,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.update", json=kwargs)
+
+    def slackLists_update(
+        self,
+        *,
+        id: str,
+        name: Optional[str] = None,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update a List.
+        https://docs.slack.dev/reference/methods/slackLists.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "name": name,
+                "description_blocks": description_blocks,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.update", json=kwargs)
+
+    def stars_add(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Adds a star to an item.
+        https://docs.slack.dev/reference/methods/stars.add
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.add", params=kwargs)
+
+    def stars_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists stars for a user.
+        https://docs.slack.dev/reference/methods/stars.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+    def stars_remove(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Removes a star from an item.
+        https://docs.slack.dev/reference/methods/stars.remove
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.remove", params=kwargs)
+
+    def team_accessLogs(
+        self,
+        *,
+        before: Optional[Union[int, str]] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the access logs for the current team.
+        https://docs.slack.dev/reference/methods/team.accessLogs
+        """
+        kwargs.update(
+            {
+                "before": before,
+                "count": count,
+                "page": page,
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+    def team_billableInfo(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets billable users information for the current team.
+        https://docs.slack.dev/reference/methods/team.billableInfo
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+    def team_billing_info(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Reads a workspace's billing plan information.
+        https://docs.slack.dev/reference/methods/team.billing.info
+        """
+        return self.api_call("team.billing.info", params=kwargs)
+
+    def team_externalTeams_disconnect(
+        self,
+        *,
+        target_team: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disconnects an external organization.
+        https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+        """
+        kwargs.update(
+            {
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+    def team_externalTeams_list(
+        self,
+        *,
+        connection_status_filter: Optional[str] = None,
+        slack_connect_pref_filter: Optional[Sequence[str]] = None,
+        sort_direction: Optional[str] = None,
+        sort_field: Optional[str] = None,
+        workspace_filter: Optional[Sequence[str]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Returns a list of all the external teams connected and details about the connection.
+        https://docs.slack.dev/reference/methods/team.externalTeams.list
+        """
+        kwargs.update(
+            {
+                "connection_status_filter": connection_status_filter,
+                "sort_direction": sort_direction,
+                "sort_field": sort_field,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if slack_connect_pref_filter is not None:
+            if isinstance(slack_connect_pref_filter, (list, tuple)):
+                kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+            else:
+                kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+        if workspace_filter is not None:
+            if isinstance(workspace_filter, (list, tuple)):
+                kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+            else:
+                kwargs.update({"workspace_filter": workspace_filter})
+        return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+    def team_info(
+        self,
+        *,
+        team: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about the current team.
+        https://docs.slack.dev/reference/methods/team.info
+        """
+        kwargs.update({"team": team, "domain": domain})
+        return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+    def team_integrationLogs(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        change_type: Optional[str] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        service_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets the integration logs for the current team.
+        https://docs.slack.dev/reference/methods/team.integrationLogs
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "change_type": change_type,
+                "count": count,
+                "page": page,
+                "service_id": service_id,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+    def team_profile_get(
+        self,
+        *,
+        visibility: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a team's profile.
+        https://docs.slack.dev/reference/methods/team.profile.get
+        """
+        kwargs.update({"visibility": visibility})
+        return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+    def team_preferences_list(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieve a list of a workspace's team preferences.
+        https://docs.slack.dev/reference/methods/team.preferences.list
+        """
+        return self.api_call("team.preferences.list", params=kwargs)
+
+    def usergroups_create(
+        self,
+        *,
+        name: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Create a User Group
+        https://docs.slack.dev/reference/methods/usergroups.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.create", params=kwargs)
+
+    def usergroups_disable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Disable an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.disable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.disable", params=kwargs)
+
+    def usergroups_enable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Enable a User Group
+        https://docs.slack.dev/reference/methods/usergroups.enable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.enable", params=kwargs)
+
+    def usergroups_list(
+        self,
+        *,
+        include_count: Optional[bool] = None,
+        include_disabled: Optional[bool] = None,
+        include_users: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all User Groups for a team
+        https://docs.slack.dev/reference/methods/usergroups.list
+        """
+        kwargs.update(
+            {
+                "include_count": include_count,
+                "include_disabled": include_disabled,
+                "include_users": include_users,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+    def usergroups_update(
+        self,
+        *,
+        usergroup: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "name": name,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.update", params=kwargs)
+
+    def usergroups_users_list(
+        self,
+        *,
+        usergroup: str,
+        include_disabled: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List all users in a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.list
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_disabled": include_disabled,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+    def usergroups_users_update(
+        self,
+        *,
+        usergroup: str,
+        users: Union[str, Sequence[str]],
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the list of users for a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("usergroups.users.update", params=kwargs)
+
+    def users_conversations(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """List conversations the calling user may access.
+        https://docs.slack.dev/reference/methods/users.conversations
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+    def users_deletePhoto(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Delete the user profile photo
+        https://docs.slack.dev/reference/methods/users.deletePhoto
+        """
+        return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+    def users_getPresence(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets user presence information.
+        https://docs.slack.dev/reference/methods/users.getPresence
+        """
+        kwargs.update({"user": user})
+        return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+    def users_identity(
+        self,
+        **kwargs,
+    ) -> SlackResponse:
+        """Get a user's identity.
+        https://docs.slack.dev/reference/methods/users.identity
+        """
+        return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+    def users_info(
+        self,
+        *,
+        user: str,
+        include_locale: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Gets information about a user.
+        https://docs.slack.dev/reference/methods/users.info
+        """
+        kwargs.update({"user": user, "include_locale": include_locale})
+        return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+    def users_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_locale: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lists all users in a Slack team.
+        https://docs.slack.dev/reference/methods/users.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_locale": include_locale,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+    def users_lookupByEmail(
+        self,
+        *,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Find a user with an email address.
+        https://docs.slack.dev/reference/methods/users.lookupByEmail
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+    def users_setPhoto(
+        self,
+        *,
+        image: Union[str, IOBase],
+        crop_w: Optional[Union[int, str]] = None,
+        crop_x: Optional[Union[int, str]] = None,
+        crop_y: Optional[Union[int, str]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the user profile photo
+        https://docs.slack.dev/reference/methods/users.setPhoto
+        """
+        kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+        return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+    def users_setPresence(
+        self,
+        *,
+        presence: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Manually sets user presence.
+        https://docs.slack.dev/reference/methods/users.setPresence
+        """
+        kwargs.update({"presence": presence})
+        return self.api_call("users.setPresence", params=kwargs)
+
+    def users_discoverableContacts_lookup(
+        self,
+        email: str,
+        **kwargs,
+    ) -> SlackResponse:
+        """Lookup an email address to see if someone is on Slack
+        https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+    def users_profile_get(
+        self,
+        *,
+        user: Optional[str] = None,
+        include_labels: Optional[bool] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Retrieves a user's profile information.
+        https://docs.slack.dev/reference/methods/users.profile.get
+        """
+        kwargs.update({"user": user, "include_labels": include_labels})
+        return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+    def users_profile_set(
+        self,
+        *,
+        name: Optional[str] = None,
+        value: Optional[str] = None,
+        user: Optional[str] = None,
+        profile: Optional[Dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Set the profile information for a user.
+        https://docs.slack.dev/reference/methods/users.profile.set
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "profile": profile,
+                "user": user,
+                "value": value,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "profile" parameter
+        return self.api_call("users.profile.set", json=kwargs)
+
+    def views_open(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Open a view for a user.
+        https://docs.slack.dev/reference/methods/views.open
+        See https://docs.slack.dev/surfaces/modals/ for details.
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.open", json=kwargs)
+
+    def views_push(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> SlackResponse:
+        """Push a view onto the stack of a root view.
+        Push a new view onto the existing view stack by passing a view
+        payload and a valid trigger_id generated from an interaction
+        within the existing modal.
+        Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+        to learn more about the lifecycle and intricacies of views.
+        https://docs.slack.dev/reference/methods/views.push
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.push", json=kwargs)
+
+    def views_update(
+        self,
+        *,
+        view: Union[dict, View],
+        external_id: Optional[str] = None,
+        view_id: Optional[str] = None,
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update an existing view.
+        Update a view by passing a new view definition along with the
+        view_id returned in views.open or the external_id.
+        See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+        to learn more about updating views and avoiding race conditions with the hash argument.
+        https://docs.slack.dev/reference/methods/views.update
+        """
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        if external_id:
+            kwargs.update({"external_id": external_id})
+        elif view_id:
+            kwargs.update({"view_id": view_id})
+        else:
+            raise e.SlackRequestError("Either view_id or external_id is required.")
+        kwargs.update({"hash": hash})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.update", json=kwargs)
+
+    def views_publish(
+        self,
+        *,
+        user_id: str,
+        view: Union[dict, View],
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Publish a static view for a User.
+        Create or update the view that comprises an
+        app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+        https://docs.slack.dev/reference/methods/views.publish
+        """
+        kwargs.update({"user_id": user_id, "hash": hash})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.publish", json=kwargs)
+
+    def workflows_featured_add(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Add featured workflows to a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.add
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.add", params=kwargs)
+
+    def workflows_featured_list(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """List the featured workflows for specified channels.
+        https://docs.slack.dev/reference/methods/workflows.featured.list
+        """
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("workflows.featured.list", params=kwargs)
+
+    def workflows_featured_remove(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Remove featured workflows from a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.remove
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.remove", params=kwargs)
+
+    def workflows_featured_set(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> SlackResponse:
+        """Set featured workflows for a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.set
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.set", params=kwargs)
+
+    def workflows_stepCompleted(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        outputs: Optional[dict] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate a successful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepCompleted
+        """
+        kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "outputs" parameter
+        return self.api_call("workflows.stepCompleted", json=kwargs)
+
+    def workflows_stepFailed(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        error: Dict[str, str],
+        **kwargs,
+    ) -> SlackResponse:
+        """Indicate an unsuccessful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepFailed
+        """
+        kwargs.update(
+            {
+                "workflow_step_execute_id": workflow_step_execute_id,
+                "error": error,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "error" parameter
+        return self.api_call("workflows.stepFailed", json=kwargs)
+
+    def workflows_updateStep(
+        self,
+        *,
+        workflow_step_edit_id: str,
+        inputs: Optional[Dict[str, Any]] = None,
+        outputs: Optional[List[Dict[str, str]]] = None,
+        **kwargs,
+    ) -> SlackResponse:
+        """Update the configuration for a workflow extension step.
+        https://docs.slack.dev/reference/methods/workflows.updateStep
+        """
+        kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+        if inputs is not None:
+            kwargs.update({"inputs": inputs})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+        return self.api_call("workflows.updateStep", json=kwargs)
+
+

A WebClient allows apps to communicate with the Slack Platform's Web API.

+

https://docs.slack.dev/reference/methods

+

The Slack Web API is an interface for querying information from +and enacting change in a Slack workspace.

+

This client handles constructing and sending HTTP requests to Slack +as well as parsing any responses received into a SlackResponse.

+

Attributes

+
+
token : str
+
A string specifying an xoxp-* or xoxb-* token.
+
base_url : str
+
A string representing the Slack API base URL. +Default is 'https://slack.com/api/'
+
timeout : int
+
The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.
+
ssl : SSLContext
+
An ssl.SSLContext instance, helpful for specifying +your own custom certificate chain.
+
proxy : str
+
String representing a fully-qualified URL to a proxy through +which to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.
+
headers : dict
+
Additional request headers to attach to all requests.
+
+

Methods

+

api_call: Constructs a request and executes the API call to Slack.

+

Example of recommended usage:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.chat_postMessage(
+        channel='#random',
+        text="Hello world!")
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Example manually creating an API request:

+
    import os
+    from slack_sdk import WebClient
+
+    client = WebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.api_call(
+        api_method='chat.postMessage',
+        json={'channel': '#random','text': "Hello world!"}
+    )
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Note

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Ancestors

+ +

Methods

+
+
+def admin_analytics_getFile(self,
*,
type:Β str,
date:Β strΒ |Β NoneΒ =Β None,
metadata_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_analytics_getFile(
+    self,
+    *,
+    type: str,
+    date: Optional[str] = None,
+    metadata_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve analytics data for a given date, presented as a compressed JSON file
+    https://docs.slack.dev/reference/methods/admin.analytics.getFile
+    """
+    kwargs.update({"type": type})
+    if date is not None:
+        kwargs.update({"date": date})
+    if metadata_only is not None:
+        kwargs.update({"metadata_only": metadata_only})
+    return self.api_call("admin.analytics.getFile", params=kwargs)
+
+

Retrieve analytics data for a given date, presented as a compressed JSON file +https://docs.slack.dev/reference/methods/admin.analytics.getFile

+
+
+def admin_apps_activities_list(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
component_id:Β strΒ |Β NoneΒ =Β None,
component_type:Β strΒ |Β NoneΒ =Β None,
log_event_type:Β strΒ |Β NoneΒ =Β None,
max_date_created:Β intΒ |Β NoneΒ =Β None,
min_date_created:Β intΒ |Β NoneΒ =Β None,
min_log_level:Β strΒ |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
trace_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_activities_list(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    component_id: Optional[str] = None,
+    component_type: Optional[str] = None,
+    log_event_type: Optional[str] = None,
+    max_date_created: Optional[int] = None,
+    min_date_created: Optional[int] = None,
+    min_log_level: Optional[str] = None,
+    sort_direction: Optional[str] = None,
+    source: Optional[str] = None,
+    team_id: Optional[str] = None,
+    trace_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get logs for a specified team/org
+    https://docs.slack.dev/reference/methods/admin.apps.activities.list
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "component_id": component_id,
+            "component_type": component_type,
+            "log_event_type": log_event_type,
+            "max_date_created": max_date_created,
+            "min_date_created": min_date_created,
+            "min_log_level": min_log_level,
+            "sort_direction": sort_direction,
+            "source": source,
+            "team_id": team_id,
+            "trace_id": trace_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.apps.activities.list", params=kwargs)
+
+ +
+
+def admin_apps_approve(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approve(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve an app for installation on a workspace.
+    Either app_id or request_id is required.
+    These IDs can be obtained either directly via the app_requested event,
+    or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.approve
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approve", params=kwargs)
+
+

Approve an app for installation on a workspace. +Either app_id or request_id is required. +These IDs can be obtained either directly via the app_requested event, +or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.approve

+
+
+def admin_apps_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List approved apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+

List approved apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.approved.list

+
+
+def admin_apps_clearResolution(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_clearResolution(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Clear an app resolution
+    https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_config_lookup(self, *, app_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_apps_config_lookup(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Look up the app config for connectors by their IDs
+    https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+

Look up the app config for connectors by their IDs +https://docs.slack.dev/reference/methods/admin.apps.config.lookup

+
+
+def admin_apps_config_set(self,
*,
app_id:Β str,
domain_restrictions:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_auth_strategy:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_config_set(
+    self,
+    *,
+    app_id: str,
+    domain_restrictions: Optional[Dict[str, Any]] = None,
+    workflow_auth_strategy: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the app config for a connector
+    https://docs.slack.dev/reference/methods/admin.apps.config.set
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "workflow_auth_strategy": workflow_auth_strategy,
+        }
+    )
+    if domain_restrictions is not None:
+        kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+    return self.api_call("admin.apps.config.set", params=kwargs)
+
+ +
+
+def admin_apps_requests_cancel(self,
*,
request_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_cancel(
+    self,
+    *,
+    request_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+    """
+    kwargs.update(
+        {
+            "request_id": request_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_requests_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_apps_restrict(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restrict(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Restrict an app for installation on a workspace.
+    Exactly one of the team_id or enterprise_id arguments is required, not both.
+    Either app_id or request_id is required. These IDs can be obtained either directly
+    via the app_requested event, or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.restrict
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restrict", params=kwargs)
+
+

Restrict an app for installation on a workspace. +Exactly one of the team_id or enterprise_id arguments is required, not both. +Either app_id or request_id is required. These IDs can be obtained either directly +via the app_requested event, or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.restrict

+
+
+def admin_apps_restricted_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restricted_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List restricted apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+

List restricted apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.restricted.list

+
+
+def admin_apps_uninstall(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_uninstall(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+    With an org-level token, enterprise_id or team_ids is required.
+    https://docs.slack.dev/reference/methods/admin.apps.uninstall
+    """
+    kwargs.update({"app_id": app_id})
+    if enterprise_id is not None:
+        kwargs.update({"enterprise_id": enterprise_id})
+    if team_ids is not None:
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+

Uninstall an app from one or many workspaces, or an entire enterprise organization. +With an org-level token, enterprise_id or team_ids is required. +https://docs.slack.dev/reference/methods/admin.apps.uninstall

+
+
+def admin_auth_policy_assignEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_assignEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Assign entities to a particular authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+

Assign entities to a particular authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities

+
+
+def admin_auth_policy_getEntities(self,
*,
policy_name:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_getEntities(
+    self,
+    *,
+    policy_name: str,
+    cursor: Optional[str] = None,
+    entity_type: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch all the entities assigned to a particular authentication policy by name.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+    """
+    kwargs.update({"policy_name": policy_name})
+    if cursor is not None:
+        kwargs.update({"cursor": cursor})
+    if entity_type is not None:
+        kwargs.update({"entity_type": entity_type})
+    if limit is not None:
+        kwargs.update({"limit": limit})
+    return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+

Fetch all the entities assigned to a particular authentication policy by name. +https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities

+
+
+def admin_auth_policy_removeEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_removeEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove specified entities from a specified authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+

Remove specified entities from a specified authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities

+
+
+def admin_barriers_create(self,
*,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_create(
+    self,
+    *,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.create
+    """
+    kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_delete(self, *, barrier_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_delete(
+    self,
+    *,
+    barrier_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.delete
+    """
+    kwargs.update({"barrier_id": barrier_id})
+    return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get all Information Barriers for your organization
+    https://docs.slack.dev/reference/methods/admin.barriers.list"""
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+

Get all Information Barriers for your organization +https://docs.slack.dev/reference/methods/admin.barriers.list

+
+
+def admin_barriers_update(self,
*,
barrier_id:Β str,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_update(
+    self,
+    *,
+    barrier_id: str,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.update
+    """
+    kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_conversations_archive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_archive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.archive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkArchive(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkArchive(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Archive public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkDelete(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkDelete(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> SlackResponse:
+    """Delete public or private channels in bulk.
+    https://slack.com/api/admin.conversations.bulkDelete
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+

Delete public or private channels in bulk. +https://slack.com/api/admin.conversations.bulkDelete

+
+
+def admin_conversations_bulkMove(self, *, channel_ids:Β strΒ |Β Sequence[str], target_team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkMove(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    target_team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Move public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+    """
+    kwargs.update(
+        {
+            "target_team_id": target_team_id,
+            "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+        }
+    )
+    return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPrivate(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPrivate(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a public channel to a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPublic(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPublic(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Convert a privte channel to a public channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+ +
+
+def admin_conversations_create(self,
*,
is_private:Β bool,
name:Β str,
description:Β strΒ |Β NoneΒ =Β None,
org_wide:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_create(
+    self,
+    *,
+    is_private: bool,
+    name: str,
+    description: Optional[str] = None,
+    org_wide: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a public or private channel-based conversation.
+    https://docs.slack.dev/reference/methods/admin.conversations.create
+    """
+    kwargs.update(
+        {
+            "is_private": is_private,
+            "name": name,
+            "description": description,
+            "org_wide": org_wide,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.conversations.create", params=kwargs)
+
+

Create a public or private channel-based conversation. +https://docs.slack.dev/reference/methods/admin.conversations.create

+
+
+def admin_conversations_createForObjects(self,
*,
object_id:Β str,
salesforce_org_id:Β str,
invite_object_team:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_createForObjects(
+    self,
+    *,
+    object_id: str,
+    salesforce_org_id: str,
+    invite_object_team: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Salesforce channel for the corresponding object provided.
+    https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+    """
+    kwargs.update(
+        {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+    )
+    return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+

Create a Salesforce channel for the corresponding object provided. +https://docs.slack.dev/reference/methods/admin.conversations.createForObjects

+
+
+def admin_conversations_delete(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_delete(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Delete a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.delete
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.delete", params=kwargs)
+
+ +
+
+def admin_conversations_disconnectShared(self,
*,
channel_id:Β str,
leaving_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_disconnectShared(
+    self,
+    *,
+    channel_id: str,
+    leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnect a connected channel from one or more workspaces.
+    https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(leaving_team_ids, (list, tuple)):
+        kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+    else:
+        kwargs.update({"leaving_team_ids": leaving_team_ids})
+    return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+

Disconnect a connected channel from one or more workspaces. +https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared

+
+
+def admin_conversations_ekm_listOriginalConnectedChannelInfo(self,
*,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+    self,
+    *,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all disconnected channelsβ€”i.e.,
+    channels that were once connected to other workspaces and then disconnectedβ€”and
+    the corresponding original channel IDs for key revocation with EKM.
+    https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+

List all disconnected channelsβ€”i.e., +channels that were once connected to other workspaces and then disconnectedβ€”and +the corresponding original channel IDs for key revocation with EKM. +https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo

+
+
+def admin_conversations_getConversationPrefs(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get conversation preferences for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+

Get conversation preferences for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs

+
+
+def admin_conversations_getCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Get a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_getTeams(self,
*,
channel_id:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_getTeams(
+    self,
+    *,
+    channel_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a channel. +https://docs.slack.dev/reference/methods/admin.conversations.getTeams

+
+
+def admin_conversations_invite(self, *, channel_id:Β str, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_invite(
+    self,
+    *,
+    channel_id: str,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.invite
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+    return self.api_call("admin.conversations.invite", params=kwargs)
+
+

Invite a user to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.invite

+
+
+def admin_conversations_linkObjects(self, *, channel:Β str, record_id:Β str, salesforce_org_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_linkObjects(
+    self,
+    *,
+    channel: str,
+    record_id: str,
+    salesforce_org_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Link a Salesforce record to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "record_id": record_id,
+            "salesforce_org_id": salesforce_org_id,
+        }
+    )
+    return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+ +
+
+def admin_conversations_lookup(self,
*,
last_message_activity_before:Β int,
team_ids:Β strΒ |Β Sequence[str],
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
max_member_count:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_lookup(
+    self,
+    *,
+    last_message_activity_before: int,
+    team_ids: Union[str, Sequence[str]],
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    max_member_count: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns channels on the given team using the filters.
+    https://docs.slack.dev/reference/methods/admin.conversations.lookup
+    """
+    kwargs.update(
+        {
+            "last_message_activity_before": last_message_activity_before,
+            "cursor": cursor,
+            "limit": limit,
+            "max_member_count": max_member_count,
+        }
+    )
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.lookup", params=kwargs)
+
+

Returns channels on the given team using the filters. +https://docs.slack.dev/reference/methods/admin.conversations.lookup

+
+
+def admin_conversations_removeCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_removeCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_rename(self, *, channel_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_rename(
+    self,
+    *,
+    channel_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.rename
+    """
+    kwargs.update({"channel_id": channel_id, "name": name})
+    return self.api_call("admin.conversations.rename", params=kwargs)
+
+ +
+
+def admin_conversations_restrictAccess_addGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_addGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an allowlist of IDP groups for accessing a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.addGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Add an allowlist of IDP groups for accessing a channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup

+
+
+def admin_conversations_restrictAccess_listGroups(self, *, channel_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_listGroups(
+    self,
+    *,
+    channel_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all IDP Groups linked to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.listGroups",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+ +
+
+def admin_conversations_restrictAccess_removeGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_removeGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a linked IDP group linked from a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.removeGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Remove a linked IDP group linked from a private channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup

+
+ +
+
+ +Expand source code + +
def admin_conversations_search(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    query: Optional[str] = None,
+    search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search for public or private channels in an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.conversations.search
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+        }
+    )
+
+    if isinstance(search_channel_types, (list, tuple)):
+        kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+    else:
+        kwargs.update({"search_channel_types": search_channel_types})
+
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+
+    return self.api_call("admin.conversations.search", params=kwargs)
+
+

Search for public or private channels in an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.conversations.search

+
+
+def admin_conversations_setConversationPrefs(self, *, channel_id:Β str, prefs:Β strΒ |Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    prefs: Union[str, Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the posting permissions for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(prefs, dict):
+        kwargs.update({"prefs": json.dumps(prefs)})
+    else:
+        kwargs.update({"prefs": prefs})
+    return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+

Set the posting permissions for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs

+
+
+def admin_conversations_setCustomRetention(self, *, channel_id:Β str, duration_days:Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    duration_days: int,
+    **kwargs,
+) -> SlackResponse:
+    """Set a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+    return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_setTeams(self,
*,
channel_id:Β str,
org_channel:Β boolΒ |Β NoneΒ =Β None,
target_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_setTeams(
+    self,
+    *,
+    channel_id: str,
+    org_channel: Optional[bool] = None,
+    target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "org_channel": org_channel,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(target_team_ids, (list, tuple)):
+        kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+    else:
+        kwargs.update({"target_team_ids": target_team_ids})
+    return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setTeams

+
+
+def admin_conversations_unarchive(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unarchive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+ +
+
+def admin_conversations_unlinkObjects(self, *, channel:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unlinkObjects(
+    self,
+    *,
+    channel: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unlink a Salesforce record from a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "new_name": new_name,
+        }
+    )
+    return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+ +
+
+def admin_emoji_add(self, *, name:Β str, url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_add(
+    self,
+    *,
+    name: str,
+    url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.add
+    """
+    kwargs.update({"name": name, "url": url})
+    return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_addAlias(self, *, alias_for:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_addAlias(
+    self,
+    *,
+    alias_for: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Add an emoji alias.
+    https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+    """
+    kwargs.update({"alias_for": alias_for, "name": name})
+    return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List emoji for an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+

List emoji for an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.list

+
+
+def admin_emoji_remove(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_remove(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove an emoji across an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.remove
+    """
+    kwargs.update({"name": name})
+    return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+

Remove an emoji across an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.remove

+
+
+def admin_emoji_rename(self, *, name:Β str, new_name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_rename(
+    self,
+    *,
+    name: str,
+    new_name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Rename an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.rename
+    """
+    kwargs.update({"name": name, "new_name": new_name})
+    return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_functions_list(self,
*,
app_ids:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_list(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up functions by a set of apps
+    https://docs.slack.dev/reference/methods/admin.functions.list
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.functions.list", params=kwargs)
+
+ +
+
+def admin_functions_permissions_lookup(self, *, function_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_functions_permissions_lookup(
+    self,
+    *,
+    function_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Lookup the visibility of multiple Slack functions
+    and include the users if it is limited to particular named entities.
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+    """
+    if isinstance(function_ids, (list, tuple)):
+        kwargs.update({"function_ids": ",".join(function_ids)})
+    else:
+        kwargs.update({"function_ids": function_ids})
+    return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+

Lookup the visibility of multiple Slack functions +and include the users if it is limited to particular named entities. +https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup

+
+
+def admin_functions_permissions_set(self,
*,
function_id:Β str,
visibility:Β str,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_permissions_set(
+    self,
+    *,
+    function_id: str,
+    visibility: str,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the visibility of a Slack function
+    and define the users or workspaces if it is set to named_entities
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+    """
+    kwargs.update(
+        {
+            "function_id": function_id,
+            "visibility": visibility,
+        }
+    )
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+

Set the visibility of a Slack function +and define the users or workspaces if it is set to named_entities +https://docs.slack.dev/reference/methods/admin.functions.permissions.set

+
+
+def admin_inviteRequests_approve(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_approve(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+ +
+
+def admin_inviteRequests_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all approved workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_denied_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_denied_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all denied workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_deny(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_deny(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+ +
+
+def admin_inviteRequests_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """List all pending workspace invite requests."""
+    return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+

List all pending workspace invite requests.

+
+
+def admin_roles_addAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_addAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Adds members to the specified role with the specified scopes
+    https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+

Adds members to the specified role with the specified scopes +https://docs.slack.dev/reference/methods/admin.roles.addAssignments

+
+
+def admin_roles_listAssignments(self,
*,
role_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
entity_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β strΒ |Β intΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_listAssignments(
+    self,
+    *,
+    role_ids: Optional[Union[str, Sequence[str]]] = None,
+    entity_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[Union[str, int]] = None,
+    sort_dir: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists assignments for all roles across entities.
+        Options to scope results by any combination of roles or entities
+    https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(role_ids, (list, tuple)):
+        kwargs.update({"role_ids": ",".join(role_ids)})
+    else:
+        kwargs.update({"role_ids": role_ids})
+    return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+

Lists assignments for all roles across entities. +Options to scope results by any combination of roles or entities +https://docs.slack.dev/reference/methods/admin.roles.listAssignments

+
+
+def admin_roles_removeAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_removeAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Removes a set of users from a role for the given scopes and entities
+    https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+

Removes a set of users from a role for the given scopes and entities +https://docs.slack.dev/reference/methods/admin.roles.removeAssignments

+
+
+def admin_teams_admins_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_admins_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.inviteRequests.list

+
+
+def admin_teams_create(self,
*,
team_domain:Β str,
team_name:Β str,
team_description:Β strΒ |Β NoneΒ =Β None,
team_discoverability:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_teams_create(
+    self,
+    *,
+    team_domain: str,
+    team_name: str,
+    team_description: Optional[str] = None,
+    team_discoverability: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create an Enterprise team.
+    https://docs.slack.dev/reference/methods/admin.teams.create
+    """
+    kwargs.update(
+        {
+            "team_domain": team_domain,
+            "team_name": team_name,
+            "team_description": team_description,
+            "team_discoverability": team_discoverability,
+        }
+    )
+    return self.api_call("admin.teams.create", params=kwargs)
+
+ +
+
+def admin_teams_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all teams on an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.list", params=kwargs)
+
+

List all teams on an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.teams.list

+
+
+def admin_teams_owners_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_owners_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.owners.list
+    """
+    kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.teams.owners.list

+
+
+def admin_teams_settings_info(self, *, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_info(
+    self,
+    *,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetch information about settings in a workspace
+    https://docs.slack.dev/reference/methods/admin.teams.settings.info
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("admin.teams.settings.info", params=kwargs)
+
+

Fetch information about settings in a workspace +https://docs.slack.dev/reference/methods/admin.teams.settings.info

+
+
+def admin_teams_settings_setDefaultChannels(self, *, team_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDefaultChannels(
+    self,
+    *,
+    team_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set the default channels of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+    """
+    kwargs.update({"team_id": team_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDescription(self, *, team_id:Β str, description:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDescription(
+    self,
+    *,
+    team_id: str,
+    description: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the description of a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+    """
+    kwargs.update({"team_id": team_id, "description": description})
+    return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDiscoverability(self, *, team_id:Β str, discoverability:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDiscoverability(
+    self,
+    *,
+    team_id: str,
+    discoverability: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+    """
+    kwargs.update({"team_id": team_id, "discoverability": discoverability})
+    return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+ +
+
+def admin_teams_settings_setIcon(self, *, team_id:Β str, image_url:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setIcon(
+    self,
+    *,
+    team_id: str,
+    image_url: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+    """
+    kwargs.update({"team_id": team_id, "image_url": image_url})
+    return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setName(self, *, team_id:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setName(
+    self,
+    *,
+    team_id: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+    """
+    kwargs.update({"team_id": team_id, "name": name})
+    return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+ +
+
+def admin_usergroups_addChannels(self,
*,
channel_ids:Β strΒ |Β Sequence[str],
usergroup_id:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addChannels(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    usergroup_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+    """
+    kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addChannels

+
+
+def admin_usergroups_addTeams(self,
*,
usergroup_id:Β str,
team_ids:Β strΒ |Β Sequence[str],
auto_provision:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addTeams(
+    self,
+    *,
+    usergroup_id: str,
+    team_ids: Union[str, Sequence[str]],
+    auto_provision: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Associate one or more default workspaces with an organization-wide IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+    """
+    kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+

Associate one or more default workspaces with an organization-wide IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addTeams

+
+
+def admin_usergroups_listChannels(self,
*,
usergroup_id:Β str,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
team_id:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_listChannels(
+    self,
+    *,
+    usergroup_id: str,
+    include_num_members: Optional[bool] = None,
+    team_id: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+    """
+    kwargs.update(
+        {
+            "usergroup_id": usergroup_id,
+            "include_num_members": include_num_members,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.listChannels

+
+
+def admin_usergroups_removeChannels(self, *, usergroup_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_usergroups_removeChannels(
+    self,
+    *,
+    usergroup_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+    """
+    kwargs.update({"usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels

+
+
+def admin_users_assign(self,
*,
team_id:Β str,
user_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_assign(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add an Enterprise user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.assign
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "user_id": user_id,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.assign", params=kwargs)
+
+

Add an Enterprise user to a workspace. +https://docs.slack.dev/reference/methods/admin.users.assign

+
+
+def admin_users_invite(self,
*,
team_id:Β str,
email:Β str,
channel_ids:Β strΒ |Β Sequence[str],
custom_message:Β strΒ |Β NoneΒ =Β None,
email_password_policy_enabled:Β boolΒ |Β NoneΒ =Β None,
guest_expiration_ts:Β strΒ |Β floatΒ |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
real_name:Β strΒ |Β NoneΒ =Β None,
resend:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_invite(
+    self,
+    *,
+    team_id: str,
+    email: str,
+    channel_ids: Union[str, Sequence[str]],
+    custom_message: Optional[str] = None,
+    email_password_policy_enabled: Optional[bool] = None,
+    guest_expiration_ts: Optional[Union[str, float]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    real_name: Optional[str] = None,
+    resend: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invite a user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.invite
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "email": email,
+            "custom_message": custom_message,
+            "email_password_policy_enabled": email_password_policy_enabled,
+            "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+            "real_name": real_name,
+            "resend": resend,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.invite", params=kwargs)
+
+ +
+
+def admin_users_list(self,
*,
team_id:Β strΒ |Β NoneΒ =Β None,
include_deactivated_user_workspaces:Β boolΒ |Β NoneΒ =Β None,
is_active:Β boolΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    include_deactivated_user_workspaces: Optional[bool] = None,
+    is_active: Optional[bool] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List users on a workspace
+    https://docs.slack.dev/reference/methods/admin.users.list
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+            "is_active": is_active,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.users.list", params=kwargs)
+
+ +
+
+def admin_users_remove(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_remove(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a user from a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.remove
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.remove", params=kwargs)
+
+ +
+
+def admin_users_session_clearSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_clearSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Clear user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”for a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+

Clear user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”for a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.clearSettings

+
+
+def admin_users_session_getSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_getSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Get user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”given a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+

Get user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”given a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.getSettings

+
+
+def admin_users_session_invalidate(self, *, session_id:Β str, team_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_invalidate(
+    self,
+    *,
+    session_id: str,
+    team_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invalidate a single session for a user by session_id.
+    https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+    """
+    kwargs.update({"session_id": session_id, "team_id": team_id})
+    return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+

Invalidate a single session for a user by session_id. +https://docs.slack.dev/reference/methods/admin.users.session.invalidate

+
+
+def admin_users_session_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all active user sessions for an organization
+    https://docs.slack.dev/reference/methods/admin.users.session.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+            "user_id": user_id,
+        }
+    )
+    return self.api_call("admin.users.session.list", params=kwargs)
+
+

Lists all active user sessions for an organization +https://docs.slack.dev/reference/methods/admin.users.session.list

+
+
+def admin_users_session_reset(self,
*,
user_id:Β str,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_reset(
+    self,
+    *,
+    user_id: str,
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Wipes all valid sessions on all devices for a given user.
+    https://docs.slack.dev/reference/methods/admin.users.session.reset
+    """
+    kwargs.update(
+        {
+            "user_id": user_id,
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.reset", params=kwargs)
+
+

Wipes all valid sessions on all devices for a given user. +https://docs.slack.dev/reference/methods/admin.users.session.reset

+
+
+def admin_users_session_resetBulk(self,
*,
user_ids:Β strΒ |Β Sequence[str],
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_resetBulk(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+    https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+

Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users +https://docs.slack.dev/reference/methods/admin.users.session.resetBulk

+
+
+def admin_users_session_setSettings(self,
*,
user_ids:Β strΒ |Β Sequence[str],
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_setSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    desktop_app_browser_quit: Optional[bool] = None,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Configure the user-level session settingsβ€”the session duration
+    and what happens when the client closesβ€”for one or more users.
+    https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "desktop_app_browser_quit": desktop_app_browser_quit,
+            "duration": duration,
+        }
+    )
+    return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+

Configure the user-level session settingsβ€”the session duration +and what happens when the client closesβ€”for one or more users. +https://docs.slack.dev/reference/methods/admin.users.session.setSettings

+
+
+def admin_users_setAdmin(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setAdmin(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or owner to be an admin user.
+    https://docs.slack.dev/reference/methods/admin.users.setAdmin
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setAdmin", params=kwargs)
+
+

Set an existing guest, regular user, or owner to be an admin user. +https://docs.slack.dev/reference/methods/admin.users.setAdmin

+
+
+def admin_users_setExpiration(self, *, expiration_ts:Β int, user_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setExpiration(
+    self,
+    *,
+    expiration_ts: int,
+    user_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set an expiration for a guest user.
+    https://docs.slack.dev/reference/methods/admin.users.setExpiration
+    """
+    kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setExpiration", params=kwargs)
+
+ +
+
+def admin_users_setOwner(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setOwner(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest, regular user, or admin user to be a workspace owner.
+    https://docs.slack.dev/reference/methods/admin.users.setOwner
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setOwner", params=kwargs)
+
+

Set an existing guest, regular user, or admin user to be a workspace owner. +https://docs.slack.dev/reference/methods/admin.users.setOwner

+
+
+def admin_users_setRegular(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_users_setRegular(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set an existing guest user, admin user, or owner to be a regular user.
+    https://docs.slack.dev/reference/methods/admin.users.setRegular
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setRegular", params=kwargs)
+
+

Set an existing guest user, admin user, or owner to be a regular user. +https://docs.slack.dev/reference/methods/admin.users.setRegular

+
+
+def admin_users_unsupportedVersions_export(self,
*,
date_end_of_support:Β strΒ |Β intΒ |Β NoneΒ =Β None,
date_sessions_started:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_users_unsupportedVersions_export(
+    self,
+    *,
+    date_end_of_support: Optional[Union[str, int]] = None,
+    date_sessions_started: Optional[Union[str, int]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+    presented as a zipped CSV file.
+    https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+    """
+    kwargs.update(
+        {
+            "date_end_of_support": date_end_of_support,
+            "date_sessions_started": date_sessions_started,
+        }
+    )
+    return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+

Ask Slackbot to send you an export listing all workspace members using unsupported software, +presented as a zipped CSV file. +https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export

+
+
+def admin_workflows_collaborators_add(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_add(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add collaborators to workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+

Add collaborators to workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add

+
+
+def admin_workflows_collaborators_remove(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_remove(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove collaborators from workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+

Remove collaborators from workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove

+
+
+def admin_workflows_permissions_lookup(self,
*,
workflow_ids:Β strΒ |Β Sequence[str],
max_workflow_triggers:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_permissions_lookup(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    max_workflow_triggers: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Look up the permissions for a set of workflows
+    https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    kwargs.update(
+        {
+            "max_workflow_triggers": max_workflow_triggers,
+        }
+    )
+    return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def admin_workflows_search(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    no_collaborators: Optional[bool] = None,
+    num_trigger_ids: Optional[int] = None,
+    query: Optional[str] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    source: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Search workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.search
+    """
+    if collaborator_ids is not None:
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "cursor": cursor,
+            "limit": limit,
+            "no_collaborators": no_collaborators,
+            "num_trigger_ids": num_trigger_ids,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "source": source,
+        }
+    )
+    return self.api_call("admin.workflows.search", params=kwargs)
+
+

Search workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.search

+
+
+def admin_workflows_unpublish(self, *, workflow_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def admin_workflows_unpublish(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Unpublish workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+

Unpublish workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.unpublish

+
+
+def api_test(self, *, error:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def api_test(
+    self,
+    *,
+    error: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Checks API calling code.
+    https://docs.slack.dev/reference/methods/api.test
+    """
+    kwargs.update({"error": error})
+    return self.api_call("api.test", params=kwargs)
+
+ +
+
+def apps_connections_open(self, *, app_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_connections_open(
+    self,
+    *,
+    app_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+    in order to receive events and interactive payloads
+    https://docs.slack.dev/reference/methods/apps.connections.open
+    """
+    kwargs.update({"token": app_token})
+    return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+

Generate a temporary Socket Mode WebSocket URL that your app can connect to +in order to receive events and interactive payloads +https://docs.slack.dev/reference/methods/apps.connections.open

+
+
+def apps_event_authorizations_list(self,
*,
event_context:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def apps_event_authorizations_list(
+    self,
+    *,
+    event_context: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a list of authorizations for the given event context.
+    Each authorization represents an app installation that the event is visible to.
+    https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+    """
+    kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+    return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+

Get a list of authorizations for the given event context. +Each authorization represents an app installation that the event is visible to. +https://docs.slack.dev/reference/methods/apps.event.authorizations.list

+
+
+def apps_manifest_create(self, *, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_create(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Create an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.create
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    return self.api_call("apps.manifest.create", params=kwargs)
+
+ +
+
+def apps_manifest_delete(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_delete(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Permanently deletes an app created through app manifests
+    https://docs.slack.dev/reference/methods/apps.manifest.delete
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.delete", params=kwargs)
+
+

Permanently deletes an app created through app manifests +https://docs.slack.dev/reference/methods/apps.manifest.delete

+
+
+def apps_manifest_export(self, *, app_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_export(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Export an app manifest from an existing app
+    https://docs.slack.dev/reference/methods/apps.manifest.export
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.export", params=kwargs)
+
+

Export an app manifest from an existing app +https://docs.slack.dev/reference/methods/apps.manifest.export

+
+
+def apps_manifest_update(self, *, app_id:Β str, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_update(
+    self,
+    *,
+    app_id: str,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.update
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.update", params=kwargs)
+
+ +
+
+def apps_manifest_validate(self, *, manifest:Β strΒ |Β Dict[str,Β Any], app_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_validate(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    app_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Validate an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.validate
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.validate", params=kwargs)
+
+ +
+
+def apps_uninstall(self, *, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def apps_uninstall(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Uninstalls your app from a workspace.
+    https://docs.slack.dev/reference/methods/apps.uninstall
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret})
+    return self.api_call("apps.uninstall", params=kwargs)
+
+

Uninstalls your app from a workspace. +https://docs.slack.dev/reference/methods/apps.uninstall

+
+
+def assistant_threads_setStatus(self,
*,
channel_id:Β str,
thread_ts:Β str,
status:Β str,
loading_messages:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setStatus(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    status: str,
+    loading_messages: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the status for an AI assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+    """
+    kwargs.update(
+        {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+ +
+
+def assistant_threads_setSuggestedPrompts(self,
*,
channel_id:Β str,
thread_ts:Β str,
title:Β strΒ |Β NoneΒ =Β None,
prompts:Β List[Dict[str,Β str]],
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setSuggestedPrompts(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: Optional[str] = None,
+    prompts: List[Dict[str, str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set suggested prompts for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+    if title is not None:
+        kwargs.update({"title": title})
+    return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+

Set suggested prompts for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts

+
+
+def assistant_threads_setTitle(self, *, channel_id:Β str, thread_ts:Β str, title:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def assistant_threads_setTitle(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: str,
+    **kwargs,
+) -> SlackResponse:
+    """Set the title for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+    return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+

Set the title for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setTitle

+
+
+def auth_revoke(self, *, test:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_revoke(
+    self,
+    *,
+    test: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes a token.
+    https://docs.slack.dev/reference/methods/auth.revoke
+    """
+    kwargs.update({"test": test})
+    return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+ +
+
+def auth_teams_list(self,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
include_icon:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def auth_teams_list(
+    self,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    include_icon: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List the workspaces a token can access.
+    https://docs.slack.dev/reference/methods/auth.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+    return self.api_call("auth.teams.list", params=kwargs)
+
+

List the workspaces a token can access. +https://docs.slack.dev/reference/methods/auth.teams.list

+
+
+def auth_test(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def auth_test(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Checks authentication & identity.
+    https://docs.slack.dev/reference/methods/auth.test
+    """
+    return self.api_call("auth.test", params=kwargs)
+
+

Checks authentication & identity. +https://docs.slack.dev/reference/methods/auth.test

+
+
+def bookmarks_add(self,
*,
channel_id:Β str,
title:Β str,
type:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
entity_id:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
parent_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_add(
+    self,
+    *,
+    channel_id: str,
+    title: str,
+    type: str,
+    emoji: Optional[str] = None,
+    entity_id: Optional[str] = None,
+    link: Optional[str] = None,  # include when type is 'link'
+    parent_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add bookmark to a channel.
+    https://docs.slack.dev/reference/methods/bookmarks.add
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "title": title,
+            "type": type,
+            "emoji": emoji,
+            "entity_id": entity_id,
+            "link": link,
+            "parent_id": parent_id,
+        }
+    )
+    return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_edit(self,
*,
bookmark_id:Β str,
channel_id:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_edit(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    emoji: Optional[str] = None,
+    link: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Edit bookmark.
+    https://docs.slack.dev/reference/methods/bookmarks.edit
+    """
+    kwargs.update(
+        {
+            "bookmark_id": bookmark_id,
+            "channel_id": channel_id,
+            "emoji": emoji,
+            "link": link,
+            "title": title,
+        }
+    )
+    return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_list(self, *, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_list(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """List bookmark for the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.list
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_remove(self, *, bookmark_id:Β str, channel_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bookmarks_remove(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Remove bookmark from the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.remove
+    """
+    kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+    return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def bots_info(self, *, bot:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def bots_info(
+    self,
+    *,
+    bot: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a bot user.
+    https://docs.slack.dev/reference/methods/bots.info
+    """
+    kwargs.update({"bot": bot, "team_id": team_id})
+    return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+

Gets information about a bot user. +https://docs.slack.dev/reference/methods/bots.info

+
+
+def calls_add(self,
*,
external_unique_id:Β str,
join_url:Β str,
created_by:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
external_display_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_add(
+    self,
+    *,
+    external_unique_id: str,
+    join_url: str,
+    created_by: Optional[str] = None,
+    date_start: Optional[int] = None,
+    desktop_app_join_url: Optional[str] = None,
+    external_display_id: Optional[str] = None,
+    title: Optional[str] = None,
+    users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Registers a new Call.
+    https://docs.slack.dev/reference/methods/calls.add
+    """
+    kwargs.update(
+        {
+            "external_unique_id": external_unique_id,
+            "join_url": join_url,
+            "created_by": created_by,
+            "date_start": date_start,
+            "desktop_app_join_url": desktop_app_join_url,
+            "external_display_id": external_display_id,
+            "title": title,
+        }
+    )
+    _update_call_participants(
+        kwargs,
+        users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+    )
+    return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_end(self, *, id:Β str, duration:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_end(
+    self,
+    *,
+    id: str,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Ends a Call.
+    https://docs.slack.dev/reference/methods/calls.end
+    """
+    kwargs.update({"id": id, "duration": duration})
+    return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_info(self, *, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_info(
+    self,
+    *,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Returns information about a Call.
+    https://docs.slack.dev/reference/methods/calls.info
+    """
+    kwargs.update({"id": id})
+    return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+

Returns information about a Call. +https://docs.slack.dev/reference/methods/calls.info

+
+
+def calls_participants_add(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_add(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers new participants added to a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.add
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+

Registers new participants added to a Call. +https://docs.slack.dev/reference/methods/calls.participants.add

+
+
+def calls_participants_remove(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def calls_participants_remove(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> SlackResponse:
+    """Registers participants removed from a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.remove
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+

Registers participants removed from a Call. +https://docs.slack.dev/reference/methods/calls.participants.remove

+
+
+def calls_update(self,
*,
id:Β str,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
join_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def calls_update(
+    self,
+    *,
+    id: str,
+    desktop_app_join_url: Optional[str] = None,
+    join_url: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates information about a Call.
+    https://docs.slack.dev/reference/methods/calls.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "desktop_app_join_url": desktop_app_join_url,
+            "join_url": join_url,
+            "title": title,
+        }
+    )
+    return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+ +
+
+def canvases_access_delete(self,
*,
canvas_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_delete(
+    self,
+    *,
+    canvas_id: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/canvases.access.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("canvases.access.delete", params=kwargs)
+
+ +
+
+def canvases_access_set(self,
*,
canvas_id:Β str,
access_level:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_set(
+    self,
+    *,
+    canvas_id: str,
+    access_level: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the access level to a canvas for specified entities
+    https://docs.slack.dev/reference/methods/canvases.access.set
+    """
+    kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+
+    return self.api_call("canvases.access.set", params=kwargs)
+
+

Sets the access level to a canvas for specified entities +https://docs.slack.dev/reference/methods/canvases.access.set

+
+
+def canvases_create(self, *, title:Β strΒ |Β NoneΒ =Β None, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_create(
+    self,
+    *,
+    title: Optional[str] = None,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create Canvas for a user
+    https://docs.slack.dev/reference/methods/canvases.create
+    """
+    kwargs.update({"title": title, "document_content": document_content})
+    return self.api_call("canvases.create", json=kwargs)
+
+ +
+
+def canvases_delete(self, *, canvas_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_delete(
+    self,
+    *,
+    canvas_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a canvas
+    https://docs.slack.dev/reference/methods/canvases.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    return self.api_call("canvases.delete", params=kwargs)
+
+ +
+
+def canvases_edit(self, *, canvas_id:Β str, changes:Β Sequence[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_edit(
+    self,
+    *,
+    canvas_id: str,
+    changes: Sequence[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing canvas
+    https://docs.slack.dev/reference/methods/canvases.edit
+    """
+    kwargs.update({"canvas_id": canvas_id, "changes": changes})
+    return self.api_call("canvases.edit", json=kwargs)
+
+ +
+
+def canvases_sections_lookup(self, *, canvas_id:Β str, criteria:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def canvases_sections_lookup(
+    self,
+    *,
+    canvas_id: str,
+    criteria: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Find sections matching the provided criteria
+    https://docs.slack.dev/reference/methods/canvases.sections.lookup
+    """
+    kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+    return self.api_call("canvases.sections.lookup", params=kwargs)
+
+

Find sections matching the provided criteria +https://docs.slack.dev/reference/methods/canvases.sections.lookup

+
+
+def channels_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.archive", json=kwargs)
+
+

Archives a channel.

+
+
+def channels_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.create", json=kwargs)
+
+

Creates a channel.

+
+
+def channels_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a channel.

+
+
+def channels_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+

Gets information about a channel.

+
+
+def channels_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.invite", json=kwargs)
+
+

Invites a user to a channel.

+
+
+def channels_join(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_join(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins a channel, creating it if needed."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.join", json=kwargs)
+
+

Joins a channel, creating it if needed.

+
+
+def channels_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.kick", json=kwargs)
+
+

Removes a user from a channel.

+
+
+def channels_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.leave", json=kwargs)
+
+

Leaves a channel.

+
+
+def channels_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team."""
+    return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+

Lists all channels in a Slack team.

+
+
+def channels_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.mark", json=kwargs)
+
+

Sets the read cursor in a channel.

+
+
+def channels_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.rename", json=kwargs)
+
+

Renames a channel.

+
+
+def channels_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a channel

+
+
+def channels_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setPurpose", json=kwargs)
+
+

Sets the purpose for a channel.

+
+
+def channels_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setTopic", json=kwargs)
+
+

Sets the topic for a channel.

+
+
+def channels_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def channels_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.unarchive", json=kwargs)
+
+

Unarchives a channel.

+
+
+def chat_appendStream(self, *, channel:Β str, ts:Β str, markdown_text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_appendStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Appends text to an existing streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.appendStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.appendStream", json=kwargs)
+
+

Appends text to an existing streaming conversation. +https://docs.slack.dev/reference/methods/chat.appendStream

+
+
+def chat_delete(self, *, channel:Β str, ts:Β str, as_user:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_delete(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a message.
+    https://docs.slack.dev/reference/methods/chat.delete
+    """
+    kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+    return self.api_call("chat.delete", params=kwargs)
+
+ +
+
+def chat_deleteScheduledMessage(self,
*,
channel:Β str,
scheduled_message_id:Β str,
as_user:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_deleteScheduledMessage(
+    self,
+    *,
+    channel: str,
+    scheduled_message_id: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a scheduled message.
+    https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "scheduled_message_id": scheduled_message_id,
+            "as_user": as_user,
+        }
+    )
+    return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def chat_getPermalink(
+    self,
+    *,
+    channel: str,
+    message_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a permalink URL for a specific extant message
+    https://docs.slack.dev/reference/methods/chat.getPermalink
+    """
+    kwargs.update({"channel": channel, "message_ts": message_ts})
+    return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+

Retrieve a permalink URL for a specific extant message +https://docs.slack.dev/reference/methods/chat.getPermalink

+
+
+def chat_meMessage(self, *, channel:Β str, text:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def chat_meMessage(
+    self,
+    *,
+    channel: str,
+    text: str,
+    **kwargs,
+) -> SlackResponse:
+    """Share a me message into a channel.
+    https://docs.slack.dev/reference/methods/chat.meMessage
+    """
+    kwargs.update({"channel": channel, "text": text})
+    return self.api_call("chat.meMessage", params=kwargs)
+
+ +
+
+def chat_postEphemeral(self,
*,
channel:Β str,
user:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postEphemeral(
+    self,
+    *,
+    channel: str,
+    user: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an ephemeral message to a user in a channel.
+    https://docs.slack.dev/reference/methods/chat.postEphemeral
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "user": user,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postEphemeral", json=kwargs)
+
+

Sends an ephemeral message to a user in a channel. +https://docs.slack.dev/reference/methods/chat.postEphemeral

+
+
+def chat_postMessage(self,
*,
channel:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
container_id:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
mrkdwn:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_postMessage(
+    self,
+    *,
+    channel: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    container_id: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    mrkdwn: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,  # none, full
+    metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends a message to a channel.
+    https://docs.slack.dev/reference/methods/chat.postMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "container_id": container_id,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "mrkdwn": mrkdwn,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postMessage", json=kwargs)
+
+ +
+
+def chat_scheduleMessage(self,
*,
channel:Β str,
post_at:Β strΒ |Β int,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduleMessage(
+    self,
+    *,
+    channel: str,
+    post_at: Union[str, int],
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    parse: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Schedules a message.
+    https://docs.slack.dev/reference/methods/chat.scheduleMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "post_at": post_at,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "parse": parse,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "link_names": link_names,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.scheduleMessage", json=kwargs)
+
+ +
+
+def chat_scheduledMessages_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduledMessages_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all scheduled messages.
+    https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "latest": latest,
+            "limit": limit,
+            "oldest": oldest,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+ +
+
+def chat_startStream(self,
*,
channel:Β str,
thread_ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_startStream(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    markdown_text: Optional[str] = None,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a new streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.startStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "markdown_text": markdown_text,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.startStream", json=kwargs)
+
+

Starts a new streaming conversation. +https://docs.slack.dev/reference/methods/chat.startStream

+
+
+def chat_stopStream(self,
*,
channel:Β str,
ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_stopStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Stops a streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.stopStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+            "blocks": blocks,
+            "metadata": metadata,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.stopStream", json=kwargs)
+
+ +
+
+def chat_stream(self,
*,
buffer_size:Β intΒ =Β 256,
channel:Β str,
thread_ts:Β str,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β ChatStream
+
+
+
+ +Expand source code + +
def chat_stream(
+    self,
+    *,
+    buffer_size: int = 256,
+    channel: str,
+    thread_ts: str,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> ChatStream:
+    """Stream markdown text into a conversation.
+
+    This method starts a new chat stream in a conversation that can be appended to. After appending an entire message,
+    the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.
+
+    The following methods are used:
+
+    - chat.startStream: Starts a new streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.startStream).
+    - chat.appendStream: Appends text to an existing streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.appendStream).
+    - chat.stopStream: Stops a streaming conversation.
+      [Reference](https://docs.slack.dev/reference/methods/chat.stopStream).
+
+    Args:
+        buffer_size: The length of markdown_text to buffer in-memory before calling a stream method. Increasing this
+          value decreases the number of method calls made for the same amount of text, which is useful to avoid rate
+          limits. Default: 256.
+        channel: An encoded ID that represents a channel, private group, or DM.
+        thread_ts: Provide another message's ts value to reply to. Streamed messages should always be replies to a user
+          request.
+        recipient_team_id: The encoded ID of the team the user receiving the streaming text belongs to. Required when
+          streaming to channels.
+        recipient_user_id: The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+        **kwargs: Additional arguments passed to the underlying API calls.
+
+    Returns:
+        ChatStream instance for managing the stream
+
+    Example:
+        ```python
+        streamer = client.chat_stream(
+            channel="C0123456789",
+            thread_ts="1700000001.123456",
+            recipient_team_id="T0123456789",
+            recipient_user_id="U0123456789",
+        )
+        streamer.append(markdown_text="**hello wo")
+        streamer.append(markdown_text="rld!**")
+        streamer.stop()
+        ```
+    """
+    return ChatStream(
+        self,
+        logger=self._logger,
+        channel=channel,
+        thread_ts=thread_ts,
+        recipient_team_id=recipient_team_id,
+        recipient_user_id=recipient_user_id,
+        buffer_size=buffer_size,
+        **kwargs,
+    )
+
+

Stream markdown text into a conversation.

+

This method starts a new chat stream in a conversation that can be appended to. After appending an entire message, +the stream can be stopped with concluding arguments such as "blocks" for gathering feedback.

+

The following methods are used:

+
    +
  • chat.startStream: Starts a new streaming conversation. +Reference.
  • +
  • chat.appendStream: Appends text to an existing streaming conversation. +Reference.
  • +
  • chat.stopStream: Stops a streaming conversation. +Reference.
  • +
+

Args

+
+
buffer_size
+
The length of markdown_text to buffer in-memory before calling a stream method. Increasing this +value decreases the number of method calls made for the same amount of text, which is useful to avoid rate +limits. Default: 256.
+
channel
+
An encoded ID that represents a channel, private group, or DM.
+
thread_ts
+
Provide another message's ts value to reply to. Streamed messages should always be replies to a user +request.
+
recipient_team_id
+
The encoded ID of the team the user receiving the streaming text belongs to. Required when +streaming to channels.
+
recipient_user_id
+
The encoded ID of the user to receive the streaming text. Required when streaming to channels.
+
**kwargs
+
Additional arguments passed to the underlying API calls.
+
+

Returns

+

ChatStream instance for managing the stream

+

Example

+
streamer = client.chat_stream(
+    channel="C0123456789",
+    thread_ts="1700000001.123456",
+    recipient_team_id="T0123456789",
+    recipient_user_id="U0123456789",
+)
+streamer.append(markdown_text="**hello wo")
+streamer.append(markdown_text="rld!**")
+streamer.stop()
+
+
+
+def chat_unfurl(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
ts:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
unfurl_id:Β strΒ |Β NoneΒ =Β None,
unfurls:Β Dict[str,Β Dict]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
user_auth_blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
user_auth_message:Β strΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_unfurl(
+    self,
+    *,
+    channel: Optional[str] = None,
+    ts: Optional[str] = None,
+    source: Optional[str] = None,
+    unfurl_id: Optional[str] = None,
+    unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+    metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+    user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    user_auth_message: Optional[str] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provide custom unfurl behavior for user-posted URLs.
+    https://docs.slack.dev/reference/methods/chat.unfurl
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "source": source,
+            "unfurl_id": unfurl_id,
+            "unfurls": unfurls,
+            "metadata": metadata,
+            "user_auth_blocks": user_auth_blocks,
+            "user_auth_message": user_auth_message,
+            "user_auth_required": user_auth_required,
+            "user_auth_url": user_auth_url,
+        }
+    )
+    _parse_web_class_objects(kwargs)  # for user_auth_blocks
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.unfurl", json=kwargs)
+
+

Provide custom unfurl behavior for user-posted URLs. +https://docs.slack.dev/reference/methods/chat.unfurl

+
+
+def chat_update(self,
*,
channel:Β str,
ts:Β str,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
file_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def chat_update(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    text: Optional[str] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    as_user: Optional[bool] = None,
+    file_ids: Optional[Union[str, Sequence[str]]] = None,
+    link_names: Optional[bool] = None,
+    parse: Optional[str] = None,  # none, full
+    reply_broadcast: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates a message in a channel.
+    https://docs.slack.dev/reference/methods/chat.update
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "as_user": as_user,
+            "link_names": link_names,
+            "parse": parse,
+            "reply_broadcast": reply_broadcast,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    if isinstance(file_ids, (list, tuple)):
+        kwargs.update({"file_ids": ",".join(file_ids)})
+    else:
+        kwargs.update({"file_ids": file_ids})
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.update", kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.update", json=kwargs)
+
+ +
+
+def conversations_acceptSharedInvite(self,
*,
channel_name:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
free_trial_accepted:Β boolΒ |Β NoneΒ =Β None,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_acceptSharedInvite(
+    self,
+    *,
+    channel_name: str,
+    channel_id: Optional[str] = None,
+    invite_id: Optional[str] = None,
+    free_trial_accepted: Optional[bool] = None,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Accepts an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+    """
+    if channel_id is None and invite_id is None:
+        raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+    kwargs.update(
+        {
+            "channel_name": channel_name,
+            "channel_id": channel_id,
+            "invite_id": invite_id,
+            "free_trial_accepted": free_trial_accepted,
+            "is_private": is_private,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+

Accepts an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite

+
+
+def conversations_approveSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_approveSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approves an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+

Approves an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.approveSharedInvite

+
+
+def conversations_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a conversation.
+    https://docs.slack.dev/reference/methods/conversations.archive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.archive", params=kwargs)
+
+ +
+
+def conversations_canvases_create(self, *, channel_id:Β str, document_content:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_canvases_create(
+    self,
+    *,
+    channel_id: str,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/conversations.canvases.create
+    """
+    kwargs.update({"channel_id": channel_id, "document_content": document_content})
+    return self.api_call("conversations.canvases.create", json=kwargs)
+
+ +
+
+def conversations_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.close
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.close", params=kwargs)
+
+

Closes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.close

+
+
+def conversations_create(self,
*,
name:Β str,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_create(
+    self,
+    *,
+    name: str,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiates a public or private channel-based conversation
+    https://docs.slack.dev/reference/methods/conversations.create
+    """
+    kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+    return self.api_call("conversations.create", params=kwargs)
+
+

Initiates a public or private channel-based conversation +https://docs.slack.dev/reference/methods/conversations.create

+
+
+def conversations_declineSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_declineSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Declines a Slack Connect channel invite.
+    https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_externalInvitePermissions_set(self, *, action:Β str, channel:Β str, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_externalInvitePermissions_set(
+    self, *, action: str, channel: str, target_team: str, **kwargs
+) -> SlackResponse:
+    """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+    https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+    """
+    kwargs.update(
+        {
+            "action": action,
+            "channel": channel,
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+

Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa. +https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set

+
+
+def conversations_history(self,
*,
channel:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_history(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches a conversation's history of messages and events.
+    https://docs.slack.dev/reference/methods/conversations.history
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+

Fetches a conversation's history of messages and events. +https://docs.slack.dev/reference/methods/conversations.history

+
+
+def conversations_info(self,
*,
channel:Β str,
include_locale:Β boolΒ |Β NoneΒ =Β None,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_info(
+    self,
+    *,
+    channel: str,
+    include_locale: Optional[bool] = None,
+    include_num_members: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a conversation.
+    https://docs.slack.dev/reference/methods/conversations.info
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "include_locale": include_locale,
+            "include_num_members": include_num_members,
+        }
+    )
+    return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a conversation. +https://docs.slack.dev/reference/methods/conversations.info

+
+
+def conversations_invite(self,
*,
channel:Β str,
users:Β strΒ |Β Sequence[str],
force:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_invite(
+    self,
+    *,
+    channel: str,
+    users: Union[str, Sequence[str]],
+    force: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Invites users to a channel.
+    https://docs.slack.dev/reference/methods/conversations.invite
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "force": force,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.invite", params=kwargs)
+
+ +
+
+def conversations_inviteShared(self,
*,
channel:Β str,
emails:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_inviteShared(
+    self,
+    *,
+    channel: str,
+    emails: Optional[Union[str, Sequence[str]]] = None,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Sends an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.inviteShared
+    """
+    if emails is None and user_ids is None:
+        raise e.SlackRequestError("Either emails or user ids must be provided.")
+    kwargs.update({"channel": channel})
+    if isinstance(emails, (list, tuple)):
+        kwargs.update({"emails": ",".join(emails)})
+    else:
+        kwargs.update({"emails": emails})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+

Sends an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.inviteShared

+
+
+def conversations_join(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_join(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Joins an existing conversation.
+    https://docs.slack.dev/reference/methods/conversations.join
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.join", params=kwargs)
+
+ +
+
+def conversations_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a conversation.
+    https://docs.slack.dev/reference/methods/conversations.kick
+    """
+    kwargs.update({"channel": channel, "user": user})
+    return self.api_call("conversations.kick", params=kwargs)
+
+ +
+
+def conversations_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a conversation.
+    https://docs.slack.dev/reference/methods/conversations.leave
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.leave", params=kwargs)
+
+ +
+
+def conversations_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all channels in a Slack team.
+    https://docs.slack.dev/reference/methods/conversations.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_listConnectInvites(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_listConnectInvites(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List shared channel invites that have been generated
+    or received but have not yet been approved by all parties.
+    https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+    """
+    kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+    return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+

List shared channel invites that have been generated +or received but have not yet been approved by all parties. +https://docs.slack.dev/reference/methods/conversations.listConnectInvites

+
+
+def conversations_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a channel.
+    https://docs.slack.dev/reference/methods/conversations.mark
+    """
+    kwargs.update({"channel": channel, "ts": ts})
+    return self.api_call("conversations.mark", params=kwargs)
+
+ +
+
+def conversations_members(self, *, channel:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_members(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve members of a conversation.
+    https://docs.slack.dev/reference/methods/conversations.members
+    """
+    kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+    return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_open(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
return_im:Β boolΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_open(
+    self,
+    *,
+    channel: Optional[str] = None,
+    return_im: Optional[bool] = None,
+    users: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Opens or resumes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.open
+    """
+    if channel is None and users is None:
+        raise e.SlackRequestError("Either channel or users must be provided.")
+    kwargs.update({"channel": channel, "return_im": return_im})
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.open", params=kwargs)
+
+

Opens or resumes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.open

+
+
+def conversations_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a conversation.
+    https://docs.slack.dev/reference/methods/conversations.rename
+    """
+    kwargs.update({"channel": channel, "name": name})
+    return self.api_call("conversations.rename", params=kwargs)
+
+ +
+
+def conversations_replies(self,
*,
channel:Β str,
ts:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_replies(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a conversation
+    https://docs.slack.dev/reference/methods/conversations.replies
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a conversation +https://docs.slack.dev/reference/methods/conversations.replies

+
+
+def conversations_requestSharedInvite_approve(self,
*,
invite_id:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
is_external_limited:Β strΒ |Β NoneΒ =Β None,
message:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_approve(
+    self,
+    *,
+    invite_id: str,
+    channel_id: Optional[str] = None,
+    is_external_limited: Optional[str] = None,
+    message: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+    """
+    kwargs.update(
+        {
+            "invite_id": invite_id,
+            "channel_id": channel_id,
+            "is_external_limited": is_external_limited,
+        }
+    )
+    if message is not None:
+        kwargs.update({"message": json.dumps(message)})
+    return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+

Approve a request to add an external user to a channel. This also sends them a Slack Connect invite. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve

+
+
+def conversations_requestSharedInvite_deny(self, *, invite_id:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_deny(
+    self,
+    *,
+    invite_id: str,
+    message: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deny a request to invite an external user to a channel.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+    """
+    kwargs.update({"invite_id": invite_id, "message": message})
+    return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+

Deny a request to invite an external user to a channel. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny

+
+
+def conversations_requestSharedInvite_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_approved:Β boolΒ |Β NoneΒ =Β None,
include_denied:Β boolΒ |Β NoneΒ =Β None,
include_expired:Β boolΒ |Β NoneΒ =Β None,
invite_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_approved: Optional[bool] = None,
+    include_denied: Optional[bool] = None,
+    include_expired: Optional[bool] = None,
+    invite_ids: Optional[Union[str, Sequence[str]]] = None,
+    limit: Optional[int] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists requests to add external users to channels with ability to filter.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_approved": include_approved,
+            "include_denied": include_denied,
+            "include_expired": include_expired,
+            "limit": limit,
+            "user_id": user_id,
+        }
+    )
+    if invite_ids is not None:
+        if isinstance(invite_ids, (list, tuple)):
+            kwargs.update({"invite_ids": ",".join(invite_ids)})
+        else:
+            kwargs.update({"invite_ids": invite_ids})
+    return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+

Lists requests to add external users to channels with ability to filter. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list

+
+
+def conversations_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setPurpose
+    """
+    kwargs.update({"channel": channel, "purpose": purpose})
+    return self.api_call("conversations.setPurpose", params=kwargs)
+
+ +
+
+def conversations_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setTopic
+    """
+    kwargs.update({"channel": channel, "topic": topic})
+    return self.api_call("conversations.setTopic", params=kwargs)
+
+ +
+
+def conversations_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def conversations_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Reverses conversation archival.
+    https://docs.slack.dev/reference/methods/conversations.unarchive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.unarchive", params=kwargs)
+
+ +
+
+def dialog_open(self, *, dialog:Β Dict[str,Β Any], trigger_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dialog_open(
+    self,
+    *,
+    dialog: Dict[str, Any],
+    trigger_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Open a dialog with a user.
+    https://docs.slack.dev/reference/methods/dialog.open
+    """
+    kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: As the dialog can be a dict, this API call works only with json format.
+    return self.api_call("dialog.open", json=kwargs)
+
+ +
+
+def dnd_endDnd(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endDnd(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's Do Not Disturb session immediately.
+    https://docs.slack.dev/reference/methods/dnd.endDnd
+    """
+    return self.api_call("dnd.endDnd", params=kwargs)
+
+

Ends the current user's Do Not Disturb session immediately. +https://docs.slack.dev/reference/methods/dnd.endDnd

+
+
+def dnd_endSnooze(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_endSnooze(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Ends the current user's snooze mode immediately.
+    https://docs.slack.dev/reference/methods/dnd.endSnooze
+    """
+    return self.api_call("dnd.endSnooze", params=kwargs)
+
+

Ends the current user's snooze mode immediately. +https://docs.slack.dev/reference/methods/dnd.endSnooze

+
+
+def dnd_info(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_info(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's current Do Not Disturb status.
+    https://docs.slack.dev/reference/methods/dnd.info
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+

Retrieves a user's current Do Not Disturb status. +https://docs.slack.dev/reference/methods/dnd.info

+
+
+def dnd_setSnooze(self, *, num_minutes:Β strΒ |Β int, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_setSnooze(
+    self,
+    *,
+    num_minutes: Union[int, str],
+    **kwargs,
+) -> SlackResponse:
+    """Turns on Do Not Disturb mode for the current user, or changes its duration.
+    https://docs.slack.dev/reference/methods/dnd.setSnooze
+    """
+    kwargs.update({"num_minutes": num_minutes})
+    return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+

Turns on Do Not Disturb mode for the current user, or changes its duration. +https://docs.slack.dev/reference/methods/dnd.setSnooze

+
+
+def dnd_teamInfo(self, users:Β strΒ |Β Sequence[str], team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def dnd_teamInfo(
+    self,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves the Do Not Disturb status for users on a team.
+    https://docs.slack.dev/reference/methods/dnd.teamInfo
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id})
+    return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+

Retrieves the Do Not Disturb status for users on a team. +https://docs.slack.dev/reference/methods/dnd.teamInfo

+
+
+def emoji_list(self, include_categories:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def emoji_list(
+    self,
+    include_categories: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists custom emoji for a team.
+    https://docs.slack.dev/reference/methods/emoji.list
+    """
+    kwargs.update({"include_categories": include_categories})
+    return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+ +
+
+def entity_presentDetails(self,
trigger_id:Β str,
metadata:Β DictΒ |Β EntityMetadataΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def entity_presentDetails(
+    self,
+    trigger_id: str,
+    metadata: Optional[Union[Dict, EntityMetadata]] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    error: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Provides entity details for the flexpane.
+    https://docs.slack.dev/reference/methods/entity.presentDetails/
+    """
+    kwargs.update({"trigger_id": trigger_id})
+    if metadata is not None:
+        kwargs.update({"metadata": metadata})
+    if user_auth_required is not None:
+        kwargs.update({"user_auth_required": user_auth_required})
+    if user_auth_url is not None:
+        kwargs.update({"user_auth_url": user_auth_url})
+    if error is not None:
+        kwargs.update({"error": error})
+    _parse_web_class_objects(kwargs)
+    return self.api_call("entity.presentDetails", json=kwargs)
+
+

Provides entity details for the flexpane. +https://docs.slack.dev/reference/methods/entity.presentDetails/

+
+
+def files_comments_delete(self, *, file:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_comments_delete(
+    self,
+    *,
+    file: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an existing comment on a file.
+    https://docs.slack.dev/reference/methods/files.comments.delete
+    """
+    kwargs.update({"file": file, "id": id})
+    return self.api_call("files.comments.delete", params=kwargs)
+
+ +
+
+def files_completeUploadExternal(self,
*,
files:Β List[Dict[str,Β str]],
channel_id:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_completeUploadExternal(
+    self,
+    *,
+    files: List[Dict[str, str]],
+    channel_id: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Finishes an upload started with files.getUploadURLExternal.
+    https://docs.slack.dev/reference/methods/files.completeUploadExternal
+    """
+    _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+    kwargs.update(
+        {
+            "files": json.dumps(_files),
+            "channel_id": channel_id,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+        }
+    )
+    if channels:
+        kwargs["channels"] = ",".join(channels)
+    return self.api_call("files.completeUploadExternal", params=kwargs)
+
+

Finishes an upload started with files.getUploadURLExternal. +https://docs.slack.dev/reference/methods/files.completeUploadExternal

+
+
+def files_delete(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_delete(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a file.
+    https://docs.slack.dev/reference/methods/files.delete
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.delete", params=kwargs)
+
+ +
+
+def files_getUploadURLExternal(self,
*,
filename:Β str,
length:Β int,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_getUploadURLExternal(
+    self,
+    *,
+    filename: str,
+    length: int,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets a URL for an edge external upload.
+    https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+    """
+    kwargs.update(
+        {
+            "filename": filename,
+            "length": length,
+            "alt_txt": alt_txt,
+            "snippet_type": snippet_type,
+        }
+    )
+    return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+ +
+
+def files_info(self,
*,
file:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_info(
+    self,
+    *,
+    file: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a team file.
+    https://docs.slack.dev/reference/methods/files.info
+    """
+    kwargs.update(
+        {
+            "file": file,
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+        }
+    )
+    return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+

Gets information about a team file. +https://docs.slack.dev/reference/methods/files.info

+
+
+def files_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
count:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
show_files_hidden_by_limit:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    count: Optional[int] = None,
+    page: Optional[int] = None,
+    show_files_hidden_by_limit: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists & filters team files.
+    https://docs.slack.dev/reference/methods/files.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "count": count,
+            "page": page,
+            "show_files_hidden_by_limit": show_files_hidden_by_limit,
+            "team_id": team_id,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_add(self,
*,
external_id:Β str,
external_url:Β str,
title:Β str,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_add(
+    self,
+    *,
+    external_id: str,
+    external_url: str,
+    title: str,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+    preview_image: Optional[Union[str, bytes, IOBase]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a file from a remote service.
+    https://docs.slack.dev/reference/methods/files.remote.add
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.add",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_remote_info(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_info(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.info
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.info

+
+
+def files_remote_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "limit": limit,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+        }
+    )
+    return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.list

+
+
+def files_remote_remove(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_remote_remove(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Remove a remote file.
+    https://docs.slack.dev/reference/methods/files.remote.remove
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def files_remote_share(self,
*,
channels:Β strΒ |Β Sequence[str],
external_id:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_share(
+    self,
+    *,
+    channels: Union[str, Sequence[str]],
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Share a remote file into a channel.
+    https://docs.slack.dev/reference/methods/files.remote.share
+    """
+    if external_id is None and file is None:
+        raise e.SlackRequestError("Either external_id or file must be provided.")
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_update(self,
*,
external_id:Β strΒ |Β NoneΒ =Β None,
external_url:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_remote_update(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    external_url: Optional[str] = None,
+    file: Optional[str] = None,
+    title: Optional[str] = None,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[str] = None,
+    preview_image: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Updates an existing remote file.
+    https://docs.slack.dev/reference/methods/files.remote.update
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "file": file,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.update",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_revokePublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_revokePublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Revokes public/external sharing access for a file
+    https://docs.slack.dev/reference/methods/files.revokePublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.revokePublicURL", params=kwargs)
+
+

Revokes public/external sharing access for a file +https://docs.slack.dev/reference/methods/files.revokePublicURL

+
+
+def files_sharedPublicURL(self, *, file:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def files_sharedPublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> SlackResponse:
+    """Enables a file for public/external sharing.
+    https://docs.slack.dev/reference/methods/files.sharedPublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.sharedPublicURL", params=kwargs)
+
+

Enables a file for public/external sharing. +https://docs.slack.dev/reference/methods/files.sharedPublicURL

+
+
+def files_upload(self,
*,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
filename:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload(
+    self,
+    *,
+    file: Optional[Union[str, bytes, IOBase]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    filename: Optional[str] = None,
+    filetype: Optional[str] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    title: Optional[str] = None,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Uploads or creates a file.
+    https://docs.slack.dev/reference/methods/files.upload
+    """
+    _print_files_upload_v2_suggestion()
+
+    if file is None and content is None:
+        raise e.SlackRequestError("The file or content argument must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update(
+        {
+            "filename": filename,
+            "filetype": filetype,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+            "title": title,
+        }
+    )
+    if file:
+        if kwargs.get("filename") is None and isinstance(file, str):
+            # use the local filename if filename is missing
+            if kwargs.get("filename") is None:
+                kwargs["filename"] = file.split(os.path.sep)[-1]
+        return self.api_call("files.upload", files={"file": file}, data=kwargs)
+    else:
+        kwargs["content"] = content
+        return self.api_call("files.upload", data=kwargs)
+
+ +
+
+def files_upload_v2(self,
*,
filename:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β os.PathLikeΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
file_uploads:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
request_file_info:Β boolΒ =Β True,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def files_upload_v2(
+    self,
+    *,
+    # for sending a single file
+    filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+    file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    title: Optional[str] = None,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    # To upload multiple files at a time
+    file_uploads: Optional[List[Dict[str, Any]]] = None,
+    channel: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+    **kwargs,
+) -> SlackResponse:
+    """This wrapper method provides an easy way to upload files using the following endpoints:
+
+    - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+    - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+    - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        and https://docs.slack.dev/reference/methods/files.info
+
+    """
+    if file is None and content is None and file_uploads is None:
+        raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    # deprecated arguments:
+    filetype = kwargs.get("filetype")
+
+    if filetype is not None:
+        warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+    # step1: files.getUploadURLExternal per file
+    files: List[Dict[str, Any]] = []
+    if file_uploads is not None:
+        for f in file_uploads:
+            files.append(_to_v2_file_upload_item(f))
+    else:
+        f = _to_v2_file_upload_item(
+            {
+                "filename": filename,
+                "file": file,
+                "content": content,
+                "title": title,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        files.append(f)
+
+    for f in files:
+        url_response = self.files_getUploadURLExternal(
+            filename=f.get("filename"),  # type: ignore[arg-type]
+            length=f.get("length"),  # type: ignore[arg-type]
+            alt_txt=f.get("alt_txt"),
+            snippet_type=f.get("snippet_type"),
+            token=kwargs.get("token"),
+        )
+        _validate_for_legacy_client(url_response)
+        f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+        f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+    # step2: "https://files.slack.com/upload/v1/..." per file
+    for f in files:
+        upload_result = self._upload_file(
+            url=f["upload_url"],
+            data=f["data"],
+            logger=self._logger,
+            timeout=self.timeout,
+            proxy=self.proxy,
+            ssl=self.ssl,
+        )
+        if upload_result.status != 200:
+            status = upload_result.status
+            body = upload_result.body
+            message = (
+                "Failed to upload a file "
+                f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+            )
+            raise e.SlackRequestError(message)
+
+    # step3: files.completeUploadExternal with all the sets of (file_id + title)
+    completion = self.files_completeUploadExternal(
+        files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+        channel_id=channel,
+        channels=channels,
+        initial_comment=initial_comment,
+        thread_ts=thread_ts,
+        **kwargs,
+    )
+    if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+        completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+    return completion
+
+

This wrapper method provides an easy way to upload files using the following endpoints:

+
+
+
+def functions_completeError(self, *, function_execution_id:Β str, error:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeError(
+    self,
+    *,
+    function_execution_id: str,
+    error: str,
+    **kwargs,
+) -> SlackResponse:
+    """Signal the failure to execute a function
+    https://docs.slack.dev/reference/methods/functions.completeError
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "error": error})
+    return self.api_call("functions.completeError", params=kwargs)
+
+ +
+
+def functions_completeSuccess(self, *, function_execution_id:Β str, outputs:Β Dict[str,Β Any], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def functions_completeSuccess(
+    self,
+    *,
+    function_execution_id: str,
+    outputs: Dict[str, Any],
+    **kwargs,
+) -> SlackResponse:
+    """Signal the successful completion of a function
+    https://docs.slack.dev/reference/methods/functions.completeSuccess
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+    return self.api_call("functions.completeSuccess", params=kwargs)
+
+

Signal the successful completion of a function +https://docs.slack.dev/reference/methods/functions.completeSuccess

+
+
+def groups_archive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Archives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.archive", json=kwargs)
+
+

Archives a private channel.

+
+
+def groups_create(self, *, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a private channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.create", json=kwargs)
+
+

Creates a private channel.

+
+
+def groups_createChild(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_createChild(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Clones and archives a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+

Clones and archives a private channel.

+
+
+def groups_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a private channel.

+
+
+def groups_info(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+

Gets information about a private channel.

+
+
+def groups_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Invites a user to a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.invite", json=kwargs)
+
+

Invites a user to a private channel.

+
+
+def groups_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a user from a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.kick", json=kwargs)
+
+

Removes a user from a private channel.

+
+
+def groups_leave(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Leaves a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.leave", json=kwargs)
+
+

Leaves a private channel.

+
+
+def groups_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists private channels that the calling user has access to."""
+    return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+

Lists private channels that the calling user has access to.

+
+
+def groups_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a private channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.mark", json=kwargs)
+
+

Sets the read cursor in a private channel.

+
+
+def groups_open(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_open(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.open", json=kwargs)
+
+

Opens a private channel.

+
+
+def groups_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> SlackResponse:
+    """Renames a private channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.rename", json=kwargs)
+
+

Renames a private channel.

+
+
+def groups_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a private channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a private channel

+
+
+def groups_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the purpose for a private channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setPurpose", json=kwargs)
+
+

Sets the purpose for a private channel.

+
+
+def groups_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the topic for a private channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setTopic", json=kwargs)
+
+

Sets the topic for a private channel.

+
+
+def groups_unarchive(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def groups_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Unarchives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.unarchive", json=kwargs)
+
+

Unarchives a private channel.

+
+
+def im_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Close a direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.close", json=kwargs)
+
+

Close a direct message channel.

+
+
+def im_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from direct message channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from direct message channel.

+
+
+def im_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists direct message channels for the calling user."""
+    return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+

Lists direct message channels for the calling user.

+
+
+def im_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.mark", json=kwargs)
+
+

Sets the read cursor in a direct message channel.

+
+
+def im_open(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_open(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Opens a direct message channel."""
+    kwargs.update({"user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.open", json=kwargs)
+
+

Opens a direct message channel.

+
+
+def im_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def im_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation

+
+
+def migration_exchange(self,
*,
users:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
to_old:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def migration_exchange(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    to_old: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """For Enterprise Grid workspaces, map local user IDs to global user IDs
+    https://docs.slack.dev/reference/methods/migration.exchange
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id, "to_old": to_old})
+    return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+

For Enterprise Grid workspaces, map local user IDs to global user IDs +https://docs.slack.dev/reference/methods/migration.exchange

+
+
+def mpim_close(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Closes a multiparty direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.close", json=kwargs)
+
+

Closes a multiparty direct message channel.

+
+
+def mpim_history(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Fetches history of messages and events from a multiparty direct message."""
+    kwargs.update({"channel": channel})
+    return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a multiparty direct message.

+
+
+def mpim_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Lists multiparty direct message channels for the calling user."""
+    return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+

Lists multiparty direct message channels for the calling user.

+
+
+def mpim_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Sets the read cursor in a multiparty direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.mark", json=kwargs)
+
+

Sets the read cursor in a multiparty direct message channel.

+
+
+def mpim_open(self, *, users:Β strΒ |Β Sequence[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_open(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """This method opens a multiparty direct message."""
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("mpim.open", params=kwargs)
+
+

This method opens a multiparty direct message.

+
+
+def mpim_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def mpim_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a thread of messages posted to a direct message conversation from a
+    multiparty direct message.
+    """
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation from a +multiparty direct message.

+
+
+def oauth_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    code: str,
+    redirect_uri: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    kwargs.update({"code": code})
+    return self.api_call(
+        "oauth.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.access

+
+
+def oauth_v2_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def oauth_v2_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    # This field is required when processing the OAuth redirect URL requests
+    # while it's absent for token rotation
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    # This field is required for token rotation
+    grant_type: Optional[str] = None,
+    # This field is required for token rotation
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.v2.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "oauth.v2.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.v2.access

+
+
+def oauth_v2_exchange(self, *, token:Β str, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def oauth_v2_exchange(
+    self,
+    *,
+    token: str,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a legacy access token for a new expiring access token and refresh token
+    https://docs.slack.dev/reference/methods/oauth.v2.exchange
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+    return self.api_call("oauth.v2.exchange", params=kwargs)
+
+

Exchanges a legacy access token for a new expiring access token and refresh token +https://docs.slack.dev/reference/methods/oauth.v2.exchange

+
+
+def openid_connect_token(self,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def openid_connect_token(
+    self,
+    client_id: str,
+    client_secret: str,
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    grant_type: Optional[str] = None,
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.token
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "openid.connect.token",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.token

+
+
+def openid_connect_userInfo(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def openid_connect_userInfo(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get the identity of a user who has authorized Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.userInfo
+    """
+    return self.api_call("openid.connect.userInfo", params=kwargs)
+
+

Get the identity of a user who has authorized Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.userInfo

+
+
+def pins_add(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_add(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Pins an item to a channel.
+    https://docs.slack.dev/reference/methods/pins.add
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.add", params=kwargs)
+
+ +
+
+def pins_list(self, *, channel:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_list(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lists items pinned to a channel.
+    https://docs.slack.dev/reference/methods/pins.list
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+

Lists items pinned to a channel. +https://docs.slack.dev/reference/methods/pins.list

+
+
+def pins_remove(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def pins_remove(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Un-pins an item from a channel.
+    https://docs.slack.dev/reference/methods/pins.remove
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.remove", params=kwargs)
+
+ +
+
+def reactions_add(self, *, channel:Β str, name:Β str, timestamp:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reactions_add(
+    self,
+    *,
+    channel: str,
+    name: str,
+    timestamp: str,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a reaction to an item.
+    https://docs.slack.dev/reference/methods/reactions.add
+    """
+    kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+    return self.api_call("reactions.add", params=kwargs)
+
+ +
+
+def reactions_get(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_get(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    full: Optional[bool] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets reactions for an item.
+    https://docs.slack.dev/reference/methods/reactions.get
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "full": full,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    full: Optional[bool] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists reactions made by a user.
+    https://docs.slack.dev/reference/methods/reactions.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "full": full,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_remove(self,
*,
name:Β str,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reactions_remove(
+    self,
+    *,
+    name: str,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a reaction from an item.
+    https://docs.slack.dev/reference/methods/reactions.remove
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.remove", params=kwargs)
+
+ +
+
+def reminders_add(self,
*,
text:Β str,
time:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
recurrence:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def reminders_add(
+    self,
+    *,
+    text: str,
+    time: str,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    recurrence: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a reminder.
+    https://docs.slack.dev/reference/methods/reminders.add
+    """
+    kwargs.update(
+        {
+            "text": text,
+            "time": time,
+            "team_id": team_id,
+            "user": user,
+            "recurrence": recurrence,
+        }
+    )
+    return self.api_call("reminders.add", params=kwargs)
+
+ +
+
+def reminders_complete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_complete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Marks a reminder as complete.
+    https://docs.slack.dev/reference/methods/reminders.complete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.complete", params=kwargs)
+
+ +
+
+def reminders_delete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_delete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes a reminder.
+    https://docs.slack.dev/reference/methods/reminders.delete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.delete", params=kwargs)
+
+ +
+
+def reminders_info(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_info(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a reminder.
+    https://docs.slack.dev/reference/methods/reminders.info
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+ +
+
+def reminders_list(self, *, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def reminders_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all reminders created by or for a given user.
+    https://docs.slack.dev/reference/methods/reminders.list
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+

Lists all reminders created by or for a given user. +https://docs.slack.dev/reference/methods/reminders.list

+
+
+def rtm_connect(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_connect(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.connect
+    """
+    kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+    return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.connect

+
+
+def rtm_start(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
mpim_aware:Β boolΒ |Β NoneΒ =Β None,
no_latest:Β boolΒ |Β NoneΒ =Β None,
no_unreads:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
simple_latest:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def rtm_start(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    include_locale: Optional[bool] = None,
+    mpim_aware: Optional[bool] = None,
+    no_latest: Optional[bool] = None,
+    no_unreads: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    simple_latest: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.start
+    """
+    kwargs.update(
+        {
+            "batch_presence_aware": batch_presence_aware,
+            "include_locale": include_locale,
+            "mpim_aware": mpim_aware,
+            "no_latest": no_latest,
+            "no_unreads": no_unreads,
+            "presence_sub": presence_sub,
+            "simple_latest": simple_latest,
+        }
+    )
+    return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.start

+
+
+def search_all(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_all(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages and files matching a query.
+    https://docs.slack.dev/reference/methods/search.all
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+

Searches for messages and files matching a query. +https://docs.slack.dev/reference/methods/search.all

+
+
+def search_files(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_files(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for files matching a query.
+    https://docs.slack.dev/reference/methods/search.files
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+

Searches for files matching a query. +https://docs.slack.dev/reference/methods/search.files

+
+
+def search_messages(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def search_messages(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Searches for messages matching a query.
+    https://docs.slack.dev/reference/methods/search.messages
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "cursor": cursor,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+

Searches for messages matching a query. +https://docs.slack.dev/reference/methods/search.messages

+
+
+def slackLists_access_delete(self,
*,
list_id:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_delete(
+    self,
+    *,
+    list_id: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Revoke access to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.delete
+    """
+    kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.delete", json=kwargs)
+
+

Revoke access to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.delete

+
+
+def slackLists_access_set(self,
*,
list_id:Β str,
access_level:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_set(
+    self,
+    *,
+    list_id: str,
+    access_level: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the access level to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.set
+    """
+    kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.set", json=kwargs)
+
+

Set the access level to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.set

+
+
+def slackLists_create(self,
*,
name:Β str,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
schema:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
copy_from_list_id:Β strΒ |Β NoneΒ =Β None,
include_copied_list_records:Β boolΒ |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_create(
+    self,
+    *,
+    name: str,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    schema: Optional[List[Dict[str, Any]]] = None,
+    copy_from_list_id: Optional[str] = None,
+    include_copied_list_records: Optional[bool] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Creates a List.
+    https://docs.slack.dev/reference/methods/slackLists.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description_blocks": description_blocks,
+            "schema": schema,
+            "copy_from_list_id": copy_from_list_id,
+            "include_copied_list_records": include_copied_list_records,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.create", json=kwargs)
+
+ +
+
+def slackLists_download_get(self, *, list_id:Β str, job_id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_get(
+    self,
+    *,
+    list_id: str,
+    job_id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve List download URL from an export job to download List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.get
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "job_id": job_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.get", json=kwargs)
+
+

Retrieve List download URL from an export job to download List contents. +https://docs.slack.dev/reference/methods/slackLists.download.get

+
+
+def slackLists_download_start(self, *, list_id:Β str, include_archived:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_start(
+    self,
+    *,
+    list_id: str,
+    include_archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Initiate a job to export List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.start
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "include_archived": include_archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.start", json=kwargs)
+
+ +
+
+def slackLists_items_create(self,
*,
list_id:Β str,
duplicated_item_id:Β strΒ |Β NoneΒ =Β None,
parent_item_id:Β strΒ |Β NoneΒ =Β None,
initial_fields:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_create(
+    self,
+    *,
+    list_id: str,
+    duplicated_item_id: Optional[str] = None,
+    parent_item_id: Optional[str] = None,
+    initial_fields: Optional[List[Dict[str, Any]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Add a new item to an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.create
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "duplicated_item_id": duplicated_item_id,
+            "parent_item_id": parent_item_id,
+            "initial_fields": initial_fields,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.create", json=kwargs)
+
+ +
+
+def slackLists_items_delete(self, *, list_id:Β str, id:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_delete(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    **kwargs,
+) -> SlackResponse:
+    """Deletes an item from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.delete
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.delete", json=kwargs)
+
+ +
+
+def slackLists_items_deleteMultiple(self, *, list_id:Β str, ids:Β List[str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_deleteMultiple(
+    self,
+    *,
+    list_id: str,
+    ids: List[str],
+    **kwargs,
+) -> SlackResponse:
+    """Deletes multiple items from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "ids": ids,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+ +
+
+def slackLists_items_info(self, *, list_id:Β str, id:Β str, include_is_subscribed:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_info(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    include_is_subscribed: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get a row from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.info
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+            "include_is_subscribed": include_is_subscribed,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.info", json=kwargs)
+
+ +
+
+def slackLists_items_list(self,
*,
list_id:Β str,
limit:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
archived:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_list(
+    self,
+    *,
+    list_id: str,
+    limit: Optional[int] = None,
+    cursor: Optional[str] = None,
+    archived: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Get records from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.list
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "limit": limit,
+            "cursor": cursor,
+            "archived": archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.list", json=kwargs)
+
+ +
+
+def slackLists_items_update(self, *, list_id:Β str, cells:Β List[Dict[str,Β Any]], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_update(
+    self,
+    *,
+    list_id: str,
+    cells: List[Dict[str, Any]],
+    **kwargs,
+) -> SlackResponse:
+    """Updates cells in a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.update
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "cells": cells,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.update", json=kwargs)
+
+ +
+
+def slackLists_update(self,
*,
id:Β str,
name:Β strΒ |Β NoneΒ =Β None,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def slackLists_update(
+    self,
+    *,
+    id: str,
+    name: Optional[str] = None,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update a List.
+    https://docs.slack.dev/reference/methods/slackLists.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "name": name,
+            "description_blocks": description_blocks,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.update", json=kwargs)
+
+ +
+
+def stars_add(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_add(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Adds a star to an item.
+    https://docs.slack.dev/reference/methods/stars.add
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.add", params=kwargs)
+
+ +
+
+def stars_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists stars for a user.
+    https://docs.slack.dev/reference/methods/stars.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+ +
+
+def stars_remove(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def stars_remove(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Removes a star from an item.
+    https://docs.slack.dev/reference/methods/stars.remove
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.remove", params=kwargs)
+
+ +
+
+def team_accessLogs(self,
*,
before:Β strΒ |Β intΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_accessLogs(
+    self,
+    *,
+    before: Optional[Union[int, str]] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the access logs for the current team.
+    https://docs.slack.dev/reference/methods/team.accessLogs
+    """
+    kwargs.update(
+        {
+            "before": before,
+            "count": count,
+            "page": page,
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+

Gets the access logs for the current team. +https://docs.slack.dev/reference/methods/team.accessLogs

+
+
+def team_billableInfo(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billableInfo(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets billable users information for the current team.
+    https://docs.slack.dev/reference/methods/team.billableInfo
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+

Gets billable users information for the current team. +https://docs.slack.dev/reference/methods/team.billableInfo

+
+
+def team_billing_info(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_billing_info(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Reads a workspace's billing plan information.
+    https://docs.slack.dev/reference/methods/team.billing.info
+    """
+    return self.api_call("team.billing.info", params=kwargs)
+
+

Reads a workspace's billing plan information. +https://docs.slack.dev/reference/methods/team.billing.info

+
+
+def team_externalTeams_disconnect(self, *, target_team:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_externalTeams_disconnect(
+    self,
+    *,
+    target_team: str,
+    **kwargs,
+) -> SlackResponse:
+    """Disconnects an external organization.
+    https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+    """
+    kwargs.update(
+        {
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+ +
+
+def team_externalTeams_list(self,
*,
connection_status_filter:Β strΒ |Β NoneΒ =Β None,
slack_connect_pref_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
sort_field:Β strΒ |Β NoneΒ =Β None,
workspace_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_externalTeams_list(
+    self,
+    *,
+    connection_status_filter: Optional[str] = None,
+    slack_connect_pref_filter: Optional[Sequence[str]] = None,
+    sort_direction: Optional[str] = None,
+    sort_field: Optional[str] = None,
+    workspace_filter: Optional[Sequence[str]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Returns a list of all the external teams connected and details about the connection.
+    https://docs.slack.dev/reference/methods/team.externalTeams.list
+    """
+    kwargs.update(
+        {
+            "connection_status_filter": connection_status_filter,
+            "sort_direction": sort_direction,
+            "sort_field": sort_field,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if slack_connect_pref_filter is not None:
+        if isinstance(slack_connect_pref_filter, (list, tuple)):
+            kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+        else:
+            kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+    if workspace_filter is not None:
+        if isinstance(workspace_filter, (list, tuple)):
+            kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+        else:
+            kwargs.update({"workspace_filter": workspace_filter})
+    return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+

Returns a list of all the external teams connected and details about the connection. +https://docs.slack.dev/reference/methods/team.externalTeams.list

+
+
+def team_info(self, *, team:Β strΒ |Β NoneΒ =Β None, domain:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_info(
+    self,
+    *,
+    team: Optional[str] = None,
+    domain: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about the current team.
+    https://docs.slack.dev/reference/methods/team.info
+    """
+    kwargs.update({"team": team, "domain": domain})
+    return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+

Gets information about the current team. +https://docs.slack.dev/reference/methods/team.info

+
+
+def team_integrationLogs(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
change_type:Β strΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
service_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def team_integrationLogs(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    change_type: Optional[str] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    service_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets the integration logs for the current team.
+    https://docs.slack.dev/reference/methods/team.integrationLogs
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "change_type": change_type,
+            "count": count,
+            "page": page,
+            "service_id": service_id,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+

Gets the integration logs for the current team. +https://docs.slack.dev/reference/methods/team.integrationLogs

+
+
+def team_preferences_list(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_preferences_list(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a list of a workspace's team preferences.
+    https://docs.slack.dev/reference/methods/team.preferences.list
+    """
+    return self.api_call("team.preferences.list", params=kwargs)
+
+

Retrieve a list of a workspace's team preferences. +https://docs.slack.dev/reference/methods/team.preferences.list

+
+
+def team_profile_get(self, *, visibility:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def team_profile_get(
+    self,
+    *,
+    visibility: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieve a team's profile.
+    https://docs.slack.dev/reference/methods/team.profile.get
+    """
+    kwargs.update({"visibility": visibility})
+    return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+ +
+
+def tooling_tokens_rotate(self, *, refresh_token:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def tooling_tokens_rotate(
+    self,
+    *,
+    refresh_token: str,
+    **kwargs,
+) -> SlackResponse:
+    """Exchanges a refresh token for a new app configuration token
+    https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+    """
+    kwargs.update({"refresh_token": refresh_token})
+    return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+

Exchanges a refresh token for a new app configuration token +https://docs.slack.dev/reference/methods/tooling.tokens.rotate

+
+
+def usergroups_create(self,
*,
name:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_create(
+    self,
+    *,
+    name: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Create a User Group
+    https://docs.slack.dev/reference/methods/usergroups.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.create", params=kwargs)
+
+ +
+
+def usergroups_disable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_disable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Disable an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.disable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.disable", params=kwargs)
+
+ +
+
+def usergroups_enable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_enable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Enable a User Group
+    https://docs.slack.dev/reference/methods/usergroups.enable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.enable", params=kwargs)
+
+ +
+
+def usergroups_list(self,
*,
include_count:Β boolΒ |Β NoneΒ =Β None,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
include_users:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_list(
+    self,
+    *,
+    include_count: Optional[bool] = None,
+    include_disabled: Optional[bool] = None,
+    include_users: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all User Groups for a team
+    https://docs.slack.dev/reference/methods/usergroups.list
+    """
+    kwargs.update(
+        {
+            "include_count": include_count,
+            "include_disabled": include_disabled,
+            "include_users": include_users,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_update(self,
*,
usergroup:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_update(
+    self,
+    *,
+    usergroup: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    name: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "name": name,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.update", params=kwargs)
+
+ +
+
+def usergroups_users_list(self,
*,
usergroup:Β str,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_list(
+    self,
+    *,
+    usergroup: str,
+    include_disabled: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List all users in a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.list
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_disabled": include_disabled,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_users_update(self,
*,
usergroup:Β str,
users:Β strΒ |Β Sequence[str],
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_update(
+    self,
+    *,
+    usergroup: str,
+    users: Union[str, Sequence[str]],
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the list of users for a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("usergroups.users.update", params=kwargs)
+
+

Update the list of users for a User Group +https://docs.slack.dev/reference/methods/usergroups.users.update

+
+
+def users_conversations(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_conversations(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """List conversations the calling user may access.
+    https://docs.slack.dev/reference/methods/users.conversations
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+

List conversations the calling user may access. +https://docs.slack.dev/reference/methods/users.conversations

+
+
+def users_deletePhoto(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_deletePhoto(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Delete the user profile photo
+    https://docs.slack.dev/reference/methods/users.deletePhoto
+    """
+    return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+ +
+
+def users_discoverableContacts_lookup(self, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_discoverableContacts_lookup(
+    self,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Lookup an email address to see if someone is on Slack
+    https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+

Lookup an email address to see if someone is on Slack +https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup

+
+
+def users_getPresence(self, *, user:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_getPresence(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> SlackResponse:
+    """Gets user presence information.
+    https://docs.slack.dev/reference/methods/users.getPresence
+    """
+    kwargs.update({"user": user})
+    return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+ +
+
+def users_identity(self, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_identity(
+    self,
+    **kwargs,
+) -> SlackResponse:
+    """Get a user's identity.
+    https://docs.slack.dev/reference/methods/users.identity
+    """
+    return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+ +
+
+def users_info(self, *, user:Β str, include_locale:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_info(
+    self,
+    *,
+    user: str,
+    include_locale: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Gets information about a user.
+    https://docs.slack.dev/reference/methods/users.info
+    """
+    kwargs.update({"user": user, "include_locale": include_locale})
+    return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+ +
+
+def users_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_locale: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Lists all users in a Slack team.
+    https://docs.slack.dev/reference/methods/users.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_locale": include_locale,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+

Lists all users in a Slack team. +https://docs.slack.dev/reference/methods/users.list

+
+
+def users_lookupByEmail(self, *, email:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_lookupByEmail(
+    self,
+    *,
+    email: str,
+    **kwargs,
+) -> SlackResponse:
+    """Find a user with an email address.
+    https://docs.slack.dev/reference/methods/users.lookupByEmail
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+ +
+
+def users_profile_get(self, *, user:Β strΒ |Β NoneΒ =Β None, include_labels:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_profile_get(
+    self,
+    *,
+    user: Optional[str] = None,
+    include_labels: Optional[bool] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Retrieves a user's profile information.
+    https://docs.slack.dev/reference/methods/users.profile.get
+    """
+    kwargs.update({"user": user, "include_labels": include_labels})
+    return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+

Retrieves a user's profile information. +https://docs.slack.dev/reference/methods/users.profile.get

+
+
+def users_profile_set(self,
*,
name:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
profile:Β DictΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_profile_set(
+    self,
+    *,
+    name: Optional[str] = None,
+    value: Optional[str] = None,
+    user: Optional[str] = None,
+    profile: Optional[Dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the profile information for a user.
+    https://docs.slack.dev/reference/methods/users.profile.set
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "profile": profile,
+            "user": user,
+            "value": value,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "profile" parameter
+    return self.api_call("users.profile.set", json=kwargs)
+
+

Set the profile information for a user. +https://docs.slack.dev/reference/methods/users.profile.set

+
+
+def users_setPhoto(self,
*,
image:Β strΒ |Β io.IOBase,
crop_w:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_x:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_y:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def users_setPhoto(
+    self,
+    *,
+    image: Union[str, IOBase],
+    crop_w: Optional[Union[int, str]] = None,
+    crop_x: Optional[Union[int, str]] = None,
+    crop_y: Optional[Union[int, str]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Set the user profile photo
+    https://docs.slack.dev/reference/methods/users.setPhoto
+    """
+    kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+    return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+ +
+
+def users_setPresence(self, *, presence:Β str, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def users_setPresence(
+    self,
+    *,
+    presence: str,
+    **kwargs,
+) -> SlackResponse:
+    """Manually sets user presence.
+    https://docs.slack.dev/reference/methods/users.setPresence
+    """
+    kwargs.update({"presence": presence})
+    return self.api_call("users.setPresence", params=kwargs)
+
+ +
+
+def views_open(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_open(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Open a view for a user.
+    https://docs.slack.dev/reference/methods/views.open
+    See https://docs.slack.dev/surfaces/modals/ for details.
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.open", json=kwargs)
+
+ +
+
+def views_publish(self,
*,
user_id:Β str,
view:Β dictΒ |Β View,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_publish(
+    self,
+    *,
+    user_id: str,
+    view: Union[dict, View],
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Publish a static view for a User.
+    Create or update the view that comprises an
+    app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+    https://docs.slack.dev/reference/methods/views.publish
+    """
+    kwargs.update({"user_id": user_id, "hash": hash})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.publish", json=kwargs)
+
+

Publish a static view for a User. +Create or update the view that comprises an +app's Home tab (https://docs.slack.dev/surfaces/app-home/) +https://docs.slack.dev/reference/methods/views.publish

+
+
+def views_push(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_push(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> SlackResponse:
+    """Push a view onto the stack of a root view.
+    Push a new view onto the existing view stack by passing a view
+    payload and a valid trigger_id generated from an interaction
+    within the existing modal.
+    Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+    to learn more about the lifecycle and intricacies of views.
+    https://docs.slack.dev/reference/methods/views.push
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.push", json=kwargs)
+
+

Push a view onto the stack of a root view. +Push a new view onto the existing view stack by passing a view +payload and a valid trigger_id generated from an interaction +within the existing modal. +Read the modals documentation (https://docs.slack.dev/surfaces/modals/) +to learn more about the lifecycle and intricacies of views. +https://docs.slack.dev/reference/methods/views.push

+
+
+def views_update(self,
*,
view:Β dictΒ |Β View,
external_id:Β strΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def views_update(
+    self,
+    *,
+    view: Union[dict, View],
+    external_id: Optional[str] = None,
+    view_id: Optional[str] = None,
+    hash: Optional[str] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update an existing view.
+    Update a view by passing a new view definition along with the
+    view_id returned in views.open or the external_id.
+    See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+    to learn more about updating views and avoiding race conditions with the hash argument.
+    https://docs.slack.dev/reference/methods/views.update
+    """
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    if external_id:
+        kwargs.update({"external_id": external_id})
+    elif view_id:
+        kwargs.update({"view_id": view_id})
+    else:
+        raise e.SlackRequestError("Either view_id or external_id is required.")
+    kwargs.update({"hash": hash})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.update", json=kwargs)
+
+

Update an existing view. +Update a view by passing a new view definition along with the +view_id returned in views.open or the external_id. +See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views) +to learn more about updating views and avoiding race conditions with the hash argument. +https://docs.slack.dev/reference/methods/views.update

+
+ +
+
+ +Expand source code + +
def workflows_featured_add(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Add featured workflows to a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.add
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.add", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_list(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """List the featured workflows for specified channels.
+    https://docs.slack.dev/reference/methods/workflows.featured.list
+    """
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("workflows.featured.list", params=kwargs)
+
+

List the featured workflows for specified channels. +https://docs.slack.dev/reference/methods/workflows.featured.list

+
+ +
+
+ +Expand source code + +
def workflows_featured_remove(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Remove featured workflows from a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.remove
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.remove", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_set(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> SlackResponse:
+    """Set featured workflows for a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.set
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.set", params=kwargs)
+
+ +
+
+def workflows_stepCompleted(self, *, workflow_step_execute_id:Β str, outputs:Β dictΒ |Β NoneΒ =Β None, **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepCompleted(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    outputs: Optional[dict] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Indicate a successful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepCompleted
+    """
+    kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "outputs" parameter
+    return self.api_call("workflows.stepCompleted", json=kwargs)
+
+

Indicate a successful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepCompleted

+
+
+def workflows_stepFailed(self, *, workflow_step_execute_id:Β str, error:Β Dict[str,Β str], **kwargs) ‑>Β SlackResponse +
+
+
+ +Expand source code + +
def workflows_stepFailed(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    error: Dict[str, str],
+    **kwargs,
+) -> SlackResponse:
+    """Indicate an unsuccessful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepFailed
+    """
+    kwargs.update(
+        {
+            "workflow_step_execute_id": workflow_step_execute_id,
+            "error": error,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "error" parameter
+    return self.api_call("workflows.stepFailed", json=kwargs)
+
+

Indicate an unsuccessful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepFailed

+
+
+def workflows_updateStep(self,
*,
workflow_step_edit_id:Β str,
inputs:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
outputs:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β SlackResponse
+
+
+
+ +Expand source code + +
def workflows_updateStep(
+    self,
+    *,
+    workflow_step_edit_id: str,
+    inputs: Optional[Dict[str, Any]] = None,
+    outputs: Optional[List[Dict[str, str]]] = None,
+    **kwargs,
+) -> SlackResponse:
+    """Update the configuration for a workflow extension step.
+    https://docs.slack.dev/reference/methods/workflows.updateStep
+    """
+    kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+    if inputs is not None:
+        kwargs.update({"inputs": inputs})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+    return self.api_call("workflows.updateStep", json=kwargs)
+
+

Update the configuration for a workflow extension step. +https://docs.slack.dev/reference/methods/workflows.updateStep

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/web/internal_utils.html b/docs/reference/web/internal_utils.html new file mode 100644 index 000000000..89227edce --- /dev/null +++ b/docs/reference/web/internal_utils.html @@ -0,0 +1,143 @@ + + + + + + +slack_sdk.web.internal_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.internal_utils

+
+
+
+
+
+
+
+
+

Functions

+
+
+def convert_bool_to_0_or_1(params:Β Dict[str,Β Any]Β |Β None) ‑>Β Dict[str,Β Any]Β |Β None +
+
+
+ +Expand source code + +
def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+    """Converts all bool values in dict to "0" or "1".
+
+    Slack APIs safely accept "0"/"1" as boolean values.
+    Using True/False (bool in Python) doesn't work with aiohttp.
+    This method converts only the bool values in top-level of a given dict.
+
+    Args:
+        params: params as a dict
+
+    Returns:
+        Modified dict
+    """
+    if params:
+        return {k: _to_0_or_1_if_bool(v) for k, v in params.items()}
+    return None
+
+

Converts all bool values in dict to "0" or "1".

+

Slack APIs safely accept "0"/"1" as boolean values. +Using True/False (bool in Python) doesn't work with aiohttp. +This method converts only the bool values in top-level of a given dict.

+

Args

+
+
params
+
params as a dict
+
+

Returns

+

Modified dict

+
+
+def get_user_agent(prefix:Β strΒ |Β NoneΒ =Β None, suffix:Β strΒ |Β NoneΒ =Β None) +
+
+
+ +Expand source code + +
def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None):
+    """Construct the user-agent header with the package info,
+    Python version and OS version.
+
+    Returns:
+        The user agent string.
+        e.g. 'Python/3.7.17 slackclient/2.0.0 Darwin/17.7.0'
+    """
+    # __name__ returns all classes, we only want the client
+    client = "{0}/{1}".format("slackclient", version.__version__)
+    python_version = "Python/{v.major}.{v.minor}.{v.micro}".format(v=sys.version_info)
+    system_info = "{0}/{1}".format(platform.system(), platform.release())
+    user_agent_string = " ".join([python_version, client, system_info])
+    prefix = f"{prefix} " if prefix else ""
+    suffix = f" {suffix}" if suffix else ""
+    return prefix + user_agent_string + suffix
+
+

Construct the user-agent header with the package info, +Python version and OS version.

+

Returns

+

The user agent string. +e.g. 'Python/3.7.17 slackclient/2.0.0 Darwin/17.7.0'

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/legacy_base_client.html b/docs/reference/web/legacy_base_client.html new file mode 100644 index 000000000..2abe94377 --- /dev/null +++ b/docs/reference/web/legacy_base_client.html @@ -0,0 +1,896 @@ + + + + + + +slack_sdk.web.legacy_base_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.legacy_base_client

+
+
+

A Python module for interacting with Slack's Web API.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class LegacyBaseClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
loop:Β asyncio.events.AbstractEventLoopΒ |Β NoneΒ =Β None,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
run_async:Β boolΒ =Β False,
use_sync_aiohttp:Β boolΒ =Β False,
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class LegacyBaseClient:
+    BASE_URL = "https://slack.com/api/"
+
+    def __init__(
+        self,
+        token: Optional[str] = None,
+        base_url: str = BASE_URL,
+        timeout: int = 30,
+        loop: Optional[asyncio.AbstractEventLoop] = None,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        run_async: bool = False,
+        use_sync_aiohttp: bool = False,
+        session: Optional[aiohttp.ClientSession] = None,
+        headers: Optional[dict] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        # for Org-Wide App installation
+        team_id: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+    ):
+        self.token = None if token is None else token.strip()
+        """A string specifying an `xoxp-*` or `xoxb-*` token."""
+        if not base_url.endswith("/"):
+            base_url += "/"
+        self.base_url = base_url
+        """A string representing the Slack API base URL.
+        Default is `'https://slack.com/api/'`."""
+        self.timeout = timeout
+        """The maximum number of seconds the client will wait
+        to connect and receive a response from Slack.
+        Default is 30 seconds."""
+        self.ssl = ssl
+        """An [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
+        instance, helpful for specifying your own custom
+        certificate chain."""
+        self.proxy = proxy
+        """String representing a fully-qualified URL to a proxy through which
+        to route all requests to the Slack API. Even if this parameter
+        is not specified, if any of the following environment variables are
+        present, they will be loaded into this parameter: `HTTPS_PROXY`,
+        `https_proxy`, `HTTP_PROXY` or `http_proxy`."""
+        self.run_async = run_async
+        self.use_sync_aiohttp = use_sync_aiohttp
+        self.session = session
+        self.headers = headers or {}
+        """`dict` representing additional request headers to attach to all requests."""
+        self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.default_params = {}
+        if team_id is not None:
+            self.default_params["team_id"] = team_id
+        self._logger = logger if logger is not None else logging.getLogger(__name__)
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self._logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+        self._event_loop = loop
+
+    def api_call(
+        self,
+        api_method: str,
+        *,
+        http_verb: str = "POST",
+        files: Optional[dict] = None,
+        data: Union[dict, FormData] = None,
+        params: Optional[dict] = None,
+        json: Optional[dict] = None,
+        headers: Optional[dict] = None,
+        auth: Optional[dict] = None,
+    ) -> Union[asyncio.Future, SlackResponse]:
+        """Create a request and execute the API call to Slack.
+        Args:
+            api_method (str): The target Slack API method.
+                e.g. 'chat.postMessage'
+            http_verb (str): HTTP Verb. e.g. 'POST'
+            files (dict): Files to multipart upload.
+                e.g. {image OR file: file_object OR file_path}
+            data: The body to attach to the request. If a dictionary is
+                provided, form-encoding will take place.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            params (dict): The URL parameters to append to the URL.
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            json (dict): JSON for the body to attach to the request
+                (if files or data is not specified).
+                e.g. {'key1': 'value1', 'key2': 'value2'}
+            headers (dict): Additional request headers
+            auth (dict): A dictionary that consists of client_id and client_secret
+        Returns:
+            (SlackResponse)
+                The server's response to an HTTP request. Data
+                from the response can be accessed like a dict.
+                If the response included 'next_cursor' it can
+                be iterated on to execute subsequent requests.
+        Raises:
+            SlackApiError: The following Slack API call failed:
+                'chat.postMessage'.
+            SlackRequestError: Json data can only be submitted as
+                POST requests.
+        """
+
+        api_url = _get_url(self.base_url, api_method)
+
+        headers = headers or {}
+        headers.update(self.headers)
+
+        if auth is not None:
+            if isinstance(auth, dict):
+                auth = BasicAuth(auth["client_id"], auth["client_secret"])
+            elif isinstance(auth, BasicAuth):
+                headers["Authorization"] = auth.encode()
+
+        req_args = _build_req_args(
+            token=self.token,
+            http_verb=http_verb,
+            files=files,
+            data=data,
+            default_params=self.default_params,
+            params=params,
+            json=json,
+            headers=headers,
+            auth=auth,
+            ssl=self.ssl,
+            proxy=self.proxy,
+        )
+
+        show_deprecation_warning_if_any(api_method)
+
+        if self.run_async or self.use_sync_aiohttp:
+            if self._event_loop is None:
+                self._event_loop = _get_event_loop()
+
+            future = asyncio.ensure_future(
+                self._send(http_verb=http_verb, api_url=api_url, req_args=req_args),
+                loop=self._event_loop,
+            )
+            if self.run_async:
+                return future
+            if self.use_sync_aiohttp:
+                # Using this is no longer recommended - just keep this for backward-compatibility
+                return self._event_loop.run_until_complete(future)
+
+        return self._sync_send(api_url=api_url, req_args=req_args)
+
+    # =================================================================
+    # aiohttp based async WebClient
+    # =================================================================
+
+    async def _send(self, http_verb: str, api_url: str, req_args: dict) -> SlackResponse:
+        """Sends the request out for transmission.
+        Args:
+            http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
+            api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
+            req_args (dict): The request arguments to be attached to the request.
+            e.g.
+            {
+                json: {
+                    'attachments': [{"pretext": "pre-hello", "text": "text-world"}],
+                    'channel': '#random'
+                }
+            }
+        Returns:
+            The response parsed into a SlackResponse object.
+        """
+        open_files = _files_to_data(req_args)
+        try:
+            if "params" in req_args:
+                # True/False -> "1"/"0"
+                req_args["params"] = convert_bool_to_0_or_1(req_args["params"])
+
+            res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args)
+        finally:
+            for f in open_files:
+                f.close()
+
+        data = {
+            "client": self,
+            "http_verb": http_verb,
+            "api_url": api_url,
+            "req_args": req_args,
+            "use_sync_aiohttp": self.use_sync_aiohttp,
+        }
+        return SlackResponse(**{**data, **res}).validate()
+
+    async def _request(self, *, http_verb, api_url, req_args) -> Dict[str, Any]:
+        """Submit the HTTP request with the running session or a new session.
+        Returns:
+            A dictionary of the response data.
+        """
+        return await _request_with_session(
+            current_session=self.session,
+            timeout=self.timeout,
+            logger=self._logger,
+            http_verb=http_verb,
+            api_url=api_url,
+            req_args=req_args,
+        )
+
+    # =================================================================
+    # urllib based WebClient
+    # =================================================================
+
+    def _sync_send(self, api_url, req_args) -> SlackResponse:
+        params = req_args["params"] if "params" in req_args else None
+        data = req_args["data"] if "data" in req_args else None
+        files = req_args["files"] if "files" in req_args else None
+        _json = req_args["json"] if "json" in req_args else None
+        headers = req_args["headers"] if "headers" in req_args else None
+        token = params.get("token") if params and "token" in params else None
+        auth = req_args["auth"] if "auth" in req_args else None  # Basic Auth for oauth.v2.access / oauth.access
+        if auth is not None:
+            headers = {}
+            if isinstance(auth, BasicAuth):
+                headers["Authorization"] = auth.encode()
+            elif isinstance(auth, str):
+                headers["Authorization"] = auth
+            else:
+                self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped")
+
+        body_params = {}
+        if params:
+            body_params.update(params)
+        if data:
+            body_params.update(data)
+
+        return self._urllib_api_call(
+            token=token,
+            url=api_url,
+            query_params={},
+            body_params=body_params,
+            files=files,
+            json_body=_json,
+            additional_headers=headers,
+        )
+
+    def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
+        """This method is supposed to be used only for SlackResponse pagination
+        You can paginate using Python's for iterator as below:
+          for response in client.conversations_list(limit=100):
+              # do something with each response here
+        """
+        response = self._perform_urllib_http_request(url=api_url, args=req_args)
+        return {
+            "status_code": int(response["status"]),
+            "headers": dict(response["headers"]),
+            "data": json.loads(response["body"]),
+        }
+
+    def _urllib_api_call(
+        self,
+        *,
+        token: Optional[str] = None,
+        url: str,
+        query_params: Dict[str, str],
+        json_body: Dict,
+        body_params: Dict[str, str],
+        files: Dict[str, io.BytesIO],
+        additional_headers: Dict[str, str],
+    ) -> SlackResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            token: Slack API Token (either bot token or user token)
+            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
+            query_params: Query string
+            json_body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            body_params: Form body params
+            files: Files to upload
+            additional_headers: Request headers to append
+        Returns:
+            API response
+        """
+        files_to_close: List[BinaryIO] = []
+        try:
+            # True/False -> "1"/"0"
+            query_params = convert_bool_to_0_or_1(query_params)
+            body_params = convert_bool_to_0_or_1(body_params)
+
+            if self._logger.level <= logging.DEBUG:
+
+                def convert_params(values: dict) -> dict:
+                    if not values or not isinstance(values, dict):
+                        return {}
+                    return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()}
+
+                headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()}
+                self._logger.debug(
+                    f"Sending a request - url: {url}, "
+                    f"query_params: {convert_params(query_params)}, "
+                    f"body_params: {convert_params(body_params)}, "
+                    f"files: {convert_params(files)}, "
+                    f"json_body: {json_body}, "
+                    f"headers: {headers}"
+                )
+
+            request_data = {}
+            if files is not None and isinstance(files, dict) and len(files) > 0:
+                if body_params:
+                    for k, v in body_params.items():
+                        request_data.update({k: v})
+
+                for k, v in files.items():
+                    if isinstance(v, str):
+                        f: BinaryIO = open(v.encode("utf-8", "ignore"), "rb")
+                        files_to_close.append(f)
+                        request_data.update({k: f})
+                    elif isinstance(v, (bytearray, bytes)):
+                        request_data.update({k: io.BytesIO(v)})
+                    else:
+                        request_data.update({k: v})
+
+            request_headers = self._build_urllib_request_headers(
+                token=token or self.token,
+                has_json=json is not None,
+                has_files=files is not None,
+                additional_headers=additional_headers,
+            )
+            request_args = {
+                "headers": request_headers,
+                "data": request_data,
+                "params": body_params,
+                "files": files,
+                "json": json_body,
+            }
+            if query_params:
+                q = urlencode(query_params)
+                url = f"{url}&{q}" if "?" in url else f"{url}?{q}"
+
+            response = self._perform_urllib_http_request(url=url, args=request_args)
+            body = response.get("body", None)
+            response_body_data: Optional[Union[dict, bytes]] = body
+            if body is not None and not isinstance(body, bytes):
+                try:
+                    response_body_data = json.loads(response["body"])
+                except json.decoder.JSONDecodeError:
+                    message = _build_unexpected_body_error_message(response.get("body", ""))
+                    raise err.SlackApiError(message, response)
+
+            all_params: Dict[str, Any] = copy.copy(body_params) if body_params is not None else {}
+            if query_params:
+                all_params.update(query_params)
+            request_args["params"] = all_params  # for backward-compatibility
+
+            return SlackResponse(
+                client=self,
+                http_verb="POST",  # you can use POST method for all the Web APIs
+                api_url=url,
+                req_args=request_args,
+                data=response_body_data,
+                headers=dict(response["headers"]),
+                status_code=response["status"],
+                use_sync_aiohttp=False,
+            ).validate()
+        finally:
+            for f in files_to_close:
+                if not f.closed:
+                    f.close()
+
+    def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
+        """Performs an HTTP request and parses the response.
+
+        Args:
+            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
+            args: args has "headers", "data", "params", and "json"
+                "headers": Dict[str, str]
+                "data": Dict[str, Any]
+                "params": Dict[str, str],
+                "json": Dict[str, Any],
+
+        Returns:
+            dict {status: int, headers: Headers, body: str}
+        """
+        headers = args["headers"]
+        if args["json"]:
+            body = json.dumps(args["json"])
+            headers["Content-Type"] = "application/json;charset=utf-8"
+        elif args["data"]:
+            boundary = f"--------------{uuid.uuid4()}"
+            sep_boundary = b"\r\n--" + boundary.encode("ascii")
+            end_boundary = sep_boundary + b"--\r\n"
+            body = io.BytesIO()
+            data = args["data"]
+            for key, value in data.items():
+                readable = getattr(value, "readable", None)
+                if readable and value.readable():
+                    filename = "Uploaded file"
+                    name_attr = getattr(value, "name", None)
+                    if name_attr:
+                        filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr
+                    if "filename" in data:
+                        filename = data["filename"]
+                    mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
+                    title = (
+                        f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n'
+                        + f"Content-Type: {mimetype}\r\n"
+                    )
+                    value = value.read()
+                else:
+                    title = f'\r\nContent-Disposition: form-data; name="{key}"\r\n'
+                    value = str(value).encode("utf-8")
+                body.write(sep_boundary)
+                body.write(title.encode("utf-8"))
+                body.write(b"\r\n")
+                body.write(value)
+
+            body.write(end_boundary)
+            body = body.getvalue()
+            headers["Content-Type"] = f"multipart/form-data; boundary={boundary}"
+            headers["Content-Length"] = len(body)
+        elif args["params"]:
+            body = urlencode(args["params"])
+            headers["Content-Type"] = "application/x-www-form-urlencoded"
+        else:
+            body = None
+
+        if isinstance(body, str):
+            body = body.encode("utf-8")
+
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        try:
+            # urllib not only opens http:// or https:// URLs, but also ftp:// and file://.
+            # With this it might be possible to open local files on the executing machine
+            # which might be a security risk if the URL to open can be manipulated by an external user.
+            # (BAN-B310)
+            if url.lower().startswith("http"):
+                req = Request(method="POST", url=url, data=body, headers=headers)
+                opener: Optional[OpenerDirector] = None
+                if self.proxy is not None:
+                    if isinstance(self.proxy, str):
+                        opener = urllib.request.build_opener(
+                            ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                            HTTPSHandler(context=self.ssl),
+                        )
+                    else:
+                        raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+
+                # NOTE: BAN-B310 is already checked above
+                resp: Optional[HTTPResponse] = None
+                if opener:
+                    resp = opener.open(req, timeout=self.timeout)
+                else:
+                    resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+                if resp.headers.get_content_type() == "application/gzip":
+                    # admin.analytics.getFile
+                    body: bytes = resp.read()
+                    return {"status": resp.code, "headers": resp.headers, "body": body}
+
+                charset = resp.headers.get_content_charset() or "utf-8"
+                body: str = resp.read().decode(charset)  # read the response body here
+                return {"status": resp.code, "headers": resp.headers, "body": body}
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+        except HTTPError as e:
+            # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+            response_headers = dict(e.headers.items())
+            resp = {"status": e.code, "headers": response_headers}
+            if e.code == 429:
+                # for compatibility with aiohttp
+                if "retry-after" not in response_headers and "Retry-After" in response_headers:
+                    response_headers["retry-after"] = response_headers["Retry-After"]
+                if "Retry-After" not in response_headers and "retry-after" in response_headers:
+                    response_headers["Retry-After"] = response_headers["retry-after"]
+
+            # read the response body here
+            charset = e.headers.get_content_charset() or "utf-8"
+            body: str = e.read().decode(charset)
+            resp["body"] = body
+            return resp
+
+        except Exception as err:
+            self._logger.error(f"Failed to send a request to Slack API server: {err}")
+            raise err
+
+    def _build_urllib_request_headers(
+        self, token: str, has_json: bool, has_files: bool, additional_headers: dict
+    ) -> Dict[str, str]:
+        headers = {"Content-Type": "application/x-www-form-urlencoded"}
+        headers.update(self.headers)
+        if token:
+            headers.update({"Authorization": "Bearer {}".format(token)})
+        if additional_headers:
+            headers.update(additional_headers)
+        if has_json:
+            headers.update({"Content-Type": "application/json;charset=utf-8"})
+        if has_files:
+            # will be set afterward
+            headers.pop("Content-Type", None)
+        return headers
+
+    def _upload_file(
+        self,
+        *,
+        url: str,
+        data: bytes,
+        logger: logging.Logger,
+        timeout: int,
+        proxy: Optional[str],
+        ssl: Optional[SSLContext],
+    ) -> FileUploadV2Result:
+        result = _upload_file_via_v2_url(
+            url=url,
+            data=data,
+            logger=logger,
+            timeout=timeout,
+            proxy=proxy,
+            ssl=ssl,
+        )
+        return FileUploadV2Result(
+            status=result.get("status"),
+            body=result.get("body"),
+        )
+
+    # =================================================================
+
+    @staticmethod
+    def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool:
+        """
+        Slack creates a unique string for your app and shares it with you. Verify
+        requests from Slack with confidence by verifying signatures using your
+        signing secret.
+        On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP
+        header. The signature is created by combining the signing secret with the
+        body of the request we're sending using a standard HMAC-SHA256 keyed hash.
+        https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview
+        Args:
+            signing_secret: Your application's signing secret, available in the
+                Slack API dashboard
+            data: The raw body of the incoming request - no headers, just the body.
+            timestamp: from the 'X-Slack-Request-Timestamp' header
+            signature: from the 'X-Slack-Signature' header - the calculated signature
+                should match this.
+        Returns:
+            True if signatures matches
+        """
+        warnings.warn(
+            "As this method is deprecated since slackclient 2.6.0, "
+            "use `from slack.signature import SignatureVerifier` instead",
+            DeprecationWarning,
+        )
+        format_req = str.encode(f"v0:{timestamp}:{data}")
+        encoded_secret = str.encode(signing_secret)
+        request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+        calculated_signature = f"v0={request_hash}"
+        return hmac.compare_digest(calculated_signature, signature)
+
+
+

Subclasses

+ +

Class variables

+
+
var BASE_URL
+
+

The type of the None singleton.

+
+
+

Static methods

+
+
+def validate_slack_signature(*, signing_secret:Β str, data:Β str, timestamp:Β str, signature:Β str) ‑>Β bool +
+
+
+ +Expand source code + +
@staticmethod
+def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool:
+    """
+    Slack creates a unique string for your app and shares it with you. Verify
+    requests from Slack with confidence by verifying signatures using your
+    signing secret.
+    On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP
+    header. The signature is created by combining the signing secret with the
+    body of the request we're sending using a standard HMAC-SHA256 keyed hash.
+    https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview
+    Args:
+        signing_secret: Your application's signing secret, available in the
+            Slack API dashboard
+        data: The raw body of the incoming request - no headers, just the body.
+        timestamp: from the 'X-Slack-Request-Timestamp' header
+        signature: from the 'X-Slack-Signature' header - the calculated signature
+            should match this.
+    Returns:
+        True if signatures matches
+    """
+    warnings.warn(
+        "As this method is deprecated since slackclient 2.6.0, "
+        "use `from slack.signature import SignatureVerifier` instead",
+        DeprecationWarning,
+    )
+    format_req = str.encode(f"v0:{timestamp}:{data}")
+    encoded_secret = str.encode(signing_secret)
+    request_hash = hmac.new(encoded_secret, format_req, hashlib.sha256).hexdigest()
+    calculated_signature = f"v0={request_hash}"
+    return hmac.compare_digest(calculated_signature, signature)
+
+

Slack creates a unique string for your app and shares it with you. Verify +requests from Slack with confidence by verifying signatures using your +signing secret. +On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP +header. The signature is created by combining the signing secret with the +body of the request we're sending using a standard HMAC-SHA256 keyed hash. +https://docs.slack.dev/authentication/verifying-requests-from-slack/#how_to_make_a_request_signature_in_4_easy_steps__an_overview

+

Args

+
+
signing_secret
+
Your application's signing secret, available in the +Slack API dashboard
+
data
+
The raw body of the incoming request - no headers, just the body.
+
timestamp
+
from the 'X-Slack-Request-Timestamp' header
+
signature
+
from the 'X-Slack-Signature' header - the calculated signature +should match this.
+
+

Returns

+

True if signatures matches

+
+
+

Instance variables

+
+
var base_url
+
+

A string representing the Slack API base URL. +Default is 'https://slack.com/api/'.

+
+
var headers
+
+

dict representing additional request headers to attach to all requests.

+
+
var proxy
+
+

String representing a fully-qualified URL to a proxy through which +to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.

+
+
var ssl
+
+

An ssl.SSLContext +instance, helpful for specifying your own custom +certificate chain.

+
+
var timeout
+
+

The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.

+
+
var token
+
+

A string specifying an xoxp-* or xoxb-* token.

+
+
+

Methods

+
+
+def api_call(self,
api_method:Β str,
*,
http_verb:Β strΒ =Β 'POST',
files:Β dictΒ |Β NoneΒ =Β None,
data:Β dictΒ |Β aiohttp.formdata.FormDataΒ =Β None,
params:Β dictΒ |Β NoneΒ =Β None,
json:Β dictΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
auth:Β dictΒ |Β NoneΒ =Β None) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def api_call(
+    self,
+    api_method: str,
+    *,
+    http_verb: str = "POST",
+    files: Optional[dict] = None,
+    data: Union[dict, FormData] = None,
+    params: Optional[dict] = None,
+    json: Optional[dict] = None,
+    headers: Optional[dict] = None,
+    auth: Optional[dict] = None,
+) -> Union[asyncio.Future, SlackResponse]:
+    """Create a request and execute the API call to Slack.
+    Args:
+        api_method (str): The target Slack API method.
+            e.g. 'chat.postMessage'
+        http_verb (str): HTTP Verb. e.g. 'POST'
+        files (dict): Files to multipart upload.
+            e.g. {image OR file: file_object OR file_path}
+        data: The body to attach to the request. If a dictionary is
+            provided, form-encoding will take place.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        params (dict): The URL parameters to append to the URL.
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        json (dict): JSON for the body to attach to the request
+            (if files or data is not specified).
+            e.g. {'key1': 'value1', 'key2': 'value2'}
+        headers (dict): Additional request headers
+        auth (dict): A dictionary that consists of client_id and client_secret
+    Returns:
+        (SlackResponse)
+            The server's response to an HTTP request. Data
+            from the response can be accessed like a dict.
+            If the response included 'next_cursor' it can
+            be iterated on to execute subsequent requests.
+    Raises:
+        SlackApiError: The following Slack API call failed:
+            'chat.postMessage'.
+        SlackRequestError: Json data can only be submitted as
+            POST requests.
+    """
+
+    api_url = _get_url(self.base_url, api_method)
+
+    headers = headers or {}
+    headers.update(self.headers)
+
+    if auth is not None:
+        if isinstance(auth, dict):
+            auth = BasicAuth(auth["client_id"], auth["client_secret"])
+        elif isinstance(auth, BasicAuth):
+            headers["Authorization"] = auth.encode()
+
+    req_args = _build_req_args(
+        token=self.token,
+        http_verb=http_verb,
+        files=files,
+        data=data,
+        default_params=self.default_params,
+        params=params,
+        json=json,
+        headers=headers,
+        auth=auth,
+        ssl=self.ssl,
+        proxy=self.proxy,
+    )
+
+    show_deprecation_warning_if_any(api_method)
+
+    if self.run_async or self.use_sync_aiohttp:
+        if self._event_loop is None:
+            self._event_loop = _get_event_loop()
+
+        future = asyncio.ensure_future(
+            self._send(http_verb=http_verb, api_url=api_url, req_args=req_args),
+            loop=self._event_loop,
+        )
+        if self.run_async:
+            return future
+        if self.use_sync_aiohttp:
+            # Using this is no longer recommended - just keep this for backward-compatibility
+            return self._event_loop.run_until_complete(future)
+
+    return self._sync_send(api_url=api_url, req_args=req_args)
+
+

Create a request and execute the API call to Slack.

+

Args

+
+
api_method : str
+
The target Slack API method. +e.g. 'chat.postMessage'
+
http_verb : str
+
HTTP Verb. e.g. 'POST'
+
files : dict
+
Files to multipart upload. +e.g. {image OR file: file_object OR file_path}
+
data
+
The body to attach to the request. If a dictionary is +provided, form-encoding will take place. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
params : dict
+
The URL parameters to append to the URL. +e.g. {'key1': 'value1', 'key2': 'value2'}
+
json : dict
+
JSON for the body to attach to the request +(if files or data is not specified). +e.g. {'key1': 'value1', 'key2': 'value2'}
+
headers : dict
+
Additional request headers
+
auth : dict
+
A dictionary that consists of client_id and client_secret
+
+

Returns

+

(SlackResponse) +The server's response to an HTTP request. Data +from the response can be accessed like a dict. +If the response included 'next_cursor' it can +be iterated on to execute subsequent requests.

+

Raises

+
+
SlackApiError
+
The following Slack API call failed: +'chat.postMessage'.
+
SlackRequestError
+
Json data can only be submitted as +POST requests.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/legacy_client.html b/docs/reference/web/legacy_client.html new file mode 100644 index 000000000..d100178dc --- /dev/null +++ b/docs/reference/web/legacy_client.html @@ -0,0 +1,15605 @@ + + + + + + +slack_sdk.web.legacy_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.legacy_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class LegacyWebClient +(token:Β strΒ |Β NoneΒ =Β None,
base_url:Β strΒ =Β 'https://slack.com/api/',
timeout:Β intΒ =Β 30,
loop:Β asyncio.events.AbstractEventLoopΒ |Β NoneΒ =Β None,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
run_async:Β boolΒ =Β False,
use_sync_aiohttp:Β boolΒ =Β False,
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
headers:Β dictΒ |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class LegacyWebClient(LegacyBaseClient):
+    """A WebClient allows apps to communicate with the Slack Platform's Web API.
+
+    https://docs.slack.dev/reference/methods
+
+    The Slack Web API is an interface for querying information from
+    and enacting change in a Slack workspace.
+
+    This client handles constructing and sending HTTP requests to Slack
+    as well as parsing any responses received into a `SlackResponse`.
+
+    Attributes:
+        token (str): A string specifying an `xoxp-*` or `xoxb-*` token.
+        base_url (str): A string representing the Slack API base URL.
+            Default is `'https://slack.com/api/'`
+        timeout (int): The maximum number of seconds the client will wait
+            to connect and receive a response from Slack.
+            Default is 30 seconds.
+        ssl (SSLContext): An [`ssl.SSLContext`][1] instance, helpful for specifying
+            your own custom certificate chain.
+        proxy (str): String representing a fully-qualified URL to a proxy through
+            which to route all requests to the Slack API. Even if this parameter
+            is not specified, if any of the following environment variables are
+            present, they will be loaded into this parameter: `HTTPS_PROXY`,
+            `https_proxy`, `HTTP_PROXY` or `http_proxy`.
+        headers (dict): Additional request headers to attach to all requests.
+
+    Methods:
+        `api_call`: Constructs a request and executes the API call to Slack.
+
+    Example of recommended usage:
+    ```python
+        import os
+        from slack_sdk.web.legacy_client import LegacyWebClient
+
+        client = LegacyWebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.chat_postMessage(
+            channel='#random',
+            text="Hello world!")
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Example manually creating an API request:
+    ```python
+        import os
+        from slack_sdk.web.legacy_client import LegacyWebClient
+
+        client = LegacyWebClient(token=os.environ['SLACK_API_TOKEN'])
+        response = client.api_call(
+            api_method='chat.postMessage',
+            json={'channel': '#random','text': "Hello world!"}
+        )
+        assert response["ok"]
+        assert response["message"]["text"] == "Hello world!"
+    ```
+
+    Note:
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+
+    [1]: https://docs.python.org/3/library/ssl.html#ssl.SSLContext
+    """
+
+    def admin_analytics_getFile(
+        self,
+        *,
+        type: str,
+        date: Optional[str] = None,
+        metadata_only: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve analytics data for a given date, presented as a compressed JSON file
+        https://docs.slack.dev/reference/methods/admin.analytics.getFile
+        """
+        kwargs.update({"type": type})
+        if date is not None:
+            kwargs.update({"date": date})
+        if metadata_only is not None:
+            kwargs.update({"metadata_only": metadata_only})
+        return self.api_call("admin.analytics.getFile", params=kwargs)
+
+    def admin_apps_approve(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Approve an app for installation on a workspace.
+        Either app_id or request_id is required.
+        These IDs can be obtained either directly via the app_requested event,
+        or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.approve
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approve", params=kwargs)
+
+    def admin_apps_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List approved apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_clearResolution(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Clear an app resolution
+        https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_cancel(
+        self,
+        *,
+        request_id: str,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+        """
+        kwargs.update(
+            {
+                "request_id": request_id,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+    def admin_apps_requests_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List app requests for a team/workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.requests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_restrict(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        request_id: Optional[str] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Restrict an app for installation on a workspace.
+        Exactly one of the team_id or enterprise_id arguments is required, not both.
+        Either app_id or request_id is required. These IDs can be obtained either directly
+        via the app_requested event, or by the admin.apps.requests.list method.
+        https://docs.slack.dev/reference/methods/admin.apps.restrict
+        """
+        if app_id:
+            kwargs.update({"app_id": app_id})
+        elif request_id:
+            kwargs.update({"request_id": request_id})
+        else:
+            raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+        kwargs.update(
+            {
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restrict", params=kwargs)
+
+    def admin_apps_restricted_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        enterprise_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List restricted apps for an org or workspace.
+        https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "enterprise_id": enterprise_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+    def admin_apps_uninstall(
+        self,
+        *,
+        app_id: str,
+        enterprise_id: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+        With an org-level token, enterprise_id or team_ids is required.
+        https://docs.slack.dev/reference/methods/admin.apps.uninstall
+        """
+        kwargs.update({"app_id": app_id})
+        if enterprise_id is not None:
+            kwargs.update({"enterprise_id": enterprise_id})
+        if team_ids is not None:
+            if isinstance(team_ids, (list, tuple)):
+                kwargs.update({"team_ids": ",".join(team_ids)})
+            else:
+                kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+    def admin_apps_activities_list(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        component_id: Optional[str] = None,
+        component_type: Optional[str] = None,
+        log_event_type: Optional[str] = None,
+        max_date_created: Optional[int] = None,
+        min_date_created: Optional[int] = None,
+        min_log_level: Optional[str] = None,
+        sort_direction: Optional[str] = None,
+        source: Optional[str] = None,
+        team_id: Optional[str] = None,
+        trace_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get logs for a specified team/org
+        https://docs.slack.dev/reference/methods/admin.apps.activities.list
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "component_id": component_id,
+                "component_type": component_type,
+                "log_event_type": log_event_type,
+                "max_date_created": max_date_created,
+                "min_date_created": min_date_created,
+                "min_log_level": min_log_level,
+                "sort_direction": sort_direction,
+                "source": source,
+                "team_id": team_id,
+                "trace_id": trace_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.apps.activities.list", params=kwargs)
+
+    def admin_apps_config_lookup(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Look up the app config for connectors by their IDs
+        https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+    def admin_apps_config_set(
+        self,
+        *,
+        app_id: str,
+        domain_restrictions: Optional[Dict[str, Any]] = None,
+        workflow_auth_strategy: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the app config for a connector
+        https://docs.slack.dev/reference/methods/admin.apps.config.set
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "workflow_auth_strategy": workflow_auth_strategy,
+            }
+        )
+        if domain_restrictions is not None:
+            kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+        return self.api_call("admin.apps.config.set", params=kwargs)
+
+    def admin_auth_policy_getEntities(
+        self,
+        *,
+        policy_name: str,
+        cursor: Optional[str] = None,
+        entity_type: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetch all the entities assigned to a particular authentication policy by name.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+        """
+        kwargs.update({"policy_name": policy_name})
+        if cursor is not None:
+            kwargs.update({"cursor": cursor})
+        if entity_type is not None:
+            kwargs.update({"entity_type": entity_type})
+        if limit is not None:
+            kwargs.update({"limit": limit})
+        return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_assignEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Assign entities to a particular authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+    def admin_auth_policy_removeEntities(
+        self,
+        *,
+        entity_ids: Union[str, Sequence[str]],
+        policy_name: str,
+        entity_type: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove specified entities from a specified authentication policy.
+        https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+        """
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        kwargs.update({"policy_name": policy_name})
+        kwargs.update({"entity_type": entity_type})
+        return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+    def admin_conversations_createForObjects(
+        self,
+        *,
+        object_id: str,
+        salesforce_org_id: str,
+        invite_object_team: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create a Salesforce channel for the corresponding object provided.
+        https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+        """
+        kwargs.update(
+            {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+        )
+        return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+    def admin_conversations_linkObjects(
+        self,
+        *,
+        channel: str,
+        record_id: str,
+        salesforce_org_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Link a Salesforce record to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "record_id": record_id,
+                "salesforce_org_id": salesforce_org_id,
+            }
+        )
+        return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+    def admin_conversations_unlinkObjects(
+        self,
+        *,
+        channel: str,
+        new_name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Unlink a Salesforce record from a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "new_name": new_name,
+            }
+        )
+        return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+    def admin_barriers_create(
+        self,
+        *,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create an Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.create
+        """
+        kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+    def admin_barriers_delete(
+        self,
+        *,
+        barrier_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Delete an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.delete
+        """
+        kwargs.update({"barrier_id": barrier_id})
+        return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+    def admin_barriers_update(
+        self,
+        *,
+        barrier_id: str,
+        barriered_from_usergroup_ids: Union[str, Sequence[str]],
+        primary_usergroup_id: str,
+        restricted_subjects: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update an existing Information Barrier
+        https://docs.slack.dev/reference/methods/admin.barriers.update
+        """
+        kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+        if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+            kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+        else:
+            kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+        if isinstance(restricted_subjects, (list, tuple)):
+            kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+        else:
+            kwargs.update({"restricted_subjects": restricted_subjects})
+        return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+    def admin_barriers_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get all Information Barriers for your organization
+        https://docs.slack.dev/reference/methods/admin.barriers.list"""
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+    def admin_conversations_create(
+        self,
+        *,
+        is_private: bool,
+        name: str,
+        description: Optional[str] = None,
+        org_wide: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create a public or private channel-based conversation.
+        https://docs.slack.dev/reference/methods/admin.conversations.create
+        """
+        kwargs.update(
+            {
+                "is_private": is_private,
+                "name": name,
+                "description": description,
+                "org_wide": org_wide,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.conversations.create", params=kwargs)
+
+    def admin_conversations_delete(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Delete a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.delete
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.delete", params=kwargs)
+
+    def admin_conversations_invite(
+        self,
+        *,
+        channel_id: str,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invite a user to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.invite
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+        return self.api_call("admin.conversations.invite", params=kwargs)
+
+    def admin_conversations_archive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Archive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.archive", params=kwargs)
+
+    def admin_conversations_unarchive(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Unarchive a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.archive
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+    def admin_conversations_rename(
+        self,
+        *,
+        channel_id: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Rename a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.rename
+        """
+        kwargs.update({"channel_id": channel_id, "name": name})
+        return self.api_call("admin.conversations.rename", params=kwargs)
+
+    def admin_conversations_search(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        query: Optional[str] = None,
+        search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Search for public or private channels in an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.conversations.search
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+            }
+        )
+
+        if isinstance(search_channel_types, (list, tuple)):
+            kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+        else:
+            kwargs.update({"search_channel_types": search_channel_types})
+
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+
+        return self.api_call("admin.conversations.search", params=kwargs)
+
+    def admin_conversations_convertToPrivate(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Convert a public channel to a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+    def admin_conversations_convertToPublic(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Convert a privte channel to a public channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+    def admin_conversations_setConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        prefs: Union[str, Dict[str, str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the posting permissions for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(prefs, dict):
+            kwargs.update({"prefs": json.dumps(prefs)})
+        else:
+            kwargs.update({"prefs": prefs})
+        return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+    def admin_conversations_getConversationPrefs(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get conversation preferences for a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+    def admin_conversations_disconnectShared(
+        self,
+        *,
+        channel_id: str,
+        leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Disconnect a connected channel from one or more workspaces.
+        https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(leaving_team_ids, (list, tuple)):
+            kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+        else:
+            kwargs.update({"leaving_team_ids": leaving_team_ids})
+        return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+    def admin_conversations_lookup(
+        self,
+        *,
+        last_message_activity_before: int,
+        team_ids: Union[str, Sequence[str]],
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        max_member_count: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Returns channels on the given team using the filters.
+        https://docs.slack.dev/reference/methods/admin.conversations.lookup
+        """
+        kwargs.update(
+            {
+                "last_message_activity_before": last_message_activity_before,
+                "cursor": cursor,
+                "limit": limit,
+                "max_member_count": max_member_count,
+            }
+        )
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.lookup", params=kwargs)
+
+    def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+        self,
+        *,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all disconnected channelsβ€”i.e.,
+        channels that were once connected to other workspaces and then disconnectedβ€”and
+        the corresponding original channel IDs for key revocation with EKM.
+        https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+    def admin_conversations_restrictAccess_addGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add an allowlist of IDP groups for accessing a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.addGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_listGroups(
+        self,
+        *,
+        channel_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all IDP Groups linked to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.listGroups",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_restrictAccess_removeGroup(
+        self,
+        *,
+        channel_id: str,
+        group_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove a linked IDP group linked from a private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "group_id": group_id,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call(
+            "admin.conversations.restrictAccess.removeGroup",
+            http_verb="GET",
+            params=kwargs,
+        )
+
+    def admin_conversations_setTeams(
+        self,
+        *,
+        channel_id: str,
+        org_channel: Optional[bool] = None,
+        target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "org_channel": org_channel,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(target_team_ids, (list, tuple)):
+            kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+        else:
+            kwargs.update({"target_team_ids": target_team_ids})
+        return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+    def admin_conversations_getTeams(
+        self,
+        *,
+        channel_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the workspaces in an Enterprise grid org that connect to a channel.
+        https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+    def admin_conversations_getCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+    def admin_conversations_removeCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+    def admin_conversations_setCustomRetention(
+        self,
+        *,
+        channel_id: str,
+        duration_days: int,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set a channel's retention policy
+        https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+        """
+        kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+        return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+    def admin_conversations_bulkArchive(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Archive public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+    def admin_conversations_bulkDelete(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Delete public or private channels in bulk.
+        https://slack.com/api/admin.conversations.bulkDelete
+        """
+        kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+        return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+    def admin_conversations_bulkMove(
+        self,
+        *,
+        channel_ids: Union[Sequence[str], str],
+        target_team_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Move public or private channels in bulk.
+        https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+        """
+        kwargs.update(
+            {
+                "target_team_id": target_team_id,
+                "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+            }
+        )
+        return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+    def admin_emoji_add(
+        self,
+        *,
+        name: str,
+        url: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.add
+        """
+        kwargs.update({"name": name, "url": url})
+        return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+    def admin_emoji_addAlias(
+        self,
+        *,
+        alias_for: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add an emoji alias.
+        https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+        """
+        kwargs.update({"alias_for": alias_for, "name": name})
+        return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+    def admin_emoji_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List emoji for an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+    def admin_emoji_remove(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove an emoji across an Enterprise Grid organization.
+        https://docs.slack.dev/reference/methods/admin.emoji.remove
+        """
+        kwargs.update({"name": name})
+        return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+    def admin_emoji_rename(
+        self,
+        *,
+        name: str,
+        new_name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Rename an emoji.
+        https://docs.slack.dev/reference/methods/admin.emoji.rename
+        """
+        kwargs.update({"name": name, "new_name": new_name})
+        return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+    def admin_functions_list(
+        self,
+        *,
+        app_ids: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Look up functions by a set of apps
+        https://docs.slack.dev/reference/methods/admin.functions.list
+        """
+        if isinstance(app_ids, (list, tuple)):
+            kwargs.update({"app_ids": ",".join(app_ids)})
+        else:
+            kwargs.update({"app_ids": app_ids})
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.functions.list", params=kwargs)
+
+    def admin_functions_permissions_lookup(
+        self,
+        *,
+        function_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lookup the visibility of multiple Slack functions
+        and include the users if it is limited to particular named entities.
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+        """
+        if isinstance(function_ids, (list, tuple)):
+            kwargs.update({"function_ids": ",".join(function_ids)})
+        else:
+            kwargs.update({"function_ids": function_ids})
+        return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+    def admin_functions_permissions_set(
+        self,
+        *,
+        function_id: str,
+        visibility: str,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the visibility of a Slack function
+        and define the users or workspaces if it is set to named_entities
+        https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+        """
+        kwargs.update(
+            {
+                "function_id": function_id,
+                "visibility": visibility,
+            }
+        )
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+    def admin_roles_addAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Adds members to the specified role with the specified scopes
+        https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+    def admin_roles_listAssignments(
+        self,
+        *,
+        role_ids: Optional[Union[str, Sequence[str]]] = None,
+        entity_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[Union[str, int]] = None,
+        sort_dir: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists assignments for all roles across entities.
+            Options to scope results by any combination of roles or entities
+        https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(role_ids, (list, tuple)):
+            kwargs.update({"role_ids": ",".join(role_ids)})
+        else:
+            kwargs.update({"role_ids": role_ids})
+        return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+    def admin_roles_removeAssignments(
+        self,
+        *,
+        role_id: str,
+        entity_ids: Union[str, Sequence[str]],
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a set of users from a role for the given scopes and entities
+        https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+        """
+        kwargs.update({"role_id": role_id})
+        if isinstance(entity_ids, (list, tuple)):
+            kwargs.update({"entity_ids": ",".join(entity_ids)})
+        else:
+            kwargs.update({"entity_ids": entity_ids})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+    def admin_users_session_reset(
+        self,
+        *,
+        user_id: str,
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Wipes all valid sessions on all devices for a given user.
+        https://docs.slack.dev/reference/methods/admin.users.session.reset
+        """
+        kwargs.update(
+            {
+                "user_id": user_id,
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.reset", params=kwargs)
+
+    def admin_users_session_resetBulk(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        mobile_only: Optional[bool] = None,
+        web_only: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+        https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "mobile_only": mobile_only,
+                "web_only": web_only,
+            }
+        )
+        return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+    def admin_users_session_invalidate(
+        self,
+        *,
+        session_id: str,
+        team_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invalidate a single session for a user by session_id.
+        https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+        """
+        kwargs.update({"session_id": session_id, "team_id": team_id})
+        return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+    def admin_users_session_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all active user sessions for an organization
+        https://docs.slack.dev/reference/methods/admin.users.session.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+                "user_id": user_id,
+            }
+        )
+        return self.api_call("admin.users.session.list", params=kwargs)
+
+    def admin_teams_settings_setDefaultChannels(
+        self,
+        *,
+        team_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the default channels of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+        """
+        kwargs.update({"team_id": team_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+    def admin_users_session_getSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”given a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+    def admin_users_session_setSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        desktop_app_browser_quit: Optional[bool] = None,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Configure the user-level session settingsβ€”the session duration
+        and what happens when the client closesβ€”for one or more users.
+        https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        kwargs.update(
+            {
+                "desktop_app_browser_quit": desktop_app_browser_quit,
+                "duration": duration,
+            }
+        )
+        return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+    def admin_users_session_clearSettings(
+        self,
+        *,
+        user_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Clear user-specific session settingsβ€”the session duration
+        and what happens when the client closesβ€”for a list of users.
+        https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+        """
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+    def admin_users_unsupportedVersions_export(
+        self,
+        *,
+        date_end_of_support: Optional[Union[str, int]] = None,
+        date_sessions_started: Optional[Union[str, int]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+        presented as a zipped CSV file.
+        https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+        """
+        kwargs.update(
+            {
+                "date_end_of_support": date_end_of_support,
+                "date_sessions_started": date_sessions_started,
+            }
+        )
+        return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+    def admin_inviteRequests_approve(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Approve a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+    def admin_inviteRequests_approved_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all approved workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+    def admin_inviteRequests_denied_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all denied workspace invite requests.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+    def admin_inviteRequests_deny(
+        self,
+        *,
+        invite_request_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deny a workspace invite request.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+        """
+        kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+        return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+    def admin_inviteRequests_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all pending workspace invite requests."""
+        return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+    def admin_teams_admins_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_create(
+        self,
+        *,
+        team_domain: str,
+        team_name: str,
+        team_description: Optional[str] = None,
+        team_discoverability: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create an Enterprise team.
+        https://docs.slack.dev/reference/methods/admin.teams.create
+        """
+        kwargs.update(
+            {
+                "team_domain": team_domain,
+                "team_name": team_name,
+                "team_description": team_description,
+                "team_discoverability": team_discoverability,
+            }
+        )
+        return self.api_call("admin.teams.create", params=kwargs)
+
+    def admin_teams_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all teams on an Enterprise organization.
+        https://docs.slack.dev/reference/methods/admin.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.list", params=kwargs)
+
+    def admin_teams_owners_list(
+        self,
+        *,
+        team_id: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all of the admins on a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.owners.list
+        """
+        kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+        return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_info(
+        self,
+        *,
+        team_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetch information about settings in a workspace
+        https://docs.slack.dev/reference/methods/admin.teams.settings.info
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("admin.teams.settings.info", params=kwargs)
+
+    def admin_teams_settings_setDescription(
+        self,
+        *,
+        team_id: str,
+        description: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the description of a given workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+        """
+        kwargs.update({"team_id": team_id, "description": description})
+        return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+    def admin_teams_settings_setDiscoverability(
+        self,
+        *,
+        team_id: str,
+        discoverability: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+        """
+        kwargs.update({"team_id": team_id, "discoverability": discoverability})
+        return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+    def admin_teams_settings_setIcon(
+        self,
+        *,
+        team_id: str,
+        image_url: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+        """
+        kwargs.update({"team_id": team_id, "image_url": image_url})
+        return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+    def admin_teams_settings_setName(
+        self,
+        *,
+        team_id: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the icon of a workspace.
+        https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+        """
+        kwargs.update({"team_id": team_id, "name": name})
+        return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+    def admin_usergroups_addChannels(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        usergroup_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+        """
+        kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+    def admin_usergroups_addTeams(
+        self,
+        *,
+        usergroup_id: str,
+        team_ids: Union[str, Sequence[str]],
+        auto_provision: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Associate one or more default workspaces with an organization-wide IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+        """
+        kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+        return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+    def admin_usergroups_listChannels(
+        self,
+        *,
+        usergroup_id: str,
+        include_num_members: Optional[bool] = None,
+        team_id: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+        """
+        kwargs.update(
+            {
+                "usergroup_id": usergroup_id,
+                "include_num_members": include_num_members,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+    def admin_usergroups_removeChannels(
+        self,
+        *,
+        usergroup_id: str,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add one or more default channels to an IDP group.
+        https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+        """
+        kwargs.update({"usergroup_id": usergroup_id})
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+    def admin_users_assign(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        channel_ids: Optional[Union[str, Sequence[str]]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add an Enterprise user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.assign
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "user_id": user_id,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.assign", params=kwargs)
+
+    def admin_users_invite(
+        self,
+        *,
+        team_id: str,
+        email: str,
+        channel_ids: Union[str, Sequence[str]],
+        custom_message: Optional[str] = None,
+        email_password_policy_enabled: Optional[bool] = None,
+        guest_expiration_ts: Optional[Union[str, float]] = None,
+        is_restricted: Optional[bool] = None,
+        is_ultra_restricted: Optional[bool] = None,
+        real_name: Optional[str] = None,
+        resend: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invite a user to a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.invite
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "email": email,
+                "custom_message": custom_message,
+                "email_password_policy_enabled": email_password_policy_enabled,
+                "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+                "is_restricted": is_restricted,
+                "is_ultra_restricted": is_ultra_restricted,
+                "real_name": real_name,
+                "resend": resend,
+            }
+        )
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("admin.users.invite", params=kwargs)
+
+    def admin_users_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        include_deactivated_user_workspaces: Optional[bool] = None,
+        is_active: Optional[bool] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List users on a workspace
+        https://docs.slack.dev/reference/methods/admin.users.list
+        """
+        kwargs.update(
+            {
+                "team_id": team_id,
+                "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+                "is_active": is_active,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("admin.users.list", params=kwargs)
+
+    def admin_users_remove(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove a user from a workspace.
+        https://docs.slack.dev/reference/methods/admin.users.remove
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.remove", params=kwargs)
+
+    def admin_users_setAdmin(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set an existing guest, regular user, or owner to be an admin user.
+        https://docs.slack.dev/reference/methods/admin.users.setAdmin
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setAdmin", params=kwargs)
+
+    def admin_users_setExpiration(
+        self,
+        *,
+        expiration_ts: int,
+        user_id: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set an expiration for a guest user.
+        https://docs.slack.dev/reference/methods/admin.users.setExpiration
+        """
+        kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setExpiration", params=kwargs)
+
+    def admin_users_setOwner(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set an existing guest, regular user, or admin user to be a workspace owner.
+        https://docs.slack.dev/reference/methods/admin.users.setOwner
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setOwner", params=kwargs)
+
+    def admin_users_setRegular(
+        self,
+        *,
+        team_id: str,
+        user_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set an existing guest user, admin user, or owner to be a regular user.
+        https://docs.slack.dev/reference/methods/admin.users.setRegular
+        """
+        kwargs.update({"team_id": team_id, "user_id": user_id})
+        return self.api_call("admin.users.setRegular", params=kwargs)
+
+    def admin_workflows_search(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        no_collaborators: Optional[bool] = None,
+        num_trigger_ids: Optional[int] = None,
+        query: Optional[str] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        source: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Search workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.search
+        """
+        if collaborator_ids is not None:
+            if isinstance(collaborator_ids, (list, tuple)):
+                kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+            else:
+                kwargs.update({"collaborator_ids": collaborator_ids})
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "cursor": cursor,
+                "limit": limit,
+                "no_collaborators": no_collaborators,
+                "num_trigger_ids": num_trigger_ids,
+                "query": query,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "source": source,
+            }
+        )
+        return self.api_call("admin.workflows.search", params=kwargs)
+
+    def admin_workflows_permissions_lookup(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        max_workflow_triggers: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Look up the permissions for a set of workflows
+        https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        kwargs.update(
+            {
+                "max_workflow_triggers": max_workflow_triggers,
+            }
+        )
+        return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+    def admin_workflows_collaborators_add(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add collaborators to workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+    def admin_workflows_collaborators_remove(
+        self,
+        *,
+        collaborator_ids: Union[str, Sequence[str]],
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove collaborators from workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+        """
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+    def admin_workflows_unpublish(
+        self,
+        *,
+        workflow_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Unpublish workflows within the team or enterprise
+        https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+        """
+        if isinstance(workflow_ids, (list, tuple)):
+            kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+        else:
+            kwargs.update({"workflow_ids": workflow_ids})
+        return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+    def api_test(
+        self,
+        *,
+        error: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Checks API calling code.
+        https://docs.slack.dev/reference/methods/api.test
+        """
+        kwargs.update({"error": error})
+        return self.api_call("api.test", params=kwargs)
+
+    def apps_connections_open(
+        self,
+        *,
+        app_token: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+        in order to receive events and interactive payloads
+        https://docs.slack.dev/reference/methods/apps.connections.open
+        """
+        kwargs.update({"token": app_token})
+        return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+    def apps_event_authorizations_list(
+        self,
+        *,
+        event_context: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get a list of authorizations for the given event context.
+        Each authorization represents an app installation that the event is visible to.
+        https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+        """
+        kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+        return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+    def apps_uninstall(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Uninstalls your app from a workspace.
+        https://docs.slack.dev/reference/methods/apps.uninstall
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret})
+        return self.api_call("apps.uninstall", params=kwargs)
+
+    def apps_manifest_create(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.create
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        return self.api_call("apps.manifest.create", params=kwargs)
+
+    def apps_manifest_delete(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Permanently deletes an app created through app manifests
+        https://docs.slack.dev/reference/methods/apps.manifest.delete
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.delete", params=kwargs)
+
+    def apps_manifest_export(
+        self,
+        *,
+        app_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Export an app manifest from an existing app
+        https://docs.slack.dev/reference/methods/apps.manifest.export
+        """
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.export", params=kwargs)
+
+    def apps_manifest_update(
+        self,
+        *,
+        app_id: str,
+        manifest: Union[str, Dict[str, Any]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update an app from an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.update
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.update", params=kwargs)
+
+    def apps_manifest_validate(
+        self,
+        *,
+        manifest: Union[str, Dict[str, Any]],
+        app_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Validate an app manifest
+        https://docs.slack.dev/reference/methods/apps.manifest.validate
+        """
+        if isinstance(manifest, str):
+            kwargs.update({"manifest": manifest})
+        else:
+            kwargs.update({"manifest": json.dumps(manifest)})
+        kwargs.update({"app_id": app_id})
+        return self.api_call("apps.manifest.validate", params=kwargs)
+
+    def tooling_tokens_rotate(
+        self,
+        *,
+        refresh_token: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Exchanges a refresh token for a new app configuration token
+        https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+        """
+        kwargs.update({"refresh_token": refresh_token})
+        return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+    def assistant_threads_setStatus(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        status: str,
+        loading_messages: Optional[List[str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the status for an AI assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+        """
+        kwargs.update(
+            {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+    def assistant_threads_setTitle(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the title for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+        return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+    def assistant_threads_setSuggestedPrompts(
+        self,
+        *,
+        channel_id: str,
+        thread_ts: str,
+        title: Optional[str] = None,
+        prompts: List[Dict[str, str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set suggested prompts for the given assistant thread.
+        https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+        """
+        kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+        if title is not None:
+            kwargs.update({"title": title})
+        return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+    def auth_revoke(
+        self,
+        *,
+        test: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Revokes a token.
+        https://docs.slack.dev/reference/methods/auth.revoke
+        """
+        kwargs.update({"test": test})
+        return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+    def auth_test(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Checks authentication & identity.
+        https://docs.slack.dev/reference/methods/auth.test
+        """
+        return self.api_call("auth.test", params=kwargs)
+
+    def auth_teams_list(
+        self,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        include_icon: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List the workspaces a token can access.
+        https://docs.slack.dev/reference/methods/auth.teams.list
+        """
+        kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+        return self.api_call("auth.teams.list", params=kwargs)
+
+    def bookmarks_add(
+        self,
+        *,
+        channel_id: str,
+        title: str,
+        type: str,
+        emoji: Optional[str] = None,
+        entity_id: Optional[str] = None,
+        link: Optional[str] = None,  # include when type is 'link'
+        parent_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add bookmark to a channel.
+        https://docs.slack.dev/reference/methods/bookmarks.add
+        """
+        kwargs.update(
+            {
+                "channel_id": channel_id,
+                "title": title,
+                "type": type,
+                "emoji": emoji,
+                "entity_id": entity_id,
+                "link": link,
+                "parent_id": parent_id,
+            }
+        )
+        return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+    def bookmarks_edit(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        emoji: Optional[str] = None,
+        link: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Edit bookmark.
+        https://docs.slack.dev/reference/methods/bookmarks.edit
+        """
+        kwargs.update(
+            {
+                "bookmark_id": bookmark_id,
+                "channel_id": channel_id,
+                "emoji": emoji,
+                "link": link,
+                "title": title,
+            }
+        )
+        return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+    def bookmarks_list(
+        self,
+        *,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List bookmark for the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.list
+        """
+        kwargs.update({"channel_id": channel_id})
+        return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+    def bookmarks_remove(
+        self,
+        *,
+        bookmark_id: str,
+        channel_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove bookmark from the channel.
+        https://docs.slack.dev/reference/methods/bookmarks.remove
+        """
+        kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+        return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+    def bots_info(
+        self,
+        *,
+        bot: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a bot user.
+        https://docs.slack.dev/reference/methods/bots.info
+        """
+        kwargs.update({"bot": bot, "team_id": team_id})
+        return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+    def calls_add(
+        self,
+        *,
+        external_unique_id: str,
+        join_url: str,
+        created_by: Optional[str] = None,
+        date_start: Optional[int] = None,
+        desktop_app_join_url: Optional[str] = None,
+        external_display_id: Optional[str] = None,
+        title: Optional[str] = None,
+        users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Registers a new Call.
+        https://docs.slack.dev/reference/methods/calls.add
+        """
+        kwargs.update(
+            {
+                "external_unique_id": external_unique_id,
+                "join_url": join_url,
+                "created_by": created_by,
+                "date_start": date_start,
+                "desktop_app_join_url": desktop_app_join_url,
+                "external_display_id": external_display_id,
+                "title": title,
+            }
+        )
+        _update_call_participants(
+            kwargs,
+            users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+        )
+        return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+    def calls_end(
+        self,
+        *,
+        id: str,
+        duration: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Ends a Call.
+        https://docs.slack.dev/reference/methods/calls.end
+        """
+        kwargs.update({"id": id, "duration": duration})
+        return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+    def calls_info(
+        self,
+        *,
+        id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Returns information about a Call.
+        https://docs.slack.dev/reference/methods/calls.info
+        """
+        kwargs.update({"id": id})
+        return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+    def calls_participants_add(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Registers new participants added to a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.add
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+    def calls_participants_remove(
+        self,
+        *,
+        id: str,
+        users: Union[str, Sequence[Dict[str, str]]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Registers participants removed from a Call.
+        https://docs.slack.dev/reference/methods/calls.participants.remove
+        """
+        kwargs.update({"id": id})
+        _update_call_participants(kwargs, users)
+        return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+    def calls_update(
+        self,
+        *,
+        id: str,
+        desktop_app_join_url: Optional[str] = None,
+        join_url: Optional[str] = None,
+        title: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Updates information about a Call.
+        https://docs.slack.dev/reference/methods/calls.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "desktop_app_join_url": desktop_app_join_url,
+                "join_url": join_url,
+                "title": title,
+            }
+        )
+        return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+    def canvases_create(
+        self,
+        *,
+        title: Optional[str] = None,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create Canvas for a user
+        https://docs.slack.dev/reference/methods/canvases.create
+        """
+        kwargs.update({"title": title, "document_content": document_content})
+        return self.api_call("canvases.create", json=kwargs)
+
+    def canvases_edit(
+        self,
+        *,
+        canvas_id: str,
+        changes: Sequence[Dict[str, Any]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update an existing canvas
+        https://docs.slack.dev/reference/methods/canvases.edit
+        """
+        kwargs.update({"canvas_id": canvas_id, "changes": changes})
+        return self.api_call("canvases.edit", json=kwargs)
+
+    def canvases_delete(
+        self,
+        *,
+        canvas_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes a canvas
+        https://docs.slack.dev/reference/methods/canvases.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        return self.api_call("canvases.delete", params=kwargs)
+
+    def canvases_access_set(
+        self,
+        *,
+        canvas_id: str,
+        access_level: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the access level to a canvas for specified entities
+        https://docs.slack.dev/reference/methods/canvases.access.set
+        """
+        kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+
+        return self.api_call("canvases.access.set", params=kwargs)
+
+    def canvases_access_delete(
+        self,
+        *,
+        canvas_id: str,
+        channel_ids: Optional[Union[Sequence[str], str]] = None,
+        user_ids: Optional[Union[Sequence[str], str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/canvases.access.delete
+        """
+        kwargs.update({"canvas_id": canvas_id})
+        if channel_ids is not None:
+            if isinstance(channel_ids, (list, tuple)):
+                kwargs.update({"channel_ids": ",".join(channel_ids)})
+            else:
+                kwargs.update({"channel_ids": channel_ids})
+        if user_ids is not None:
+            if isinstance(user_ids, (list, tuple)):
+                kwargs.update({"user_ids": ",".join(user_ids)})
+            else:
+                kwargs.update({"user_ids": user_ids})
+        return self.api_call("canvases.access.delete", params=kwargs)
+
+    def canvases_sections_lookup(
+        self,
+        *,
+        canvas_id: str,
+        criteria: Dict[str, Any],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Find sections matching the provided criteria
+        https://docs.slack.dev/reference/methods/canvases.sections.lookup
+        """
+        kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+        return self.api_call("canvases.sections.lookup", params=kwargs)
+
+    # --------------------------
+    # Deprecated: channels.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def channels_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Archives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.archive", json=kwargs)
+
+    def channels_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Creates a channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.create", json=kwargs)
+
+    def channels_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetches history of messages and events from a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+    def channels_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+    def channels_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invites a user to a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.invite", json=kwargs)
+
+    def channels_join(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Joins a channel, creating it if needed."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.join", json=kwargs)
+
+    def channels_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a user from a channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.kick", json=kwargs)
+
+    def channels_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Leaves a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.leave", json=kwargs)
+
+    def channels_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all channels in a Slack team."""
+        return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+    def channels_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the read cursor in a channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.mark", json=kwargs)
+
+    def channels_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Renames a channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.rename", json=kwargs)
+
+    def channels_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a thread of messages posted to a channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+    def channels_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the purpose for a channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setPurpose", json=kwargs)
+
+    def channels_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the topic for a channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.setTopic", json=kwargs)
+
+    def channels_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Unarchives a channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("channels.unarchive", json=kwargs)
+
+    # --------------------------
+
+    def chat_appendStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Appends text to an existing streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.appendStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.appendStream", json=kwargs)
+
+    def chat_delete(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes a message.
+        https://docs.slack.dev/reference/methods/chat.delete
+        """
+        kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+        return self.api_call("chat.delete", params=kwargs)
+
+    def chat_deleteScheduledMessage(
+        self,
+        *,
+        channel: str,
+        scheduled_message_id: str,
+        as_user: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes a scheduled message.
+        https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "scheduled_message_id": scheduled_message_id,
+                "as_user": as_user,
+            }
+        )
+        return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+    def chat_getPermalink(
+        self,
+        *,
+        channel: str,
+        message_ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a permalink URL for a specific extant message
+        https://docs.slack.dev/reference/methods/chat.getPermalink
+        """
+        kwargs.update({"channel": channel, "message_ts": message_ts})
+        return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+    def chat_meMessage(
+        self,
+        *,
+        channel: str,
+        text: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Share a me message into a channel.
+        https://docs.slack.dev/reference/methods/chat.meMessage
+        """
+        kwargs.update({"channel": channel, "text": text})
+        return self.api_call("chat.meMessage", params=kwargs)
+
+    def chat_postEphemeral(
+        self,
+        *,
+        channel: str,
+        user: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sends an ephemeral message to a user in a channel.
+        https://docs.slack.dev/reference/methods/chat.postEphemeral
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "user": user,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postEphemeral", json=kwargs)
+
+    def chat_postMessage(
+        self,
+        *,
+        channel: str,
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        container_id: Optional[str] = None,
+        icon_emoji: Optional[str] = None,
+        icon_url: Optional[str] = None,
+        mrkdwn: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        username: Optional[str] = None,
+        parse: Optional[str] = None,  # none, full
+        metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sends a message to a channel.
+        https://docs.slack.dev/reference/methods/chat.postMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "container_id": container_id,
+                "icon_emoji": icon_emoji,
+                "icon_url": icon_url,
+                "mrkdwn": mrkdwn,
+                "link_names": link_names,
+                "username": username,
+                "parse": parse,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.postMessage", json=kwargs)
+
+    def chat_scheduleMessage(
+        self,
+        *,
+        channel: str,
+        post_at: Union[str, int],
+        text: Optional[str] = None,
+        as_user: Optional[bool] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        thread_ts: Optional[str] = None,
+        parse: Optional[str] = None,
+        reply_broadcast: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        link_names: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Schedules a message.
+        https://docs.slack.dev/reference/methods/chat.scheduleMessage
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "post_at": post_at,
+                "text": text,
+                "as_user": as_user,
+                "attachments": attachments,
+                "blocks": blocks,
+                "thread_ts": thread_ts,
+                "reply_broadcast": reply_broadcast,
+                "parse": parse,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "link_names": link_names,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+        # NOTE: intentionally using json over params for the API methods using blocks/attachments
+        return self.api_call("chat.scheduleMessage", json=kwargs)
+
+    def chat_scheduledMessages_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all scheduled messages.
+        https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "latest": latest,
+                "limit": limit,
+                "oldest": oldest,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+    def chat_startStream(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        markdown_text: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Starts a new streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.startStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "thread_ts": thread_ts,
+                "markdown_text": markdown_text,
+                "recipient_team_id": recipient_team_id,
+                "recipient_user_id": recipient_user_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.startStream", json=kwargs)
+
+    def chat_stopStream(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        markdown_text: Optional[str] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Stops a streaming conversation.
+        https://docs.slack.dev/reference/methods/chat.stopStream
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "markdown_text": markdown_text,
+                "blocks": blocks,
+                "metadata": metadata,
+            }
+        )
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("chat.stopStream", json=kwargs)
+
+    def chat_unfurl(
+        self,
+        *,
+        channel: Optional[str] = None,
+        ts: Optional[str] = None,
+        source: Optional[str] = None,
+        unfurl_id: Optional[str] = None,
+        unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+        metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+        user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        user_auth_message: Optional[str] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Provide custom unfurl behavior for user-posted URLs.
+        https://docs.slack.dev/reference/methods/chat.unfurl
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "source": source,
+                "unfurl_id": unfurl_id,
+                "unfurls": unfurls,
+                "metadata": metadata,
+                "user_auth_blocks": user_auth_blocks,
+                "user_auth_message": user_auth_message,
+                "user_auth_required": user_auth_required,
+                "user_auth_url": user_auth_url,
+            }
+        )
+        _parse_web_class_objects(kwargs)  # for user_auth_blocks
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.unfurl", json=kwargs)
+
+    def chat_update(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        text: Optional[str] = None,
+        attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+        blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+        as_user: Optional[bool] = None,
+        file_ids: Optional[Union[str, Sequence[str]]] = None,
+        link_names: Optional[bool] = None,
+        parse: Optional[str] = None,  # none, full
+        reply_broadcast: Optional[bool] = None,
+        metadata: Optional[Union[Dict, Metadata]] = None,
+        markdown_text: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Updates a message in a channel.
+        https://docs.slack.dev/reference/methods/chat.update
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "as_user": as_user,
+                "link_names": link_names,
+                "parse": parse,
+                "reply_broadcast": reply_broadcast,
+                "metadata": metadata,
+                "markdown_text": markdown_text,
+            }
+        )
+        if isinstance(file_ids, (list, tuple)):
+            kwargs.update({"file_ids": ",".join(file_ids)})
+        else:
+            kwargs.update({"file_ids": file_ids})
+        _parse_web_class_objects(kwargs)
+        kwargs = _remove_none_values(kwargs)
+        _warn_if_message_text_content_is_missing("chat.update", kwargs)
+        # NOTE: intentionally using json over params for API methods using blocks/attachments
+        return self.api_call("chat.update", json=kwargs)
+
+    def conversations_acceptSharedInvite(
+        self,
+        *,
+        channel_name: str,
+        channel_id: Optional[str] = None,
+        invite_id: Optional[str] = None,
+        free_trial_accepted: Optional[bool] = None,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Accepts an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+        """
+        if channel_id is None and invite_id is None:
+            raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+        kwargs.update(
+            {
+                "channel_name": channel_name,
+                "channel_id": channel_id,
+                "invite_id": invite_id,
+                "free_trial_accepted": free_trial_accepted,
+                "is_private": is_private,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_approveSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Approves an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+    def conversations_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Archives a conversation.
+        https://docs.slack.dev/reference/methods/conversations.archive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.archive", params=kwargs)
+
+    def conversations_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Closes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.close
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.close", params=kwargs)
+
+    def conversations_create(
+        self,
+        *,
+        name: str,
+        is_private: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Initiates a public or private channel-based conversation
+        https://docs.slack.dev/reference/methods/conversations.create
+        """
+        kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+        return self.api_call("conversations.create", params=kwargs)
+
+    def conversations_declineSharedInvite(
+        self,
+        *,
+        invite_id: str,
+        target_team: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Declines a Slack Connect channel invite.
+        https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+        """
+        kwargs.update({"invite_id": invite_id, "target_team": target_team})
+        return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+    def conversations_externalInvitePermissions_set(
+        self, *, action: str, channel: str, target_team: str, **kwargs
+    ) -> Union[Future, SlackResponse]:
+        """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+        https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+        """
+        kwargs.update(
+            {
+                "action": action,
+                "channel": channel,
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+    def conversations_history(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetches a conversation's history of messages and events.
+        https://docs.slack.dev/reference/methods/conversations.history
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+    def conversations_info(
+        self,
+        *,
+        channel: str,
+        include_locale: Optional[bool] = None,
+        include_num_members: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve information about a conversation.
+        https://docs.slack.dev/reference/methods/conversations.info
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "include_locale": include_locale,
+                "include_num_members": include_num_members,
+            }
+        )
+        return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+    def conversations_invite(
+        self,
+        *,
+        channel: str,
+        users: Union[str, Sequence[str]],
+        force: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invites users to a channel.
+        https://docs.slack.dev/reference/methods/conversations.invite
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "force": force,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.invite", params=kwargs)
+
+    def conversations_inviteShared(
+        self,
+        *,
+        channel: str,
+        emails: Optional[Union[str, Sequence[str]]] = None,
+        user_ids: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sends an invitation to a Slack Connect channel.
+        https://docs.slack.dev/reference/methods/conversations.inviteShared
+        """
+        if emails is None and user_ids is None:
+            raise e.SlackRequestError("Either emails or user ids must be provided.")
+        kwargs.update({"channel": channel})
+        if isinstance(emails, (list, tuple)):
+            kwargs.update({"emails": ",".join(emails)})
+        else:
+            kwargs.update({"emails": emails})
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+        return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+    def conversations_join(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Joins an existing conversation.
+        https://docs.slack.dev/reference/methods/conversations.join
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.join", params=kwargs)
+
+    def conversations_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a user from a conversation.
+        https://docs.slack.dev/reference/methods/conversations.kick
+        """
+        kwargs.update({"channel": channel, "user": user})
+        return self.api_call("conversations.kick", params=kwargs)
+
+    def conversations_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Leaves a conversation.
+        https://docs.slack.dev/reference/methods/conversations.leave
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.leave", params=kwargs)
+
+    def conversations_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all channels in a Slack team.
+        https://docs.slack.dev/reference/methods/conversations.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+    def conversations_listConnectInvites(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List shared channel invites that have been generated
+        or received but have not yet been approved by all parties.
+        https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+        """
+        kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+        return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+    def conversations_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the read cursor in a channel.
+        https://docs.slack.dev/reference/methods/conversations.mark
+        """
+        kwargs.update({"channel": channel, "ts": ts})
+        return self.api_call("conversations.mark", params=kwargs)
+
+    def conversations_members(
+        self,
+        *,
+        channel: str,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve members of a conversation.
+        https://docs.slack.dev/reference/methods/conversations.members
+        """
+        kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+        return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+    def conversations_open(
+        self,
+        *,
+        channel: Optional[str] = None,
+        return_im: Optional[bool] = None,
+        users: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Opens or resumes a direct message or multi-person direct message.
+        https://docs.slack.dev/reference/methods/conversations.open
+        """
+        if channel is None and users is None:
+            raise e.SlackRequestError("Either channel or users must be provided.")
+        kwargs.update({"channel": channel, "return_im": return_im})
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("conversations.open", params=kwargs)
+
+    def conversations_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Renames a conversation.
+        https://docs.slack.dev/reference/methods/conversations.rename
+        """
+        kwargs.update({"channel": channel, "name": name})
+        return self.api_call("conversations.rename", params=kwargs)
+
+    def conversations_replies(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        cursor: Optional[str] = None,
+        inclusive: Optional[bool] = None,
+        include_all_metadata: Optional[bool] = None,
+        latest: Optional[str] = None,
+        limit: Optional[int] = None,
+        oldest: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a thread of messages posted to a conversation
+        https://docs.slack.dev/reference/methods/conversations.replies
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "ts": ts,
+                "cursor": cursor,
+                "inclusive": inclusive,
+                "include_all_metadata": include_all_metadata,
+                "limit": limit,
+                "latest": latest,
+                "oldest": oldest,
+            }
+        )
+        return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+    def conversations_requestSharedInvite_approve(
+        self,
+        *,
+        invite_id: str,
+        channel_id: Optional[str] = None,
+        is_external_limited: Optional[str] = None,
+        message: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+        """
+        kwargs.update(
+            {
+                "invite_id": invite_id,
+                "channel_id": channel_id,
+                "is_external_limited": is_external_limited,
+            }
+        )
+        if message is not None:
+            kwargs.update({"message": json.dumps(message)})
+        return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+    def conversations_requestSharedInvite_deny(
+        self,
+        *,
+        invite_id: str,
+        message: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deny a request to invite an external user to a channel.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+        """
+        kwargs.update({"invite_id": invite_id, "message": message})
+        return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+    def conversations_requestSharedInvite_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_approved: Optional[bool] = None,
+        include_denied: Optional[bool] = None,
+        include_expired: Optional[bool] = None,
+        invite_ids: Optional[Union[str, Sequence[str]]] = None,
+        limit: Optional[int] = None,
+        user_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists requests to add external users to channels with ability to filter.
+        https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_approved": include_approved,
+                "include_denied": include_denied,
+                "include_expired": include_expired,
+                "limit": limit,
+                "user_id": user_id,
+            }
+        )
+        if invite_ids is not None:
+            if isinstance(invite_ids, (list, tuple)):
+                kwargs.update({"invite_ids": ",".join(invite_ids)})
+            else:
+                kwargs.update({"invite_ids": invite_ids})
+        return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+    def conversations_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the purpose for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setPurpose
+        """
+        kwargs.update({"channel": channel, "purpose": purpose})
+        return self.api_call("conversations.setPurpose", params=kwargs)
+
+    def conversations_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the topic for a conversation.
+        https://docs.slack.dev/reference/methods/conversations.setTopic
+        """
+        kwargs.update({"channel": channel, "topic": topic})
+        return self.api_call("conversations.setTopic", params=kwargs)
+
+    def conversations_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Reverses conversation archival.
+        https://docs.slack.dev/reference/methods/conversations.unarchive
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("conversations.unarchive", params=kwargs)
+
+    def conversations_canvases_create(
+        self,
+        *,
+        channel_id: str,
+        document_content: Dict[str, str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create a Channel Canvas for a channel
+        https://docs.slack.dev/reference/methods/conversations.canvases.create
+        """
+        kwargs.update({"channel_id": channel_id, "document_content": document_content})
+        return self.api_call("conversations.canvases.create", json=kwargs)
+
+    def dialog_open(
+        self,
+        *,
+        dialog: Dict[str, Any],
+        trigger_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Open a dialog with a user.
+        https://docs.slack.dev/reference/methods/dialog.open
+        """
+        kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: As the dialog can be a dict, this API call works only with json format.
+        return self.api_call("dialog.open", json=kwargs)
+
+    def dnd_endDnd(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Ends the current user's Do Not Disturb session immediately.
+        https://docs.slack.dev/reference/methods/dnd.endDnd
+        """
+        return self.api_call("dnd.endDnd", params=kwargs)
+
+    def dnd_endSnooze(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Ends the current user's snooze mode immediately.
+        https://docs.slack.dev/reference/methods/dnd.endSnooze
+        """
+        return self.api_call("dnd.endSnooze", params=kwargs)
+
+    def dnd_info(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieves a user's current Do Not Disturb status.
+        https://docs.slack.dev/reference/methods/dnd.info
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+    def dnd_setSnooze(
+        self,
+        *,
+        num_minutes: Union[int, str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Turns on Do Not Disturb mode for the current user, or changes its duration.
+        https://docs.slack.dev/reference/methods/dnd.setSnooze
+        """
+        kwargs.update({"num_minutes": num_minutes})
+        return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+    def dnd_teamInfo(
+        self,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieves the Do Not Disturb status for users on a team.
+        https://docs.slack.dev/reference/methods/dnd.teamInfo
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id})
+        return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+    def emoji_list(
+        self,
+        include_categories: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists custom emoji for a team.
+        https://docs.slack.dev/reference/methods/emoji.list
+        """
+        kwargs.update({"include_categories": include_categories})
+        return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+    def entity_presentDetails(
+        self,
+        trigger_id: str,
+        metadata: Optional[Union[Dict, EntityMetadata]] = None,
+        user_auth_required: Optional[bool] = None,
+        user_auth_url: Optional[str] = None,
+        error: Optional[Dict[str, Any]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Provides entity details for the flexpane.
+        https://docs.slack.dev/reference/methods/entity.presentDetails/
+        """
+        kwargs.update({"trigger_id": trigger_id})
+        if metadata is not None:
+            kwargs.update({"metadata": metadata})
+        if user_auth_required is not None:
+            kwargs.update({"user_auth_required": user_auth_required})
+        if user_auth_url is not None:
+            kwargs.update({"user_auth_url": user_auth_url})
+        if error is not None:
+            kwargs.update({"error": error})
+        _parse_web_class_objects(kwargs)
+        return self.api_call("entity.presentDetails", json=kwargs)
+
+    def files_comments_delete(
+        self,
+        *,
+        file: str,
+        id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes an existing comment on a file.
+        https://docs.slack.dev/reference/methods/files.comments.delete
+        """
+        kwargs.update({"file": file, "id": id})
+        return self.api_call("files.comments.delete", params=kwargs)
+
+    def files_delete(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes a file.
+        https://docs.slack.dev/reference/methods/files.delete
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.delete", params=kwargs)
+
+    def files_info(
+        self,
+        *,
+        file: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a team file.
+        https://docs.slack.dev/reference/methods/files.info
+        """
+        kwargs.update(
+            {
+                "file": file,
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+            }
+        )
+        return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+    def files_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        count: Optional[int] = None,
+        page: Optional[int] = None,
+        show_files_hidden_by_limit: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists & filters team files.
+        https://docs.slack.dev/reference/methods/files.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "count": count,
+                "page": page,
+                "show_files_hidden_by_limit": show_files_hidden_by_limit,
+                "team_id": team_id,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+    def files_remote_info(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.info
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+    def files_remote_list(
+        self,
+        *,
+        channel: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        ts_from: Optional[str] = None,
+        ts_to: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve information about a remote file added to Slack.
+        https://docs.slack.dev/reference/methods/files.remote.list
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "cursor": cursor,
+                "limit": limit,
+                "ts_from": ts_from,
+                "ts_to": ts_to,
+            }
+        )
+        return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+    def files_remote_add(
+        self,
+        *,
+        external_id: str,
+        external_url: str,
+        title: str,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+        preview_image: Optional[Union[str, bytes, IOBase]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Adds a file from a remote service.
+        https://docs.slack.dev/reference/methods/files.remote.add
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.add",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_update(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        external_url: Optional[str] = None,
+        file: Optional[str] = None,
+        title: Optional[str] = None,
+        filetype: Optional[str] = None,
+        indexable_file_contents: Optional[str] = None,
+        preview_image: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Updates an existing remote file.
+        https://docs.slack.dev/reference/methods/files.remote.update
+        """
+        kwargs.update(
+            {
+                "external_id": external_id,
+                "external_url": external_url,
+                "file": file,
+                "title": title,
+                "filetype": filetype,
+            }
+        )
+        files = None
+        # preview_image (file): Preview of the document via multipart/form-data.
+        if preview_image is not None or indexable_file_contents is not None:
+            files = {
+                "preview_image": preview_image,
+                "indexable_file_contents": indexable_file_contents,
+            }
+
+        return self.api_call(
+            # Intentionally using "POST" method over "GET" here
+            "files.remote.update",
+            http_verb="POST",
+            data=kwargs,
+            files=files,
+        )
+
+    def files_remote_remove(
+        self,
+        *,
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove a remote file.
+        https://docs.slack.dev/reference/methods/files.remote.remove
+        """
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+    def files_remote_share(
+        self,
+        *,
+        channels: Union[str, Sequence[str]],
+        external_id: Optional[str] = None,
+        file: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Share a remote file into a channel.
+        https://docs.slack.dev/reference/methods/files.remote.share
+        """
+        if external_id is None and file is None:
+            raise e.SlackRequestError("Either external_id or file must be provided.")
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update({"external_id": external_id, "file": file})
+        return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+    def files_revokePublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Revokes public/external sharing access for a file
+        https://docs.slack.dev/reference/methods/files.revokePublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.revokePublicURL", params=kwargs)
+
+    def files_sharedPublicURL(
+        self,
+        *,
+        file: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Enables a file for public/external sharing.
+        https://docs.slack.dev/reference/methods/files.sharedPublicURL
+        """
+        kwargs.update({"file": file})
+        return self.api_call("files.sharedPublicURL", params=kwargs)
+
+    def files_upload(
+        self,
+        *,
+        file: Optional[Union[str, bytes, IOBase]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        filename: Optional[str] = None,
+        filetype: Optional[str] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        title: Optional[str] = None,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Uploads or creates a file.
+        https://docs.slack.dev/reference/methods/files.upload
+        """
+        _print_files_upload_v2_suggestion()
+
+        if file is None and content is None:
+            raise e.SlackRequestError("The file or content argument must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        kwargs.update(
+            {
+                "filename": filename,
+                "filetype": filetype,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+                "title": title,
+            }
+        )
+        if file:
+            if kwargs.get("filename") is None and isinstance(file, str):
+                # use the local filename if filename is missing
+                if kwargs.get("filename") is None:
+                    kwargs["filename"] = file.split(os.path.sep)[-1]
+            return self.api_call("files.upload", files={"file": file}, data=kwargs)
+        else:
+            kwargs["content"] = content
+            return self.api_call("files.upload", data=kwargs)
+
+    def files_upload_v2(
+        self,
+        *,
+        # for sending a single file
+        filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+        file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+        content: Optional[Union[str, bytes]] = None,
+        title: Optional[str] = None,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        # To upload multiple files at a time
+        file_uploads: Optional[List[Dict[str, Any]]] = None,
+        channel: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """This wrapper method provides an easy way to upload files using the following endpoints:
+
+        - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+        - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+        - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+            and https://docs.slack.dev/reference/methods/files.info
+
+        """
+        if file is None and content is None and file_uploads is None:
+            raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+        if file is not None and content is not None:
+            raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+        # deprecated arguments:
+        filetype = kwargs.get("filetype")
+
+        if filetype is not None:
+            warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+        # step1: files.getUploadURLExternal per file
+        files: List[Dict[str, Any]] = []
+        if file_uploads is not None:
+            for f in file_uploads:
+                files.append(_to_v2_file_upload_item(f))
+        else:
+            f = _to_v2_file_upload_item(
+                {
+                    "filename": filename,
+                    "file": file,
+                    "content": content,
+                    "title": title,
+                    "alt_txt": alt_txt,
+                    "snippet_type": snippet_type,
+                }
+            )
+            files.append(f)
+
+        for f in files:
+            url_response = self.files_getUploadURLExternal(
+                filename=f.get("filename"),  # type: ignore[arg-type]
+                length=f.get("length"),  # type: ignore[arg-type]
+                alt_txt=f.get("alt_txt"),
+                snippet_type=f.get("snippet_type"),
+                token=kwargs.get("token"),
+            )
+            _validate_for_legacy_client(url_response)
+            f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+            f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+        # step2: "https://files.slack.com/upload/v1/..." per file
+        for f in files:
+            upload_result = self._upload_file(
+                url=f["upload_url"],
+                data=f["data"],
+                logger=self._logger,
+                timeout=self.timeout,
+                proxy=self.proxy,
+                ssl=self.ssl,
+            )
+            if upload_result.status != 200:
+                status = upload_result.status
+                body = upload_result.body
+                message = (
+                    "Failed to upload a file "
+                    f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+                )
+                raise e.SlackRequestError(message)
+
+        # step3: files.completeUploadExternal with all the sets of (file_id + title)
+        completion = self.files_completeUploadExternal(
+            files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+            channel_id=channel,
+            channels=channels,
+            initial_comment=initial_comment,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+        if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+            completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+        return completion
+
+    def files_getUploadURLExternal(
+        self,
+        *,
+        filename: str,
+        length: int,
+        alt_txt: Optional[str] = None,
+        snippet_type: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets a URL for an edge external upload.
+        https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+        """
+        kwargs.update(
+            {
+                "filename": filename,
+                "length": length,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+    def files_completeUploadExternal(
+        self,
+        *,
+        files: List[Dict[str, str]],
+        channel_id: Optional[str] = None,
+        channels: Optional[List[str]] = None,
+        initial_comment: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Finishes an upload started with files.getUploadURLExternal.
+        https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        """
+        _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+        kwargs.update(
+            {
+                "files": json.dumps(_files),
+                "channel_id": channel_id,
+                "initial_comment": initial_comment,
+                "thread_ts": thread_ts,
+            }
+        )
+        if channels:
+            kwargs["channels"] = ",".join(channels)
+        return self.api_call("files.completeUploadExternal", params=kwargs)
+
+    def functions_completeSuccess(
+        self,
+        *,
+        function_execution_id: str,
+        outputs: Dict[str, Any],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Signal the successful completion of a function
+        https://docs.slack.dev/reference/methods/functions.completeSuccess
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+        return self.api_call("functions.completeSuccess", params=kwargs)
+
+    def functions_completeError(
+        self,
+        *,
+        function_execution_id: str,
+        error: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Signal the failure to execute a function
+        https://docs.slack.dev/reference/methods/functions.completeError
+        """
+        kwargs.update({"function_execution_id": function_execution_id, "error": error})
+        return self.api_call("functions.completeError", params=kwargs)
+
+    # --------------------------
+    # Deprecated: groups.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def groups_archive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Archives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.archive", json=kwargs)
+
+    def groups_create(
+        self,
+        *,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Creates a private channel."""
+        kwargs.update({"name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.create", json=kwargs)
+
+    def groups_createChild(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Clones and archives a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+    def groups_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetches history of messages and events from a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+    def groups_info(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a private channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+    def groups_invite(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Invites a user to a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.invite", json=kwargs)
+
+    def groups_kick(
+        self,
+        *,
+        channel: str,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a user from a private channel."""
+        kwargs.update({"channel": channel, "user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.kick", json=kwargs)
+
+    def groups_leave(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Leaves a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.leave", json=kwargs)
+
+    def groups_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists private channels that the calling user has access to."""
+        return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+    def groups_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the read cursor in a private channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.mark", json=kwargs)
+
+    def groups_open(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Opens a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.open", json=kwargs)
+
+    def groups_rename(
+        self,
+        *,
+        channel: str,
+        name: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Renames a private channel."""
+        kwargs.update({"channel": channel, "name": name})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.rename", json=kwargs)
+
+    def groups_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a thread of messages posted to a private channel"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+    def groups_setPurpose(
+        self,
+        *,
+        channel: str,
+        purpose: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the purpose for a private channel."""
+        kwargs.update({"channel": channel, "purpose": purpose})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setPurpose", json=kwargs)
+
+    def groups_setTopic(
+        self,
+        *,
+        channel: str,
+        topic: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the topic for a private channel."""
+        kwargs.update({"channel": channel, "topic": topic})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.setTopic", json=kwargs)
+
+    def groups_unarchive(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Unarchives a private channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("groups.unarchive", json=kwargs)
+
+    # --------------------------
+    # Deprecated: im.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def im_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Close a direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.close", json=kwargs)
+
+    def im_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetches history of messages and events from direct message channel."""
+        kwargs.update({"channel": channel})
+        return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+    def im_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists direct message channels for the calling user."""
+        return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+    def im_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the read cursor in a direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.mark", json=kwargs)
+
+    def im_open(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Opens a direct message channel."""
+        kwargs.update({"user": user})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("im.open", json=kwargs)
+
+    def im_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a thread of messages posted to a direct message conversation"""
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def migration_exchange(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        team_id: Optional[str] = None,
+        to_old: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """For Enterprise Grid workspaces, map local user IDs to global user IDs
+        https://docs.slack.dev/reference/methods/migration.exchange
+        """
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        kwargs.update({"team_id": team_id, "to_old": to_old})
+        return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+    # --------------------------
+    # Deprecated: mpim.*
+    # You can use conversations.* APIs instead.
+    # https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/
+    # --------------------------
+
+    def mpim_close(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Closes a multiparty direct message channel."""
+        kwargs.update({"channel": channel})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.close", json=kwargs)
+
+    def mpim_history(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Fetches history of messages and events from a multiparty direct message."""
+        kwargs.update({"channel": channel})
+        return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+    def mpim_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists multiparty direct message channels for the calling user."""
+        return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+    def mpim_mark(
+        self,
+        *,
+        channel: str,
+        ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Sets the read cursor in a multiparty direct message channel."""
+        kwargs.update({"channel": channel, "ts": ts})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("mpim.mark", json=kwargs)
+
+    def mpim_open(
+        self,
+        *,
+        users: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """This method opens a multiparty direct message."""
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("mpim.open", params=kwargs)
+
+    def mpim_replies(
+        self,
+        *,
+        channel: str,
+        thread_ts: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a thread of messages posted to a direct message conversation from a
+        multiparty direct message.
+        """
+        kwargs.update({"channel": channel, "thread_ts": thread_ts})
+        return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+    # --------------------------
+
+    def oauth_v2_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        # This field is required when processing the OAuth redirect URL requests
+        # while it's absent for token rotation
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        # This field is required for token rotation
+        grant_type: Optional[str] = None,
+        # This field is required for token rotation
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.v2.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "oauth.v2.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_access(
+        self,
+        *,
+        client_id: str,
+        client_secret: str,
+        code: str,
+        redirect_uri: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Exchanges a temporary OAuth verifier code for an access token.
+        https://docs.slack.dev/reference/methods/oauth.access
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        kwargs.update({"code": code})
+        return self.api_call(
+            "oauth.access",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def oauth_v2_exchange(
+        self,
+        *,
+        token: str,
+        client_id: str,
+        client_secret: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Exchanges a legacy access token for a new expiring access token and refresh token
+        https://docs.slack.dev/reference/methods/oauth.v2.exchange
+        """
+        kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+        return self.api_call("oauth.v2.exchange", params=kwargs)
+
+    def openid_connect_token(
+        self,
+        client_id: str,
+        client_secret: str,
+        code: Optional[str] = None,
+        redirect_uri: Optional[str] = None,
+        grant_type: Optional[str] = None,
+        refresh_token: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.token
+        """
+        if redirect_uri is not None:
+            kwargs.update({"redirect_uri": redirect_uri})
+        if code is not None:
+            kwargs.update({"code": code})
+        if grant_type is not None:
+            kwargs.update({"grant_type": grant_type})
+        if refresh_token is not None:
+            kwargs.update({"refresh_token": refresh_token})
+        return self.api_call(
+            "openid.connect.token",
+            data=kwargs,
+            auth={"client_id": client_id, "client_secret": client_secret},
+        )
+
+    def openid_connect_userInfo(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get the identity of a user who has authorized Sign in with Slack.
+        https://docs.slack.dev/reference/methods/openid.connect.userInfo
+        """
+        return self.api_call("openid.connect.userInfo", params=kwargs)
+
+    def pins_add(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Pins an item to a channel.
+        https://docs.slack.dev/reference/methods/pins.add
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.add", params=kwargs)
+
+    def pins_list(
+        self,
+        *,
+        channel: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists items pinned to a channel.
+        https://docs.slack.dev/reference/methods/pins.list
+        """
+        kwargs.update({"channel": channel})
+        return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+    def pins_remove(
+        self,
+        *,
+        channel: str,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Un-pins an item from a channel.
+        https://docs.slack.dev/reference/methods/pins.remove
+        """
+        kwargs.update({"channel": channel, "timestamp": timestamp})
+        return self.api_call("pins.remove", params=kwargs)
+
+    def reactions_add(
+        self,
+        *,
+        channel: str,
+        name: str,
+        timestamp: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Adds a reaction to an item.
+        https://docs.slack.dev/reference/methods/reactions.add
+        """
+        kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+        return self.api_call("reactions.add", params=kwargs)
+
+    def reactions_get(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        full: Optional[bool] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets reactions for an item.
+        https://docs.slack.dev/reference/methods/reactions.get
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "full": full,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+    def reactions_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        full: Optional[bool] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists reactions made by a user.
+        https://docs.slack.dev/reference/methods/reactions.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "full": full,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+    def reactions_remove(
+        self,
+        *,
+        name: str,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a reaction from an item.
+        https://docs.slack.dev/reference/methods/reactions.remove
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("reactions.remove", params=kwargs)
+
+    def reminders_add(
+        self,
+        *,
+        text: str,
+        time: str,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        recurrence: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Creates a reminder.
+        https://docs.slack.dev/reference/methods/reminders.add
+        """
+        kwargs.update(
+            {
+                "text": text,
+                "time": time,
+                "team_id": team_id,
+                "user": user,
+                "recurrence": recurrence,
+            }
+        )
+        return self.api_call("reminders.add", params=kwargs)
+
+    def reminders_complete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Marks a reminder as complete.
+        https://docs.slack.dev/reference/methods/reminders.complete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.complete", params=kwargs)
+
+    def reminders_delete(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes a reminder.
+        https://docs.slack.dev/reference/methods/reminders.delete
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.delete", params=kwargs)
+
+    def reminders_info(
+        self,
+        *,
+        reminder: str,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a reminder.
+        https://docs.slack.dev/reference/methods/reminders.info
+        """
+        kwargs.update({"reminder": reminder, "team_id": team_id})
+        return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+    def reminders_list(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all reminders created by or for a given user.
+        https://docs.slack.dev/reference/methods/reminders.list
+        """
+        kwargs.update({"team_id": team_id})
+        return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+    def rtm_connect(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.connect
+        """
+        kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+        return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+    def rtm_start(
+        self,
+        *,
+        batch_presence_aware: Optional[bool] = None,
+        include_locale: Optional[bool] = None,
+        mpim_aware: Optional[bool] = None,
+        no_latest: Optional[bool] = None,
+        no_unreads: Optional[bool] = None,
+        presence_sub: Optional[bool] = None,
+        simple_latest: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Starts a Real Time Messaging session.
+        https://docs.slack.dev/reference/methods/rtm.start
+        """
+        kwargs.update(
+            {
+                "batch_presence_aware": batch_presence_aware,
+                "include_locale": include_locale,
+                "mpim_aware": mpim_aware,
+                "no_latest": no_latest,
+                "no_unreads": no_unreads,
+                "presence_sub": presence_sub,
+                "simple_latest": simple_latest,
+            }
+        )
+        return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+    def search_all(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Searches for messages and files matching a query.
+        https://docs.slack.dev/reference/methods/search.all
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+    def search_files(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Searches for files matching a query.
+        https://docs.slack.dev/reference/methods/search.files
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+    def search_messages(
+        self,
+        *,
+        query: str,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        highlight: Optional[bool] = None,
+        page: Optional[int] = None,
+        sort: Optional[str] = None,
+        sort_dir: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Searches for messages matching a query.
+        https://docs.slack.dev/reference/methods/search.messages
+        """
+        kwargs.update(
+            {
+                "query": query,
+                "count": count,
+                "cursor": cursor,
+                "highlight": highlight,
+                "page": page,
+                "sort": sort,
+                "sort_dir": sort_dir,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+    def slackLists_access_delete(
+        self,
+        *,
+        list_id: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Revoke access to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.delete
+        """
+        kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.delete", json=kwargs)
+
+    def slackLists_access_set(
+        self,
+        *,
+        list_id: str,
+        access_level: str,
+        channel_ids: Optional[List[str]] = None,
+        user_ids: Optional[List[str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the access level to a List for specified entities.
+        https://docs.slack.dev/reference/methods/slackLists.access.set
+        """
+        kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.access.set", json=kwargs)
+
+    def slackLists_create(
+        self,
+        *,
+        name: str,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        schema: Optional[List[Dict[str, Any]]] = None,
+        copy_from_list_id: Optional[str] = None,
+        include_copied_list_records: Optional[bool] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Creates a List.
+        https://docs.slack.dev/reference/methods/slackLists.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description_blocks": description_blocks,
+                "schema": schema,
+                "copy_from_list_id": copy_from_list_id,
+                "include_copied_list_records": include_copied_list_records,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.create", json=kwargs)
+
+    def slackLists_download_get(
+        self,
+        *,
+        list_id: str,
+        job_id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve List download URL from an export job to download List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.get
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "job_id": job_id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.get", json=kwargs)
+
+    def slackLists_download_start(
+        self,
+        *,
+        list_id: str,
+        include_archived: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Initiate a job to export List contents.
+        https://docs.slack.dev/reference/methods/slackLists.download.start
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "include_archived": include_archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.download.start", json=kwargs)
+
+    def slackLists_items_create(
+        self,
+        *,
+        list_id: str,
+        duplicated_item_id: Optional[str] = None,
+        parent_item_id: Optional[str] = None,
+        initial_fields: Optional[List[Dict[str, Any]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add a new item to an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.create
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "duplicated_item_id": duplicated_item_id,
+                "parent_item_id": parent_item_id,
+                "initial_fields": initial_fields,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.create", json=kwargs)
+
+    def slackLists_items_delete(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes an item from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.delete
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.delete", json=kwargs)
+
+    def slackLists_items_deleteMultiple(
+        self,
+        *,
+        list_id: str,
+        ids: List[str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Deletes multiple items from an existing List.
+        https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "ids": ids,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+    def slackLists_items_info(
+        self,
+        *,
+        list_id: str,
+        id: str,
+        include_is_subscribed: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get a row from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.info
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "id": id,
+                "include_is_subscribed": include_is_subscribed,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.info", json=kwargs)
+
+    def slackLists_items_list(
+        self,
+        *,
+        list_id: str,
+        limit: Optional[int] = None,
+        cursor: Optional[str] = None,
+        archived: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get records from a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.list
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "limit": limit,
+                "cursor": cursor,
+                "archived": archived,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.list", json=kwargs)
+
+    def slackLists_items_update(
+        self,
+        *,
+        list_id: str,
+        cells: List[Dict[str, Any]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Updates cells in a List.
+        https://docs.slack.dev/reference/methods/slackLists.items.update
+        """
+        kwargs.update(
+            {
+                "list_id": list_id,
+                "cells": cells,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.items.update", json=kwargs)
+
+    def slackLists_update(
+        self,
+        *,
+        id: str,
+        name: Optional[str] = None,
+        description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+        todo_mode: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update a List.
+        https://docs.slack.dev/reference/methods/slackLists.update
+        """
+        kwargs.update(
+            {
+                "id": id,
+                "name": name,
+                "description_blocks": description_blocks,
+                "todo_mode": todo_mode,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        return self.api_call("slackLists.update", json=kwargs)
+
+    def stars_add(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Adds a star to an item.
+        https://docs.slack.dev/reference/methods/stars.add
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.add", params=kwargs)
+
+    def stars_list(
+        self,
+        *,
+        count: Optional[int] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        page: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists stars for a user.
+        https://docs.slack.dev/reference/methods/stars.list
+        """
+        kwargs.update(
+            {
+                "count": count,
+                "cursor": cursor,
+                "limit": limit,
+                "page": page,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+    def stars_remove(
+        self,
+        *,
+        channel: Optional[str] = None,
+        file: Optional[str] = None,
+        file_comment: Optional[str] = None,
+        timestamp: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Removes a star from an item.
+        https://docs.slack.dev/reference/methods/stars.remove
+        """
+        kwargs.update(
+            {
+                "channel": channel,
+                "file": file,
+                "file_comment": file_comment,
+                "timestamp": timestamp,
+            }
+        )
+        return self.api_call("stars.remove", params=kwargs)
+
+    def team_accessLogs(
+        self,
+        *,
+        before: Optional[Union[int, str]] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        team_id: Optional[str] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets the access logs for the current team.
+        https://docs.slack.dev/reference/methods/team.accessLogs
+        """
+        kwargs.update(
+            {
+                "before": before,
+                "count": count,
+                "page": page,
+                "team_id": team_id,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+    def team_billableInfo(
+        self,
+        *,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets billable users information for the current team.
+        https://docs.slack.dev/reference/methods/team.billableInfo
+        """
+        kwargs.update({"team_id": team_id, "user": user})
+        return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+    def team_billing_info(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Reads a workspace's billing plan information.
+        https://docs.slack.dev/reference/methods/team.billing.info
+        """
+        return self.api_call("team.billing.info", params=kwargs)
+
+    def team_externalTeams_disconnect(
+        self,
+        *,
+        target_team: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Disconnects an external organization.
+        https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+        """
+        kwargs.update(
+            {
+                "target_team": target_team,
+            }
+        )
+        return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+    def team_externalTeams_list(
+        self,
+        *,
+        connection_status_filter: Optional[str] = None,
+        slack_connect_pref_filter: Optional[Sequence[str]] = None,
+        sort_direction: Optional[str] = None,
+        sort_field: Optional[str] = None,
+        workspace_filter: Optional[Sequence[str]] = None,
+        cursor: Optional[str] = None,
+        limit: Optional[int] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Returns a list of all the external teams connected and details about the connection.
+        https://docs.slack.dev/reference/methods/team.externalTeams.list
+        """
+        kwargs.update(
+            {
+                "connection_status_filter": connection_status_filter,
+                "sort_direction": sort_direction,
+                "sort_field": sort_field,
+                "cursor": cursor,
+                "limit": limit,
+            }
+        )
+        if slack_connect_pref_filter is not None:
+            if isinstance(slack_connect_pref_filter, (list, tuple)):
+                kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+            else:
+                kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+        if workspace_filter is not None:
+            if isinstance(workspace_filter, (list, tuple)):
+                kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+            else:
+                kwargs.update({"workspace_filter": workspace_filter})
+        return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+    def team_info(
+        self,
+        *,
+        team: Optional[str] = None,
+        domain: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about the current team.
+        https://docs.slack.dev/reference/methods/team.info
+        """
+        kwargs.update({"team": team, "domain": domain})
+        return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+    def team_integrationLogs(
+        self,
+        *,
+        app_id: Optional[str] = None,
+        change_type: Optional[str] = None,
+        count: Optional[Union[int, str]] = None,
+        page: Optional[Union[int, str]] = None,
+        service_id: Optional[str] = None,
+        team_id: Optional[str] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets the integration logs for the current team.
+        https://docs.slack.dev/reference/methods/team.integrationLogs
+        """
+        kwargs.update(
+            {
+                "app_id": app_id,
+                "change_type": change_type,
+                "count": count,
+                "page": page,
+                "service_id": service_id,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+    def team_profile_get(
+        self,
+        *,
+        visibility: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a team's profile.
+        https://docs.slack.dev/reference/methods/team.profile.get
+        """
+        kwargs.update({"visibility": visibility})
+        return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+    def team_preferences_list(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieve a list of a workspace's team preferences.
+        https://docs.slack.dev/reference/methods/team.preferences.list
+        """
+        return self.api_call("team.preferences.list", params=kwargs)
+
+    def usergroups_create(
+        self,
+        *,
+        name: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Create a User Group
+        https://docs.slack.dev/reference/methods/usergroups.create
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.create", params=kwargs)
+
+    def usergroups_disable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Disable an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.disable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.disable", params=kwargs)
+
+    def usergroups_enable(
+        self,
+        *,
+        usergroup: str,
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Enable a User Group
+        https://docs.slack.dev/reference/methods/usergroups.enable
+        """
+        kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+        return self.api_call("usergroups.enable", params=kwargs)
+
+    def usergroups_list(
+        self,
+        *,
+        include_count: Optional[bool] = None,
+        include_disabled: Optional[bool] = None,
+        include_users: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all User Groups for a team
+        https://docs.slack.dev/reference/methods/usergroups.list
+        """
+        kwargs.update(
+            {
+                "include_count": include_count,
+                "include_disabled": include_disabled,
+                "include_users": include_users,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+    def usergroups_update(
+        self,
+        *,
+        usergroup: str,
+        channels: Optional[Union[str, Sequence[str]]] = None,
+        description: Optional[str] = None,
+        handle: Optional[str] = None,
+        include_count: Optional[bool] = None,
+        name: Optional[str] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update an existing User Group
+        https://docs.slack.dev/reference/methods/usergroups.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "description": description,
+                "handle": handle,
+                "include_count": include_count,
+                "name": name,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(channels, (list, tuple)):
+            kwargs.update({"channels": ",".join(channels)})
+        else:
+            kwargs.update({"channels": channels})
+        return self.api_call("usergroups.update", params=kwargs)
+
+    def usergroups_users_list(
+        self,
+        *,
+        usergroup: str,
+        include_disabled: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List all users in a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.list
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_disabled": include_disabled,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+    def usergroups_users_update(
+        self,
+        *,
+        usergroup: str,
+        users: Union[str, Sequence[str]],
+        include_count: Optional[bool] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update the list of users for a User Group
+        https://docs.slack.dev/reference/methods/usergroups.users.update
+        """
+        kwargs.update(
+            {
+                "usergroup": usergroup,
+                "include_count": include_count,
+                "team_id": team_id,
+            }
+        )
+        if isinstance(users, (list, tuple)):
+            kwargs.update({"users": ",".join(users)})
+        else:
+            kwargs.update({"users": users})
+        return self.api_call("usergroups.users.update", params=kwargs)
+
+    def users_conversations(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        exclude_archived: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        types: Optional[Union[str, Sequence[str]]] = None,
+        user: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List conversations the calling user may access.
+        https://docs.slack.dev/reference/methods/users.conversations
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "exclude_archived": exclude_archived,
+                "limit": limit,
+                "team_id": team_id,
+                "user": user,
+            }
+        )
+        if isinstance(types, (list, tuple)):
+            kwargs.update({"types": ",".join(types)})
+        else:
+            kwargs.update({"types": types})
+        return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+    def users_deletePhoto(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Delete the user profile photo
+        https://docs.slack.dev/reference/methods/users.deletePhoto
+        """
+        return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+    def users_getPresence(
+        self,
+        *,
+        user: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets user presence information.
+        https://docs.slack.dev/reference/methods/users.getPresence
+        """
+        kwargs.update({"user": user})
+        return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+    def users_identity(
+        self,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Get a user's identity.
+        https://docs.slack.dev/reference/methods/users.identity
+        """
+        return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+    def users_info(
+        self,
+        *,
+        user: str,
+        include_locale: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Gets information about a user.
+        https://docs.slack.dev/reference/methods/users.info
+        """
+        kwargs.update({"user": user, "include_locale": include_locale})
+        return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+    def users_list(
+        self,
+        *,
+        cursor: Optional[str] = None,
+        include_locale: Optional[bool] = None,
+        limit: Optional[int] = None,
+        team_id: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lists all users in a Slack team.
+        https://docs.slack.dev/reference/methods/users.list
+        """
+        kwargs.update(
+            {
+                "cursor": cursor,
+                "include_locale": include_locale,
+                "limit": limit,
+                "team_id": team_id,
+            }
+        )
+        return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+    def users_lookupByEmail(
+        self,
+        *,
+        email: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Find a user with an email address.
+        https://docs.slack.dev/reference/methods/users.lookupByEmail
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+    def users_setPhoto(
+        self,
+        *,
+        image: Union[str, IOBase],
+        crop_w: Optional[Union[int, str]] = None,
+        crop_x: Optional[Union[int, str]] = None,
+        crop_y: Optional[Union[int, str]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the user profile photo
+        https://docs.slack.dev/reference/methods/users.setPhoto
+        """
+        kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+        return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+    def users_setPresence(
+        self,
+        *,
+        presence: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Manually sets user presence.
+        https://docs.slack.dev/reference/methods/users.setPresence
+        """
+        kwargs.update({"presence": presence})
+        return self.api_call("users.setPresence", params=kwargs)
+
+    def users_discoverableContacts_lookup(
+        self,
+        email: str,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Lookup an email address to see if someone is on Slack
+        https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+        """
+        kwargs.update({"email": email})
+        return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+    def users_profile_get(
+        self,
+        *,
+        user: Optional[str] = None,
+        include_labels: Optional[bool] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Retrieves a user's profile information.
+        https://docs.slack.dev/reference/methods/users.profile.get
+        """
+        kwargs.update({"user": user, "include_labels": include_labels})
+        return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+    def users_profile_set(
+        self,
+        *,
+        name: Optional[str] = None,
+        value: Optional[str] = None,
+        user: Optional[str] = None,
+        profile: Optional[Dict] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set the profile information for a user.
+        https://docs.slack.dev/reference/methods/users.profile.set
+        """
+        kwargs.update(
+            {
+                "name": name,
+                "profile": profile,
+                "user": user,
+                "value": value,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "profile" parameter
+        return self.api_call("users.profile.set", json=kwargs)
+
+    def views_open(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Open a view for a user.
+        https://docs.slack.dev/reference/methods/views.open
+        See https://docs.slack.dev/surfaces/modals/ for details.
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.open", json=kwargs)
+
+    def views_push(
+        self,
+        *,
+        trigger_id: Optional[str] = None,
+        interactivity_pointer: Optional[str] = None,
+        view: Union[dict, View],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Push a view onto the stack of a root view.
+        Push a new view onto the existing view stack by passing a view
+        payload and a valid trigger_id generated from an interaction
+        within the existing modal.
+        Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+        to learn more about the lifecycle and intricacies of views.
+        https://docs.slack.dev/reference/methods/views.push
+        """
+        kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.push", json=kwargs)
+
+    def views_update(
+        self,
+        *,
+        view: Union[dict, View],
+        external_id: Optional[str] = None,
+        view_id: Optional[str] = None,
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update an existing view.
+        Update a view by passing a new view definition along with the
+        view_id returned in views.open or the external_id.
+        See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+        to learn more about updating views and avoiding race conditions with the hash argument.
+        https://docs.slack.dev/reference/methods/views.update
+        """
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        if external_id:
+            kwargs.update({"external_id": external_id})
+        elif view_id:
+            kwargs.update({"view_id": view_id})
+        else:
+            raise e.SlackRequestError("Either view_id or external_id is required.")
+        kwargs.update({"hash": hash})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.update", json=kwargs)
+
+    def views_publish(
+        self,
+        *,
+        user_id: str,
+        view: Union[dict, View],
+        hash: Optional[str] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Publish a static view for a User.
+        Create or update the view that comprises an
+        app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+        https://docs.slack.dev/reference/methods/views.publish
+        """
+        kwargs.update({"user_id": user_id, "hash": hash})
+        if isinstance(view, View):
+            kwargs.update({"view": view.to_dict()})
+        else:
+            kwargs.update({"view": view})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "view" parameter
+        return self.api_call("views.publish", json=kwargs)
+
+    def workflows_featured_add(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Add featured workflows to a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.add
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.add", params=kwargs)
+
+    def workflows_featured_list(
+        self,
+        *,
+        channel_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """List the featured workflows for specified channels.
+        https://docs.slack.dev/reference/methods/workflows.featured.list
+        """
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+        return self.api_call("workflows.featured.list", params=kwargs)
+
+    def workflows_featured_remove(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Remove featured workflows from a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.remove
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.remove", params=kwargs)
+
+    def workflows_featured_set(
+        self,
+        *,
+        channel_id: str,
+        trigger_ids: Union[str, Sequence[str]],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Set featured workflows for a channel.
+        https://docs.slack.dev/reference/methods/workflows.featured.set
+        """
+        kwargs.update({"channel_id": channel_id})
+        if isinstance(trigger_ids, (list, tuple)):
+            kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+        else:
+            kwargs.update({"trigger_ids": trigger_ids})
+        return self.api_call("workflows.featured.set", params=kwargs)
+
+    def workflows_stepCompleted(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        outputs: Optional[dict] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Indicate a successful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepCompleted
+        """
+        kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "outputs" parameter
+        return self.api_call("workflows.stepCompleted", json=kwargs)
+
+    def workflows_stepFailed(
+        self,
+        *,
+        workflow_step_execute_id: str,
+        error: Dict[str, str],
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Indicate an unsuccessful outcome of a workflow step's execution.
+        https://docs.slack.dev/reference/methods/workflows.stepFailed
+        """
+        kwargs.update(
+            {
+                "workflow_step_execute_id": workflow_step_execute_id,
+                "error": error,
+            }
+        )
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "error" parameter
+        return self.api_call("workflows.stepFailed", json=kwargs)
+
+    def workflows_updateStep(
+        self,
+        *,
+        workflow_step_edit_id: str,
+        inputs: Optional[Dict[str, Any]] = None,
+        outputs: Optional[List[Dict[str, str]]] = None,
+        **kwargs,
+    ) -> Union[Future, SlackResponse]:
+        """Update the configuration for a workflow extension step.
+        https://docs.slack.dev/reference/methods/workflows.updateStep
+        """
+        kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+        if inputs is not None:
+            kwargs.update({"inputs": inputs})
+        if outputs is not None:
+            kwargs.update({"outputs": outputs})
+        kwargs = _remove_none_values(kwargs)
+        # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+        return self.api_call("workflows.updateStep", json=kwargs)
+
+

A WebClient allows apps to communicate with the Slack Platform's Web API.

+

https://docs.slack.dev/reference/methods

+

The Slack Web API is an interface for querying information from +and enacting change in a Slack workspace.

+

This client handles constructing and sending HTTP requests to Slack +as well as parsing any responses received into a SlackResponse.

+

Attributes

+
+
token : str
+
A string specifying an xoxp-* or xoxb-* token.
+
base_url : str
+
A string representing the Slack API base URL. +Default is 'https://slack.com/api/'
+
timeout : int
+
The maximum number of seconds the client will wait +to connect and receive a response from Slack. +Default is 30 seconds.
+
ssl : SSLContext
+
An ssl.SSLContext instance, helpful for specifying +your own custom certificate chain.
+
proxy : str
+
String representing a fully-qualified URL to a proxy through +which to route all requests to the Slack API. Even if this parameter +is not specified, if any of the following environment variables are +present, they will be loaded into this parameter: HTTPS_PROXY, +https_proxy, HTTP_PROXY or http_proxy.
+
headers : dict
+
Additional request headers to attach to all requests.
+
+

Methods

+

api_call: Constructs a request and executes the API call to Slack.

+

Example of recommended usage:

+
    import os
+    from slack_sdk.web.legacy_client import LegacyWebClient
+
+    client = LegacyWebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.chat_postMessage(
+        channel='#random',
+        text="Hello world!")
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Example manually creating an API request:

+
    import os
+    from slack_sdk.web.legacy_client import LegacyWebClient
+
+    client = LegacyWebClient(token=os.environ['SLACK_API_TOKEN'])
+    response = client.api_call(
+        api_method='chat.postMessage',
+        json={'channel': '#random','text': "Hello world!"}
+    )
+    assert response["ok"]
+    assert response["message"]["text"] == "Hello world!"
+
+

Note

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Ancestors

+ +

Methods

+
+
+def admin_analytics_getFile(self,
*,
type:Β str,
date:Β strΒ |Β NoneΒ =Β None,
metadata_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_analytics_getFile(
+    self,
+    *,
+    type: str,
+    date: Optional[str] = None,
+    metadata_only: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve analytics data for a given date, presented as a compressed JSON file
+    https://docs.slack.dev/reference/methods/admin.analytics.getFile
+    """
+    kwargs.update({"type": type})
+    if date is not None:
+        kwargs.update({"date": date})
+    if metadata_only is not None:
+        kwargs.update({"metadata_only": metadata_only})
+    return self.api_call("admin.analytics.getFile", params=kwargs)
+
+

Retrieve analytics data for a given date, presented as a compressed JSON file +https://docs.slack.dev/reference/methods/admin.analytics.getFile

+
+
+def admin_apps_activities_list(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
component_id:Β strΒ |Β NoneΒ =Β None,
component_type:Β strΒ |Β NoneΒ =Β None,
log_event_type:Β strΒ |Β NoneΒ =Β None,
max_date_created:Β intΒ |Β NoneΒ =Β None,
min_date_created:Β intΒ |Β NoneΒ =Β None,
min_log_level:Β strΒ |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
trace_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_activities_list(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    component_id: Optional[str] = None,
+    component_type: Optional[str] = None,
+    log_event_type: Optional[str] = None,
+    max_date_created: Optional[int] = None,
+    min_date_created: Optional[int] = None,
+    min_log_level: Optional[str] = None,
+    sort_direction: Optional[str] = None,
+    source: Optional[str] = None,
+    team_id: Optional[str] = None,
+    trace_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get logs for a specified team/org
+    https://docs.slack.dev/reference/methods/admin.apps.activities.list
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "component_id": component_id,
+            "component_type": component_type,
+            "log_event_type": log_event_type,
+            "max_date_created": max_date_created,
+            "min_date_created": min_date_created,
+            "min_log_level": min_log_level,
+            "sort_direction": sort_direction,
+            "source": source,
+            "team_id": team_id,
+            "trace_id": trace_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.apps.activities.list", params=kwargs)
+
+ +
+
+def admin_apps_approve(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approve(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Approve an app for installation on a workspace.
+    Either app_id or request_id is required.
+    These IDs can be obtained either directly via the app_requested event,
+    or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.approve
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approve", params=kwargs)
+
+

Approve an app for installation on a workspace. +Either app_id or request_id is required. +These IDs can be obtained either directly via the app_requested event, +or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.approve

+
+
+def admin_apps_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List approved apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.approved.list", http_verb="GET", params=kwargs)
+
+

List approved apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.approved.list

+
+
+def admin_apps_clearResolution(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_clearResolution(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Clear an app resolution
+    https://docs.slack.dev/reference/methods/admin.apps.clearResolution
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.clearResolution", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_config_lookup(self, *, app_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_apps_config_lookup(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Look up the app config for connectors by their IDs
+    https://docs.slack.dev/reference/methods/admin.apps.config.lookup
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    return self.api_call("admin.apps.config.lookup", params=kwargs)
+
+

Look up the app config for connectors by their IDs +https://docs.slack.dev/reference/methods/admin.apps.config.lookup

+
+
+def admin_apps_config_set(self,
*,
app_id:Β str,
domain_restrictions:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
workflow_auth_strategy:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_config_set(
+    self,
+    *,
+    app_id: str,
+    domain_restrictions: Optional[Dict[str, Any]] = None,
+    workflow_auth_strategy: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the app config for a connector
+    https://docs.slack.dev/reference/methods/admin.apps.config.set
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "workflow_auth_strategy": workflow_auth_strategy,
+        }
+    )
+    if domain_restrictions is not None:
+        kwargs.update({"domain_restrictions": json.dumps(domain_restrictions)})
+    return self.api_call("admin.apps.config.set", params=kwargs)
+
+ +
+
+def admin_apps_requests_cancel(self,
*,
request_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_cancel(
+    self,
+    *,
+    request_id: str,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.cancel
+    """
+    kwargs.update(
+        {
+            "request_id": request_id,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.cancel", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_apps_requests_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_requests_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List app requests for a team/workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.requests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.requests.list", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_apps_restrict(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
request_id:Β strΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restrict(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    request_id: Optional[str] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Restrict an app for installation on a workspace.
+    Exactly one of the team_id or enterprise_id arguments is required, not both.
+    Either app_id or request_id is required. These IDs can be obtained either directly
+    via the app_requested event, or by the admin.apps.requests.list method.
+    https://docs.slack.dev/reference/methods/admin.apps.restrict
+    """
+    if app_id:
+        kwargs.update({"app_id": app_id})
+    elif request_id:
+        kwargs.update({"request_id": request_id})
+    else:
+        raise e.SlackRequestError("The app_id or request_id argument must be specified.")
+
+    kwargs.update(
+        {
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restrict", params=kwargs)
+
+

Restrict an app for installation on a workspace. +Exactly one of the team_id or enterprise_id arguments is required, not both. +Either app_id or request_id is required. These IDs can be obtained either directly +via the app_requested event, or by the admin.apps.requests.list method. +https://docs.slack.dev/reference/methods/admin.apps.restrict

+
+
+def admin_apps_restricted_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_restricted_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    enterprise_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List restricted apps for an org or workspace.
+    https://docs.slack.dev/reference/methods/admin.apps.restricted.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "enterprise_id": enterprise_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.apps.restricted.list", http_verb="GET", params=kwargs)
+
+

List restricted apps for an org or workspace. +https://docs.slack.dev/reference/methods/admin.apps.restricted.list

+
+
+def admin_apps_uninstall(self,
*,
app_id:Β str,
enterprise_id:Β strΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_apps_uninstall(
+    self,
+    *,
+    app_id: str,
+    enterprise_id: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Uninstall an app from one or many workspaces, or an entire enterprise organization.
+    With an org-level token, enterprise_id or team_ids is required.
+    https://docs.slack.dev/reference/methods/admin.apps.uninstall
+    """
+    kwargs.update({"app_id": app_id})
+    if enterprise_id is not None:
+        kwargs.update({"enterprise_id": enterprise_id})
+    if team_ids is not None:
+        if isinstance(team_ids, (list, tuple)):
+            kwargs.update({"team_ids": ",".join(team_ids)})
+        else:
+            kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.apps.uninstall", http_verb="POST", params=kwargs)
+
+

Uninstall an app from one or many workspaces, or an entire enterprise organization. +With an org-level token, enterprise_id or team_ids is required. +https://docs.slack.dev/reference/methods/admin.apps.uninstall

+
+
+def admin_auth_policy_assignEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_assignEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Assign entities to a particular authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.assignEntities", http_verb="POST", params=kwargs)
+
+

Assign entities to a particular authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.assignEntities

+
+
+def admin_auth_policy_getEntities(self,
*,
policy_name:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
entity_type:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_getEntities(
+    self,
+    *,
+    policy_name: str,
+    cursor: Optional[str] = None,
+    entity_type: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetch all the entities assigned to a particular authentication policy by name.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities
+    """
+    kwargs.update({"policy_name": policy_name})
+    if cursor is not None:
+        kwargs.update({"cursor": cursor})
+    if entity_type is not None:
+        kwargs.update({"entity_type": entity_type})
+    if limit is not None:
+        kwargs.update({"limit": limit})
+    return self.api_call("admin.auth.policy.getEntities", http_verb="POST", params=kwargs)
+
+

Fetch all the entities assigned to a particular authentication policy by name. +https://docs.slack.dev/reference/methods/admin.auth.policy.getEntities

+
+
+def admin_auth_policy_removeEntities(self,
*,
entity_ids:Β strΒ |Β Sequence[str],
policy_name:Β str,
entity_type:Β str,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_auth_policy_removeEntities(
+    self,
+    *,
+    entity_ids: Union[str, Sequence[str]],
+    policy_name: str,
+    entity_type: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove specified entities from a specified authentication policy.
+    https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities
+    """
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    kwargs.update({"policy_name": policy_name})
+    kwargs.update({"entity_type": entity_type})
+    return self.api_call("admin.auth.policy.removeEntities", http_verb="POST", params=kwargs)
+
+

Remove specified entities from a specified authentication policy. +https://docs.slack.dev/reference/methods/admin.auth.policy.removeEntities

+
+
+def admin_barriers_create(self,
*,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_create(
+    self,
+    *,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create an Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.create
+    """
+    kwargs.update({"primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.create", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_delete(self, *, barrier_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_delete(
+    self,
+    *,
+    barrier_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Delete an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.delete
+    """
+    kwargs.update({"barrier_id": barrier_id})
+    return self.api_call("admin.barriers.delete", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_barriers_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_barriers_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get all Information Barriers for your organization
+    https://docs.slack.dev/reference/methods/admin.barriers.list"""
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.barriers.list", http_verb="GET", params=kwargs)
+
+

Get all Information Barriers for your organization +https://docs.slack.dev/reference/methods/admin.barriers.list

+
+
+def admin_barriers_update(self,
*,
barrier_id:Β str,
barriered_from_usergroup_ids:Β strΒ |Β Sequence[str],
primary_usergroup_id:Β str,
restricted_subjects:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_barriers_update(
+    self,
+    *,
+    barrier_id: str,
+    barriered_from_usergroup_ids: Union[str, Sequence[str]],
+    primary_usergroup_id: str,
+    restricted_subjects: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update an existing Information Barrier
+    https://docs.slack.dev/reference/methods/admin.barriers.update
+    """
+    kwargs.update({"barrier_id": barrier_id, "primary_usergroup_id": primary_usergroup_id})
+    if isinstance(barriered_from_usergroup_ids, (list, tuple)):
+        kwargs.update({"barriered_from_usergroup_ids": ",".join(barriered_from_usergroup_ids)})
+    else:
+        kwargs.update({"barriered_from_usergroup_ids": barriered_from_usergroup_ids})
+    if isinstance(restricted_subjects, (list, tuple)):
+        kwargs.update({"restricted_subjects": ",".join(restricted_subjects)})
+    else:
+        kwargs.update({"restricted_subjects": restricted_subjects})
+    return self.api_call("admin.barriers.update", http_verb="POST", params=kwargs)
+
+ +
+
+def admin_conversations_archive(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_archive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Archive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.archive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkArchive(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkArchive(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Archive public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkArchive
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkArchive", params=kwargs)
+
+ +
+
+def admin_conversations_bulkDelete(self, *, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkDelete(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Delete public or private channels in bulk.
+    https://slack.com/api/admin.conversations.bulkDelete
+    """
+    kwargs.update({"channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids})
+    return self.api_call("admin.conversations.bulkDelete", params=kwargs)
+
+

Delete public or private channels in bulk. +https://slack.com/api/admin.conversations.bulkDelete

+
+
+def admin_conversations_bulkMove(self, *, channel_ids:Β strΒ |Β Sequence[str], target_team_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_bulkMove(
+    self,
+    *,
+    channel_ids: Union[Sequence[str], str],
+    target_team_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Move public or private channels in bulk.
+    https://docs.slack.dev/reference/methods/admin.conversations.bulkMove
+    """
+    kwargs.update(
+        {
+            "target_team_id": target_team_id,
+            "channel_ids": ",".join(channel_ids) if isinstance(channel_ids, (list, tuple)) else channel_ids,
+        }
+    )
+    return self.api_call("admin.conversations.bulkMove", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPrivate(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPrivate(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Convert a public channel to a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPrivate
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPrivate", params=kwargs)
+
+ +
+
+def admin_conversations_convertToPublic(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_convertToPublic(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Convert a privte channel to a public channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.convertToPublic
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.convertToPublic", params=kwargs)
+
+ +
+
+def admin_conversations_create(self,
*,
is_private:Β bool,
name:Β str,
description:Β strΒ |Β NoneΒ =Β None,
org_wide:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_create(
+    self,
+    *,
+    is_private: bool,
+    name: str,
+    description: Optional[str] = None,
+    org_wide: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create a public or private channel-based conversation.
+    https://docs.slack.dev/reference/methods/admin.conversations.create
+    """
+    kwargs.update(
+        {
+            "is_private": is_private,
+            "name": name,
+            "description": description,
+            "org_wide": org_wide,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.conversations.create", params=kwargs)
+
+

Create a public or private channel-based conversation. +https://docs.slack.dev/reference/methods/admin.conversations.create

+
+
+def admin_conversations_createForObjects(self,
*,
object_id:Β str,
salesforce_org_id:Β str,
invite_object_team:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_createForObjects(
+    self,
+    *,
+    object_id: str,
+    salesforce_org_id: str,
+    invite_object_team: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create a Salesforce channel for the corresponding object provided.
+    https://docs.slack.dev/reference/methods/admin.conversations.createForObjects
+    """
+    kwargs.update(
+        {"object_id": object_id, "salesforce_org_id": salesforce_org_id, "invite_object_team": invite_object_team}
+    )
+    return self.api_call("admin.conversations.createForObjects", params=kwargs)
+
+

Create a Salesforce channel for the corresponding object provided. +https://docs.slack.dev/reference/methods/admin.conversations.createForObjects

+
+
+def admin_conversations_delete(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_delete(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Delete a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.delete
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.delete", params=kwargs)
+
+ +
+
+def admin_conversations_disconnectShared(self,
*,
channel_id:Β str,
leaving_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_disconnectShared(
+    self,
+    *,
+    channel_id: str,
+    leaving_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Disconnect a connected channel from one or more workspaces.
+    https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(leaving_team_ids, (list, tuple)):
+        kwargs.update({"leaving_team_ids": ",".join(leaving_team_ids)})
+    else:
+        kwargs.update({"leaving_team_ids": leaving_team_ids})
+    return self.api_call("admin.conversations.disconnectShared", params=kwargs)
+
+

Disconnect a connected channel from one or more workspaces. +https://docs.slack.dev/reference/methods/admin.conversations.disconnectShared

+
+
+def admin_conversations_ekm_listOriginalConnectedChannelInfo(self,
*,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_ekm_listOriginalConnectedChannelInfo(
+    self,
+    *,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all disconnected channelsβ€”i.e.,
+    channels that were once connected to other workspaces and then disconnectedβ€”and
+    the corresponding original channel IDs for key revocation with EKM.
+    https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.ekm.listOriginalConnectedChannelInfo", params=kwargs)
+
+

List all disconnected channelsβ€”i.e., +channels that were once connected to other workspaces and then disconnectedβ€”and +the corresponding original channel IDs for key revocation with EKM. +https://docs.slack.dev/reference/methods/admin.conversations.ekm.listOriginalConnectedChannelInfo

+
+
+def admin_conversations_getConversationPrefs(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get conversation preferences for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getConversationPrefs", params=kwargs)
+
+

Get conversation preferences for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.getConversationPrefs

+
+
+def admin_conversations_getCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_getCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.getCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.getCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_getTeams(self,
*,
channel_id:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_getTeams(
+    self,
+    *,
+    channel_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the workspaces in an Enterprise grid org that connect to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.getTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.conversations.getTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a channel. +https://docs.slack.dev/reference/methods/admin.conversations.getTeams

+
+
+def admin_conversations_invite(self, *, channel_id:Β str, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_invite(
+    self,
+    *,
+    channel_id: str,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invite a user to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.invite
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    # NOTE: the endpoint is unable to handle Content-Type: application/json as of Sep 3, 2020.
+    return self.api_call("admin.conversations.invite", params=kwargs)
+
+

Invite a user to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.invite

+
+
+def admin_conversations_linkObjects(self, *, channel:Β str, record_id:Β str, salesforce_org_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_linkObjects(
+    self,
+    *,
+    channel: str,
+    record_id: str,
+    salesforce_org_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Link a Salesforce record to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.linkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "record_id": record_id,
+            "salesforce_org_id": salesforce_org_id,
+        }
+    )
+    return self.api_call("admin.conversations.linkObjects", params=kwargs)
+
+ +
+
+def admin_conversations_lookup(self,
*,
last_message_activity_before:Β int,
team_ids:Β strΒ |Β Sequence[str],
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
max_member_count:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_lookup(
+    self,
+    *,
+    last_message_activity_before: int,
+    team_ids: Union[str, Sequence[str]],
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    max_member_count: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Returns channels on the given team using the filters.
+    https://docs.slack.dev/reference/methods/admin.conversations.lookup
+    """
+    kwargs.update(
+        {
+            "last_message_activity_before": last_message_activity_before,
+            "cursor": cursor,
+            "limit": limit,
+            "max_member_count": max_member_count,
+        }
+    )
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.conversations.lookup", params=kwargs)
+
+

Returns channels on the given team using the filters. +https://docs.slack.dev/reference/methods/admin.conversations.lookup

+
+
+def admin_conversations_removeCustomRetention(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_removeCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.removeCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.removeCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_rename(self, *, channel_id:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_rename(
+    self,
+    *,
+    channel_id: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Rename a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.rename
+    """
+    kwargs.update({"channel_id": channel_id, "name": name})
+    return self.api_call("admin.conversations.rename", params=kwargs)
+
+ +
+
+def admin_conversations_restrictAccess_addGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_addGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add an allowlist of IDP groups for accessing a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.addGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Add an allowlist of IDP groups for accessing a channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.addGroup

+
+
+def admin_conversations_restrictAccess_listGroups(self, *, channel_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_listGroups(
+    self,
+    *,
+    channel_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all IDP Groups linked to a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.listGroups
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.listGroups",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+ +
+
+def admin_conversations_restrictAccess_removeGroup(self, *, channel_id:Β str, group_id:Β str, team_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_restrictAccess_removeGroup(
+    self,
+    *,
+    channel_id: str,
+    group_id: str,
+    team_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove a linked IDP group linked from a private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "group_id": group_id,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call(
+        "admin.conversations.restrictAccess.removeGroup",
+        http_verb="GET",
+        params=kwargs,
+    )
+
+

Remove a linked IDP group linked from a private channel. +https://docs.slack.dev/reference/methods/admin.conversations.restrictAccess.removeGroup

+
+ +
+
+ +Expand source code + +
def admin_conversations_search(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    query: Optional[str] = None,
+    search_channel_types: Optional[Union[str, Sequence[str]]] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Search for public or private channels in an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.conversations.search
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+        }
+    )
+
+    if isinstance(search_channel_types, (list, tuple)):
+        kwargs.update({"search_channel_types": ",".join(search_channel_types)})
+    else:
+        kwargs.update({"search_channel_types": search_channel_types})
+
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+
+    return self.api_call("admin.conversations.search", params=kwargs)
+
+

Search for public or private channels in an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.conversations.search

+
+
+def admin_conversations_setConversationPrefs(self, *, channel_id:Β str, prefs:Β strΒ |Β Dict[str,Β str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setConversationPrefs(
+    self,
+    *,
+    channel_id: str,
+    prefs: Union[str, Dict[str, str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the posting permissions for a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(prefs, dict):
+        kwargs.update({"prefs": json.dumps(prefs)})
+    else:
+        kwargs.update({"prefs": prefs})
+    return self.api_call("admin.conversations.setConversationPrefs", params=kwargs)
+
+

Set the posting permissions for a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setConversationPrefs

+
+
+def admin_conversations_setCustomRetention(self, *, channel_id:Β str, duration_days:Β int, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_setCustomRetention(
+    self,
+    *,
+    channel_id: str,
+    duration_days: int,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set a channel's retention policy
+    https://docs.slack.dev/reference/methods/admin.conversations.setCustomRetention
+    """
+    kwargs.update({"channel_id": channel_id, "duration_days": duration_days})
+    return self.api_call("admin.conversations.setCustomRetention", params=kwargs)
+
+ +
+
+def admin_conversations_setTeams(self,
*,
channel_id:Β str,
org_channel:Β boolΒ |Β NoneΒ =Β None,
target_team_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_conversations_setTeams(
+    self,
+    *,
+    channel_id: str,
+    org_channel: Optional[bool] = None,
+    target_team_ids: Optional[Union[str, Sequence[str]]] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the workspaces in an Enterprise grid org that connect to a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.setTeams
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "org_channel": org_channel,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(target_team_ids, (list, tuple)):
+        kwargs.update({"target_team_ids": ",".join(target_team_ids)})
+    else:
+        kwargs.update({"target_team_ids": target_team_ids})
+    return self.api_call("admin.conversations.setTeams", params=kwargs)
+
+

Set the workspaces in an Enterprise grid org that connect to a public or private channel. +https://docs.slack.dev/reference/methods/admin.conversations.setTeams

+
+
+def admin_conversations_unarchive(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unarchive(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Unarchive a public or private channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.archive
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("admin.conversations.unarchive", params=kwargs)
+
+ +
+
+def admin_conversations_unlinkObjects(self, *, channel:Β str, new_name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_conversations_unlinkObjects(
+    self,
+    *,
+    channel: str,
+    new_name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Unlink a Salesforce record from a channel.
+    https://docs.slack.dev/reference/methods/admin.conversations.unlinkObjects
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "new_name": new_name,
+        }
+    )
+    return self.api_call("admin.conversations.unlinkObjects", params=kwargs)
+
+ +
+
+def admin_emoji_add(self, *, name:Β str, url:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_add(
+    self,
+    *,
+    name: str,
+    url: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.add
+    """
+    kwargs.update({"name": name, "url": url})
+    return self.api_call("admin.emoji.add", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_addAlias(self, *, alias_for:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_addAlias(
+    self,
+    *,
+    alias_for: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add an emoji alias.
+    https://docs.slack.dev/reference/methods/admin.emoji.addAlias
+    """
+    kwargs.update({"alias_for": alias_for, "name": name})
+    return self.api_call("admin.emoji.addAlias", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_emoji_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List emoji for an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.emoji.list", http_verb="GET", params=kwargs)
+
+

List emoji for an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.list

+
+
+def admin_emoji_remove(self, *, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_remove(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove an emoji across an Enterprise Grid organization.
+    https://docs.slack.dev/reference/methods/admin.emoji.remove
+    """
+    kwargs.update({"name": name})
+    return self.api_call("admin.emoji.remove", http_verb="GET", params=kwargs)
+
+

Remove an emoji across an Enterprise Grid organization. +https://docs.slack.dev/reference/methods/admin.emoji.remove

+
+
+def admin_emoji_rename(self, *, name:Β str, new_name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_emoji_rename(
+    self,
+    *,
+    name: str,
+    new_name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Rename an emoji.
+    https://docs.slack.dev/reference/methods/admin.emoji.rename
+    """
+    kwargs.update({"name": name, "new_name": new_name})
+    return self.api_call("admin.emoji.rename", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_functions_list(self,
*,
app_ids:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_list(
+    self,
+    *,
+    app_ids: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Look up functions by a set of apps
+    https://docs.slack.dev/reference/methods/admin.functions.list
+    """
+    if isinstance(app_ids, (list, tuple)):
+        kwargs.update({"app_ids": ",".join(app_ids)})
+    else:
+        kwargs.update({"app_ids": app_ids})
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.functions.list", params=kwargs)
+
+ +
+
+def admin_functions_permissions_lookup(self, *, function_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_functions_permissions_lookup(
+    self,
+    *,
+    function_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lookup the visibility of multiple Slack functions
+    and include the users if it is limited to particular named entities.
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup
+    """
+    if isinstance(function_ids, (list, tuple)):
+        kwargs.update({"function_ids": ",".join(function_ids)})
+    else:
+        kwargs.update({"function_ids": function_ids})
+    return self.api_call("admin.functions.permissions.lookup", params=kwargs)
+
+

Lookup the visibility of multiple Slack functions +and include the users if it is limited to particular named entities. +https://docs.slack.dev/reference/methods/admin.functions.permissions.lookup

+
+
+def admin_functions_permissions_set(self,
*,
function_id:Β str,
visibility:Β str,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_functions_permissions_set(
+    self,
+    *,
+    function_id: str,
+    visibility: str,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the visibility of a Slack function
+    and define the users or workspaces if it is set to named_entities
+    https://docs.slack.dev/reference/methods/admin.functions.permissions.set
+    """
+    kwargs.update(
+        {
+            "function_id": function_id,
+            "visibility": visibility,
+        }
+    )
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.functions.permissions.set", params=kwargs)
+
+

Set the visibility of a Slack function +and define the users or workspaces if it is set to named_entities +https://docs.slack.dev/reference/methods/admin.functions.permissions.set

+
+
+def admin_inviteRequests_approve(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_approve(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Approve a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approve
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.approve", params=kwargs)
+
+ +
+
+def admin_inviteRequests_approved_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_approved_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all approved workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.approved.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.approved.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_denied_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_inviteRequests_denied_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all denied workspace invite requests.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.denied.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.inviteRequests.denied.list", params=kwargs)
+
+ +
+
+def admin_inviteRequests_deny(self, *, invite_request_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_deny(
+    self,
+    *,
+    invite_request_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deny a workspace invite request.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.deny
+    """
+    kwargs.update({"invite_request_id": invite_request_id, "team_id": team_id})
+    return self.api_call("admin.inviteRequests.deny", params=kwargs)
+
+ +
+
+def admin_inviteRequests_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_inviteRequests_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all pending workspace invite requests."""
+    return self.api_call("admin.inviteRequests.list", params=kwargs)
+
+

List all pending workspace invite requests.

+
+
+def admin_roles_addAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_addAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Adds members to the specified role with the specified scopes
+    https://docs.slack.dev/reference/methods/admin.roles.addAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.addAssignments", params=kwargs)
+
+

Adds members to the specified role with the specified scopes +https://docs.slack.dev/reference/methods/admin.roles.addAssignments

+
+
+def admin_roles_listAssignments(self,
*,
role_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
entity_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β strΒ |Β intΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_listAssignments(
+    self,
+    *,
+    role_ids: Optional[Union[str, Sequence[str]]] = None,
+    entity_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[Union[str, int]] = None,
+    sort_dir: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists assignments for all roles across entities.
+        Options to scope results by any combination of roles or entities
+    https://docs.slack.dev/reference/methods/admin.roles.listAssignments
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "sort_dir": sort_dir})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(role_ids, (list, tuple)):
+        kwargs.update({"role_ids": ",".join(role_ids)})
+    else:
+        kwargs.update({"role_ids": role_ids})
+    return self.api_call("admin.roles.listAssignments", params=kwargs)
+
+

Lists assignments for all roles across entities. +Options to scope results by any combination of roles or entities +https://docs.slack.dev/reference/methods/admin.roles.listAssignments

+
+
+def admin_roles_removeAssignments(self,
*,
role_id:Β str,
entity_ids:Β strΒ |Β Sequence[str],
user_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_roles_removeAssignments(
+    self,
+    *,
+    role_id: str,
+    entity_ids: Union[str, Sequence[str]],
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a set of users from a role for the given scopes and entities
+    https://docs.slack.dev/reference/methods/admin.roles.removeAssignments
+    """
+    kwargs.update({"role_id": role_id})
+    if isinstance(entity_ids, (list, tuple)):
+        kwargs.update({"entity_ids": ",".join(entity_ids)})
+    else:
+        kwargs.update({"entity_ids": entity_ids})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.roles.removeAssignments", params=kwargs)
+
+

Removes a set of users from a role for the given scopes and entities +https://docs.slack.dev/reference/methods/admin.roles.removeAssignments

+
+
+def admin_teams_admins_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_admins_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.inviteRequests.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.teams.admins.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.inviteRequests.list

+
+
+def admin_teams_create(self,
*,
team_domain:Β str,
team_name:Β str,
team_description:Β strΒ |Β NoneΒ =Β None,
team_discoverability:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_teams_create(
+    self,
+    *,
+    team_domain: str,
+    team_name: str,
+    team_description: Optional[str] = None,
+    team_discoverability: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create an Enterprise team.
+    https://docs.slack.dev/reference/methods/admin.teams.create
+    """
+    kwargs.update(
+        {
+            "team_domain": team_domain,
+            "team_name": team_name,
+            "team_description": team_description,
+            "team_discoverability": team_discoverability,
+        }
+    )
+    return self.api_call("admin.teams.create", params=kwargs)
+
+ +
+
+def admin_teams_list(self, *, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all teams on an Enterprise organization.
+    https://docs.slack.dev/reference/methods/admin.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.list", params=kwargs)
+
+

List all teams on an Enterprise organization. +https://docs.slack.dev/reference/methods/admin.teams.list

+
+
+def admin_teams_owners_list(self, *, team_id:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_owners_list(
+    self,
+    *,
+    team_id: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all of the admins on a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.owners.list
+    """
+    kwargs.update({"team_id": team_id, "cursor": cursor, "limit": limit})
+    return self.api_call("admin.teams.owners.list", http_verb="GET", params=kwargs)
+
+

List all of the admins on a given workspace. +https://docs.slack.dev/reference/methods/admin.teams.owners.list

+
+
+def admin_teams_settings_info(self, *, team_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_info(
+    self,
+    *,
+    team_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetch information about settings in a workspace
+    https://docs.slack.dev/reference/methods/admin.teams.settings.info
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("admin.teams.settings.info", params=kwargs)
+
+

Fetch information about settings in a workspace +https://docs.slack.dev/reference/methods/admin.teams.settings.info

+
+
+def admin_teams_settings_setDefaultChannels(self, *, team_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDefaultChannels(
+    self,
+    *,
+    team_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the default channels of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDefaultChannels
+    """
+    kwargs.update({"team_id": team_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.teams.settings.setDefaultChannels", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDescription(self, *, team_id:Β str, description:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDescription(
+    self,
+    *,
+    team_id: str,
+    description: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the description of a given workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDescription
+    """
+    kwargs.update({"team_id": team_id, "description": description})
+    return self.api_call("admin.teams.settings.setDescription", params=kwargs)
+
+ +
+
+def admin_teams_settings_setDiscoverability(self, *, team_id:Β str, discoverability:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setDiscoverability(
+    self,
+    *,
+    team_id: str,
+    discoverability: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setDiscoverability
+    """
+    kwargs.update({"team_id": team_id, "discoverability": discoverability})
+    return self.api_call("admin.teams.settings.setDiscoverability", params=kwargs)
+
+ +
+
+def admin_teams_settings_setIcon(self, *, team_id:Β str, image_url:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setIcon(
+    self,
+    *,
+    team_id: str,
+    image_url: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setIcon
+    """
+    kwargs.update({"team_id": team_id, "image_url": image_url})
+    return self.api_call("admin.teams.settings.setIcon", http_verb="GET", params=kwargs)
+
+ +
+
+def admin_teams_settings_setName(self, *, team_id:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_teams_settings_setName(
+    self,
+    *,
+    team_id: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the icon of a workspace.
+    https://docs.slack.dev/reference/methods/admin.teams.settings.setName
+    """
+    kwargs.update({"team_id": team_id, "name": name})
+    return self.api_call("admin.teams.settings.setName", params=kwargs)
+
+ +
+
+def admin_usergroups_addChannels(self,
*,
channel_ids:Β strΒ |Β Sequence[str],
usergroup_id:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addChannels(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    usergroup_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addChannels
+    """
+    kwargs.update({"team_id": team_id, "usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.addChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addChannels

+
+
+def admin_usergroups_addTeams(self,
*,
usergroup_id:Β str,
team_ids:Β strΒ |Β Sequence[str],
auto_provision:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_addTeams(
+    self,
+    *,
+    usergroup_id: str,
+    team_ids: Union[str, Sequence[str]],
+    auto_provision: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Associate one or more default workspaces with an organization-wide IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.addTeams
+    """
+    kwargs.update({"usergroup_id": usergroup_id, "auto_provision": auto_provision})
+    if isinstance(team_ids, (list, tuple)):
+        kwargs.update({"team_ids": ",".join(team_ids)})
+    else:
+        kwargs.update({"team_ids": team_ids})
+    return self.api_call("admin.usergroups.addTeams", params=kwargs)
+
+

Associate one or more default workspaces with an organization-wide IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.addTeams

+
+
+def admin_usergroups_listChannels(self,
*,
usergroup_id:Β str,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
team_id:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_usergroups_listChannels(
+    self,
+    *,
+    usergroup_id: str,
+    include_num_members: Optional[bool] = None,
+    team_id: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.listChannels
+    """
+    kwargs.update(
+        {
+            "usergroup_id": usergroup_id,
+            "include_num_members": include_num_members,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("admin.usergroups.listChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.listChannels

+
+
+def admin_usergroups_removeChannels(self, *, usergroup_id:Β str, channel_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_usergroups_removeChannels(
+    self,
+    *,
+    usergroup_id: str,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add one or more default channels to an IDP group.
+    https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels
+    """
+    kwargs.update({"usergroup_id": usergroup_id})
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.usergroups.removeChannels", params=kwargs)
+
+

Add one or more default channels to an IDP group. +https://docs.slack.dev/reference/methods/admin.usergroups.removeChannels

+
+
+def admin_users_assign(self,
*,
team_id:Β str,
user_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_assign(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    channel_ids: Optional[Union[str, Sequence[str]]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add an Enterprise user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.assign
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "user_id": user_id,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.assign", params=kwargs)
+
+

Add an Enterprise user to a workspace. +https://docs.slack.dev/reference/methods/admin.users.assign

+
+
+def admin_users_invite(self,
*,
team_id:Β str,
email:Β str,
channel_ids:Β strΒ |Β Sequence[str],
custom_message:Β strΒ |Β NoneΒ =Β None,
email_password_policy_enabled:Β boolΒ |Β NoneΒ =Β None,
guest_expiration_ts:Β strΒ |Β floatΒ |Β NoneΒ =Β None,
is_restricted:Β boolΒ |Β NoneΒ =Β None,
is_ultra_restricted:Β boolΒ |Β NoneΒ =Β None,
real_name:Β strΒ |Β NoneΒ =Β None,
resend:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_invite(
+    self,
+    *,
+    team_id: str,
+    email: str,
+    channel_ids: Union[str, Sequence[str]],
+    custom_message: Optional[str] = None,
+    email_password_policy_enabled: Optional[bool] = None,
+    guest_expiration_ts: Optional[Union[str, float]] = None,
+    is_restricted: Optional[bool] = None,
+    is_ultra_restricted: Optional[bool] = None,
+    real_name: Optional[str] = None,
+    resend: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invite a user to a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.invite
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "email": email,
+            "custom_message": custom_message,
+            "email_password_policy_enabled": email_password_policy_enabled,
+            "guest_expiration_ts": str(guest_expiration_ts) if guest_expiration_ts is not None else None,
+            "is_restricted": is_restricted,
+            "is_ultra_restricted": is_ultra_restricted,
+            "real_name": real_name,
+            "resend": resend,
+        }
+    )
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("admin.users.invite", params=kwargs)
+
+ +
+
+def admin_users_list(self,
*,
team_id:Β strΒ |Β NoneΒ =Β None,
include_deactivated_user_workspaces:Β boolΒ |Β NoneΒ =Β None,
is_active:Β boolΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    include_deactivated_user_workspaces: Optional[bool] = None,
+    is_active: Optional[bool] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List users on a workspace
+    https://docs.slack.dev/reference/methods/admin.users.list
+    """
+    kwargs.update(
+        {
+            "team_id": team_id,
+            "include_deactivated_user_workspaces": include_deactivated_user_workspaces,
+            "is_active": is_active,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("admin.users.list", params=kwargs)
+
+ +
+
+def admin_users_remove(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_remove(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove a user from a workspace.
+    https://docs.slack.dev/reference/methods/admin.users.remove
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.remove", params=kwargs)
+
+ +
+
+def admin_users_session_clearSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_clearSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Clear user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”for a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.clearSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.clearSettings", params=kwargs)
+
+

Clear user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”for a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.clearSettings

+
+
+def admin_users_session_getSettings(self, *, user_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_getSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get user-specific session settingsβ€”the session duration
+    and what happens when the client closesβ€”given a list of users.
+    https://docs.slack.dev/reference/methods/admin.users.session.getSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("admin.users.session.getSettings", params=kwargs)
+
+

Get user-specific session settingsβ€”the session duration +and what happens when the client closesβ€”given a list of users. +https://docs.slack.dev/reference/methods/admin.users.session.getSettings

+
+
+def admin_users_session_invalidate(self, *, session_id:Β str, team_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_session_invalidate(
+    self,
+    *,
+    session_id: str,
+    team_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invalidate a single session for a user by session_id.
+    https://docs.slack.dev/reference/methods/admin.users.session.invalidate
+    """
+    kwargs.update({"session_id": session_id, "team_id": team_id})
+    return self.api_call("admin.users.session.invalidate", params=kwargs)
+
+

Invalidate a single session for a user by session_id. +https://docs.slack.dev/reference/methods/admin.users.session.invalidate

+
+
+def admin_users_session_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all active user sessions for an organization
+    https://docs.slack.dev/reference/methods/admin.users.session.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "limit": limit,
+            "team_id": team_id,
+            "user_id": user_id,
+        }
+    )
+    return self.api_call("admin.users.session.list", params=kwargs)
+
+

Lists all active user sessions for an organization +https://docs.slack.dev/reference/methods/admin.users.session.list

+
+
+def admin_users_session_reset(self,
*,
user_id:Β str,
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_reset(
+    self,
+    *,
+    user_id: str,
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Wipes all valid sessions on all devices for a given user.
+    https://docs.slack.dev/reference/methods/admin.users.session.reset
+    """
+    kwargs.update(
+        {
+            "user_id": user_id,
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.reset", params=kwargs)
+
+

Wipes all valid sessions on all devices for a given user. +https://docs.slack.dev/reference/methods/admin.users.session.reset

+
+
+def admin_users_session_resetBulk(self,
*,
user_ids:Β strΒ |Β Sequence[str],
mobile_only:Β boolΒ |Β NoneΒ =Β None,
web_only:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_resetBulk(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    mobile_only: Optional[bool] = None,
+    web_only: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users
+    https://docs.slack.dev/reference/methods/admin.users.session.resetBulk
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "mobile_only": mobile_only,
+            "web_only": web_only,
+        }
+    )
+    return self.api_call("admin.users.session.resetBulk", params=kwargs)
+
+

Enqueues an asynchronous job to wipe all valid sessions on all devices for a given list of users +https://docs.slack.dev/reference/methods/admin.users.session.resetBulk

+
+
+def admin_users_session_setSettings(self,
*,
user_ids:Β strΒ |Β Sequence[str],
desktop_app_browser_quit:Β boolΒ |Β NoneΒ =Β None,
duration:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_session_setSettings(
+    self,
+    *,
+    user_ids: Union[str, Sequence[str]],
+    desktop_app_browser_quit: Optional[bool] = None,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Configure the user-level session settingsβ€”the session duration
+    and what happens when the client closesβ€”for one or more users.
+    https://docs.slack.dev/reference/methods/admin.users.session.setSettings
+    """
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    kwargs.update(
+        {
+            "desktop_app_browser_quit": desktop_app_browser_quit,
+            "duration": duration,
+        }
+    )
+    return self.api_call("admin.users.session.setSettings", params=kwargs)
+
+

Configure the user-level session settingsβ€”the session duration +and what happens when the client closesβ€”for one or more users. +https://docs.slack.dev/reference/methods/admin.users.session.setSettings

+
+
+def admin_users_setAdmin(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_setAdmin(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set an existing guest, regular user, or owner to be an admin user.
+    https://docs.slack.dev/reference/methods/admin.users.setAdmin
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setAdmin", params=kwargs)
+
+

Set an existing guest, regular user, or owner to be an admin user. +https://docs.slack.dev/reference/methods/admin.users.setAdmin

+
+
+def admin_users_setExpiration(self, *, expiration_ts:Β int, user_id:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_setExpiration(
+    self,
+    *,
+    expiration_ts: int,
+    user_id: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set an expiration for a guest user.
+    https://docs.slack.dev/reference/methods/admin.users.setExpiration
+    """
+    kwargs.update({"expiration_ts": expiration_ts, "team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setExpiration", params=kwargs)
+
+ +
+
+def admin_users_setOwner(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_setOwner(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set an existing guest, regular user, or admin user to be a workspace owner.
+    https://docs.slack.dev/reference/methods/admin.users.setOwner
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setOwner", params=kwargs)
+
+

Set an existing guest, regular user, or admin user to be a workspace owner. +https://docs.slack.dev/reference/methods/admin.users.setOwner

+
+
+def admin_users_setRegular(self, *, team_id:Β str, user_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_users_setRegular(
+    self,
+    *,
+    team_id: str,
+    user_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set an existing guest user, admin user, or owner to be a regular user.
+    https://docs.slack.dev/reference/methods/admin.users.setRegular
+    """
+    kwargs.update({"team_id": team_id, "user_id": user_id})
+    return self.api_call("admin.users.setRegular", params=kwargs)
+
+

Set an existing guest user, admin user, or owner to be a regular user. +https://docs.slack.dev/reference/methods/admin.users.setRegular

+
+
+def admin_users_unsupportedVersions_export(self,
*,
date_end_of_support:Β strΒ |Β intΒ |Β NoneΒ =Β None,
date_sessions_started:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_users_unsupportedVersions_export(
+    self,
+    *,
+    date_end_of_support: Optional[Union[str, int]] = None,
+    date_sessions_started: Optional[Union[str, int]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Ask Slackbot to send you an export listing all workspace members using unsupported software,
+    presented as a zipped CSV file.
+    https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export
+    """
+    kwargs.update(
+        {
+            "date_end_of_support": date_end_of_support,
+            "date_sessions_started": date_sessions_started,
+        }
+    )
+    return self.api_call("admin.users.unsupportedVersions.export", params=kwargs)
+
+

Ask Slackbot to send you an export listing all workspace members using unsupported software, +presented as a zipped CSV file. +https://docs.slack.dev/reference/methods/admin.users.unsupportedVersions.export

+
+
+def admin_workflows_collaborators_add(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_add(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add collaborators to workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.add", params=kwargs)
+
+

Add collaborators to workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.add

+
+
+def admin_workflows_collaborators_remove(self,
*,
collaborator_ids:Β strΒ |Β Sequence[str],
workflow_ids:Β strΒ |Β Sequence[str],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_collaborators_remove(
+    self,
+    *,
+    collaborator_ids: Union[str, Sequence[str]],
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove collaborators from workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove
+    """
+    if isinstance(collaborator_ids, (list, tuple)):
+        kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+    else:
+        kwargs.update({"collaborator_ids": collaborator_ids})
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.collaborators.remove", params=kwargs)
+
+

Remove collaborators from workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.collaborators.remove

+
+
+def admin_workflows_permissions_lookup(self,
*,
workflow_ids:Β strΒ |Β Sequence[str],
max_workflow_triggers:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def admin_workflows_permissions_lookup(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    max_workflow_triggers: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Look up the permissions for a set of workflows
+    https://docs.slack.dev/reference/methods/admin.workflows.permissions.lookup
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    kwargs.update(
+        {
+            "max_workflow_triggers": max_workflow_triggers,
+        }
+    )
+    return self.api_call("admin.workflows.permissions.lookup", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def admin_workflows_search(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    collaborator_ids: Optional[Union[str, Sequence[str]]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    no_collaborators: Optional[bool] = None,
+    num_trigger_ids: Optional[int] = None,
+    query: Optional[str] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    source: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Search workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.search
+    """
+    if collaborator_ids is not None:
+        if isinstance(collaborator_ids, (list, tuple)):
+            kwargs.update({"collaborator_ids": ",".join(collaborator_ids)})
+        else:
+            kwargs.update({"collaborator_ids": collaborator_ids})
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "cursor": cursor,
+            "limit": limit,
+            "no_collaborators": no_collaborators,
+            "num_trigger_ids": num_trigger_ids,
+            "query": query,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "source": source,
+        }
+    )
+    return self.api_call("admin.workflows.search", params=kwargs)
+
+

Search workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.search

+
+
+def admin_workflows_unpublish(self, *, workflow_ids:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def admin_workflows_unpublish(
+    self,
+    *,
+    workflow_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Unpublish workflows within the team or enterprise
+    https://docs.slack.dev/reference/methods/admin.workflows.unpublish
+    """
+    if isinstance(workflow_ids, (list, tuple)):
+        kwargs.update({"workflow_ids": ",".join(workflow_ids)})
+    else:
+        kwargs.update({"workflow_ids": workflow_ids})
+    return self.api_call("admin.workflows.unpublish", params=kwargs)
+
+

Unpublish workflows within the team or enterprise +https://docs.slack.dev/reference/methods/admin.workflows.unpublish

+
+
+def api_test(self, *, error:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def api_test(
+    self,
+    *,
+    error: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Checks API calling code.
+    https://docs.slack.dev/reference/methods/api.test
+    """
+    kwargs.update({"error": error})
+    return self.api_call("api.test", params=kwargs)
+
+ +
+
+def apps_connections_open(self, *, app_token:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_connections_open(
+    self,
+    *,
+    app_token: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Generate a temporary Socket Mode WebSocket URL that your app can connect to
+    in order to receive events and interactive payloads
+    https://docs.slack.dev/reference/methods/apps.connections.open
+    """
+    kwargs.update({"token": app_token})
+    return self.api_call("apps.connections.open", http_verb="POST", params=kwargs)
+
+

Generate a temporary Socket Mode WebSocket URL that your app can connect to +in order to receive events and interactive payloads +https://docs.slack.dev/reference/methods/apps.connections.open

+
+
+def apps_event_authorizations_list(self,
*,
event_context:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def apps_event_authorizations_list(
+    self,
+    *,
+    event_context: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get a list of authorizations for the given event context.
+    Each authorization represents an app installation that the event is visible to.
+    https://docs.slack.dev/reference/methods/apps.event.authorizations.list
+    """
+    kwargs.update({"event_context": event_context, "cursor": cursor, "limit": limit})
+    return self.api_call("apps.event.authorizations.list", params=kwargs)
+
+

Get a list of authorizations for the given event context. +Each authorization represents an app installation that the event is visible to. +https://docs.slack.dev/reference/methods/apps.event.authorizations.list

+
+
+def apps_manifest_create(self, *, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_create(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.create
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    return self.api_call("apps.manifest.create", params=kwargs)
+
+ +
+
+def apps_manifest_delete(self, *, app_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_delete(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Permanently deletes an app created through app manifests
+    https://docs.slack.dev/reference/methods/apps.manifest.delete
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.delete", params=kwargs)
+
+

Permanently deletes an app created through app manifests +https://docs.slack.dev/reference/methods/apps.manifest.delete

+
+
+def apps_manifest_export(self, *, app_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_export(
+    self,
+    *,
+    app_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Export an app manifest from an existing app
+    https://docs.slack.dev/reference/methods/apps.manifest.export
+    """
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.export", params=kwargs)
+
+

Export an app manifest from an existing app +https://docs.slack.dev/reference/methods/apps.manifest.export

+
+
+def apps_manifest_update(self, *, app_id:Β str, manifest:Β strΒ |Β Dict[str,Β Any], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_update(
+    self,
+    *,
+    app_id: str,
+    manifest: Union[str, Dict[str, Any]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update an app from an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.update
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.update", params=kwargs)
+
+ +
+
+def apps_manifest_validate(self, *, manifest:Β strΒ |Β Dict[str,Β Any], app_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_manifest_validate(
+    self,
+    *,
+    manifest: Union[str, Dict[str, Any]],
+    app_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Validate an app manifest
+    https://docs.slack.dev/reference/methods/apps.manifest.validate
+    """
+    if isinstance(manifest, str):
+        kwargs.update({"manifest": manifest})
+    else:
+        kwargs.update({"manifest": json.dumps(manifest)})
+    kwargs.update({"app_id": app_id})
+    return self.api_call("apps.manifest.validate", params=kwargs)
+
+ +
+
+def apps_uninstall(self, *, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def apps_uninstall(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Uninstalls your app from a workspace.
+    https://docs.slack.dev/reference/methods/apps.uninstall
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret})
+    return self.api_call("apps.uninstall", params=kwargs)
+
+

Uninstalls your app from a workspace. +https://docs.slack.dev/reference/methods/apps.uninstall

+
+
+def assistant_threads_setStatus(self,
*,
channel_id:Β str,
thread_ts:Β str,
status:Β str,
loading_messages:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setStatus(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    status: str,
+    loading_messages: Optional[List[str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the status for an AI assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setStatus
+    """
+    kwargs.update(
+        {"channel_id": channel_id, "thread_ts": thread_ts, "status": status, "loading_messages": loading_messages}
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("assistant.threads.setStatus", json=kwargs)
+
+ +
+
+def assistant_threads_setSuggestedPrompts(self,
*,
channel_id:Β str,
thread_ts:Β str,
title:Β strΒ |Β NoneΒ =Β None,
prompts:Β List[Dict[str,Β str]],
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def assistant_threads_setSuggestedPrompts(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: Optional[str] = None,
+    prompts: List[Dict[str, str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set suggested prompts for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "prompts": prompts})
+    if title is not None:
+        kwargs.update({"title": title})
+    return self.api_call("assistant.threads.setSuggestedPrompts", json=kwargs)
+
+

Set suggested prompts for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setSuggestedPrompts

+
+
+def assistant_threads_setTitle(self, *, channel_id:Β str, thread_ts:Β str, title:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def assistant_threads_setTitle(
+    self,
+    *,
+    channel_id: str,
+    thread_ts: str,
+    title: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the title for the given assistant thread.
+    https://docs.slack.dev/reference/methods/assistant.threads.setTitle
+    """
+    kwargs.update({"channel_id": channel_id, "thread_ts": thread_ts, "title": title})
+    return self.api_call("assistant.threads.setTitle", params=kwargs)
+
+

Set the title for the given assistant thread. +https://docs.slack.dev/reference/methods/assistant.threads.setTitle

+
+
+def auth_revoke(self, *, test:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def auth_revoke(
+    self,
+    *,
+    test: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Revokes a token.
+    https://docs.slack.dev/reference/methods/auth.revoke
+    """
+    kwargs.update({"test": test})
+    return self.api_call("auth.revoke", http_verb="GET", params=kwargs)
+
+ +
+
+def auth_teams_list(self,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
include_icon:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def auth_teams_list(
+    self,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    include_icon: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List the workspaces a token can access.
+    https://docs.slack.dev/reference/methods/auth.teams.list
+    """
+    kwargs.update({"cursor": cursor, "limit": limit, "include_icon": include_icon})
+    return self.api_call("auth.teams.list", params=kwargs)
+
+

List the workspaces a token can access. +https://docs.slack.dev/reference/methods/auth.teams.list

+
+
+def auth_test(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def auth_test(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Checks authentication & identity.
+    https://docs.slack.dev/reference/methods/auth.test
+    """
+    return self.api_call("auth.test", params=kwargs)
+
+

Checks authentication & identity. +https://docs.slack.dev/reference/methods/auth.test

+
+
+def bookmarks_add(self,
*,
channel_id:Β str,
title:Β str,
type:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
entity_id:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
parent_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_add(
+    self,
+    *,
+    channel_id: str,
+    title: str,
+    type: str,
+    emoji: Optional[str] = None,
+    entity_id: Optional[str] = None,
+    link: Optional[str] = None,  # include when type is 'link'
+    parent_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add bookmark to a channel.
+    https://docs.slack.dev/reference/methods/bookmarks.add
+    """
+    kwargs.update(
+        {
+            "channel_id": channel_id,
+            "title": title,
+            "type": type,
+            "emoji": emoji,
+            "entity_id": entity_id,
+            "link": link,
+            "parent_id": parent_id,
+        }
+    )
+    return self.api_call("bookmarks.add", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_edit(self,
*,
bookmark_id:Β str,
channel_id:Β str,
emoji:Β strΒ |Β NoneΒ =Β None,
link:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def bookmarks_edit(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    emoji: Optional[str] = None,
+    link: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Edit bookmark.
+    https://docs.slack.dev/reference/methods/bookmarks.edit
+    """
+    kwargs.update(
+        {
+            "bookmark_id": bookmark_id,
+            "channel_id": channel_id,
+            "emoji": emoji,
+            "link": link,
+            "title": title,
+        }
+    )
+    return self.api_call("bookmarks.edit", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_list(self, *, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def bookmarks_list(
+    self,
+    *,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List bookmark for the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.list
+    """
+    kwargs.update({"channel_id": channel_id})
+    return self.api_call("bookmarks.list", http_verb="POST", params=kwargs)
+
+ +
+
+def bookmarks_remove(self, *, bookmark_id:Β str, channel_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def bookmarks_remove(
+    self,
+    *,
+    bookmark_id: str,
+    channel_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove bookmark from the channel.
+    https://docs.slack.dev/reference/methods/bookmarks.remove
+    """
+    kwargs.update({"bookmark_id": bookmark_id, "channel_id": channel_id})
+    return self.api_call("bookmarks.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def bots_info(self, *, bot:Β strΒ |Β NoneΒ =Β None, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def bots_info(
+    self,
+    *,
+    bot: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a bot user.
+    https://docs.slack.dev/reference/methods/bots.info
+    """
+    kwargs.update({"bot": bot, "team_id": team_id})
+    return self.api_call("bots.info", http_verb="GET", params=kwargs)
+
+

Gets information about a bot user. +https://docs.slack.dev/reference/methods/bots.info

+
+
+def calls_add(self,
*,
external_unique_id:Β str,
join_url:Β str,
created_by:Β strΒ |Β NoneΒ =Β None,
date_start:Β intΒ |Β NoneΒ =Β None,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
external_display_id:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def calls_add(
+    self,
+    *,
+    external_unique_id: str,
+    join_url: str,
+    created_by: Optional[str] = None,
+    date_start: Optional[int] = None,
+    desktop_app_join_url: Optional[str] = None,
+    external_display_id: Optional[str] = None,
+    title: Optional[str] = None,
+    users: Optional[Union[str, Sequence[Dict[str, str]]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Registers a new Call.
+    https://docs.slack.dev/reference/methods/calls.add
+    """
+    kwargs.update(
+        {
+            "external_unique_id": external_unique_id,
+            "join_url": join_url,
+            "created_by": created_by,
+            "date_start": date_start,
+            "desktop_app_join_url": desktop_app_join_url,
+            "external_display_id": external_display_id,
+            "title": title,
+        }
+    )
+    _update_call_participants(
+        kwargs,
+        users if users is not None else kwargs.get("users"),  # type: ignore[arg-type]
+    )
+    return self.api_call("calls.add", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_end(self, *, id:Β str, duration:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def calls_end(
+    self,
+    *,
+    id: str,
+    duration: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Ends a Call.
+    https://docs.slack.dev/reference/methods/calls.end
+    """
+    kwargs.update({"id": id, "duration": duration})
+    return self.api_call("calls.end", http_verb="POST", params=kwargs)
+
+ +
+
+def calls_info(self, *, id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def calls_info(
+    self,
+    *,
+    id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Returns information about a Call.
+    https://docs.slack.dev/reference/methods/calls.info
+    """
+    kwargs.update({"id": id})
+    return self.api_call("calls.info", http_verb="POST", params=kwargs)
+
+

Returns information about a Call. +https://docs.slack.dev/reference/methods/calls.info

+
+
+def calls_participants_add(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def calls_participants_add(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Registers new participants added to a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.add
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.add", http_verb="POST", params=kwargs)
+
+

Registers new participants added to a Call. +https://docs.slack.dev/reference/methods/calls.participants.add

+
+
+def calls_participants_remove(self, *, id:Β str, users:Β strΒ |Β Sequence[Dict[str,Β str]], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def calls_participants_remove(
+    self,
+    *,
+    id: str,
+    users: Union[str, Sequence[Dict[str, str]]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Registers participants removed from a Call.
+    https://docs.slack.dev/reference/methods/calls.participants.remove
+    """
+    kwargs.update({"id": id})
+    _update_call_participants(kwargs, users)
+    return self.api_call("calls.participants.remove", http_verb="POST", params=kwargs)
+
+

Registers participants removed from a Call. +https://docs.slack.dev/reference/methods/calls.participants.remove

+
+
+def calls_update(self,
*,
id:Β str,
desktop_app_join_url:Β strΒ |Β NoneΒ =Β None,
join_url:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def calls_update(
+    self,
+    *,
+    id: str,
+    desktop_app_join_url: Optional[str] = None,
+    join_url: Optional[str] = None,
+    title: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Updates information about a Call.
+    https://docs.slack.dev/reference/methods/calls.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "desktop_app_join_url": desktop_app_join_url,
+            "join_url": join_url,
+            "title": title,
+        }
+    )
+    return self.api_call("calls.update", http_verb="POST", params=kwargs)
+
+ +
+
+def canvases_access_delete(self,
*,
canvas_id:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_delete(
+    self,
+    *,
+    canvas_id: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/canvases.access.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+    return self.api_call("canvases.access.delete", params=kwargs)
+
+ +
+
+def canvases_access_set(self,
*,
canvas_id:Β str,
access_level:Β str,
channel_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def canvases_access_set(
+    self,
+    *,
+    canvas_id: str,
+    access_level: str,
+    channel_ids: Optional[Union[Sequence[str], str]] = None,
+    user_ids: Optional[Union[Sequence[str], str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the access level to a canvas for specified entities
+    https://docs.slack.dev/reference/methods/canvases.access.set
+    """
+    kwargs.update({"canvas_id": canvas_id, "access_level": access_level})
+    if channel_ids is not None:
+        if isinstance(channel_ids, (list, tuple)):
+            kwargs.update({"channel_ids": ",".join(channel_ids)})
+        else:
+            kwargs.update({"channel_ids": channel_ids})
+    if user_ids is not None:
+        if isinstance(user_ids, (list, tuple)):
+            kwargs.update({"user_ids": ",".join(user_ids)})
+        else:
+            kwargs.update({"user_ids": user_ids})
+
+    return self.api_call("canvases.access.set", params=kwargs)
+
+

Sets the access level to a canvas for specified entities +https://docs.slack.dev/reference/methods/canvases.access.set

+
+
+def canvases_create(self, *, title:Β strΒ |Β NoneΒ =Β None, document_content:Β Dict[str,Β str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def canvases_create(
+    self,
+    *,
+    title: Optional[str] = None,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create Canvas for a user
+    https://docs.slack.dev/reference/methods/canvases.create
+    """
+    kwargs.update({"title": title, "document_content": document_content})
+    return self.api_call("canvases.create", json=kwargs)
+
+ +
+
+def canvases_delete(self, *, canvas_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def canvases_delete(
+    self,
+    *,
+    canvas_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes a canvas
+    https://docs.slack.dev/reference/methods/canvases.delete
+    """
+    kwargs.update({"canvas_id": canvas_id})
+    return self.api_call("canvases.delete", params=kwargs)
+
+ +
+
+def canvases_edit(self, *, canvas_id:Β str, changes:Β Sequence[Dict[str,Β Any]], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def canvases_edit(
+    self,
+    *,
+    canvas_id: str,
+    changes: Sequence[Dict[str, Any]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update an existing canvas
+    https://docs.slack.dev/reference/methods/canvases.edit
+    """
+    kwargs.update({"canvas_id": canvas_id, "changes": changes})
+    return self.api_call("canvases.edit", json=kwargs)
+
+ +
+
+def canvases_sections_lookup(self, *, canvas_id:Β str, criteria:Β Dict[str,Β Any], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def canvases_sections_lookup(
+    self,
+    *,
+    canvas_id: str,
+    criteria: Dict[str, Any],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Find sections matching the provided criteria
+    https://docs.slack.dev/reference/methods/canvases.sections.lookup
+    """
+    kwargs.update({"canvas_id": canvas_id, "criteria": json.dumps(criteria)})
+    return self.api_call("canvases.sections.lookup", params=kwargs)
+
+

Find sections matching the provided criteria +https://docs.slack.dev/reference/methods/canvases.sections.lookup

+
+
+def channels_archive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Archives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.archive", json=kwargs)
+
+

Archives a channel.

+
+
+def channels_create(self, *, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Creates a channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.create", json=kwargs)
+
+

Creates a channel.

+
+
+def channels_history(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetches history of messages and events from a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a channel.

+
+
+def channels_info(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("channels.info", http_verb="GET", params=kwargs)
+
+

Gets information about a channel.

+
+
+def channels_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invites a user to a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.invite", json=kwargs)
+
+

Invites a user to a channel.

+
+
+def channels_join(self, *, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_join(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Joins a channel, creating it if needed."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.join", json=kwargs)
+
+

Joins a channel, creating it if needed.

+
+
+def channels_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a user from a channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.kick", json=kwargs)
+
+

Removes a user from a channel.

+
+
+def channels_leave(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Leaves a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.leave", json=kwargs)
+
+

Leaves a channel.

+
+
+def channels_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all channels in a Slack team."""
+    return self.api_call("channels.list", http_verb="GET", params=kwargs)
+
+

Lists all channels in a Slack team.

+
+
+def channels_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the read cursor in a channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.mark", json=kwargs)
+
+

Sets the read cursor in a channel.

+
+
+def channels_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Renames a channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.rename", json=kwargs)
+
+

Renames a channel.

+
+
+def channels_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a thread of messages posted to a channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("channels.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a channel

+
+
+def channels_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the purpose for a channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setPurpose", json=kwargs)
+
+

Sets the purpose for a channel.

+
+
+def channels_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the topic for a channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.setTopic", json=kwargs)
+
+

Sets the topic for a channel.

+
+
+def channels_unarchive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def channels_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Unarchives a channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("channels.unarchive", json=kwargs)
+
+

Unarchives a channel.

+
+
+def chat_appendStream(self, *, channel:Β str, ts:Β str, markdown_text:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def chat_appendStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Appends text to an existing streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.appendStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.appendStream", json=kwargs)
+
+

Appends text to an existing streaming conversation. +https://docs.slack.dev/reference/methods/chat.appendStream

+
+
+def chat_delete(self, *, channel:Β str, ts:Β str, as_user:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def chat_delete(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes a message.
+    https://docs.slack.dev/reference/methods/chat.delete
+    """
+    kwargs.update({"channel": channel, "ts": ts, "as_user": as_user})
+    return self.api_call("chat.delete", params=kwargs)
+
+ +
+
+def chat_deleteScheduledMessage(self,
*,
channel:Β str,
scheduled_message_id:Β str,
as_user:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_deleteScheduledMessage(
+    self,
+    *,
+    channel: str,
+    scheduled_message_id: str,
+    as_user: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes a scheduled message.
+    https://docs.slack.dev/reference/methods/chat.deleteScheduledMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "scheduled_message_id": scheduled_message_id,
+            "as_user": as_user,
+        }
+    )
+    return self.api_call("chat.deleteScheduledMessage", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def chat_getPermalink(
+    self,
+    *,
+    channel: str,
+    message_ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a permalink URL for a specific extant message
+    https://docs.slack.dev/reference/methods/chat.getPermalink
+    """
+    kwargs.update({"channel": channel, "message_ts": message_ts})
+    return self.api_call("chat.getPermalink", http_verb="GET", params=kwargs)
+
+

Retrieve a permalink URL for a specific extant message +https://docs.slack.dev/reference/methods/chat.getPermalink

+
+
+def chat_meMessage(self, *, channel:Β str, text:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def chat_meMessage(
+    self,
+    *,
+    channel: str,
+    text: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Share a me message into a channel.
+    https://docs.slack.dev/reference/methods/chat.meMessage
+    """
+    kwargs.update({"channel": channel, "text": text})
+    return self.api_call("chat.meMessage", params=kwargs)
+
+ +
+
+def chat_postEphemeral(self,
*,
channel:Β str,
user:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_postEphemeral(
+    self,
+    *,
+    channel: str,
+    user: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sends an ephemeral message to a user in a channel.
+    https://docs.slack.dev/reference/methods/chat.postEphemeral
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "user": user,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postEphemeral", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postEphemeral", json=kwargs)
+
+

Sends an ephemeral message to a user in a channel. +https://docs.slack.dev/reference/methods/chat.postEphemeral

+
+
+def chat_postMessage(self,
*,
channel:Β str,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
container_id:Β strΒ |Β NoneΒ =Β None,
icon_emoji:Β strΒ |Β NoneΒ =Β None,
icon_url:Β strΒ |Β NoneΒ =Β None,
mrkdwn:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
username:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_postMessage(
+    self,
+    *,
+    channel: str,
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    container_id: Optional[str] = None,
+    icon_emoji: Optional[str] = None,
+    icon_url: Optional[str] = None,
+    mrkdwn: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    username: Optional[str] = None,
+    parse: Optional[str] = None,  # none, full
+    metadata: Optional[Union[Dict, Metadata, EventAndEntityMetadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sends a message to a channel.
+    https://docs.slack.dev/reference/methods/chat.postMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "container_id": container_id,
+            "icon_emoji": icon_emoji,
+            "icon_url": icon_url,
+            "mrkdwn": mrkdwn,
+            "link_names": link_names,
+            "username": username,
+            "parse": parse,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.postMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.postMessage", json=kwargs)
+
+ +
+
+def chat_scheduleMessage(self,
*,
channel:Β str,
post_at:Β strΒ |Β int,
text:Β strΒ |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduleMessage(
+    self,
+    *,
+    channel: str,
+    post_at: Union[str, int],
+    text: Optional[str] = None,
+    as_user: Optional[bool] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    thread_ts: Optional[str] = None,
+    parse: Optional[str] = None,
+    reply_broadcast: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    link_names: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Schedules a message.
+    https://docs.slack.dev/reference/methods/chat.scheduleMessage
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "post_at": post_at,
+            "text": text,
+            "as_user": as_user,
+            "attachments": attachments,
+            "blocks": blocks,
+            "thread_ts": thread_ts,
+            "reply_broadcast": reply_broadcast,
+            "parse": parse,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "link_names": link_names,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.scheduleMessage", kwargs)
+    # NOTE: intentionally using json over params for the API methods using blocks/attachments
+    return self.api_call("chat.scheduleMessage", json=kwargs)
+
+ +
+
+def chat_scheduledMessages_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_scheduledMessages_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all scheduled messages.
+    https://docs.slack.dev/reference/methods/chat.scheduledMessages.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "latest": latest,
+            "limit": limit,
+            "oldest": oldest,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("chat.scheduledMessages.list", params=kwargs)
+
+ +
+
+def chat_startStream(self,
*,
channel:Β str,
thread_ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
recipient_team_id:Β strΒ |Β NoneΒ =Β None,
recipient_user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_startStream(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    markdown_text: Optional[str] = None,
+    recipient_team_id: Optional[str] = None,
+    recipient_user_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Starts a new streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.startStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "thread_ts": thread_ts,
+            "markdown_text": markdown_text,
+            "recipient_team_id": recipient_team_id,
+            "recipient_user_id": recipient_user_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.startStream", json=kwargs)
+
+

Starts a new streaming conversation. +https://docs.slack.dev/reference/methods/chat.startStream

+
+
+def chat_stopStream(self,
*,
channel:Β str,
ts:Β str,
markdown_text:Β strΒ |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_stopStream(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    markdown_text: Optional[str] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Stops a streaming conversation.
+    https://docs.slack.dev/reference/methods/chat.stopStream
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "markdown_text": markdown_text,
+            "blocks": blocks,
+            "metadata": metadata,
+        }
+    )
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("chat.stopStream", json=kwargs)
+
+ +
+
+def chat_unfurl(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
ts:Β strΒ |Β NoneΒ =Β None,
source:Β strΒ |Β NoneΒ =Β None,
unfurl_id:Β strΒ |Β NoneΒ =Β None,
unfurls:Β Dict[str,Β Dict]Β |Β NoneΒ =Β None,
metadata:Β DictΒ |Β EventAndEntityMetadataΒ |Β NoneΒ =Β None,
user_auth_blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
user_auth_message:Β strΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_unfurl(
+    self,
+    *,
+    channel: Optional[str] = None,
+    ts: Optional[str] = None,
+    source: Optional[str] = None,
+    unfurl_id: Optional[str] = None,
+    unfurls: Optional[Dict[str, Dict]] = None,  # or user_auth_*
+    metadata: Optional[Union[Dict, EventAndEntityMetadata]] = None,
+    user_auth_blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    user_auth_message: Optional[str] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Provide custom unfurl behavior for user-posted URLs.
+    https://docs.slack.dev/reference/methods/chat.unfurl
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "source": source,
+            "unfurl_id": unfurl_id,
+            "unfurls": unfurls,
+            "metadata": metadata,
+            "user_auth_blocks": user_auth_blocks,
+            "user_auth_message": user_auth_message,
+            "user_auth_required": user_auth_required,
+            "user_auth_url": user_auth_url,
+        }
+    )
+    _parse_web_class_objects(kwargs)  # for user_auth_blocks
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.unfurl", json=kwargs)
+
+

Provide custom unfurl behavior for user-posted URLs. +https://docs.slack.dev/reference/methods/chat.unfurl

+
+
+def chat_update(self,
*,
channel:Β str,
ts:Β str,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β strΒ |Β Sequence[DictΒ |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β strΒ |Β Sequence[DictΒ |Β Block]Β |Β NoneΒ =Β None,
as_user:Β boolΒ |Β NoneΒ =Β None,
file_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
link_names:Β boolΒ |Β NoneΒ =Β None,
parse:Β strΒ |Β NoneΒ =Β None,
reply_broadcast:Β boolΒ |Β NoneΒ =Β None,
metadata:Β DictΒ |Β MetadataΒ |Β NoneΒ =Β None,
markdown_text:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def chat_update(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    text: Optional[str] = None,
+    attachments: Optional[Union[str, Sequence[Union[Dict, Attachment]]]] = None,
+    blocks: Optional[Union[str, Sequence[Union[Dict, Block]]]] = None,
+    as_user: Optional[bool] = None,
+    file_ids: Optional[Union[str, Sequence[str]]] = None,
+    link_names: Optional[bool] = None,
+    parse: Optional[str] = None,  # none, full
+    reply_broadcast: Optional[bool] = None,
+    metadata: Optional[Union[Dict, Metadata]] = None,
+    markdown_text: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Updates a message in a channel.
+    https://docs.slack.dev/reference/methods/chat.update
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "as_user": as_user,
+            "link_names": link_names,
+            "parse": parse,
+            "reply_broadcast": reply_broadcast,
+            "metadata": metadata,
+            "markdown_text": markdown_text,
+        }
+    )
+    if isinstance(file_ids, (list, tuple)):
+        kwargs.update({"file_ids": ",".join(file_ids)})
+    else:
+        kwargs.update({"file_ids": file_ids})
+    _parse_web_class_objects(kwargs)
+    kwargs = _remove_none_values(kwargs)
+    _warn_if_message_text_content_is_missing("chat.update", kwargs)
+    # NOTE: intentionally using json over params for API methods using blocks/attachments
+    return self.api_call("chat.update", json=kwargs)
+
+ +
+
+def conversations_acceptSharedInvite(self,
*,
channel_name:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
invite_id:Β strΒ |Β NoneΒ =Β None,
free_trial_accepted:Β boolΒ |Β NoneΒ =Β None,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_acceptSharedInvite(
+    self,
+    *,
+    channel_name: str,
+    channel_id: Optional[str] = None,
+    invite_id: Optional[str] = None,
+    free_trial_accepted: Optional[bool] = None,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Accepts an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite
+    """
+    if channel_id is None and invite_id is None:
+        raise e.SlackRequestError("Either channel_id or invite_id must be provided.")
+    kwargs.update(
+        {
+            "channel_name": channel_name,
+            "channel_id": channel_id,
+            "invite_id": invite_id,
+            "free_trial_accepted": free_trial_accepted,
+            "is_private": is_private,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("conversations.acceptSharedInvite", http_verb="POST", params=kwargs)
+
+

Accepts an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.acceptSharedInvite

+
+
+def conversations_approveSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_approveSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Approves an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.approveSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.approveSharedInvite", http_verb="POST", params=kwargs)
+
+

Approves an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.approveSharedInvite

+
+
+def conversations_archive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Archives a conversation.
+    https://docs.slack.dev/reference/methods/conversations.archive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.archive", params=kwargs)
+
+ +
+
+def conversations_canvases_create(self, *, channel_id:Β str, document_content:Β Dict[str,Β str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_canvases_create(
+    self,
+    *,
+    channel_id: str,
+    document_content: Dict[str, str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create a Channel Canvas for a channel
+    https://docs.slack.dev/reference/methods/conversations.canvases.create
+    """
+    kwargs.update({"channel_id": channel_id, "document_content": document_content})
+    return self.api_call("conversations.canvases.create", json=kwargs)
+
+ +
+
+def conversations_close(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Closes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.close
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.close", params=kwargs)
+
+

Closes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.close

+
+
+def conversations_create(self,
*,
name:Β str,
is_private:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_create(
+    self,
+    *,
+    name: str,
+    is_private: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Initiates a public or private channel-based conversation
+    https://docs.slack.dev/reference/methods/conversations.create
+    """
+    kwargs.update({"name": name, "is_private": is_private, "team_id": team_id})
+    return self.api_call("conversations.create", params=kwargs)
+
+

Initiates a public or private channel-based conversation +https://docs.slack.dev/reference/methods/conversations.create

+
+
+def conversations_declineSharedInvite(self, *, invite_id:Β str, target_team:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_declineSharedInvite(
+    self,
+    *,
+    invite_id: str,
+    target_team: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Declines a Slack Connect channel invite.
+    https://docs.slack.dev/reference/methods/conversations.declineSharedInvite
+    """
+    kwargs.update({"invite_id": invite_id, "target_team": target_team})
+    return self.api_call("conversations.declineSharedInvite", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_externalInvitePermissions_set(self, *, action:Β str, channel:Β str, target_team:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_externalInvitePermissions_set(
+    self, *, action: str, channel: str, target_team: str, **kwargs
+) -> Union[Future, SlackResponse]:
+    """Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa.
+    https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set
+    """
+    kwargs.update(
+        {
+            "action": action,
+            "channel": channel,
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("conversations.externalInvitePermissions.set", params=kwargs)
+
+

Sets a team in a shared External Limited channel to a shared Slack Connect channel or vice versa. +https://docs.slack.dev/reference/methods/conversations.externalInvitePermissions.set

+
+
+def conversations_history(self,
*,
channel:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_history(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetches a conversation's history of messages and events.
+    https://docs.slack.dev/reference/methods/conversations.history
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.history", http_verb="GET", params=kwargs)
+
+

Fetches a conversation's history of messages and events. +https://docs.slack.dev/reference/methods/conversations.history

+
+
+def conversations_info(self,
*,
channel:Β str,
include_locale:Β boolΒ |Β NoneΒ =Β None,
include_num_members:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_info(
+    self,
+    *,
+    channel: str,
+    include_locale: Optional[bool] = None,
+    include_num_members: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve information about a conversation.
+    https://docs.slack.dev/reference/methods/conversations.info
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "include_locale": include_locale,
+            "include_num_members": include_num_members,
+        }
+    )
+    return self.api_call("conversations.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a conversation. +https://docs.slack.dev/reference/methods/conversations.info

+
+
+def conversations_invite(self,
*,
channel:Β str,
users:Β strΒ |Β Sequence[str],
force:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_invite(
+    self,
+    *,
+    channel: str,
+    users: Union[str, Sequence[str]],
+    force: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invites users to a channel.
+    https://docs.slack.dev/reference/methods/conversations.invite
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "force": force,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.invite", params=kwargs)
+
+ +
+
+def conversations_inviteShared(self,
*,
channel:Β str,
emails:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_inviteShared(
+    self,
+    *,
+    channel: str,
+    emails: Optional[Union[str, Sequence[str]]] = None,
+    user_ids: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sends an invitation to a Slack Connect channel.
+    https://docs.slack.dev/reference/methods/conversations.inviteShared
+    """
+    if emails is None and user_ids is None:
+        raise e.SlackRequestError("Either emails or user ids must be provided.")
+    kwargs.update({"channel": channel})
+    if isinstance(emails, (list, tuple)):
+        kwargs.update({"emails": ",".join(emails)})
+    else:
+        kwargs.update({"emails": emails})
+    if isinstance(user_ids, (list, tuple)):
+        kwargs.update({"user_ids": ",".join(user_ids)})
+    else:
+        kwargs.update({"user_ids": user_ids})
+    return self.api_call("conversations.inviteShared", http_verb="GET", params=kwargs)
+
+

Sends an invitation to a Slack Connect channel. +https://docs.slack.dev/reference/methods/conversations.inviteShared

+
+
+def conversations_join(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_join(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Joins an existing conversation.
+    https://docs.slack.dev/reference/methods/conversations.join
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.join", params=kwargs)
+
+ +
+
+def conversations_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a user from a conversation.
+    https://docs.slack.dev/reference/methods/conversations.kick
+    """
+    kwargs.update({"channel": channel, "user": user})
+    return self.api_call("conversations.kick", params=kwargs)
+
+ +
+
+def conversations_leave(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Leaves a conversation.
+    https://docs.slack.dev/reference/methods/conversations.leave
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.leave", params=kwargs)
+
+ +
+
+def conversations_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all channels in a Slack team.
+    https://docs.slack.dev/reference/methods/conversations.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("conversations.list", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_listConnectInvites(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_listConnectInvites(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List shared channel invites that have been generated
+    or received but have not yet been approved by all parties.
+    https://docs.slack.dev/reference/methods/conversations.listConnectInvites
+    """
+    kwargs.update({"count": count, "cursor": cursor, "team_id": team_id})
+    return self.api_call("conversations.listConnectInvites", params=kwargs)
+
+

List shared channel invites that have been generated +or received but have not yet been approved by all parties. +https://docs.slack.dev/reference/methods/conversations.listConnectInvites

+
+
+def conversations_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the read cursor in a channel.
+    https://docs.slack.dev/reference/methods/conversations.mark
+    """
+    kwargs.update({"channel": channel, "ts": ts})
+    return self.api_call("conversations.mark", params=kwargs)
+
+ +
+
+def conversations_members(self, *, channel:Β str, cursor:Β strΒ |Β NoneΒ =Β None, limit:Β intΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_members(
+    self,
+    *,
+    channel: str,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve members of a conversation.
+    https://docs.slack.dev/reference/methods/conversations.members
+    """
+    kwargs.update({"channel": channel, "cursor": cursor, "limit": limit})
+    return self.api_call("conversations.members", http_verb="GET", params=kwargs)
+
+ +
+
+def conversations_open(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
return_im:Β boolΒ |Β NoneΒ =Β None,
users:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_open(
+    self,
+    *,
+    channel: Optional[str] = None,
+    return_im: Optional[bool] = None,
+    users: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Opens or resumes a direct message or multi-person direct message.
+    https://docs.slack.dev/reference/methods/conversations.open
+    """
+    if channel is None and users is None:
+        raise e.SlackRequestError("Either channel or users must be provided.")
+    kwargs.update({"channel": channel, "return_im": return_im})
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("conversations.open", params=kwargs)
+
+

Opens or resumes a direct message or multi-person direct message. +https://docs.slack.dev/reference/methods/conversations.open

+
+
+def conversations_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Renames a conversation.
+    https://docs.slack.dev/reference/methods/conversations.rename
+    """
+    kwargs.update({"channel": channel, "name": name})
+    return self.api_call("conversations.rename", params=kwargs)
+
+ +
+
+def conversations_replies(self,
*,
channel:Β str,
ts:Β str,
cursor:Β strΒ |Β NoneΒ =Β None,
inclusive:Β boolΒ |Β NoneΒ =Β None,
include_all_metadata:Β boolΒ |Β NoneΒ =Β None,
latest:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
oldest:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_replies(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    cursor: Optional[str] = None,
+    inclusive: Optional[bool] = None,
+    include_all_metadata: Optional[bool] = None,
+    latest: Optional[str] = None,
+    limit: Optional[int] = None,
+    oldest: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a thread of messages posted to a conversation
+    https://docs.slack.dev/reference/methods/conversations.replies
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "ts": ts,
+            "cursor": cursor,
+            "inclusive": inclusive,
+            "include_all_metadata": include_all_metadata,
+            "limit": limit,
+            "latest": latest,
+            "oldest": oldest,
+        }
+    )
+    return self.api_call("conversations.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a conversation +https://docs.slack.dev/reference/methods/conversations.replies

+
+
+def conversations_requestSharedInvite_approve(self,
*,
invite_id:Β str,
channel_id:Β strΒ |Β NoneΒ =Β None,
is_external_limited:Β strΒ |Β NoneΒ =Β None,
message:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_approve(
+    self,
+    *,
+    invite_id: str,
+    channel_id: Optional[str] = None,
+    is_external_limited: Optional[str] = None,
+    message: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Approve a request to add an external user to a channel. This also sends them a Slack Connect invite.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve
+    """
+    kwargs.update(
+        {
+            "invite_id": invite_id,
+            "channel_id": channel_id,
+            "is_external_limited": is_external_limited,
+        }
+    )
+    if message is not None:
+        kwargs.update({"message": json.dumps(message)})
+    return self.api_call("conversations.requestSharedInvite.approve", params=kwargs)
+
+

Approve a request to add an external user to a channel. This also sends them a Slack Connect invite. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.approve

+
+
+def conversations_requestSharedInvite_deny(self, *, invite_id:Β str, message:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_deny(
+    self,
+    *,
+    invite_id: str,
+    message: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deny a request to invite an external user to a channel.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny
+    """
+    kwargs.update({"invite_id": invite_id, "message": message})
+    return self.api_call("conversations.requestSharedInvite.deny", params=kwargs)
+
+

Deny a request to invite an external user to a channel. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.deny

+
+
+def conversations_requestSharedInvite_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_approved:Β boolΒ |Β NoneΒ =Β None,
include_denied:Β boolΒ |Β NoneΒ =Β None,
include_expired:Β boolΒ |Β NoneΒ =Β None,
invite_ids:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
user_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def conversations_requestSharedInvite_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_approved: Optional[bool] = None,
+    include_denied: Optional[bool] = None,
+    include_expired: Optional[bool] = None,
+    invite_ids: Optional[Union[str, Sequence[str]]] = None,
+    limit: Optional[int] = None,
+    user_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists requests to add external users to channels with ability to filter.
+    https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_approved": include_approved,
+            "include_denied": include_denied,
+            "include_expired": include_expired,
+            "limit": limit,
+            "user_id": user_id,
+        }
+    )
+    if invite_ids is not None:
+        if isinstance(invite_ids, (list, tuple)):
+            kwargs.update({"invite_ids": ",".join(invite_ids)})
+        else:
+            kwargs.update({"invite_ids": invite_ids})
+    return self.api_call("conversations.requestSharedInvite.list", params=kwargs)
+
+

Lists requests to add external users to channels with ability to filter. +https://docs.slack.dev/reference/methods/conversations.requestSharedInvite.list

+
+
+def conversations_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the purpose for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setPurpose
+    """
+    kwargs.update({"channel": channel, "purpose": purpose})
+    return self.api_call("conversations.setPurpose", params=kwargs)
+
+ +
+
+def conversations_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the topic for a conversation.
+    https://docs.slack.dev/reference/methods/conversations.setTopic
+    """
+    kwargs.update({"channel": channel, "topic": topic})
+    return self.api_call("conversations.setTopic", params=kwargs)
+
+ +
+
+def conversations_unarchive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def conversations_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Reverses conversation archival.
+    https://docs.slack.dev/reference/methods/conversations.unarchive
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("conversations.unarchive", params=kwargs)
+
+ +
+
+def dialog_open(self, *, dialog:Β Dict[str,Β Any], trigger_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dialog_open(
+    self,
+    *,
+    dialog: Dict[str, Any],
+    trigger_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Open a dialog with a user.
+    https://docs.slack.dev/reference/methods/dialog.open
+    """
+    kwargs.update({"dialog": dialog, "trigger_id": trigger_id})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: As the dialog can be a dict, this API call works only with json format.
+    return self.api_call("dialog.open", json=kwargs)
+
+ +
+
+def dnd_endDnd(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dnd_endDnd(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Ends the current user's Do Not Disturb session immediately.
+    https://docs.slack.dev/reference/methods/dnd.endDnd
+    """
+    return self.api_call("dnd.endDnd", params=kwargs)
+
+

Ends the current user's Do Not Disturb session immediately. +https://docs.slack.dev/reference/methods/dnd.endDnd

+
+
+def dnd_endSnooze(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dnd_endSnooze(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Ends the current user's snooze mode immediately.
+    https://docs.slack.dev/reference/methods/dnd.endSnooze
+    """
+    return self.api_call("dnd.endSnooze", params=kwargs)
+
+

Ends the current user's snooze mode immediately. +https://docs.slack.dev/reference/methods/dnd.endSnooze

+
+
+def dnd_info(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dnd_info(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieves a user's current Do Not Disturb status.
+    https://docs.slack.dev/reference/methods/dnd.info
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("dnd.info", http_verb="GET", params=kwargs)
+
+

Retrieves a user's current Do Not Disturb status. +https://docs.slack.dev/reference/methods/dnd.info

+
+
+def dnd_setSnooze(self, *, num_minutes:Β strΒ |Β int, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dnd_setSnooze(
+    self,
+    *,
+    num_minutes: Union[int, str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Turns on Do Not Disturb mode for the current user, or changes its duration.
+    https://docs.slack.dev/reference/methods/dnd.setSnooze
+    """
+    kwargs.update({"num_minutes": num_minutes})
+    return self.api_call("dnd.setSnooze", http_verb="GET", params=kwargs)
+
+

Turns on Do Not Disturb mode for the current user, or changes its duration. +https://docs.slack.dev/reference/methods/dnd.setSnooze

+
+
+def dnd_teamInfo(self, users:Β strΒ |Β Sequence[str], team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def dnd_teamInfo(
+    self,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieves the Do Not Disturb status for users on a team.
+    https://docs.slack.dev/reference/methods/dnd.teamInfo
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id})
+    return self.api_call("dnd.teamInfo", http_verb="GET", params=kwargs)
+
+

Retrieves the Do Not Disturb status for users on a team. +https://docs.slack.dev/reference/methods/dnd.teamInfo

+
+
+def emoji_list(self, include_categories:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def emoji_list(
+    self,
+    include_categories: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists custom emoji for a team.
+    https://docs.slack.dev/reference/methods/emoji.list
+    """
+    kwargs.update({"include_categories": include_categories})
+    return self.api_call("emoji.list", http_verb="GET", params=kwargs)
+
+ +
+
+def entity_presentDetails(self,
trigger_id:Β str,
metadata:Β DictΒ |Β EntityMetadataΒ |Β NoneΒ =Β None,
user_auth_required:Β boolΒ |Β NoneΒ =Β None,
user_auth_url:Β strΒ |Β NoneΒ =Β None,
error:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def entity_presentDetails(
+    self,
+    trigger_id: str,
+    metadata: Optional[Union[Dict, EntityMetadata]] = None,
+    user_auth_required: Optional[bool] = None,
+    user_auth_url: Optional[str] = None,
+    error: Optional[Dict[str, Any]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Provides entity details for the flexpane.
+    https://docs.slack.dev/reference/methods/entity.presentDetails/
+    """
+    kwargs.update({"trigger_id": trigger_id})
+    if metadata is not None:
+        kwargs.update({"metadata": metadata})
+    if user_auth_required is not None:
+        kwargs.update({"user_auth_required": user_auth_required})
+    if user_auth_url is not None:
+        kwargs.update({"user_auth_url": user_auth_url})
+    if error is not None:
+        kwargs.update({"error": error})
+    _parse_web_class_objects(kwargs)
+    return self.api_call("entity.presentDetails", json=kwargs)
+
+

Provides entity details for the flexpane. +https://docs.slack.dev/reference/methods/entity.presentDetails/

+
+
+def files_comments_delete(self, *, file:Β str, id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_comments_delete(
+    self,
+    *,
+    file: str,
+    id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes an existing comment on a file.
+    https://docs.slack.dev/reference/methods/files.comments.delete
+    """
+    kwargs.update({"file": file, "id": id})
+    return self.api_call("files.comments.delete", params=kwargs)
+
+ +
+
+def files_completeUploadExternal(self,
*,
files:Β List[Dict[str,Β str]],
channel_id:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_completeUploadExternal(
+    self,
+    *,
+    files: List[Dict[str, str]],
+    channel_id: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Finishes an upload started with files.getUploadURLExternal.
+    https://docs.slack.dev/reference/methods/files.completeUploadExternal
+    """
+    _files = [{k: v for k, v in f.items() if v is not None} for f in files]
+    kwargs.update(
+        {
+            "files": json.dumps(_files),
+            "channel_id": channel_id,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+        }
+    )
+    if channels:
+        kwargs["channels"] = ",".join(channels)
+    return self.api_call("files.completeUploadExternal", params=kwargs)
+
+

Finishes an upload started with files.getUploadURLExternal. +https://docs.slack.dev/reference/methods/files.completeUploadExternal

+
+
+def files_delete(self, *, file:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_delete(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes a file.
+    https://docs.slack.dev/reference/methods/files.delete
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.delete", params=kwargs)
+
+ +
+
+def files_getUploadURLExternal(self,
*,
filename:Β str,
length:Β int,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_getUploadURLExternal(
+    self,
+    *,
+    filename: str,
+    length: int,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets a URL for an edge external upload.
+    https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+    """
+    kwargs.update(
+        {
+            "filename": filename,
+            "length": length,
+            "alt_txt": alt_txt,
+            "snippet_type": snippet_type,
+        }
+    )
+    return self.api_call("files.getUploadURLExternal", params=kwargs)
+
+ +
+
+def files_info(self,
*,
file:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_info(
+    self,
+    *,
+    file: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a team file.
+    https://docs.slack.dev/reference/methods/files.info
+    """
+    kwargs.update(
+        {
+            "file": file,
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+        }
+    )
+    return self.api_call("files.info", http_verb="GET", params=kwargs)
+
+

Gets information about a team file. +https://docs.slack.dev/reference/methods/files.info

+
+
+def files_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
count:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
show_files_hidden_by_limit:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    count: Optional[int] = None,
+    page: Optional[int] = None,
+    show_files_hidden_by_limit: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists & filters team files.
+    https://docs.slack.dev/reference/methods/files.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "count": count,
+            "page": page,
+            "show_files_hidden_by_limit": show_files_hidden_by_limit,
+            "team_id": team_id,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("files.list", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_add(self,
*,
external_id:Β str,
external_url:Β str,
title:Β str,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_remote_add(
+    self,
+    *,
+    external_id: str,
+    external_url: str,
+    title: str,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[Union[str, bytes, IOBase]] = None,
+    preview_image: Optional[Union[str, bytes, IOBase]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Adds a file from a remote service.
+    https://docs.slack.dev/reference/methods/files.remote.add
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.add",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_remote_info(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_remote_info(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.info
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.info", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.info

+
+
+def files_remote_list(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
ts_from:Β strΒ |Β NoneΒ =Β None,
ts_to:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_remote_list(
+    self,
+    *,
+    channel: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    ts_from: Optional[str] = None,
+    ts_to: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve information about a remote file added to Slack.
+    https://docs.slack.dev/reference/methods/files.remote.list
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "cursor": cursor,
+            "limit": limit,
+            "ts_from": ts_from,
+            "ts_to": ts_to,
+        }
+    )
+    return self.api_call("files.remote.list", http_verb="GET", params=kwargs)
+
+

Retrieve information about a remote file added to Slack. +https://docs.slack.dev/reference/methods/files.remote.list

+
+
+def files_remote_remove(self, *, external_id:Β strΒ |Β NoneΒ =Β None, file:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_remote_remove(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove a remote file.
+    https://docs.slack.dev/reference/methods/files.remote.remove
+    """
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.remove", http_verb="POST", params=kwargs)
+
+ +
+
+def files_remote_share(self,
*,
channels:Β strΒ |Β Sequence[str],
external_id:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_remote_share(
+    self,
+    *,
+    channels: Union[str, Sequence[str]],
+    external_id: Optional[str] = None,
+    file: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Share a remote file into a channel.
+    https://docs.slack.dev/reference/methods/files.remote.share
+    """
+    if external_id is None and file is None:
+        raise e.SlackRequestError("Either external_id or file must be provided.")
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update({"external_id": external_id, "file": file})
+    return self.api_call("files.remote.share", http_verb="GET", params=kwargs)
+
+ +
+
+def files_remote_update(self,
*,
external_id:Β strΒ |Β NoneΒ =Β None,
external_url:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
indexable_file_contents:Β strΒ |Β NoneΒ =Β None,
preview_image:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_remote_update(
+    self,
+    *,
+    external_id: Optional[str] = None,
+    external_url: Optional[str] = None,
+    file: Optional[str] = None,
+    title: Optional[str] = None,
+    filetype: Optional[str] = None,
+    indexable_file_contents: Optional[str] = None,
+    preview_image: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Updates an existing remote file.
+    https://docs.slack.dev/reference/methods/files.remote.update
+    """
+    kwargs.update(
+        {
+            "external_id": external_id,
+            "external_url": external_url,
+            "file": file,
+            "title": title,
+            "filetype": filetype,
+        }
+    )
+    files = None
+    # preview_image (file): Preview of the document via multipart/form-data.
+    if preview_image is not None or indexable_file_contents is not None:
+        files = {
+            "preview_image": preview_image,
+            "indexable_file_contents": indexable_file_contents,
+        }
+
+    return self.api_call(
+        # Intentionally using "POST" method over "GET" here
+        "files.remote.update",
+        http_verb="POST",
+        data=kwargs,
+        files=files,
+    )
+
+ +
+
+def files_revokePublicURL(self, *, file:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_revokePublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Revokes public/external sharing access for a file
+    https://docs.slack.dev/reference/methods/files.revokePublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.revokePublicURL", params=kwargs)
+
+

Revokes public/external sharing access for a file +https://docs.slack.dev/reference/methods/files.revokePublicURL

+
+
+def files_sharedPublicURL(self, *, file:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def files_sharedPublicURL(
+    self,
+    *,
+    file: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Enables a file for public/external sharing.
+    https://docs.slack.dev/reference/methods/files.sharedPublicURL
+    """
+    kwargs.update({"file": file})
+    return self.api_call("files.sharedPublicURL", params=kwargs)
+
+

Enables a file for public/external sharing. +https://docs.slack.dev/reference/methods/files.sharedPublicURL

+
+
+def files_upload(self,
*,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
filename:Β strΒ |Β NoneΒ =Β None,
filetype:Β strΒ |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_upload(
+    self,
+    *,
+    file: Optional[Union[str, bytes, IOBase]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    filename: Optional[str] = None,
+    filetype: Optional[str] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    title: Optional[str] = None,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Uploads or creates a file.
+    https://docs.slack.dev/reference/methods/files.upload
+    """
+    _print_files_upload_v2_suggestion()
+
+    if file is None and content is None:
+        raise e.SlackRequestError("The file or content argument must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    kwargs.update(
+        {
+            "filename": filename,
+            "filetype": filetype,
+            "initial_comment": initial_comment,
+            "thread_ts": thread_ts,
+            "title": title,
+        }
+    )
+    if file:
+        if kwargs.get("filename") is None and isinstance(file, str):
+            # use the local filename if filename is missing
+            if kwargs.get("filename") is None:
+                kwargs["filename"] = file.split(os.path.sep)[-1]
+        return self.api_call("files.upload", files={"file": file}, data=kwargs)
+    else:
+        kwargs["content"] = content
+        return self.api_call("files.upload", data=kwargs)
+
+ +
+
+def files_upload_v2(self,
*,
filename:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β bytesΒ |Β io.IOBaseΒ |Β os.PathLikeΒ |Β NoneΒ =Β None,
content:Β strΒ |Β bytesΒ |Β NoneΒ =Β None,
title:Β strΒ |Β NoneΒ =Β None,
alt_txt:Β strΒ |Β NoneΒ =Β None,
snippet_type:Β strΒ |Β NoneΒ =Β None,
file_uploads:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
channel:Β strΒ |Β NoneΒ =Β None,
channels:Β List[str]Β |Β NoneΒ =Β None,
initial_comment:Β strΒ |Β NoneΒ =Β None,
thread_ts:Β strΒ |Β NoneΒ =Β None,
request_file_info:Β boolΒ =Β True,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def files_upload_v2(
+    self,
+    *,
+    # for sending a single file
+    filename: Optional[str] = None,  # you can skip this only when sending along with content parameter
+    file: Optional[Union[str, bytes, IOBase, os.PathLike]] = None,
+    content: Optional[Union[str, bytes]] = None,
+    title: Optional[str] = None,
+    alt_txt: Optional[str] = None,
+    snippet_type: Optional[str] = None,
+    # To upload multiple files at a time
+    file_uploads: Optional[List[Dict[str, Any]]] = None,
+    channel: Optional[str] = None,
+    channels: Optional[List[str]] = None,
+    initial_comment: Optional[str] = None,
+    thread_ts: Optional[str] = None,
+    request_file_info: bool = True,  # since v3.23, this flag is no longer necessary
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """This wrapper method provides an easy way to upload files using the following endpoints:
+
+    - step1: https://docs.slack.dev/reference/methods/files.getUploadURLExternal
+
+    - step2: "https://files.slack.com/upload/v1/..." URLs returned from files.getUploadURLExternal API
+
+    - step3: https://docs.slack.dev/reference/methods/files.completeUploadExternal
+        and https://docs.slack.dev/reference/methods/files.info
+
+    """
+    if file is None and content is None and file_uploads is None:
+        raise e.SlackRequestError("Any of file, content, and file_uploads must be specified.")
+    if file is not None and content is not None:
+        raise e.SlackRequestError("You cannot specify both the file and the content argument.")
+
+    # deprecated arguments:
+    filetype = kwargs.get("filetype")
+
+    if filetype is not None:
+        warnings.warn("The filetype parameter is no longer supported. Please remove it from the arguments.")
+
+    # step1: files.getUploadURLExternal per file
+    files: List[Dict[str, Any]] = []
+    if file_uploads is not None:
+        for f in file_uploads:
+            files.append(_to_v2_file_upload_item(f))
+    else:
+        f = _to_v2_file_upload_item(
+            {
+                "filename": filename,
+                "file": file,
+                "content": content,
+                "title": title,
+                "alt_txt": alt_txt,
+                "snippet_type": snippet_type,
+            }
+        )
+        files.append(f)
+
+    for f in files:
+        url_response = self.files_getUploadURLExternal(
+            filename=f.get("filename"),  # type: ignore[arg-type]
+            length=f.get("length"),  # type: ignore[arg-type]
+            alt_txt=f.get("alt_txt"),
+            snippet_type=f.get("snippet_type"),
+            token=kwargs.get("token"),
+        )
+        _validate_for_legacy_client(url_response)
+        f["file_id"] = url_response.get("file_id")  # type: ignore[union-attr, unused-ignore]
+        f["upload_url"] = url_response.get("upload_url")  # type: ignore[union-attr, unused-ignore]
+
+    # step2: "https://files.slack.com/upload/v1/..." per file
+    for f in files:
+        upload_result = self._upload_file(
+            url=f["upload_url"],
+            data=f["data"],
+            logger=self._logger,
+            timeout=self.timeout,
+            proxy=self.proxy,
+            ssl=self.ssl,
+        )
+        if upload_result.status != 200:
+            status = upload_result.status
+            body = upload_result.body
+            message = (
+                "Failed to upload a file "
+                f"(status: {status}, body: {body}, filename: {f.get('filename')}, title: {f.get('title')})"
+            )
+            raise e.SlackRequestError(message)
+
+    # step3: files.completeUploadExternal with all the sets of (file_id + title)
+    completion = self.files_completeUploadExternal(
+        files=[{"id": f["file_id"], "title": f["title"]} for f in files],
+        channel_id=channel,
+        channels=channels,
+        initial_comment=initial_comment,
+        thread_ts=thread_ts,
+        **kwargs,
+    )
+    if len(completion.get("files")) == 1:  # type: ignore[arg-type, union-attr, unused-ignore]
+        completion.data["file"] = completion.get("files")[0]  # type: ignore[index, union-attr, unused-ignore]
+    return completion
+
+

This wrapper method provides an easy way to upload files using the following endpoints:

+
+
+
+def functions_completeError(self, *, function_execution_id:Β str, error:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def functions_completeError(
+    self,
+    *,
+    function_execution_id: str,
+    error: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Signal the failure to execute a function
+    https://docs.slack.dev/reference/methods/functions.completeError
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "error": error})
+    return self.api_call("functions.completeError", params=kwargs)
+
+ +
+
+def functions_completeSuccess(self, *, function_execution_id:Β str, outputs:Β Dict[str,Β Any], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def functions_completeSuccess(
+    self,
+    *,
+    function_execution_id: str,
+    outputs: Dict[str, Any],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Signal the successful completion of a function
+    https://docs.slack.dev/reference/methods/functions.completeSuccess
+    """
+    kwargs.update({"function_execution_id": function_execution_id, "outputs": json.dumps(outputs)})
+    return self.api_call("functions.completeSuccess", params=kwargs)
+
+

Signal the successful completion of a function +https://docs.slack.dev/reference/methods/functions.completeSuccess

+
+
+def groups_archive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_archive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Archives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.archive", json=kwargs)
+
+

Archives a private channel.

+
+
+def groups_create(self, *, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_create(
+    self,
+    *,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Creates a private channel."""
+    kwargs.update({"name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.create", json=kwargs)
+
+

Creates a private channel.

+
+
+def groups_createChild(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_createChild(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Clones and archives a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.createChild", http_verb="GET", params=kwargs)
+
+

Clones and archives a private channel.

+
+
+def groups_history(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetches history of messages and events from a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a private channel.

+
+
+def groups_info(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_info(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a private channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("groups.info", http_verb="GET", params=kwargs)
+
+

Gets information about a private channel.

+
+
+def groups_invite(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_invite(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Invites a user to a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.invite", json=kwargs)
+
+

Invites a user to a private channel.

+
+
+def groups_kick(self, *, channel:Β str, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_kick(
+    self,
+    *,
+    channel: str,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a user from a private channel."""
+    kwargs.update({"channel": channel, "user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.kick", json=kwargs)
+
+

Removes a user from a private channel.

+
+
+def groups_leave(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_leave(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Leaves a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.leave", json=kwargs)
+
+

Leaves a private channel.

+
+
+def groups_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists private channels that the calling user has access to."""
+    return self.api_call("groups.list", http_verb="GET", params=kwargs)
+
+

Lists private channels that the calling user has access to.

+
+
+def groups_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the read cursor in a private channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.mark", json=kwargs)
+
+

Sets the read cursor in a private channel.

+
+
+def groups_open(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_open(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Opens a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.open", json=kwargs)
+
+

Opens a private channel.

+
+
+def groups_rename(self, *, channel:Β str, name:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_rename(
+    self,
+    *,
+    channel: str,
+    name: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Renames a private channel."""
+    kwargs.update({"channel": channel, "name": name})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.rename", json=kwargs)
+
+

Renames a private channel.

+
+
+def groups_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a thread of messages posted to a private channel"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("groups.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a private channel

+
+
+def groups_setPurpose(self, *, channel:Β str, purpose:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_setPurpose(
+    self,
+    *,
+    channel: str,
+    purpose: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the purpose for a private channel."""
+    kwargs.update({"channel": channel, "purpose": purpose})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setPurpose", json=kwargs)
+
+

Sets the purpose for a private channel.

+
+
+def groups_setTopic(self, *, channel:Β str, topic:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_setTopic(
+    self,
+    *,
+    channel: str,
+    topic: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the topic for a private channel."""
+    kwargs.update({"channel": channel, "topic": topic})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.setTopic", json=kwargs)
+
+

Sets the topic for a private channel.

+
+
+def groups_unarchive(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def groups_unarchive(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Unarchives a private channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("groups.unarchive", json=kwargs)
+
+

Unarchives a private channel.

+
+
+def im_close(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Close a direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.close", json=kwargs)
+
+

Close a direct message channel.

+
+
+def im_history(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetches history of messages and events from direct message channel."""
+    kwargs.update({"channel": channel})
+    return self.api_call("im.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from direct message channel.

+
+
+def im_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists direct message channels for the calling user."""
+    return self.api_call("im.list", http_verb="GET", params=kwargs)
+
+

Lists direct message channels for the calling user.

+
+
+def im_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the read cursor in a direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.mark", json=kwargs)
+
+

Sets the read cursor in a direct message channel.

+
+
+def im_open(self, *, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_open(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Opens a direct message channel."""
+    kwargs.update({"user": user})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("im.open", json=kwargs)
+
+

Opens a direct message channel.

+
+
+def im_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def im_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a thread of messages posted to a direct message conversation"""
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("im.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation

+
+
+def migration_exchange(self,
*,
users:Β strΒ |Β Sequence[str],
team_id:Β strΒ |Β NoneΒ =Β None,
to_old:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def migration_exchange(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    team_id: Optional[str] = None,
+    to_old: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """For Enterprise Grid workspaces, map local user IDs to global user IDs
+    https://docs.slack.dev/reference/methods/migration.exchange
+    """
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    kwargs.update({"team_id": team_id, "to_old": to_old})
+    return self.api_call("migration.exchange", http_verb="GET", params=kwargs)
+
+

For Enterprise Grid workspaces, map local user IDs to global user IDs +https://docs.slack.dev/reference/methods/migration.exchange

+
+
+def mpim_close(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_close(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Closes a multiparty direct message channel."""
+    kwargs.update({"channel": channel})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.close", json=kwargs)
+
+

Closes a multiparty direct message channel.

+
+
+def mpim_history(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_history(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Fetches history of messages and events from a multiparty direct message."""
+    kwargs.update({"channel": channel})
+    return self.api_call("mpim.history", http_verb="GET", params=kwargs)
+
+

Fetches history of messages and events from a multiparty direct message.

+
+
+def mpim_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists multiparty direct message channels for the calling user."""
+    return self.api_call("mpim.list", http_verb="GET", params=kwargs)
+
+

Lists multiparty direct message channels for the calling user.

+
+
+def mpim_mark(self, *, channel:Β str, ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_mark(
+    self,
+    *,
+    channel: str,
+    ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Sets the read cursor in a multiparty direct message channel."""
+    kwargs.update({"channel": channel, "ts": ts})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("mpim.mark", json=kwargs)
+
+

Sets the read cursor in a multiparty direct message channel.

+
+
+def mpim_open(self, *, users:Β strΒ |Β Sequence[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_open(
+    self,
+    *,
+    users: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """This method opens a multiparty direct message."""
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("mpim.open", params=kwargs)
+
+

This method opens a multiparty direct message.

+
+
+def mpim_replies(self, *, channel:Β str, thread_ts:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def mpim_replies(
+    self,
+    *,
+    channel: str,
+    thread_ts: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a thread of messages posted to a direct message conversation from a
+    multiparty direct message.
+    """
+    kwargs.update({"channel": channel, "thread_ts": thread_ts})
+    return self.api_call("mpim.replies", http_verb="GET", params=kwargs)
+
+

Retrieve a thread of messages posted to a direct message conversation from a +multiparty direct message.

+
+
+def oauth_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β str,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def oauth_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    code: str,
+    redirect_uri: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    kwargs.update({"code": code})
+    return self.api_call(
+        "oauth.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.access

+
+
+def oauth_v2_access(self,
*,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def oauth_v2_access(
+    self,
+    *,
+    client_id: str,
+    client_secret: str,
+    # This field is required when processing the OAuth redirect URL requests
+    # while it's absent for token rotation
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    # This field is required for token rotation
+    grant_type: Optional[str] = None,
+    # This field is required for token rotation
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Exchanges a temporary OAuth verifier code for an access token.
+    https://docs.slack.dev/reference/methods/oauth.v2.access
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "oauth.v2.access",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token. +https://docs.slack.dev/reference/methods/oauth.v2.access

+
+
+def oauth_v2_exchange(self, *, token:Β str, client_id:Β str, client_secret:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def oauth_v2_exchange(
+    self,
+    *,
+    token: str,
+    client_id: str,
+    client_secret: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Exchanges a legacy access token for a new expiring access token and refresh token
+    https://docs.slack.dev/reference/methods/oauth.v2.exchange
+    """
+    kwargs.update({"client_id": client_id, "client_secret": client_secret, "token": token})
+    return self.api_call("oauth.v2.exchange", params=kwargs)
+
+

Exchanges a legacy access token for a new expiring access token and refresh token +https://docs.slack.dev/reference/methods/oauth.v2.exchange

+
+
+def openid_connect_token(self,
client_id:Β str,
client_secret:Β str,
code:Β strΒ |Β NoneΒ =Β None,
redirect_uri:Β strΒ |Β NoneΒ =Β None,
grant_type:Β strΒ |Β NoneΒ =Β None,
refresh_token:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def openid_connect_token(
+    self,
+    client_id: str,
+    client_secret: str,
+    code: Optional[str] = None,
+    redirect_uri: Optional[str] = None,
+    grant_type: Optional[str] = None,
+    refresh_token: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.token
+    """
+    if redirect_uri is not None:
+        kwargs.update({"redirect_uri": redirect_uri})
+    if code is not None:
+        kwargs.update({"code": code})
+    if grant_type is not None:
+        kwargs.update({"grant_type": grant_type})
+    if refresh_token is not None:
+        kwargs.update({"refresh_token": refresh_token})
+    return self.api_call(
+        "openid.connect.token",
+        data=kwargs,
+        auth={"client_id": client_id, "client_secret": client_secret},
+    )
+
+

Exchanges a temporary OAuth verifier code for an access token for Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.token

+
+
+def openid_connect_userInfo(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def openid_connect_userInfo(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get the identity of a user who has authorized Sign in with Slack.
+    https://docs.slack.dev/reference/methods/openid.connect.userInfo
+    """
+    return self.api_call("openid.connect.userInfo", params=kwargs)
+
+

Get the identity of a user who has authorized Sign in with Slack. +https://docs.slack.dev/reference/methods/openid.connect.userInfo

+
+
+def pins_add(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def pins_add(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Pins an item to a channel.
+    https://docs.slack.dev/reference/methods/pins.add
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.add", params=kwargs)
+
+ +
+
+def pins_list(self, *, channel:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def pins_list(
+    self,
+    *,
+    channel: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists items pinned to a channel.
+    https://docs.slack.dev/reference/methods/pins.list
+    """
+    kwargs.update({"channel": channel})
+    return self.api_call("pins.list", http_verb="GET", params=kwargs)
+
+

Lists items pinned to a channel. +https://docs.slack.dev/reference/methods/pins.list

+
+
+def pins_remove(self, *, channel:Β str, timestamp:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def pins_remove(
+    self,
+    *,
+    channel: str,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Un-pins an item from a channel.
+    https://docs.slack.dev/reference/methods/pins.remove
+    """
+    kwargs.update({"channel": channel, "timestamp": timestamp})
+    return self.api_call("pins.remove", params=kwargs)
+
+ +
+
+def reactions_add(self, *, channel:Β str, name:Β str, timestamp:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def reactions_add(
+    self,
+    *,
+    channel: str,
+    name: str,
+    timestamp: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Adds a reaction to an item.
+    https://docs.slack.dev/reference/methods/reactions.add
+    """
+    kwargs.update({"channel": channel, "name": name, "timestamp": timestamp})
+    return self.api_call("reactions.add", params=kwargs)
+
+ +
+
+def reactions_get(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def reactions_get(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    full: Optional[bool] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets reactions for an item.
+    https://docs.slack.dev/reference/methods/reactions.get
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "full": full,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.get", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
full:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def reactions_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    full: Optional[bool] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists reactions made by a user.
+    https://docs.slack.dev/reference/methods/reactions.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "full": full,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("reactions.list", http_verb="GET", params=kwargs)
+
+ +
+
+def reactions_remove(self,
*,
name:Β str,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def reactions_remove(
+    self,
+    *,
+    name: str,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a reaction from an item.
+    https://docs.slack.dev/reference/methods/reactions.remove
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("reactions.remove", params=kwargs)
+
+ +
+
+def reminders_add(self,
*,
text:Β str,
time:Β str,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
recurrence:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def reminders_add(
+    self,
+    *,
+    text: str,
+    time: str,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    recurrence: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Creates a reminder.
+    https://docs.slack.dev/reference/methods/reminders.add
+    """
+    kwargs.update(
+        {
+            "text": text,
+            "time": time,
+            "team_id": team_id,
+            "user": user,
+            "recurrence": recurrence,
+        }
+    )
+    return self.api_call("reminders.add", params=kwargs)
+
+ +
+
+def reminders_complete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def reminders_complete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Marks a reminder as complete.
+    https://docs.slack.dev/reference/methods/reminders.complete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.complete", params=kwargs)
+
+ +
+
+def reminders_delete(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def reminders_delete(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes a reminder.
+    https://docs.slack.dev/reference/methods/reminders.delete
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.delete", params=kwargs)
+
+ +
+
+def reminders_info(self, *, reminder:Β str, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def reminders_info(
+    self,
+    *,
+    reminder: str,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a reminder.
+    https://docs.slack.dev/reference/methods/reminders.info
+    """
+    kwargs.update({"reminder": reminder, "team_id": team_id})
+    return self.api_call("reminders.info", http_verb="GET", params=kwargs)
+
+ +
+
+def reminders_list(self, *, team_id:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def reminders_list(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all reminders created by or for a given user.
+    https://docs.slack.dev/reference/methods/reminders.list
+    """
+    kwargs.update({"team_id": team_id})
+    return self.api_call("reminders.list", http_verb="GET", params=kwargs)
+
+

Lists all reminders created by or for a given user. +https://docs.slack.dev/reference/methods/reminders.list

+
+
+def rtm_connect(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def rtm_connect(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.connect
+    """
+    kwargs.update({"batch_presence_aware": batch_presence_aware, "presence_sub": presence_sub})
+    return self.api_call("rtm.connect", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.connect

+
+
+def rtm_start(self,
*,
batch_presence_aware:Β boolΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
mpim_aware:Β boolΒ |Β NoneΒ =Β None,
no_latest:Β boolΒ |Β NoneΒ =Β None,
no_unreads:Β boolΒ |Β NoneΒ =Β None,
presence_sub:Β boolΒ |Β NoneΒ =Β None,
simple_latest:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def rtm_start(
+    self,
+    *,
+    batch_presence_aware: Optional[bool] = None,
+    include_locale: Optional[bool] = None,
+    mpim_aware: Optional[bool] = None,
+    no_latest: Optional[bool] = None,
+    no_unreads: Optional[bool] = None,
+    presence_sub: Optional[bool] = None,
+    simple_latest: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Starts a Real Time Messaging session.
+    https://docs.slack.dev/reference/methods/rtm.start
+    """
+    kwargs.update(
+        {
+            "batch_presence_aware": batch_presence_aware,
+            "include_locale": include_locale,
+            "mpim_aware": mpim_aware,
+            "no_latest": no_latest,
+            "no_unreads": no_unreads,
+            "presence_sub": presence_sub,
+            "simple_latest": simple_latest,
+        }
+    )
+    return self.api_call("rtm.start", http_verb="GET", params=kwargs)
+
+

Starts a Real Time Messaging session. +https://docs.slack.dev/reference/methods/rtm.start

+
+
+def search_all(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def search_all(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Searches for messages and files matching a query.
+    https://docs.slack.dev/reference/methods/search.all
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.all", http_verb="GET", params=kwargs)
+
+

Searches for messages and files matching a query. +https://docs.slack.dev/reference/methods/search.all

+
+
+def search_files(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def search_files(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Searches for files matching a query.
+    https://docs.slack.dev/reference/methods/search.files
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.files", http_verb="GET", params=kwargs)
+
+

Searches for files matching a query. +https://docs.slack.dev/reference/methods/search.files

+
+
+def search_messages(self,
*,
query:Β str,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
highlight:Β boolΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
sort:Β strΒ |Β NoneΒ =Β None,
sort_dir:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def search_messages(
+    self,
+    *,
+    query: str,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    highlight: Optional[bool] = None,
+    page: Optional[int] = None,
+    sort: Optional[str] = None,
+    sort_dir: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Searches for messages matching a query.
+    https://docs.slack.dev/reference/methods/search.messages
+    """
+    kwargs.update(
+        {
+            "query": query,
+            "count": count,
+            "cursor": cursor,
+            "highlight": highlight,
+            "page": page,
+            "sort": sort,
+            "sort_dir": sort_dir,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("search.messages", http_verb="GET", params=kwargs)
+
+

Searches for messages matching a query. +https://docs.slack.dev/reference/methods/search.messages

+
+
+def slackLists_access_delete(self,
*,
list_id:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_delete(
+    self,
+    *,
+    list_id: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Revoke access to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.delete
+    """
+    kwargs.update({"list_id": list_id, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.delete", json=kwargs)
+
+

Revoke access to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.delete

+
+
+def slackLists_access_set(self,
*,
list_id:Β str,
access_level:Β str,
channel_ids:Β List[str]Β |Β NoneΒ =Β None,
user_ids:Β List[str]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_access_set(
+    self,
+    *,
+    list_id: str,
+    access_level: str,
+    channel_ids: Optional[List[str]] = None,
+    user_ids: Optional[List[str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the access level to a List for specified entities.
+    https://docs.slack.dev/reference/methods/slackLists.access.set
+    """
+    kwargs.update({"list_id": list_id, "access_level": access_level, "channel_ids": channel_ids, "user_ids": user_ids})
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.access.set", json=kwargs)
+
+

Set the access level to a List for specified entities. +https://docs.slack.dev/reference/methods/slackLists.access.set

+
+
+def slackLists_create(self,
*,
name:Β str,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
schema:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
copy_from_list_id:Β strΒ |Β NoneΒ =Β None,
include_copied_list_records:Β boolΒ |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_create(
+    self,
+    *,
+    name: str,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    schema: Optional[List[Dict[str, Any]]] = None,
+    copy_from_list_id: Optional[str] = None,
+    include_copied_list_records: Optional[bool] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Creates a List.
+    https://docs.slack.dev/reference/methods/slackLists.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description_blocks": description_blocks,
+            "schema": schema,
+            "copy_from_list_id": copy_from_list_id,
+            "include_copied_list_records": include_copied_list_records,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.create", json=kwargs)
+
+ +
+
+def slackLists_download_get(self, *, list_id:Β str, job_id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_get(
+    self,
+    *,
+    list_id: str,
+    job_id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve List download URL from an export job to download List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.get
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "job_id": job_id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.get", json=kwargs)
+
+

Retrieve List download URL from an export job to download List contents. +https://docs.slack.dev/reference/methods/slackLists.download.get

+
+
+def slackLists_download_start(self, *, list_id:Β str, include_archived:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_download_start(
+    self,
+    *,
+    list_id: str,
+    include_archived: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Initiate a job to export List contents.
+    https://docs.slack.dev/reference/methods/slackLists.download.start
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "include_archived": include_archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.download.start", json=kwargs)
+
+ +
+
+def slackLists_items_create(self,
*,
list_id:Β str,
duplicated_item_id:Β strΒ |Β NoneΒ =Β None,
parent_item_id:Β strΒ |Β NoneΒ =Β None,
initial_fields:Β List[Dict[str,Β Any]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_create(
+    self,
+    *,
+    list_id: str,
+    duplicated_item_id: Optional[str] = None,
+    parent_item_id: Optional[str] = None,
+    initial_fields: Optional[List[Dict[str, Any]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add a new item to an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.create
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "duplicated_item_id": duplicated_item_id,
+            "parent_item_id": parent_item_id,
+            "initial_fields": initial_fields,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.create", json=kwargs)
+
+ +
+
+def slackLists_items_delete(self, *, list_id:Β str, id:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_delete(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes an item from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.delete
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.delete", json=kwargs)
+
+ +
+
+def slackLists_items_deleteMultiple(self, *, list_id:Β str, ids:Β List[str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_deleteMultiple(
+    self,
+    *,
+    list_id: str,
+    ids: List[str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Deletes multiple items from an existing List.
+    https://docs.slack.dev/reference/methods/slackLists.items.deleteMultiple
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "ids": ids,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.deleteMultiple", json=kwargs)
+
+ +
+
+def slackLists_items_info(self, *, list_id:Β str, id:Β str, include_is_subscribed:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_info(
+    self,
+    *,
+    list_id: str,
+    id: str,
+    include_is_subscribed: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get a row from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.info
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "id": id,
+            "include_is_subscribed": include_is_subscribed,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.info", json=kwargs)
+
+ +
+
+def slackLists_items_list(self,
*,
list_id:Β str,
limit:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
archived:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_items_list(
+    self,
+    *,
+    list_id: str,
+    limit: Optional[int] = None,
+    cursor: Optional[str] = None,
+    archived: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get records from a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.list
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "limit": limit,
+            "cursor": cursor,
+            "archived": archived,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.list", json=kwargs)
+
+ +
+
+def slackLists_items_update(self, *, list_id:Β str, cells:Β List[Dict[str,Β Any]], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def slackLists_items_update(
+    self,
+    *,
+    list_id: str,
+    cells: List[Dict[str, Any]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Updates cells in a List.
+    https://docs.slack.dev/reference/methods/slackLists.items.update
+    """
+    kwargs.update(
+        {
+            "list_id": list_id,
+            "cells": cells,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.items.update", json=kwargs)
+
+ +
+
+def slackLists_update(self,
*,
id:Β str,
name:Β strΒ |Β NoneΒ =Β None,
description_blocks:Β strΒ |Β Sequence[DictΒ |Β RichTextBlock]Β |Β NoneΒ =Β None,
todo_mode:Β boolΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def slackLists_update(
+    self,
+    *,
+    id: str,
+    name: Optional[str] = None,
+    description_blocks: Optional[Union[str, Sequence[Union[Dict, RichTextBlock]]]] = None,
+    todo_mode: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update a List.
+    https://docs.slack.dev/reference/methods/slackLists.update
+    """
+    kwargs.update(
+        {
+            "id": id,
+            "name": name,
+            "description_blocks": description_blocks,
+            "todo_mode": todo_mode,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    return self.api_call("slackLists.update", json=kwargs)
+
+ +
+
+def stars_add(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def stars_add(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Adds a star to an item.
+    https://docs.slack.dev/reference/methods/stars.add
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.add", params=kwargs)
+
+ +
+
+def stars_list(self,
*,
count:Β intΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
page:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def stars_list(
+    self,
+    *,
+    count: Optional[int] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    page: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists stars for a user.
+    https://docs.slack.dev/reference/methods/stars.list
+    """
+    kwargs.update(
+        {
+            "count": count,
+            "cursor": cursor,
+            "limit": limit,
+            "page": page,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("stars.list", http_verb="GET", params=kwargs)
+
+ +
+
+def stars_remove(self,
*,
channel:Β strΒ |Β NoneΒ =Β None,
file:Β strΒ |Β NoneΒ =Β None,
file_comment:Β strΒ |Β NoneΒ =Β None,
timestamp:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def stars_remove(
+    self,
+    *,
+    channel: Optional[str] = None,
+    file: Optional[str] = None,
+    file_comment: Optional[str] = None,
+    timestamp: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Removes a star from an item.
+    https://docs.slack.dev/reference/methods/stars.remove
+    """
+    kwargs.update(
+        {
+            "channel": channel,
+            "file": file,
+            "file_comment": file_comment,
+            "timestamp": timestamp,
+        }
+    )
+    return self.api_call("stars.remove", params=kwargs)
+
+ +
+
+def team_accessLogs(self,
*,
before:Β strΒ |Β intΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def team_accessLogs(
+    self,
+    *,
+    before: Optional[Union[int, str]] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    team_id: Optional[str] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets the access logs for the current team.
+    https://docs.slack.dev/reference/methods/team.accessLogs
+    """
+    kwargs.update(
+        {
+            "before": before,
+            "count": count,
+            "page": page,
+            "team_id": team_id,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    return self.api_call("team.accessLogs", http_verb="GET", params=kwargs)
+
+

Gets the access logs for the current team. +https://docs.slack.dev/reference/methods/team.accessLogs

+
+
+def team_billableInfo(self, *, team_id:Β strΒ |Β NoneΒ =Β None, user:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_billableInfo(
+    self,
+    *,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets billable users information for the current team.
+    https://docs.slack.dev/reference/methods/team.billableInfo
+    """
+    kwargs.update({"team_id": team_id, "user": user})
+    return self.api_call("team.billableInfo", http_verb="GET", params=kwargs)
+
+

Gets billable users information for the current team. +https://docs.slack.dev/reference/methods/team.billableInfo

+
+
+def team_billing_info(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_billing_info(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Reads a workspace's billing plan information.
+    https://docs.slack.dev/reference/methods/team.billing.info
+    """
+    return self.api_call("team.billing.info", params=kwargs)
+
+

Reads a workspace's billing plan information. +https://docs.slack.dev/reference/methods/team.billing.info

+
+
+def team_externalTeams_disconnect(self, *, target_team:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_externalTeams_disconnect(
+    self,
+    *,
+    target_team: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Disconnects an external organization.
+    https://docs.slack.dev/reference/methods/team.externalTeams.disconnect
+    """
+    kwargs.update(
+        {
+            "target_team": target_team,
+        }
+    )
+    return self.api_call("team.externalTeams.disconnect", params=kwargs)
+
+ +
+
+def team_externalTeams_list(self,
*,
connection_status_filter:Β strΒ |Β NoneΒ =Β None,
slack_connect_pref_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
sort_direction:Β strΒ |Β NoneΒ =Β None,
sort_field:Β strΒ |Β NoneΒ =Β None,
workspace_filter:Β Sequence[str]Β |Β NoneΒ =Β None,
cursor:Β strΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def team_externalTeams_list(
+    self,
+    *,
+    connection_status_filter: Optional[str] = None,
+    slack_connect_pref_filter: Optional[Sequence[str]] = None,
+    sort_direction: Optional[str] = None,
+    sort_field: Optional[str] = None,
+    workspace_filter: Optional[Sequence[str]] = None,
+    cursor: Optional[str] = None,
+    limit: Optional[int] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Returns a list of all the external teams connected and details about the connection.
+    https://docs.slack.dev/reference/methods/team.externalTeams.list
+    """
+    kwargs.update(
+        {
+            "connection_status_filter": connection_status_filter,
+            "sort_direction": sort_direction,
+            "sort_field": sort_field,
+            "cursor": cursor,
+            "limit": limit,
+        }
+    )
+    if slack_connect_pref_filter is not None:
+        if isinstance(slack_connect_pref_filter, (list, tuple)):
+            kwargs.update({"slack_connect_pref_filter": ",".join(slack_connect_pref_filter)})
+        else:
+            kwargs.update({"slack_connect_pref_filter": slack_connect_pref_filter})
+    if workspace_filter is not None:
+        if isinstance(workspace_filter, (list, tuple)):
+            kwargs.update({"workspace_filter": ",".join(workspace_filter)})
+        else:
+            kwargs.update({"workspace_filter": workspace_filter})
+    return self.api_call("team.externalTeams.list", http_verb="GET", params=kwargs)
+
+

Returns a list of all the external teams connected and details about the connection. +https://docs.slack.dev/reference/methods/team.externalTeams.list

+
+
+def team_info(self, *, team:Β strΒ |Β NoneΒ =Β None, domain:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_info(
+    self,
+    *,
+    team: Optional[str] = None,
+    domain: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about the current team.
+    https://docs.slack.dev/reference/methods/team.info
+    """
+    kwargs.update({"team": team, "domain": domain})
+    return self.api_call("team.info", http_verb="GET", params=kwargs)
+
+

Gets information about the current team. +https://docs.slack.dev/reference/methods/team.info

+
+
+def team_integrationLogs(self,
*,
app_id:Β strΒ |Β NoneΒ =Β None,
change_type:Β strΒ |Β NoneΒ =Β None,
count:Β strΒ |Β intΒ |Β NoneΒ =Β None,
page:Β strΒ |Β intΒ |Β NoneΒ =Β None,
service_id:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def team_integrationLogs(
+    self,
+    *,
+    app_id: Optional[str] = None,
+    change_type: Optional[str] = None,
+    count: Optional[Union[int, str]] = None,
+    page: Optional[Union[int, str]] = None,
+    service_id: Optional[str] = None,
+    team_id: Optional[str] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets the integration logs for the current team.
+    https://docs.slack.dev/reference/methods/team.integrationLogs
+    """
+    kwargs.update(
+        {
+            "app_id": app_id,
+            "change_type": change_type,
+            "count": count,
+            "page": page,
+            "service_id": service_id,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    return self.api_call("team.integrationLogs", http_verb="GET", params=kwargs)
+
+

Gets the integration logs for the current team. +https://docs.slack.dev/reference/methods/team.integrationLogs

+
+
+def team_preferences_list(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_preferences_list(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a list of a workspace's team preferences.
+    https://docs.slack.dev/reference/methods/team.preferences.list
+    """
+    return self.api_call("team.preferences.list", params=kwargs)
+
+

Retrieve a list of a workspace's team preferences. +https://docs.slack.dev/reference/methods/team.preferences.list

+
+
+def team_profile_get(self, *, visibility:Β strΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def team_profile_get(
+    self,
+    *,
+    visibility: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieve a team's profile.
+    https://docs.slack.dev/reference/methods/team.profile.get
+    """
+    kwargs.update({"visibility": visibility})
+    return self.api_call("team.profile.get", http_verb="GET", params=kwargs)
+
+ +
+
+def tooling_tokens_rotate(self, *, refresh_token:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def tooling_tokens_rotate(
+    self,
+    *,
+    refresh_token: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Exchanges a refresh token for a new app configuration token
+    https://docs.slack.dev/reference/methods/tooling.tokens.rotate
+    """
+    kwargs.update({"refresh_token": refresh_token})
+    return self.api_call("tooling.tokens.rotate", params=kwargs)
+
+

Exchanges a refresh token for a new app configuration token +https://docs.slack.dev/reference/methods/tooling.tokens.rotate

+
+
+def usergroups_create(self,
*,
name:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_create(
+    self,
+    *,
+    name: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Create a User Group
+    https://docs.slack.dev/reference/methods/usergroups.create
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.create", params=kwargs)
+
+ +
+
+def usergroups_disable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_disable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Disable an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.disable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.disable", params=kwargs)
+
+ +
+
+def usergroups_enable(self,
*,
usergroup:Β str,
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_enable(
+    self,
+    *,
+    usergroup: str,
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Enable a User Group
+    https://docs.slack.dev/reference/methods/usergroups.enable
+    """
+    kwargs.update({"usergroup": usergroup, "include_count": include_count, "team_id": team_id})
+    return self.api_call("usergroups.enable", params=kwargs)
+
+ +
+
+def usergroups_list(self,
*,
include_count:Β boolΒ |Β NoneΒ =Β None,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
include_users:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_list(
+    self,
+    *,
+    include_count: Optional[bool] = None,
+    include_disabled: Optional[bool] = None,
+    include_users: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all User Groups for a team
+    https://docs.slack.dev/reference/methods/usergroups.list
+    """
+    kwargs.update(
+        {
+            "include_count": include_count,
+            "include_disabled": include_disabled,
+            "include_users": include_users,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_update(self,
*,
usergroup:Β str,
channels:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
description:Β strΒ |Β NoneΒ =Β None,
handle:Β strΒ |Β NoneΒ =Β None,
include_count:Β boolΒ |Β NoneΒ =Β None,
name:Β strΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_update(
+    self,
+    *,
+    usergroup: str,
+    channels: Optional[Union[str, Sequence[str]]] = None,
+    description: Optional[str] = None,
+    handle: Optional[str] = None,
+    include_count: Optional[bool] = None,
+    name: Optional[str] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update an existing User Group
+    https://docs.slack.dev/reference/methods/usergroups.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "description": description,
+            "handle": handle,
+            "include_count": include_count,
+            "name": name,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(channels, (list, tuple)):
+        kwargs.update({"channels": ",".join(channels)})
+    else:
+        kwargs.update({"channels": channels})
+    return self.api_call("usergroups.update", params=kwargs)
+
+ +
+
+def usergroups_users_list(self,
*,
usergroup:Β str,
include_disabled:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_list(
+    self,
+    *,
+    usergroup: str,
+    include_disabled: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List all users in a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.list
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_disabled": include_disabled,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("usergroups.users.list", http_verb="GET", params=kwargs)
+
+ +
+
+def usergroups_users_update(self,
*,
usergroup:Β str,
users:Β strΒ |Β Sequence[str],
include_count:Β boolΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def usergroups_users_update(
+    self,
+    *,
+    usergroup: str,
+    users: Union[str, Sequence[str]],
+    include_count: Optional[bool] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update the list of users for a User Group
+    https://docs.slack.dev/reference/methods/usergroups.users.update
+    """
+    kwargs.update(
+        {
+            "usergroup": usergroup,
+            "include_count": include_count,
+            "team_id": team_id,
+        }
+    )
+    if isinstance(users, (list, tuple)):
+        kwargs.update({"users": ",".join(users)})
+    else:
+        kwargs.update({"users": users})
+    return self.api_call("usergroups.users.update", params=kwargs)
+
+

Update the list of users for a User Group +https://docs.slack.dev/reference/methods/usergroups.users.update

+
+
+def users_conversations(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
exclude_archived:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
types:Β strΒ |Β Sequence[str]Β |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def users_conversations(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    exclude_archived: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    types: Optional[Union[str, Sequence[str]]] = None,
+    user: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List conversations the calling user may access.
+    https://docs.slack.dev/reference/methods/users.conversations
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "exclude_archived": exclude_archived,
+            "limit": limit,
+            "team_id": team_id,
+            "user": user,
+        }
+    )
+    if isinstance(types, (list, tuple)):
+        kwargs.update({"types": ",".join(types)})
+    else:
+        kwargs.update({"types": types})
+    return self.api_call("users.conversations", http_verb="GET", params=kwargs)
+
+

List conversations the calling user may access. +https://docs.slack.dev/reference/methods/users.conversations

+
+
+def users_deletePhoto(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_deletePhoto(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Delete the user profile photo
+    https://docs.slack.dev/reference/methods/users.deletePhoto
+    """
+    return self.api_call("users.deletePhoto", http_verb="GET", params=kwargs)
+
+ +
+
+def users_discoverableContacts_lookup(self, email:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_discoverableContacts_lookup(
+    self,
+    email: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lookup an email address to see if someone is on Slack
+    https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.discoverableContacts.lookup", params=kwargs)
+
+

Lookup an email address to see if someone is on Slack +https://docs.slack.dev/reference/methods/users.discoverableContacts.lookup

+
+
+def users_getPresence(self, *, user:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_getPresence(
+    self,
+    *,
+    user: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets user presence information.
+    https://docs.slack.dev/reference/methods/users.getPresence
+    """
+    kwargs.update({"user": user})
+    return self.api_call("users.getPresence", http_verb="GET", params=kwargs)
+
+ +
+
+def users_identity(self, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_identity(
+    self,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Get a user's identity.
+    https://docs.slack.dev/reference/methods/users.identity
+    """
+    return self.api_call("users.identity", http_verb="GET", params=kwargs)
+
+ +
+
+def users_info(self, *, user:Β str, include_locale:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_info(
+    self,
+    *,
+    user: str,
+    include_locale: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Gets information about a user.
+    https://docs.slack.dev/reference/methods/users.info
+    """
+    kwargs.update({"user": user, "include_locale": include_locale})
+    return self.api_call("users.info", http_verb="GET", params=kwargs)
+
+ +
+
+def users_list(self,
*,
cursor:Β strΒ |Β NoneΒ =Β None,
include_locale:Β boolΒ |Β NoneΒ =Β None,
limit:Β intΒ |Β NoneΒ =Β None,
team_id:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def users_list(
+    self,
+    *,
+    cursor: Optional[str] = None,
+    include_locale: Optional[bool] = None,
+    limit: Optional[int] = None,
+    team_id: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Lists all users in a Slack team.
+    https://docs.slack.dev/reference/methods/users.list
+    """
+    kwargs.update(
+        {
+            "cursor": cursor,
+            "include_locale": include_locale,
+            "limit": limit,
+            "team_id": team_id,
+        }
+    )
+    return self.api_call("users.list", http_verb="GET", params=kwargs)
+
+

Lists all users in a Slack team. +https://docs.slack.dev/reference/methods/users.list

+
+
+def users_lookupByEmail(self, *, email:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_lookupByEmail(
+    self,
+    *,
+    email: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Find a user with an email address.
+    https://docs.slack.dev/reference/methods/users.lookupByEmail
+    """
+    kwargs.update({"email": email})
+    return self.api_call("users.lookupByEmail", http_verb="GET", params=kwargs)
+
+ +
+
+def users_profile_get(self, *, user:Β strΒ |Β NoneΒ =Β None, include_labels:Β boolΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_profile_get(
+    self,
+    *,
+    user: Optional[str] = None,
+    include_labels: Optional[bool] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Retrieves a user's profile information.
+    https://docs.slack.dev/reference/methods/users.profile.get
+    """
+    kwargs.update({"user": user, "include_labels": include_labels})
+    return self.api_call("users.profile.get", http_verb="GET", params=kwargs)
+
+

Retrieves a user's profile information. +https://docs.slack.dev/reference/methods/users.profile.get

+
+
+def users_profile_set(self,
*,
name:Β strΒ |Β NoneΒ =Β None,
value:Β strΒ |Β NoneΒ =Β None,
user:Β strΒ |Β NoneΒ =Β None,
profile:Β DictΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def users_profile_set(
+    self,
+    *,
+    name: Optional[str] = None,
+    value: Optional[str] = None,
+    user: Optional[str] = None,
+    profile: Optional[Dict] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the profile information for a user.
+    https://docs.slack.dev/reference/methods/users.profile.set
+    """
+    kwargs.update(
+        {
+            "name": name,
+            "profile": profile,
+            "user": user,
+            "value": value,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "profile" parameter
+    return self.api_call("users.profile.set", json=kwargs)
+
+

Set the profile information for a user. +https://docs.slack.dev/reference/methods/users.profile.set

+
+
+def users_setPhoto(self,
*,
image:Β strΒ |Β io.IOBase,
crop_w:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_x:Β strΒ |Β intΒ |Β NoneΒ =Β None,
crop_y:Β strΒ |Β intΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def users_setPhoto(
+    self,
+    *,
+    image: Union[str, IOBase],
+    crop_w: Optional[Union[int, str]] = None,
+    crop_x: Optional[Union[int, str]] = None,
+    crop_y: Optional[Union[int, str]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set the user profile photo
+    https://docs.slack.dev/reference/methods/users.setPhoto
+    """
+    kwargs.update({"crop_w": crop_w, "crop_x": crop_x, "crop_y": crop_y})
+    return self.api_call("users.setPhoto", files={"image": image}, data=kwargs)
+
+ +
+
+def users_setPresence(self, *, presence:Β str, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def users_setPresence(
+    self,
+    *,
+    presence: str,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Manually sets user presence.
+    https://docs.slack.dev/reference/methods/users.setPresence
+    """
+    kwargs.update({"presence": presence})
+    return self.api_call("users.setPresence", params=kwargs)
+
+ +
+
+def views_open(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def views_open(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Open a view for a user.
+    https://docs.slack.dev/reference/methods/views.open
+    See https://docs.slack.dev/surfaces/modals/ for details.
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.open", json=kwargs)
+
+ +
+
+def views_publish(self,
*,
user_id:Β str,
view:Β dictΒ |Β View,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def views_publish(
+    self,
+    *,
+    user_id: str,
+    view: Union[dict, View],
+    hash: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Publish a static view for a User.
+    Create or update the view that comprises an
+    app's Home tab (https://docs.slack.dev/surfaces/app-home/)
+    https://docs.slack.dev/reference/methods/views.publish
+    """
+    kwargs.update({"user_id": user_id, "hash": hash})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.publish", json=kwargs)
+
+

Publish a static view for a User. +Create or update the view that comprises an +app's Home tab (https://docs.slack.dev/surfaces/app-home/) +https://docs.slack.dev/reference/methods/views.publish

+
+
+def views_push(self,
*,
trigger_id:Β strΒ |Β NoneΒ =Β None,
interactivity_pointer:Β strΒ |Β NoneΒ =Β None,
view:Β dictΒ |Β View,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def views_push(
+    self,
+    *,
+    trigger_id: Optional[str] = None,
+    interactivity_pointer: Optional[str] = None,
+    view: Union[dict, View],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Push a view onto the stack of a root view.
+    Push a new view onto the existing view stack by passing a view
+    payload and a valid trigger_id generated from an interaction
+    within the existing modal.
+    Read the modals documentation (https://docs.slack.dev/surfaces/modals/)
+    to learn more about the lifecycle and intricacies of views.
+    https://docs.slack.dev/reference/methods/views.push
+    """
+    kwargs.update({"trigger_id": trigger_id, "interactivity_pointer": interactivity_pointer})
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.push", json=kwargs)
+
+

Push a view onto the stack of a root view. +Push a new view onto the existing view stack by passing a view +payload and a valid trigger_id generated from an interaction +within the existing modal. +Read the modals documentation (https://docs.slack.dev/surfaces/modals/) +to learn more about the lifecycle and intricacies of views. +https://docs.slack.dev/reference/methods/views.push

+
+
+def views_update(self,
*,
view:Β dictΒ |Β View,
external_id:Β strΒ |Β NoneΒ =Β None,
view_id:Β strΒ |Β NoneΒ =Β None,
hash:Β strΒ |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def views_update(
+    self,
+    *,
+    view: Union[dict, View],
+    external_id: Optional[str] = None,
+    view_id: Optional[str] = None,
+    hash: Optional[str] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update an existing view.
+    Update a view by passing a new view definition along with the
+    view_id returned in views.open or the external_id.
+    See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views)
+    to learn more about updating views and avoiding race conditions with the hash argument.
+    https://docs.slack.dev/reference/methods/views.update
+    """
+    if isinstance(view, View):
+        kwargs.update({"view": view.to_dict()})
+    else:
+        kwargs.update({"view": view})
+    if external_id:
+        kwargs.update({"external_id": external_id})
+    elif view_id:
+        kwargs.update({"view_id": view_id})
+    else:
+        raise e.SlackRequestError("Either view_id or external_id is required.")
+    kwargs.update({"hash": hash})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "view" parameter
+    return self.api_call("views.update", json=kwargs)
+
+

Update an existing view. +Update a view by passing a new view definition along with the +view_id returned in views.open or the external_id. +See the modals documentation (https://docs.slack.dev/surfaces/modals/#updating_views) +to learn more about updating views and avoiding race conditions with the hash argument. +https://docs.slack.dev/reference/methods/views.update

+
+ +
+
+ +Expand source code + +
def workflows_featured_add(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Add featured workflows to a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.add
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.add", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_list(
+    self,
+    *,
+    channel_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """List the featured workflows for specified channels.
+    https://docs.slack.dev/reference/methods/workflows.featured.list
+    """
+    if isinstance(channel_ids, (list, tuple)):
+        kwargs.update({"channel_ids": ",".join(channel_ids)})
+    else:
+        kwargs.update({"channel_ids": channel_ids})
+    return self.api_call("workflows.featured.list", params=kwargs)
+
+

List the featured workflows for specified channels. +https://docs.slack.dev/reference/methods/workflows.featured.list

+
+ +
+
+ +Expand source code + +
def workflows_featured_remove(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Remove featured workflows from a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.remove
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.remove", params=kwargs)
+
+ +
+ +
+
+ +Expand source code + +
def workflows_featured_set(
+    self,
+    *,
+    channel_id: str,
+    trigger_ids: Union[str, Sequence[str]],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Set featured workflows for a channel.
+    https://docs.slack.dev/reference/methods/workflows.featured.set
+    """
+    kwargs.update({"channel_id": channel_id})
+    if isinstance(trigger_ids, (list, tuple)):
+        kwargs.update({"trigger_ids": ",".join(trigger_ids)})
+    else:
+        kwargs.update({"trigger_ids": trigger_ids})
+    return self.api_call("workflows.featured.set", params=kwargs)
+
+ +
+
+def workflows_stepCompleted(self, *, workflow_step_execute_id:Β str, outputs:Β dictΒ |Β NoneΒ =Β None, **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def workflows_stepCompleted(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    outputs: Optional[dict] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Indicate a successful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepCompleted
+    """
+    kwargs.update({"workflow_step_execute_id": workflow_step_execute_id})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "outputs" parameter
+    return self.api_call("workflows.stepCompleted", json=kwargs)
+
+

Indicate a successful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepCompleted

+
+
+def workflows_stepFailed(self, *, workflow_step_execute_id:Β str, error:Β Dict[str,Β str], **kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse +
+
+
+ +Expand source code + +
def workflows_stepFailed(
+    self,
+    *,
+    workflow_step_execute_id: str,
+    error: Dict[str, str],
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Indicate an unsuccessful outcome of a workflow step's execution.
+    https://docs.slack.dev/reference/methods/workflows.stepFailed
+    """
+    kwargs.update(
+        {
+            "workflow_step_execute_id": workflow_step_execute_id,
+            "error": error,
+        }
+    )
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "error" parameter
+    return self.api_call("workflows.stepFailed", json=kwargs)
+
+

Indicate an unsuccessful outcome of a workflow step's execution. +https://docs.slack.dev/reference/methods/workflows.stepFailed

+
+
+def workflows_updateStep(self,
*,
workflow_step_edit_id:Β str,
inputs:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
outputs:Β List[Dict[str,Β str]]Β |Β NoneΒ =Β None,
**kwargs) ‑>Β _asyncio.FutureΒ |Β LegacySlackResponse
+
+
+
+ +Expand source code + +
def workflows_updateStep(
+    self,
+    *,
+    workflow_step_edit_id: str,
+    inputs: Optional[Dict[str, Any]] = None,
+    outputs: Optional[List[Dict[str, str]]] = None,
+    **kwargs,
+) -> Union[Future, SlackResponse]:
+    """Update the configuration for a workflow extension step.
+    https://docs.slack.dev/reference/methods/workflows.updateStep
+    """
+    kwargs.update({"workflow_step_edit_id": workflow_step_edit_id})
+    if inputs is not None:
+        kwargs.update({"inputs": inputs})
+    if outputs is not None:
+        kwargs.update({"outputs": outputs})
+    kwargs = _remove_none_values(kwargs)
+    # NOTE: Intentionally using json for the "inputs" / "outputs" parameters
+    return self.api_call("workflows.updateStep", json=kwargs)
+
+

Update the configuration for a workflow extension step. +https://docs.slack.dev/reference/methods/workflows.updateStep

+
+
+

Inherited members

+ +
+
+
+
+ +
+ + + diff --git a/docs/reference/web/legacy_slack_response.html b/docs/reference/web/legacy_slack_response.html new file mode 100644 index 000000000..c0531066d --- /dev/null +++ b/docs/reference/web/legacy_slack_response.html @@ -0,0 +1,414 @@ + + + + + + +slack_sdk.web.legacy_slack_response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.legacy_slack_response

+
+
+

A Python module for interacting and consuming responses from Slack.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class LegacySlackResponse +(*,
client,
http_verb:Β str,
api_url:Β str,
req_args:Β dict,
data:Β dictΒ |Β bytes,
headers:Β dict,
status_code:Β int,
use_sync_aiohttp:Β boolΒ =Β True)
+
+
+
+ +Expand source code + +
class LegacySlackResponse(object):
+    """An iterable container of response data.
+
+    Attributes:
+        data (dict): The json-encoded content of the response. Along
+            with the headers and status code information.
+
+    Methods:
+        validate: Check if the response from Slack was successful.
+        get: Retrieves any key from the response data.
+        next: Retrieves the next portion of results,
+            if 'next_cursor' is present.
+
+    Example:
+    ```python
+    import os
+    import slack
+
+    client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+    response1 = client.auth_revoke(test='true')
+    assert not response1['revoked']
+
+    response2 = client.auth_test()
+    assert response2.get('ok', False)
+
+    users = []
+    for page in client.users_list(limit=2):
+        TODO: This example should specify when to break.
+        users = users + page['members']
+    ```
+
+    Note:
+        Some responses return collections of information
+        like channel and user lists. If they do it's likely
+        that you'll only receive a portion of results. This
+        object allows you to iterate over the response which
+        makes subsequent API requests until your code hits
+        'break' or there are no more results to be found.
+
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+    """
+
+    def __init__(
+        self,
+        *,
+        client,
+        http_verb: str,
+        api_url: str,
+        req_args: dict,
+        data: Union[dict, bytes],  # data can be binary data
+        headers: dict,
+        status_code: int,
+        use_sync_aiohttp: bool = True,  # True for backward-compatibility
+    ):
+        self.http_verb = http_verb
+        self.api_url = api_url
+        self.req_args = req_args
+        self.data = data
+        self.headers = headers
+        self.status_code = status_code
+        self._initial_data = data
+        self._client = client  # LegacyWebClient
+        self._use_sync_aiohttp = use_sync_aiohttp
+        self._logger = logging.getLogger(__name__)
+
+    def __str__(self):
+        """Return the Response data if object is converted to a string."""
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return f"{self.data}"
+
+    def __getitem__(self, key):
+        """Retrieves any key from the data store.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response["ok"]
+
+        Returns:
+            The value from data or None.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return self.data.get(key, None)
+
+    def __iter__(self):
+        """Enables the ability to iterate over the response.
+        It's required for the iterator protocol.
+
+        Note:
+            This enables Slack cursor-based pagination.
+
+        Returns:
+            (SlackResponse) self
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration = 0
+        self.data = self._initial_data
+        return self
+
+    def __next__(self):
+        """Retrieves the next portion of results, if 'next_cursor' is present.
+
+        Note:
+            Some responses return collections of information
+            like channel and user lists. If they do it's likely
+            that you'll only receive a portion of results. This
+            method allows you to iterate over the response until
+            your code hits 'break' or there are no more results
+            to be found.
+
+        Returns:
+            (SlackResponse) self
+                With the new response data now attached to this object.
+
+        Raises:
+            SlackApiError: If the request to the Slack API failed.
+            StopIteration: If 'next_cursor' is not present or empty.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration += 1
+        if self._iteration == 1:
+            return self
+        if self._next_cursor_is_present(self.data):
+            params = self.req_args.get("params", {})
+            if params is None:
+                params = {}
+            params.update({"cursor": self.data["response_metadata"]["next_cursor"]})
+            self.req_args.update({"params": params})
+
+            if self._use_sync_aiohttp:
+                # We no longer recommend going with this way
+                response = asyncio.get_event_loop().run_until_complete(
+                    self._client._request(
+                        http_verb=self.http_verb,
+                        api_url=self.api_url,
+                        req_args=self.req_args,
+                    )
+                )
+            else:
+                # This method sends a request in a synchronous way
+                response = self._client._request_for_pagination(api_url=self.api_url, req_args=self.req_args)
+
+            self.data = response["data"]
+            self.headers = response["headers"]
+            self.status_code = response["status_code"]
+            return self.validate()
+        else:
+            raise StopIteration
+
+    def get(self, key, default=None):
+        """Retrieves any key from the response data.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response.get("ok", False)
+
+        Returns:
+            The value from data or the specified default.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return self.data.get(key, default)
+
+    def validate(self):
+        """Check if the response from Slack was successful.
+
+        Returns:
+            (SlackResponse)
+                This method returns it's own object. e.g. 'self'
+
+        Raises:
+            SlackApiError: The request to the Slack API failed.
+        """
+        if self._logger.level <= logging.DEBUG:
+            body = self.data if isinstance(self.data, dict) else "(binary)"
+            self._logger.debug(
+                "Received the following response - "
+                f"status: {self.status_code}, "
+                f"headers: {dict(self.headers)}, "
+                f"body: {body}"
+            )
+        if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+            return self
+        msg = "The request to the Slack API failed."
+        raise e.SlackApiError(message=msg, response=self)
+
+    @staticmethod
+    def _next_cursor_is_present(data):
+        """Determine if the response contains 'next_cursor'
+        and 'next_cursor' is not empty.
+
+        Returns:
+            A boolean value.
+        """
+        present = (
+            "response_metadata" in data
+            and "next_cursor" in data["response_metadata"]
+            and data["response_metadata"]["next_cursor"] != ""
+        )
+        return present
+
+

An iterable container of response data.

+

Attributes

+
+
data : dict
+
The json-encoded content of the response. Along +with the headers and status code information.
+
+

Methods

+

validate: Check if the response from Slack was successful. +get: Retrieves any key from the response data. +next: Retrieves the next portion of results, +if 'next_cursor' is present.

+

Example:

+
import os
+import slack
+
+client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+response1 = client.auth_revoke(test='true')
+assert not response1['revoked']
+
+response2 = client.auth_test()
+assert response2.get('ok', False)
+
+users = []
+for page in client.users_list(limit=2):
+    TODO: This example should specify when to break.
+    users = users + page['members']
+
+

Note

+

Some responses return collections of information +like channel and user lists. If they do it's likely +that you'll only receive a portion of results. This +object allows you to iterate over the response which +makes subsequent API requests until your code hits +'break' or there are no more results to be found.

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Methods

+
+
+def get(self, key, default=None) +
+
+
+ +Expand source code + +
def get(self, key, default=None):
+    """Retrieves any key from the response data.
+
+    Note:
+        This is implemented so users can reference the
+        SlackResponse object like a dictionary.
+        e.g. response.get("ok", False)
+
+    Returns:
+        The value from data or the specified default.
+    """
+    if isinstance(self.data, bytes):
+        raise ValueError("As the response.data is binary data, this operation is unsupported")
+    return self.data.get(key, default)
+
+

Retrieves any key from the response data.

+

Note

+

This is implemented so users can reference the +SlackResponse object like a dictionary. +e.g. response.get("ok", False)

+

Returns

+

The value from data or the specified default.

+
+
+def validate(self) +
+
+
+ +Expand source code + +
def validate(self):
+    """Check if the response from Slack was successful.
+
+    Returns:
+        (SlackResponse)
+            This method returns it's own object. e.g. 'self'
+
+    Raises:
+        SlackApiError: The request to the Slack API failed.
+    """
+    if self._logger.level <= logging.DEBUG:
+        body = self.data if isinstance(self.data, dict) else "(binary)"
+        self._logger.debug(
+            "Received the following response - "
+            f"status: {self.status_code}, "
+            f"headers: {dict(self.headers)}, "
+            f"body: {body}"
+        )
+    if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+        return self
+    msg = "The request to the Slack API failed."
+    raise e.SlackApiError(message=msg, response=self)
+
+

Check if the response from Slack was successful.

+

Returns

+

(SlackResponse) +This method returns it's own object. e.g. 'self'

+

Raises

+
+
SlackApiError
+
The request to the Slack API failed.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/web/slack_response.html b/docs/reference/web/slack_response.html new file mode 100644 index 000000000..6746b3c7d --- /dev/null +++ b/docs/reference/web/slack_response.html @@ -0,0 +1,385 @@ + + + + + + +slack_sdk.web.slack_response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.web.slack_response

+
+
+

A Python module for interacting and consuming responses from Slack.

+
+
+
+
+
+
+
+
+

Classes

+
+
+class SlackResponse +(*,
client,
http_verb:Β str,
api_url:Β str,
req_args:Β dict,
data:Β dictΒ |Β bytes,
headers:Β dict,
status_code:Β int)
+
+
+
+ +Expand source code + +
class SlackResponse:
+    """An iterable container of response data.
+
+    Attributes:
+        data (dict): The json-encoded content of the response. Along
+            with the headers and status code information.
+
+    Methods:
+        validate: Check if the response from Slack was successful.
+        get: Retrieves any key from the response data.
+        next: Retrieves the next portion of results,
+            if 'next_cursor' is present.
+
+    Example:
+    ```python
+    import os
+    import slack
+
+    client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+    response1 = client.auth_revoke(test='true')
+    assert not response1['revoked']
+
+    response2 = client.auth_test()
+    assert response2.get('ok', False)
+
+    users = []
+    for page in client.users_list(limit=2):
+        users = users + page['members']
+    ```
+
+    Note:
+        Some responses return collections of information
+        like channel and user lists. If they do it's likely
+        that you'll only receive a portion of results. This
+        object allows you to iterate over the response which
+        makes subsequent API requests until your code hits
+        'break' or there are no more results to be found.
+
+        Any attributes or methods prefixed with _underscores are
+        intended to be "private" internal use only. They may be changed or
+        removed at anytime.
+    """
+
+    def __init__(
+        self,
+        *,
+        client,
+        http_verb: str,
+        api_url: str,
+        req_args: dict,
+        data: Union[dict, bytes],  # data can be binary data
+        headers: dict,
+        status_code: int,
+    ):
+        self.http_verb = http_verb
+        self.api_url = api_url
+        self.req_args = req_args
+        self.data = data
+        self.headers = headers
+        self.status_code = status_code
+        self._initial_data = data
+        self._iteration = None  # for __iter__ & __next__
+        self._client = client
+        self._logger = logging.getLogger(__name__)
+
+    def __str__(self):
+        """Return the Response data if object is converted to a string."""
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        return f"{self.data}"
+
+    def __contains__(self, key: str) -> bool:
+        return self.get(key) is not None
+
+    def __getitem__(self, key):
+        """Retrieves any key from the data store.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response["ok"]
+
+        Returns:
+            The value from data or None.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            raise ValueError("As the response.data is empty, this operation is unsupported")
+        return self.data.get(key, None)
+
+    def __iter__(self):
+        """Enables the ability to iterate over the response.
+        It's required for the iterator protocol.
+
+        Note:
+            This enables Slack cursor-based pagination.
+
+        Returns:
+            (SlackResponse) self
+        """
+        self._iteration = 0
+        self.data = self._initial_data
+        return self
+
+    def __next__(self):
+        """Retrieves the next portion of results, if 'next_cursor' is present.
+
+        Note:
+            Some responses return collections of information
+            like channel and user lists. If they do it's likely
+            that you'll only receive a portion of results. This
+            method allows you to iterate over the response until
+            your code hits 'break' or there are no more results
+            to be found.
+
+        Returns:
+            (SlackResponse) self
+                With the new response data now attached to this object.
+
+        Raises:
+            SlackApiError: If the request to the Slack API failed.
+            StopIteration: If 'next_cursor' is not present or empty.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        self._iteration += 1
+        if self._iteration == 1:
+            return self
+        if _next_cursor_is_present(self.data):
+            params = self.req_args.get("params", {})
+            if params is None:
+                params = {}
+            next_cursor = self.data.get("response_metadata", {}).get("next_cursor") or self.data.get("next_cursor")
+            params.update({"cursor": next_cursor})
+            self.req_args.update({"params": params})
+
+            # This method sends a request in a synchronous way
+            response = self._client._request_for_pagination(api_url=self.api_url, req_args=self.req_args)
+            self.data = response["data"]
+            self.headers = response["headers"]
+            self.status_code = response["status_code"]
+            return self.validate()
+        else:
+            raise StopIteration
+
+    @overload
+    def get(self, key: str, default: None = None) -> Optional[Any]:
+        ...
+
+    @overload
+    def get(self, key: str, default: T) -> T:
+        ...
+
+    def get(self, key, default=None):
+        """Retrieves any key from the response data.
+
+        Note:
+            This is implemented so users can reference the
+            SlackResponse object like a dictionary.
+            e.g. response.get("ok", False)
+
+        Returns:
+            The value from data or the specified default.
+        """
+        if isinstance(self.data, bytes):
+            raise ValueError("As the response.data is binary data, this operation is unsupported")
+        if self.data is None:
+            return None
+        return self.data.get(key, default)
+
+    def validate(self):
+        """Check if the response from Slack was successful.
+
+        Returns:
+            (SlackResponse)
+                This method returns it's own object. e.g. 'self'
+
+        Raises:
+            SlackApiError: The request to the Slack API failed.
+        """
+        if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+            return self
+        msg = f"The request to the Slack API failed. (url: {self.api_url})"
+        raise e.SlackApiError(message=msg, response=self)
+
+

An iterable container of response data.

+

Attributes

+
+
data : dict
+
The json-encoded content of the response. Along +with the headers and status code information.
+
+

Methods

+

validate: Check if the response from Slack was successful. +get: Retrieves any key from the response data. +next: Retrieves the next portion of results, +if 'next_cursor' is present.

+

Example:

+
import os
+import slack
+
+client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
+
+response1 = client.auth_revoke(test='true')
+assert not response1['revoked']
+
+response2 = client.auth_test()
+assert response2.get('ok', False)
+
+users = []
+for page in client.users_list(limit=2):
+    users = users + page['members']
+
+

Note

+

Some responses return collections of information +like channel and user lists. If they do it's likely +that you'll only receive a portion of results. This +object allows you to iterate over the response which +makes subsequent API requests until your code hits +'break' or there are no more results to be found.

+

Any attributes or methods prefixed with _underscores are +intended to be "private" internal use only. They may be changed or +removed at anytime.

+

Methods

+
+
+def get(self, key, default=None) +
+
+
+ +Expand source code + +
def get(self, key, default=None):
+    """Retrieves any key from the response data.
+
+    Note:
+        This is implemented so users can reference the
+        SlackResponse object like a dictionary.
+        e.g. response.get("ok", False)
+
+    Returns:
+        The value from data or the specified default.
+    """
+    if isinstance(self.data, bytes):
+        raise ValueError("As the response.data is binary data, this operation is unsupported")
+    if self.data is None:
+        return None
+    return self.data.get(key, default)
+
+

Retrieves any key from the response data.

+

Note

+

This is implemented so users can reference the +SlackResponse object like a dictionary. +e.g. response.get("ok", False)

+

Returns

+

The value from data or the specified default.

+
+
+def validate(self) +
+
+
+ +Expand source code + +
def validate(self):
+    """Check if the response from Slack was successful.
+
+    Returns:
+        (SlackResponse)
+            This method returns it's own object. e.g. 'self'
+
+    Raises:
+        SlackApiError: The request to the Slack API failed.
+    """
+    if self.status_code == 200 and self.data and (isinstance(self.data, bytes) or self.data.get("ok", False)):
+        return self
+    msg = f"The request to the Slack API failed. (url: {self.api_url})"
+    raise e.SlackApiError(message=msg, response=self)
+
+

Check if the response from Slack was successful.

+

Returns

+

(SlackResponse) +This method returns it's own object. e.g. 'self'

+

Raises

+
+
SlackApiError
+
The request to the Slack API failed.
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/webhook/async_client.html b/docs/reference/webhook/async_client.html new file mode 100644 index 000000000..15c7e4a45 --- /dev/null +++ b/docs/reference/webhook/async_client.html @@ -0,0 +1,537 @@ + + + + + + +slack_sdk.webhook.async_client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.webhook.async_client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class AsyncWebhookClient +(url:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
session:Β aiohttp.client.ClientSessionΒ |Β NoneΒ =Β None,
trust_env_in_session:Β boolΒ =Β False,
auth:Β aiohttp.helpers.BasicAuthΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class AsyncWebhookClient:
+    url: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    session: Optional[ClientSession]
+    trust_env_in_session: bool
+    auth: Optional[BasicAuth]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[AsyncRetryHandler]
+
+    def __init__(
+        self,
+        url: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        session: Optional[ClientSession] = None,
+        trust_env_in_session: bool = False,
+        auth: Optional[BasicAuth] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[AsyncRetryHandler]] = None,
+    ):
+        """API client for Incoming Webhooks and `response_url`
+
+        https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/
+
+        Args:
+            url: Complete URL to send data (e.g., `https://hooks.slack.com/XXX`)
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            session: `aiohttp.ClientSession` instance
+            trust_env_in_session: True/False for `aiohttp.ClientSession`
+            auth: Basic auth info for `aiohttp.ClientSession`
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+        """
+        self.url = url
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.trust_env_in_session = trust_env_in_session
+        self.session = session
+        self.auth = auth
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    async def send(
+        self,
+        *,
+        text: Optional[str] = None,
+        attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+        blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+        response_type: Optional[str] = None,
+        replace_original: Optional[bool] = None,
+        delete_original: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        metadata: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            text: The text message (even when having blocks, setting this as well is recommended as it works as fallback)
+            attachments: A collection of attachments
+            blocks: A collection of Block Kit UI components
+            response_type: The type of message (either 'in_channel' or 'ephemeral')
+            replace_original: True if you use this option for response_url requests
+            delete_original: True if you use this option for response_url requests
+            unfurl_links: Option to indicate whether text url should unfurl
+            unfurl_media: Option to indicate whether media url should unfurl
+            metadata: Metadata attached to the message
+            headers: Request headers to append only for this request
+
+        Returns:
+            Webhook response
+        """
+        return await self.send_dict(
+            # It's fine to have None value elements here
+            # because _build_body() filters them out when constructing the actual body data
+            body={
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "response_type": response_type,
+                "replace_original": replace_original,
+                "delete_original": delete_original,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "metadata": metadata,
+            },
+            headers=headers,
+        )
+
+    async def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            headers: Request headers to append only for this request
+        Returns:
+            Webhook response
+        """
+        return await self._perform_http_request(
+            body=_build_body(body),  # type: ignore[arg-type]
+            headers=_build_request_headers(self.default_headers, headers),
+        )
+
+    async def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse:
+        str_body: str = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        session: Optional[ClientSession] = None
+        use_running_session = self.session and not self.session.closed
+        if use_running_session:
+            session = self.session
+        else:
+            session = aiohttp.ClientSession(
+                timeout=aiohttp.ClientTimeout(total=self.timeout),
+                auth=self.auth,
+                trust_env=self.trust_env_in_session,
+            )
+
+        last_error: Optional[Exception] = None
+        resp: Optional[WebhookResponse] = None
+        try:
+            request_kwargs = {
+                "headers": headers,
+                "data": str_body,
+                "ssl": self.ssl,
+                "proxy": self.proxy,
+            }
+            retry_request = RetryHttpRequest(
+                method="POST",
+                url=self.url,
+                headers=headers,  # type: ignore[arg-type]
+                body_params=body,
+            )
+
+            retry_state = RetryState()
+            counter_for_safety = 0
+            while counter_for_safety < 100:
+                counter_for_safety += 1
+                # If this is a retry, the next try started here. We can reset the flag.
+                retry_state.next_attempt_requested = False
+                retry_response: Optional[RetryHttpResponse] = None
+                response_body = ""
+
+                if self.logger.level <= logging.DEBUG:
+                    self.logger.debug(f"Sending a request - url: {self.url}, body: {str_body}, headers: {headers}")
+
+                try:
+                    async with session.request("POST", self.url, **request_kwargs) as res:  # type: ignore[arg-type, union-attr] # noqa: E501
+                        try:
+                            response_body = await res.text()
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                                data=response_body.encode("utf-8") if response_body is not None else None,
+                            )
+                        except aiohttp.ContentTypeError:
+                            self.logger.debug(f"No response data returned from the following API call: {self.url}")
+                            retry_response = RetryHttpResponse(
+                                status_code=res.status,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+
+                        if res.status == 429:
+                            for handler in self.retry_handlers:
+                                if await handler.can_retry_async(
+                                    state=retry_state,
+                                    request=retry_request,
+                                    response=retry_response,
+                                ):
+                                    if self.logger.level <= logging.DEBUG:
+                                        self.logger.info(
+                                            f"A retry handler found: {type(handler).__name__} "
+                                            f"for POST {self.url} - rate_limited"
+                                        )
+                                    await handler.prepare_for_next_attempt_async(
+                                        state=retry_state,
+                                        request=retry_request,
+                                        response=retry_response,
+                                    )
+                                    break
+
+                        if retry_state.next_attempt_requested is False:
+                            resp = WebhookResponse(
+                                url=self.url,
+                                status_code=res.status,
+                                body=response_body,
+                                headers=res.headers,  # type: ignore[arg-type]
+                            )
+                            _debug_log_response(self.logger, resp)
+                            return resp
+
+                except Exception as e:
+                    last_error = e
+                    for handler in self.retry_handlers:
+                        if await handler.can_retry_async(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        ):
+                            if self.logger.level <= logging.DEBUG:
+                                self.logger.info(
+                                    f"A retry handler found: {type(handler).__name__} " f"for POST {self.url} - {e}"
+                                )
+                            await handler.prepare_for_next_attempt_async(
+                                state=retry_state,
+                                request=retry_request,
+                                response=retry_response,
+                                error=e,
+                            )
+                            break
+
+                    if retry_state.next_attempt_requested is False:
+                        raise last_error
+
+            if resp is not None:
+                return resp
+            raise last_error  # type: ignore[misc]
+
+        finally:
+            if not use_running_session:
+                await session.close()  # type: ignore[union-attr]
+
+        return resp
+
+

API client for Incoming Webhooks and response_url

+

https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/

+

Args

+
+
url
+
Complete URL to send data (e.g., https://hooks.slack.com/XXX)
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
session
+
aiohttp.ClientSession instance
+
trust_env_in_session
+
True/False for aiohttp.ClientSession
+
auth
+
Basic auth info for aiohttp.ClientSession
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
+

Class variables

+
+
var auth :Β aiohttp.helpers.BasicAuthΒ |Β None
+
+

The type of the None singleton.

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[slack_sdk.http_retry.async_handler.AsyncRetryHandler]
+
+

The type of the None singleton.

+
+
var session :Β aiohttp.client.ClientSessionΒ |Β None
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var trust_env_in_session :Β bool
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+async def send(self,
*,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β Sequence[Dict[str,Β Any]Β |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β Sequence[Dict[str,Β Any]Β |Β Block]Β |Β NoneΒ =Β None,
response_type:Β strΒ |Β NoneΒ =Β None,
replace_original:Β boolΒ |Β NoneΒ =Β None,
delete_original:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
metadata:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse
+
+
+
+ +Expand source code + +
async def send(
+    self,
+    *,
+    text: Optional[str] = None,
+    attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+    blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+    response_type: Optional[str] = None,
+    replace_original: Optional[bool] = None,
+    delete_original: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    metadata: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        text: The text message (even when having blocks, setting this as well is recommended as it works as fallback)
+        attachments: A collection of attachments
+        blocks: A collection of Block Kit UI components
+        response_type: The type of message (either 'in_channel' or 'ephemeral')
+        replace_original: True if you use this option for response_url requests
+        delete_original: True if you use this option for response_url requests
+        unfurl_links: Option to indicate whether text url should unfurl
+        unfurl_media: Option to indicate whether media url should unfurl
+        metadata: Metadata attached to the message
+        headers: Request headers to append only for this request
+
+    Returns:
+        Webhook response
+    """
+    return await self.send_dict(
+        # It's fine to have None value elements here
+        # because _build_body() filters them out when constructing the actual body data
+        body={
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "response_type": response_type,
+            "replace_original": replace_original,
+            "delete_original": delete_original,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "metadata": metadata,
+        },
+        headers=headers,
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
text
+
The text message (even when having blocks, setting this as well is recommended as it works as fallback)
+
attachments
+
A collection of attachments
+
blocks
+
A collection of Block Kit UI components
+
response_type
+
The type of message (either 'in_channel' or 'ephemeral')
+
replace_original
+
True if you use this option for response_url requests
+
delete_original
+
True if you use this option for response_url requests
+
unfurl_links
+
Option to indicate whether text url should unfurl
+
unfurl_media
+
Option to indicate whether media url should unfurl
+
metadata
+
Metadata attached to the message
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+async def send_dict(self, body:Β Dict[str,Β Any], headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse +
+
+
+ +Expand source code + +
async def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        body: JSON data structure (it's still a dict at this point),
+            if you give this argument, body_params and files will be skipped
+        headers: Request headers to append only for this request
+    Returns:
+        Webhook response
+    """
+    return await self._perform_http_request(
+        body=_build_body(body),  # type: ignore[arg-type]
+        headers=_build_request_headers(self.default_headers, headers),
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
body
+
JSON data structure (it's still a dict at this point), +if you give this argument, body_params and files will be skipped
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/webhook/client.html b/docs/reference/webhook/client.html new file mode 100644 index 000000000..aebec5a3f --- /dev/null +++ b/docs/reference/webhook/client.html @@ -0,0 +1,527 @@ + + + + + + +slack_sdk.webhook.client API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.webhook.client

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class WebhookClient +(url:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebhookClient:
+    url: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        url: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for Incoming Webhooks and `response_url`
+
+        https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/
+
+        Args:
+            url: Complete URL to send data (e.g., `https://hooks.slack.com/XXX`)
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.url = url
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    def send(
+        self,
+        *,
+        text: Optional[str] = None,
+        attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+        blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+        response_type: Optional[str] = None,
+        replace_original: Optional[bool] = None,
+        delete_original: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        metadata: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            text: The text message
+                (even when having blocks, setting this as well is recommended as it works as fallback)
+            attachments: A collection of attachments
+            blocks: A collection of Block Kit UI components
+            response_type: The type of message (either 'in_channel' or 'ephemeral')
+            replace_original: True if you use this option for response_url requests
+            delete_original: True if you use this option for response_url requests
+            unfurl_links: Option to indicate whether text url should unfurl
+            unfurl_media: Option to indicate whether media url should unfurl
+            metadata: Metadata attached to the message
+            headers: Request headers to append only for this request
+
+        Returns:
+            Webhook response
+        """
+        return self.send_dict(
+            # It's fine to have None value elements here
+            # because _build_body() filters them out when constructing the actual body data
+            body={
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "response_type": response_type,
+                "replace_original": replace_original,
+                "delete_original": delete_original,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "metadata": metadata,
+            },
+            headers=headers,
+        )
+
+    def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            headers: Request headers to append only for this request
+        Returns:
+            Webhook response
+        """
+        return self._perform_http_request(
+            body=_build_body(body),  # type: ignore[arg-type]
+            headers=_build_request_headers(self.default_headers, headers),
+        )
+
+    def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse:
+        raw_body = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a request - url: {self.url}, body: {raw_body}, headers: {headers}")
+
+        url = self.url
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(method="POST", url=url, data=raw_body.encode("utf-8"), headers=headers)
+        resp = None
+        last_error = Exception("undefined internal error")
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = WebhookResponse(
+                    url=url,
+                    status_code=e.code,
+                    body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error
+
+    def _perform_http_request_internal(self, url: str, req: Request):
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        http_resp: Optional[HTTPResponse] = None
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = WebhookResponse(
+            url=url,
+            status_code=http_resp.status,
+            body=response_body,
+            headers=http_resp.headers,  # type: ignore[arg-type]
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for Incoming Webhooks and response_url

+

https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/

+

Args

+
+
url
+
Complete URL to send data (e.g., https://hooks.slack.com/XXX)
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def send(self,
*,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β Sequence[Dict[str,Β Any]Β |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β Sequence[Dict[str,Β Any]Β |Β Block]Β |Β NoneΒ =Β None,
response_type:Β strΒ |Β NoneΒ =Β None,
replace_original:Β boolΒ |Β NoneΒ =Β None,
delete_original:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
metadata:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse
+
+
+
+ +Expand source code + +
def send(
+    self,
+    *,
+    text: Optional[str] = None,
+    attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+    blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+    response_type: Optional[str] = None,
+    replace_original: Optional[bool] = None,
+    delete_original: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    metadata: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        text: The text message
+            (even when having blocks, setting this as well is recommended as it works as fallback)
+        attachments: A collection of attachments
+        blocks: A collection of Block Kit UI components
+        response_type: The type of message (either 'in_channel' or 'ephemeral')
+        replace_original: True if you use this option for response_url requests
+        delete_original: True if you use this option for response_url requests
+        unfurl_links: Option to indicate whether text url should unfurl
+        unfurl_media: Option to indicate whether media url should unfurl
+        metadata: Metadata attached to the message
+        headers: Request headers to append only for this request
+
+    Returns:
+        Webhook response
+    """
+    return self.send_dict(
+        # It's fine to have None value elements here
+        # because _build_body() filters them out when constructing the actual body data
+        body={
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "response_type": response_type,
+            "replace_original": replace_original,
+            "delete_original": delete_original,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "metadata": metadata,
+        },
+        headers=headers,
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
text
+
The text message +(even when having blocks, setting this as well is recommended as it works as fallback)
+
attachments
+
A collection of attachments
+
blocks
+
A collection of Block Kit UI components
+
response_type
+
The type of message (either 'in_channel' or 'ephemeral')
+
replace_original
+
True if you use this option for response_url requests
+
delete_original
+
True if you use this option for response_url requests
+
unfurl_links
+
Option to indicate whether text url should unfurl
+
unfurl_media
+
Option to indicate whether media url should unfurl
+
metadata
+
Metadata attached to the message
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+def send_dict(self, body:Β Dict[str,Β Any], headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse +
+
+
+ +Expand source code + +
def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        body: JSON data structure (it's still a dict at this point),
+            if you give this argument, body_params and files will be skipped
+        headers: Request headers to append only for this request
+    Returns:
+        Webhook response
+    """
+    return self._perform_http_request(
+        body=_build_body(body),  # type: ignore[arg-type]
+        headers=_build_request_headers(self.default_headers, headers),
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
body
+
JSON data structure (it's still a dict at this point), +if you give this argument, body_params and files will be skipped
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/webhook/index.html b/docs/reference/webhook/index.html new file mode 100644 index 000000000..51c387ef4 --- /dev/null +++ b/docs/reference/webhook/index.html @@ -0,0 +1,585 @@ + + + + + + +slack_sdk.webhook API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.webhook

+
+
+

You can use slack_sdk.webhook.WebhookClient for Incoming Webhooks +and message responses using response_url in payloads.

+
+
+

Sub-modules

+
+
slack_sdk.webhook.async_client
+
+
+
+
slack_sdk.webhook.client
+
+
+
+
slack_sdk.webhook.internal_utils
+
+
+
+
slack_sdk.webhook.webhook_response
+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class WebhookClient +(url:Β str,
timeout:Β intΒ =Β 30,
ssl:Β ssl.SSLContextΒ |Β NoneΒ =Β None,
proxy:Β strΒ |Β NoneΒ =Β None,
default_headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None,
user_agent_prefix:Β strΒ |Β NoneΒ =Β None,
user_agent_suffix:Β strΒ |Β NoneΒ =Β None,
logger:Β logging.LoggerΒ |Β NoneΒ =Β None,
retry_handlers:Β List[RetryHandler]Β |Β NoneΒ =Β None)
+
+
+
+ +Expand source code + +
class WebhookClient:
+    url: str
+    timeout: int
+    ssl: Optional[SSLContext]
+    proxy: Optional[str]
+    default_headers: Dict[str, str]
+    logger: logging.Logger
+    retry_handlers: List[RetryHandler]
+
+    def __init__(
+        self,
+        url: str,
+        timeout: int = 30,
+        ssl: Optional[SSLContext] = None,
+        proxy: Optional[str] = None,
+        default_headers: Optional[Dict[str, str]] = None,
+        user_agent_prefix: Optional[str] = None,
+        user_agent_suffix: Optional[str] = None,
+        logger: Optional[logging.Logger] = None,
+        retry_handlers: Optional[List[RetryHandler]] = None,
+    ):
+        """API client for Incoming Webhooks and `response_url`
+
+        https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/
+
+        Args:
+            url: Complete URL to send data (e.g., `https://hooks.slack.com/XXX`)
+            timeout: Request timeout (in seconds)
+            ssl: `ssl.SSLContext` to use for requests
+            proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`)
+            default_headers: Request headers to add to all requests
+            user_agent_prefix: Prefix for User-Agent header value
+            user_agent_suffix: Suffix for User-Agent header value
+            logger: Custom logger
+            retry_handlers: Retry handlers
+        """
+        self.url = url
+        self.timeout = timeout
+        self.ssl = ssl
+        self.proxy = proxy
+        self.default_headers = default_headers if default_headers else {}
+        self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix)
+        self.logger = logger if logger is not None else logging.getLogger(__name__)
+        self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers()
+
+        if self.proxy is None or len(self.proxy.strip()) == 0:
+            env_variable = load_http_proxy_from_env(self.logger)
+            if env_variable is not None:
+                self.proxy = env_variable
+
+    def send(
+        self,
+        *,
+        text: Optional[str] = None,
+        attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+        blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+        response_type: Optional[str] = None,
+        replace_original: Optional[bool] = None,
+        delete_original: Optional[bool] = None,
+        unfurl_links: Optional[bool] = None,
+        unfurl_media: Optional[bool] = None,
+        metadata: Optional[Dict[str, Any]] = None,
+        headers: Optional[Dict[str, str]] = None,
+    ) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            text: The text message
+                (even when having blocks, setting this as well is recommended as it works as fallback)
+            attachments: A collection of attachments
+            blocks: A collection of Block Kit UI components
+            response_type: The type of message (either 'in_channel' or 'ephemeral')
+            replace_original: True if you use this option for response_url requests
+            delete_original: True if you use this option for response_url requests
+            unfurl_links: Option to indicate whether text url should unfurl
+            unfurl_media: Option to indicate whether media url should unfurl
+            metadata: Metadata attached to the message
+            headers: Request headers to append only for this request
+
+        Returns:
+            Webhook response
+        """
+        return self.send_dict(
+            # It's fine to have None value elements here
+            # because _build_body() filters them out when constructing the actual body data
+            body={
+                "text": text,
+                "attachments": attachments,
+                "blocks": blocks,
+                "response_type": response_type,
+                "replace_original": replace_original,
+                "delete_original": delete_original,
+                "unfurl_links": unfurl_links,
+                "unfurl_media": unfurl_media,
+                "metadata": metadata,
+            },
+            headers=headers,
+        )
+
+    def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+        """Performs a Slack API request and returns the result.
+
+        Args:
+            body: JSON data structure (it's still a dict at this point),
+                if you give this argument, body_params and files will be skipped
+            headers: Request headers to append only for this request
+        Returns:
+            Webhook response
+        """
+        return self._perform_http_request(
+            body=_build_body(body),  # type: ignore[arg-type]
+            headers=_build_request_headers(self.default_headers, headers),
+        )
+
+    def _perform_http_request(self, *, body: Dict[str, Any], headers: Dict[str, str]) -> WebhookResponse:
+        raw_body = json.dumps(body)
+        headers["Content-Type"] = "application/json;charset=utf-8"
+
+        if self.logger.level <= logging.DEBUG:
+            self.logger.debug(f"Sending a request - url: {self.url}, body: {raw_body}, headers: {headers}")
+
+        url = self.url
+        # NOTE: Intentionally ignore the `http_verb` here
+        # Slack APIs accepts any API method requests with POST methods
+        req = Request(method="POST", url=url, data=raw_body.encode("utf-8"), headers=headers)
+        resp = None
+        last_error = Exception("undefined internal error")
+
+        retry_state = RetryState()
+        counter_for_safety = 0
+        while counter_for_safety < 100:
+            counter_for_safety += 1
+            # If this is a retry, the next try started here. We can reset the flag.
+            retry_state.next_attempt_requested = False
+
+            try:
+                resp = self._perform_http_request_internal(url, req)
+                # The resp is a 200 OK response
+                return resp
+
+            except HTTPError as e:
+                # read the response body here
+                charset = e.headers.get_content_charset() or "utf-8"
+                response_body: str = e.read().decode(charset)
+                # As adding new values to HTTPError#headers can be ignored, building a new dict object here
+                response_headers = dict(e.headers.items())
+                resp = WebhookResponse(
+                    url=url,
+                    status_code=e.code,
+                    body=response_body,
+                    headers=response_headers,
+                )
+                if e.code == 429:
+                    # for backward-compatibility with WebClient (v.2.5.0 or older)
+                    if "retry-after" not in resp.headers and "Retry-After" in resp.headers:
+                        resp.headers["retry-after"] = resp.headers["Retry-After"]
+                    if "Retry-After" not in resp.headers and "retry-after" in resp.headers:
+                        resp.headers["Retry-After"] = resp.headers["retry-after"]
+                _debug_log_response(self.logger, resp)
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                retry_response = RetryHttpResponse(
+                    status_code=e.code,
+                    headers={k: [v] for k, v in e.headers.items()},
+                    data=response_body.encode("utf-8") if response_body is not None else None,
+                )
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=retry_response,
+                        error=e,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=retry_response,
+                            error=e,
+                        )
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    return resp
+
+            except Exception as err:
+                last_error = err
+                self.logger.error(f"Failed to send a request to Slack API server: {err}")
+
+                # Try to find a retry handler for this error
+                retry_request = RetryHttpRequest.from_urllib_http_request(req)
+                for handler in self.retry_handlers:
+                    if handler.can_retry(
+                        state=retry_state,
+                        request=retry_request,
+                        response=None,
+                        error=err,
+                    ):
+                        if self.logger.level <= logging.DEBUG:
+                            self.logger.info(
+                                f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}"
+                            )
+                        handler.prepare_for_next_attempt(
+                            state=retry_state,
+                            request=retry_request,
+                            response=None,
+                            error=err,
+                        )
+                        self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}")
+                        break
+
+                if retry_state.next_attempt_requested is False:
+                    raise err
+
+        if resp is not None:
+            return resp
+        raise last_error
+
+    def _perform_http_request_internal(self, url: str, req: Request):
+        opener: Optional[OpenerDirector] = None
+        # for security (BAN-B310)
+        if url.lower().startswith("http"):
+            if self.proxy is not None:
+                if isinstance(self.proxy, str):
+                    opener = urllib.request.build_opener(
+                        ProxyHandler({"http": self.proxy, "https": self.proxy}),
+                        HTTPSHandler(context=self.ssl),
+                    )
+                else:
+                    raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value")
+        else:
+            raise SlackRequestError(f"Invalid URL detected: {url}")
+
+        http_resp: Optional[HTTPResponse] = None
+        if opener:
+            http_resp = opener.open(req, timeout=self.timeout)
+        else:
+            http_resp = urlopen(req, context=self.ssl, timeout=self.timeout)
+        charset: str = http_resp.headers.get_content_charset() or "utf-8"
+        response_body: str = http_resp.read().decode(charset)
+        resp = WebhookResponse(
+            url=url,
+            status_code=http_resp.status,
+            body=response_body,
+            headers=http_resp.headers,  # type: ignore[arg-type]
+        )
+        _debug_log_response(self.logger, resp)
+        return resp
+
+

API client for Incoming Webhooks and response_url

+

https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/

+

Args

+
+
url
+
Complete URL to send data (e.g., https://hooks.slack.com/XXX)
+
timeout
+
Request timeout (in seconds)
+
ssl
+
ssl.SSLContext to use for requests
+
proxy
+
Proxy URL (e.g., localhost:9000, http://localhost:9000)
+
default_headers
+
Request headers to add to all requests
+
user_agent_prefix
+
Prefix for User-Agent header value
+
user_agent_suffix
+
Suffix for User-Agent header value
+
logger
+
Custom logger
+
retry_handlers
+
Retry handlers
+
+

Class variables

+
+
var default_headers :Β Dict[str,Β str]
+
+

The type of the None singleton.

+
+
var logger :Β logging.Logger
+
+

The type of the None singleton.

+
+
var proxy :Β strΒ |Β None
+
+

The type of the None singleton.

+
+
var retry_handlers :Β List[RetryHandler]
+
+

The type of the None singleton.

+
+
var ssl :Β ssl.SSLContextΒ |Β None
+
+

The type of the None singleton.

+
+
var timeout :Β int
+
+

The type of the None singleton.

+
+
var url :Β str
+
+

The type of the None singleton.

+
+
+

Methods

+
+
+def send(self,
*,
text:Β strΒ |Β NoneΒ =Β None,
attachments:Β Sequence[Dict[str,Β Any]Β |Β Attachment]Β |Β NoneΒ =Β None,
blocks:Β Sequence[Dict[str,Β Any]Β |Β Block]Β |Β NoneΒ =Β None,
response_type:Β strΒ |Β NoneΒ =Β None,
replace_original:Β boolΒ |Β NoneΒ =Β None,
delete_original:Β boolΒ |Β NoneΒ =Β None,
unfurl_links:Β boolΒ |Β NoneΒ =Β None,
unfurl_media:Β boolΒ |Β NoneΒ =Β None,
metadata:Β Dict[str,Β Any]Β |Β NoneΒ =Β None,
headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse
+
+
+
+ +Expand source code + +
def send(
+    self,
+    *,
+    text: Optional[str] = None,
+    attachments: Optional[Sequence[Union[Dict[str, Any], Attachment]]] = None,
+    blocks: Optional[Sequence[Union[Dict[str, Any], Block]]] = None,
+    response_type: Optional[str] = None,
+    replace_original: Optional[bool] = None,
+    delete_original: Optional[bool] = None,
+    unfurl_links: Optional[bool] = None,
+    unfurl_media: Optional[bool] = None,
+    metadata: Optional[Dict[str, Any]] = None,
+    headers: Optional[Dict[str, str]] = None,
+) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        text: The text message
+            (even when having blocks, setting this as well is recommended as it works as fallback)
+        attachments: A collection of attachments
+        blocks: A collection of Block Kit UI components
+        response_type: The type of message (either 'in_channel' or 'ephemeral')
+        replace_original: True if you use this option for response_url requests
+        delete_original: True if you use this option for response_url requests
+        unfurl_links: Option to indicate whether text url should unfurl
+        unfurl_media: Option to indicate whether media url should unfurl
+        metadata: Metadata attached to the message
+        headers: Request headers to append only for this request
+
+    Returns:
+        Webhook response
+    """
+    return self.send_dict(
+        # It's fine to have None value elements here
+        # because _build_body() filters them out when constructing the actual body data
+        body={
+            "text": text,
+            "attachments": attachments,
+            "blocks": blocks,
+            "response_type": response_type,
+            "replace_original": replace_original,
+            "delete_original": delete_original,
+            "unfurl_links": unfurl_links,
+            "unfurl_media": unfurl_media,
+            "metadata": metadata,
+        },
+        headers=headers,
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
text
+
The text message +(even when having blocks, setting this as well is recommended as it works as fallback)
+
attachments
+
A collection of attachments
+
blocks
+
A collection of Block Kit UI components
+
response_type
+
The type of message (either 'in_channel' or 'ephemeral')
+
replace_original
+
True if you use this option for response_url requests
+
delete_original
+
True if you use this option for response_url requests
+
unfurl_links
+
Option to indicate whether text url should unfurl
+
unfurl_media
+
Option to indicate whether media url should unfurl
+
metadata
+
Metadata attached to the message
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+def send_dict(self, body:Β Dict[str,Β Any], headers:Β Dict[str,Β str]Β |Β NoneΒ =Β None) ‑>Β WebhookResponse +
+
+
+ +Expand source code + +
def send_dict(self, body: Dict[str, Any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse:
+    """Performs a Slack API request and returns the result.
+
+    Args:
+        body: JSON data structure (it's still a dict at this point),
+            if you give this argument, body_params and files will be skipped
+        headers: Request headers to append only for this request
+    Returns:
+        Webhook response
+    """
+    return self._perform_http_request(
+        body=_build_body(body),  # type: ignore[arg-type]
+        headers=_build_request_headers(self.default_headers, headers),
+    )
+
+

Performs a Slack API request and returns the result.

+

Args

+
+
body
+
JSON data structure (it's still a dict at this point), +if you give this argument, body_params and files will be skipped
+
headers
+
Request headers to append only for this request
+
+

Returns

+

Webhook response

+
+
+
+
+class WebhookResponse +(*, url:Β str, status_code:Β int, body:Β str, headers:Β Dict[str,Β Any]) +
+
+
+ +Expand source code + +
class WebhookResponse:
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        body: str,
+        headers: Dict[str, Any],
+    ):
+        self.api_url = url
+        self.status_code = status_code
+        self.body = body
+        self.headers = headers
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/webhook/internal_utils.html b/docs/reference/webhook/internal_utils.html new file mode 100644 index 000000000..118a7100f --- /dev/null +++ b/docs/reference/webhook/internal_utils.html @@ -0,0 +1,66 @@ + + + + + + +slack_sdk.webhook.internal_utils API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.webhook.internal_utils

+
+
+
+
+
+
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/reference/webhook/webhook_response.html b/docs/reference/webhook/webhook_response.html new file mode 100644 index 000000000..f0c372b97 --- /dev/null +++ b/docs/reference/webhook/webhook_response.html @@ -0,0 +1,101 @@ + + + + + + +slack_sdk.webhook.webhook_response API documentation + + + + + + + + + + + +
+
+
+

Module slack_sdk.webhook.webhook_response

+
+
+
+
+
+
+
+
+
+
+

Classes

+
+
+class WebhookResponse +(*, url:Β str, status_code:Β int, body:Β str, headers:Β Dict[str,Β Any]) +
+
+
+ +Expand source code + +
class WebhookResponse:
+    def __init__(
+        self,
+        *,
+        url: str,
+        status_code: int,
+        body: str,
+        headers: Dict[str, Any],
+    ):
+        self.api_url = url
+        self.status_code = status_code
+        self.body = body
+        self.headers = headers
+
+
+
+
+
+
+ +
+ + + diff --git a/docs/search.html b/docs/search.html deleted file mode 100644 index 296b755dd..000000000 --- a/docs/search.html +++ /dev/null @@ -1,239 +0,0 @@ - - - - - - Search — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-

Search

-
- -

- Please activate JavaScript to enable the search - functionality. -

-
-

- Searching for multiple words only shows matches that contain - all words. -

-
- - - -
- -
- -
- -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/searchindex.js b/docs/searchindex.js deleted file mode 100644 index 20a69e7a8..000000000 --- a/docs/searchindex.js +++ /dev/null @@ -1 +0,0 @@ -Search.setIndex({docnames:["about","faq","index","installation/index","metadata","oauth/index","real_time_messaging","v3-migration/index","web/index","webhook/index"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,sphinx:56},filenames:["about.rst","faq.rst","index.rst","installation/index.rst","metadata.rst","oauth/index.rst","real_time_messaging.rst","v3-migration/index.rst","web/index.rst","webhook/index.rst"],objects:{},objnames:{},objtypes:{},terms:{"000002":[6,8],"000003":8,"111":3,"12345":8,"123456":8,"1234567890":8,"1358878749":6,"139":5,"1476745373":8,"1476746830":8,"1920":8,"200":[2,5,8,9],"222":3,"237":8,"300":5,"3000":[3,8],"400":5,"403":[5,8,9],"404":[5,8,9],"429":8,"750319":8,"boolean":8,"break":[1,7],"case":[1,5],"class":[7,8,9],"default":[5,6,8],"export":[1,8],"final":3,"function":[3,6],"import":[1,2,3,5,6,7,8,9],"int":8,"long":[7,8],"new":[1,3,7,8,9],"public":8,"return":[3,5,8,9],"short":[7,8],"super":1,"switch":[1,7],"true":[7,8],"try":[1,2,5,8],"while":[1,6,7,8],Adding:8,And:2,But:1,For:[3,7,8],IDs:[5,8],IMs:8,One:8,That:[1,7,8],The:[2,3,5,6,7,8,9],Then:[1,3],There:[1,7],Use:8,With:5,__main__:[3,8],__name__:[3,5,8,9],abil:[3,6],abl:3,about:[1,3,5,6,8],abov:[5,8],accept:3,access:[0,5,8],access_token:[3,5],accessori:8,acknowledg:9,action:[7,9],action_id:[5,8],activ:1,actual:8,adaptor:6,add:[1,3,5,7,8],add_to_slack:5,added:1,addit:[3,8],address:7,after:[3,5,8],again:5,agre:3,agreement:0,aim:1,aiohttp:[7,8,9],all:[1,3,5,7,8],allow:[6,8],along:[5,6],alreadi:[5,6,8],already_in_channel:8,also:[2,6,7,8,9],alt:5,alt_text:8,alwai:[1,2],ambiti:1,ani:[2,3,5,6,7,9],anoth:8,apart:7,api:[0,2,3,5,6,7,9],api_cal:8,api_method:8,api_respons:[2,8],api_test:[1,2],app:[0,2,3,6,8,9],app_home_open:6,app_id:5,app_ment:5,appear:8,appli:3,applic:[3,8],appropri:1,architectur:6,archiv:8,aren:6,arg:[3,5],argument:8,around:1,arrai:8,articl:8,assert:[8,9],assign:8,assist:2,associ:9,async:[7,8,9],async_cli:[2,8,9],asynchron:[8,9],asyncio:[7,8,9],asyncwebcli:7,asyncwebhookcli:7,attach:8,attribut:[1,8],attributeerror:1,auth:[3,5],auth_test:5,authed_us:5,authent:[2,5,8,9],author:[3,5],authorize_url_gener:5,authorizeurlgener:5,automat:7,avail:[3,8,9],averag:8,avoid:3,await:[7,8,9],awesom:[5,8],axe:8,b00000000:9,back:[5,6],base:6,base_dir:5,basic:[3,6,8],basicconfig:[1,2,8],becom:8,been:[3,8],befor:[7,8],beforehand:[8,9],begin:3,being:[1,8],below:[5,6,8],best:[2,8],between:[7,8],biggest:7,bin:1,bit:8,bite:1,block:[5,8,9],block_id:[5,8],bodi:[5,9],bolt:5,bond:2,bot:[3,5,6,8],bot_id:5,bot_scop:5,bot_token:5,bot_user_id:5,both:1,box:[7,8],broadcast:8,bug:2,build:[0,2,3,5,8],builder:[2,8],built:3,burst:8,button:[3,5,8],c031415926:8,c0xxxxxx:8,c0xxxxxxx:8,c0xxxxxxy:8,c16180339:8,c27182818:8,c3ukjtqac:8,call:[3,5,6,7,9],callback:[5,6,8],callback_id:[5,8],can:[1,2,3,5,6,7,8,9],cancel:8,cannot:8,capabl:2,chang:[3,7,8],changelog:1,channel:[5,6,8,9],channel_id:[5,6,8],channel_nam:8,channel_not_found:8,charact:8,chat:[5,8],chat_delet:8,chat_postephemer:8,chat_postmessag:[6,8],chat_upd:8,check:[3,5,8],choos:5,classic:6,click:[3,5],client:[1,2,3,5,7],client_id:[3,5],client_secret:[3,5],clone:2,close:8,code:[0,1,2,3,5,7,8],code_param:3,collect:8,com:[2,3,5,8,9],combin:8,comma:[5,8],command:[1,5,9],comment:8,commun:[2,6],compat:7,complet:[1,3,5,6],complex:8,compon:2,compos:8,concret:1,conduct:0,configur:[3,6,8],configuration_url:5,confus:7,connect:6,connect_method:6,consider:8,consist:7,construct:2,consum:5,contain:[6,8],content:1,context:8,continu:[1,8],contribut:0,contributor:[0,1],convers:[6,7],conversations_arch:8,conversations_cr:8,conversations_info:8,conversations_join:8,conversations_leav:8,conversations_list:8,conversations_memb:8,conversations_open:8,correspond:[2,3,6],could:1,coupl:1,cours:2,cover:8,coverag:[1,7],creat:[1,6,8],credenti:[3,6],custom:8,dai:1,danni:8,data:[2,3,5,6,8],databas:3,deal:8,debug:[1,2,8],deck:8,dedic:1,def:[3,5,6,8,9],defin:3,delai:8,delet:8,deliv:2,demonstr:[1,5],depend:[3,7,8,9],deprec:[1,7],descend:8,detail:[5,6,8],determin:3,dev:7,develop:[0,2,8],devic:9,differ:8,direct:[3,8],directli:[2,8],discuss:[1,2],displai:8,doc:[1,6,8],document:[3,6,8],doesn:[5,7],domain:[5,8],don:[1,3,5,6,7,8],done:1,door:8,driven:6,due:[5,8],dynam:8,each:[2,8],easi:2,easier:5,edg:5,edit:1,effect:3,either:[6,8],element:[5,8],elif:5,els:[5,8],emoji:8,empti:3,enabl:[2,8],encount:[1,8],encourag:6,end:5,endpoint:[3,5,8],enriquez:9,ensur:1,enterpris:5,enterprise_id:5,entir:3,env:1,environ:[1,3,5,6,8,9],environment:3,ephemer:8,error:[1,5,8],establish:6,even:6,event:[2,5,8,9],everi:3,exampl:[3,6,8],exce:8,excel:1,except:[5,8],exchang:[3,5,8],excit:[1,8],exclud:8,exclude_archiv:8,execut:6,exist:[7,8],expect:[1,7],expir:5,expiration_second:5,explain:5,explicitli:7,extern:8,external_id:8,external_url:8,facilit:3,fail:[5,8],fakelink:9,fallback:[8,9],fals:8,far:8,featur:[2,3,7],feedback:1,feel:[1,8],fellow:2,felt:8,few:[2,7],fewer:8,field:8,file:1,file_com:8,fileinstallationstor:5,fileoauthstatestor:5,files_remote_add:8,files_upload:8,find:[1,7],find_bot:5,first:[1,5,7],fit:2,fix:1,flask:[3,5,8,9],flask_env:8,flow:[2,3,7],focus:8,folder:1,follow:[1,2,5,8],forget:[1,3,8],fork:8,form:[5,8,9],format:[6,8],forward:7,found:3,framework:5,fred:9,from:[0,1,2,3,5,6,8,9],full:[3,5,8],fulli:8,fun:8,futur:1,gain:5,gener:[1,2,3,5,9],german:8,get:[3,5,8,9],get_data:[5,8,9],git:2,github:2,give:[5,6],given:1,global:8,goe:5,good:[1,2],got:8,grace:8,grant:3,great:1,greater:8,grid:5,group:8,guest:8,guidelin:1,had:8,hand:8,handl:[3,5,8,9],handler:5,happen:[2,5],has:[1,3,7,8],hash:8,haunt:8,have:[1,6,7,8,9],header:[5,8,9],height:5,hello:[6,8,9],help:1,here:[2,5,7,8],higher:2,highli:7,hit:8,hole:8,hook:9,hop:8,hotel:8,how:[3,5,8],howev:[7,8],href:[3,5],http:[2,3,5,6,7,8,9],hub:8,hurri:8,hyphen:8,imag:8,image_url:8,img:5,implement:5,importantli:1,includ:[1,3,5,8,9],include_local:8,include_num_memb:8,incom:[2,5],incoming_webhook:5,incoming_webhook_channel_id:5,incoming_webhook_configuration_url:5,incoming_webhook_url:5,inconveni:7,incorpor:1,increas:1,independ:2,indic:[5,8],industri:3,info:[5,7,8],inform:[3,6,8],initi:3,input:[5,8],insert:2,insid:[1,6,8],instal:[8,9],installation_stor:5,installationstor:5,installed_enterpris:5,installed_team:5,instanti:6,instead:[6,7,8,9],integr:8,intend:3,interact:8,interest:8,interfac:8,intern:[7,8,9],introduc:7,invalid:[5,8,9],invalid_auth:8,invit:8,invoc:[5,9],is_priv:8,is_valid:[5,9],is_valid_request:8,issu:[2,5,6],item:[1,8],its:[1,2,5,6,9],itself:8,join:8,jpeg:8,json:[3,5,8],just:[1,2,3,7,8,9],keep:[3,6],kei:[3,8],keyword:8,kind:8,kit:[8,9],know:[1,3],label:[5,8],larger:6,later:3,layout:8,learn:6,least:3,leav:8,left:8,legacywebcli:7,let:[0,1,3,5,8],letter:8,level:[1,2,8],librari:[7,8,9],licens:0,like:[6,7,8],limit:2,line:2,linear:8,link:[3,6],list:[1,3,6,8],listen:2,liter:8,live:7,load:[2,5,8],local:[2,8],localhost:[3,8],log:[1,2,8],longer:[7,8],look:[1,5,8],love:1,mai:[1,5,8],maintain:0,mainten:7,make:[1,7,8],make_respons:[5,8,9],mani:[1,8],manual:7,mean:7,member:8,messag:[2,9],metadata:8,method:[2,3,5,9],might:8,modal:5,mode:7,model:[2,6],modul:[1,7],more:[1,3,6,7,8],most:[5,6,7,8],mpim:8,mrkdwn:[8,9],much:[1,5],multi:8,multipl:3,must:[3,6,8],myapp:3,name:[7,8],natur:7,nearli:8,necessari:5,need:[1,2,3,5,6,7,8],newer:[6,7],newest:8,none:5,note:[1,5,6,8],notif:8,now:[5,7],number:8,oauth:[2,3,7,8],oauth_callback:5,oauth_redirect:3,oauth_respons:5,oauth_scop:3,oauth_start:5,oauth_v2_access:[3,5],oauthstatestor:5,object:8,occur:6,off:8,offer:2,okai:5,old:1,onc:3,one:[1,3,7,8],onli:[7,8],onto:8,open:[5,8],option:[6,7,8,9],order:3,origin:8,other:[3,7,8],our:[1,3,6,8],out:[3,7,8],output:1,over:[2,8],overlook:8,own:[5,8],packag:[1,2,7],page:[3,6],param:[3,5,8],paramet:[3,5,8],parent:8,part:2,parti:8,particularli:1,pass:[3,6,8],password:3,path:2,pattern:5,payload:[3,5,6,8,9],pdf:8,peopl:8,per:8,period:8,permiss:[3,6],persist:[3,5],person:8,pexel:8,photo:8,pick:2,pip:[1,2,8,9],place:8,plain:6,plain_text:[5,8],plain_text_input:[5,8],platform:[0,2,5,6],pleas:[1,3,5,7],png:[5,8],possibl:9,post:[5,6,8,9],post_instal:3,post_messag:8,postephemer:8,postmessag:8,potenti:3,power:2,practic:8,pre:3,pre_instal:3,prefer:6,prepar:5,preview:8,preview_imag:8,previou:8,primari:8,print:[3,5,8],privat:8,private_channel:8,private_metadata:8,process:5,program:[1,8,9],project:[1,2,7],properli:7,properti:8,propos:1,protocol:3,prototyp:8,proudli:0,provid:[3,5,6,7,8],public_channel:8,publish:3,pull:[1,2],purpos:8,push:[6,8],pypi:[1,2,7],python3:8,python:[1,3,5,6,7,8],queri:[2,3,5],question:[1,2],quickli:8,rais:8,random:[5,8],randomli:3,ratelimit:8,rather:[1,6],reaction:8,reactions_add:8,reactions_remov:8,read:[3,5,6],reason:7,rebuild:1,receiv:6,recommend:[1,2,3,6,7],redirect:[3,5],redirect_uri:5,refer:[5,7,8],reflect:8,refus:3,regular:8,reinstal:[1,3],relat:2,releas:8,releg:8,reli:[7,8,9],remot:8,remov:[1,7,8],renam:7,repl:[1,2],replac:7,repli:[8,9],reply_broadcast:8,report:2,request:[2,3,5,8,9],requir:[3,7,8,9],res:1,resolv:7,respond:8,respons:[3,5,6,8,9],response_url:2,restructuredtext:1,result:8,resum:8,retri:8,retriev:[3,5,8],review:[3,8],richer:9,right:5,room:8,round:8,rout:[3,5,8,9],rowdi:8,rst:1,rtm:[2,7],rtm_client:6,rtmclient:6,run:[1,2,3,8,9],run_async:7,run_on:6,runtim:[1,3],safe:3,sai:[1,6,7,8],said:[1,7,8,9],same:[5,8],sampl:1,save:[2,3,5,8],say_hello:6,scope:[3,5,6],script:1,sdk:[5,7],seamlessli:2,search:5,second:8,secondari:7,secret:3,section:[1,3,5,8,9],sed:7,see:[3,5,6,8],send:[2,6,8,9],send_message_via_webhook:9,send_slack_messag:8,separ:[5,8],server:[2,5],servic:9,set:[1,2,3,6,8],setup:[2,3],sever:2,share:[3,5,8],shortcut:8,should:8,show:8,side:5,signatur:[2,5,8,9],signature_verifi:[5,8,9],signatureverifi:[5,8,9],signing_secret:[5,9],silent:8,similar:7,simpl:[3,7,8],simplest:[8,9],simpli:[6,7,8],sinc:7,singl:[3,8],site:8,slack:[1,3,5,6,7,8,9],slack_api_token:8,slack_app:[5,8,9],slack_bot_token:[1,3,6,8],slack_client_id:[3,5],slack_client_secret:[3,5],slack_scop:3,slack_sdk:[1,2,3,5,6,7,8,9],slack_signing_secret:[5,8,9],slack_token:[6,8],slackapi:2,slackapierror:[5,8],slackclient:[],slash:[5,9],sleep:8,slightli:8,slow:6,small:2,snippet:5,social:8,solut:5,some:[6,7,8],someth:[1,5,7],sometim:8,sorri:7,sourc:[1,2,3,7],special:8,specif:7,specifi:[5,8],sphinx:1,src:[1,5],srcset:5,stack:5,standard:[3,7,8,9],star:8,start:[1,3,5,6,7,8],state:[3,5,8],state_stor:5,statu:8,status_cod:9,step:[1,5,7],still:[1,7],storag:8,store:[3,5,8],str:[8,9],straight:7,string:[3,5,8],stuck:[2,8],submiss:[5,8],submit:[1,5,8],submitted_data:[5,8],subsequ:8,succeed:3,success:3,successor:7,suffici:5,suppli:8,support:[2,6,7],sure:[1,8],surfac:8,synchron:7,sys:2,t00000000:9,tada:8,take:[3,5,8],team:[0,3,5,6,8],team_id:5,technic:7,tell:8,term:7,test:[1,2,8],text:[5,6,8,9],than:8,thank:[1,5],thei:[1,2,8],them:[3,8],therefor:8,thi:[1,2,3,5,6,7,8,9],thing:[1,8],think:1,those:[2,6,7,8],though:8,thought:1,thread:8,thread_t:[6,8],through:[2,5],thumbsup:8,time:[3,7,8],timelin:8,timestamp:[5,8,9],titl:[5,8],toemployeeprofil:9,togeth:[2,8],token:[1,6,8],too:[2,5,8,9],tool:0,torrenc:8,total:1,tracker:[1,2],treat:3,trigger_id:[5,8],two:1,txt:7,type:[5,6,8,9],u023becgf:6,u0xxxxxxx:8,u987654321:8,underscor:8,unifi:8,uninstal:[1,5],unit:1,unlik:7,unreli:6,unsupport:5,until:8,updat:[1,8],upgrad:6,upload:8,url:[5,6,8,9],usag:3,use:[1,2,3,5,6,7,8,9],used:[2,5,8],useful:8,user:[1,3,5,6,8,9],user_id:[5,8],user_scop:5,user_token:5,usernam:6,userwarn:7,uses:[6,8],using:[1,2,5,6,7,8,9],valid:[3,5,8],valida:5,valu:[3,5,8],variabl:[1,3],venv:1,veri:8,verif:2,verifi:[1,2,3,5,9],via:[3,9],view:[5,8],view_id:8,view_submiss:[5,8],views_open:[5,8],views_upd:8,virtual:1,virtualenv:1,visibl:8,visit:2,vote:8,w123456789:8,wai:[2,5,7,8,9],wait:8,want:[1,8],warn:7,watch:6,web:[0,2,5,6,7],web_client:6,webclient:[1,2,3,5,7,8],webhook:[2,7],webhookcli:9,webpag:5,webserv:3,websit:7,websocket:[2,6],well:[5,8],what:[1,2,5],when:[2,5,6,8],where:[3,5],which:[3,5,6,8],whole:8,why:1,width:5,window:1,wish:[3,8],without:7,won:[7,8],work:[1,2,3,7,8,9],workspac:[5,8],world:8,would:3,wrapper:8,write:[1,3,5],written:1,wrong:5,xarg:7,xoxb:[1,3,8],xxxxx:3,xxxxxxxxxxxxxxxxxxxxxxxx:9,yield:3,you:[0,1,2,3,5,6,7,8,9],your:[0,1,2,3,5,6,7,8],your_app:7,yourself:1},titles:["About","FAQ","Python Slack SDK","Installation","<no title>","OAuth Modules","RTM Client","Migration Guide","Web Client","Webhook Client"],titleterms:{about:0,access:3,ani:8,api:8,app:5,asyncwebcli:8,asyncwebhookcli:9,bug:1,call:8,client:[6,8,9],contribut:1,convers:8,document:1,event:6,faq:1,featur:1,file:8,flow:5,from:7,get:2,guid:7,help:2,incom:9,instal:[1,2,3,5],issu:1,limit:8,lookup:5,messag:[6,8],method:8,migrat:7,modal:8,modul:5,oauth:5,python:[0,2],rate:8,real:6,report:1,request:1,response_url:9,rtm:6,sdk:[0,2],slack:[0,2],slackclient:7,time:6,token:[3,5],web:8,webhook:9,workspac:3}}) \ No newline at end of file diff --git a/docs/v3-migration/index.html b/docs/v3-migration/index.html deleted file mode 100644 index 05a20ae61..000000000 --- a/docs/v3-migration/index.html +++ /dev/null @@ -1,257 +0,0 @@ - - - - - - Migration Guide — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

Migration GuideΒΆ

-

The v2 website is live here just like before. However, the slackclient project is in maintenance mode now and this slack_sdk project is the successor.

-
-

From slackclient 2.xΒΆ

-

There are a few changes introduced in v3.0:

-
    -
  • The PyPI project is renamed from slackclient to slack_sdk

  • -
  • Importing slack_sdk.* is recommended. You can still use slack.* with deprecation warnings for a while.

  • -
  • slack_sdk has no required dependencies. This means aiohttp is no longer automatically resolved.

  • -
  • WebClient no longer has run_async and aiohttp specific options. If you still need the option or other aiohttp specific options, use LegacyWebClient (slackclient v2 compatible) or AsyncWebClient.

  • -
-

We’re sorry for the inconvenience.

-
-

Change: The PyPI project is renamed from slackclient to slack_sdk

-

Action: Remove slackclient, add slack_sdk in requirements.txt

-

Since v3, the PyPI project name is slack_sdk (technically slack-sdk also works).

-

The biggest reason for the renaming is the feature coverage in v3 and newer. The SDK v3 provides not only API clients but also other modules. As the first step, it starts supporting OAuth flow out-of-the-box. The secondary reason is to make the names more consistent. The renaming addresses the long-lived confusion between the PyPI project and package names.

-
-

Change: Importing slack_sdk.* is recommended. You can still use slack.* with deprecation warnings for a while.

-

Action: Replace from slack import, import slack, and so on in your source code.

-

Most imports can be simply replaced by find your_app -name '*.py' | xargs sed -i '' 's/from slack /from slack_sdk /g' or something similar. If you use slack.web.classes.*, the conversion is not so simple that we recommend manually replacing imports for those.

-

That said, all existing code can be migrated to v3 without any code changes. If you don’t have time for it, you can use slack package with deprecation warnings saying UserWarning: slack package is deprecated. Please use slack_sdk.web/webhook/rtm package instead. For more info, go to https://slack.dev/python-slack-sdk/v3-migration/ for a while. We won’t remove the compatibility in the short term.

-
-

Change: slack_sdk has no required dependencies. This means aiohttp is no longer automatically resolved.

-

Action: Add aiohttp to requirements.txt if you use any of AsyncWebClient, AsyncWebhookClient, and LegacyWebClient

-

If you use some modules that require aiohttp, your requirements.txt needs to explicitly have aiohttp. The slack_sdk dependency doesn’t resolve it for you, unlike slackclient v2.

-
-

Change: WebClient no longer has run_async and aiohttp specific options.

-

Action: If you still need the option or other aiohttp specific options, use LegacyWebClient (slackclient v2 compatible) or AsyncWebClient.

-

The new slack_sdk.web.WebClient doesn’t rely on aiohttp internally at all. The class provides only the synchronous way to call Web APIs. If you need a v2 compatible one, you can use LegacyWebClient. Apart from the name, there is no breaking change in the class.

-

If you’re using run_async=True option, we highly recommend switching to AsyncWebClient. AsyncWebClient is a straight-forward async HTTP client. You can expect the class properly works in the nature of async/await provided by the standard asyncio library.

-
-
-

From slackclient 1.xΒΆ

-

Refer to the migration guide.

-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/web/index.html b/docs/web/index.html deleted file mode 100644 index 8438a2422..000000000 --- a/docs/web/index.html +++ /dev/null @@ -1,712 +0,0 @@ - - - - - - Web Client — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

Web ClientΒΆ

-

The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations we provide out of the box.

-

Access Slack’s API methods requires an OAuth token – see the Tokens & Authentication section for more on how Slack uses OAuth tokens as well as best practices.

-

Each of these API methods is fully documented on our developer site at https://api.slack.com/

-
-

MessagingΒΆ

-

Sending a message

-

One of the primary uses of Slack is posting messages to a channel using the channel ID or as a DM to another person using their user ID. This method will handle either a channel ID or a user ID passed to the channel parameter.

-
import logging
-logging.basicConfig(level=logging.DEBUG)
-
-import os
-from slack_sdk import WebClient
-from slack_sdk.errors import SlackApiError
-
-slack_token = os.environ["SLACK_BOT_TOKEN"]
-client = WebClient(token=slack_token)
-
-try:
-    response = client.chat_postMessage(
-        channel="C0XXXXXX",
-        text="Hello from your app! :tada:"
-    )
-except SlackApiError as e:
-    # You will get a SlackApiError if "ok" is False
-    assert e.response["error"]    # str like 'invalid_auth', 'channel_not_found'
-
-
-

Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same -as sending a regular message, but with an additional user parameter.

-
import os
-from slack_sdk import WebClient
-
-slack_token = os.environ["SLACK_BOT_TOKEN"]
-client = WebClient(token=slack_token)
-
-response = client.chat_postEphemeral(
-    channel="C0XXXXXX",
-    text="Hello silently from your app! :tada:",
-    user="U0XXXXXXX"
-)
-
-
-

See chat.postEphemeral for more info.

-

Formatting with Block Kit

-

Messages posted from apps can contain more than just text, though. They can include full user interfaces composed of blocks.

-

The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. Blocks specified in a single object literal, so just add additional keys for any optional argument.

-

To send a message to a channel, use the channel’s ID. For IMs, use the user’s ID.

-
client.chat_postMessage(
-    channel="C0XXXXXX",
-    blocks=[
-        {
-            "type": "section",
-            "text": {
-                "type": "mrkdwn",
-                "text": "Danny Torrence left the following review for your property:"
-            }
-        },
-        {
-            "type": "section",
-            "text": {
-                "type": "mrkdwn",
-                "text": "<https://example.com|Overlook Hotel> \n :star: \n Doors had too many axe holes, guest in room " +
-                    "237 was far too rowdy, whole place felt stuck in the 1920s."
-            },
-            "accessory": {
-                "type": "image",
-                "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg",
-                "alt_text": "Haunted hotel image"
-            }
-        },
-        {
-            "type": "section",
-            "fields": [
-                {
-                    "type": "mrkdwn",
-                    "text": "*Average Rating*\n1.0"
-                }
-            ]
-        }
-    ]
-)
-
-
-

Note: You can use the Block Kit Builder to prototype your message’s look and feel.

-

Threading Messages

-

Threaded messages are a way of grouping messages together to provide greater context. You can reply to a thread or start a new threaded conversation by simply passing the original message’s ts ID in the thread_ts attribute when posting a message. If you’re replying to a threaded message, you’ll pass the thread_ts ID of the message you’re replying to.

-

A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message.

-
response = client.chat_postMessage(
-    channel="C0XXXXXX",
-    thread_ts="1476746830.000003",
-    text="Hello from your app! :tada:"
-)
-
-
-

By default, reply_broadcast is set to False. To indicate your reply is germane to all members of a channel, and therefore a notification of the reply should be posted in-channel, set the reply_broadcast to True.

-
response = client.chat_postMessage(
-    channel="C0XXXXXX",
-    thread_ts="1476746830.000003",
-    text="Hello from your app! :tada:",
-    reply_broadcast=True
-)
-
-
-

Note: While threaded messages may contain attachments and message buttons, when your reply is broadcast to the -channel, it’ll actually be a reference to your reply, not the reply itself. -So, when appearing in the channel, it won’t contain any attachments or message buttons. Also note that updates and -deletion of threaded replies works the same as regular messages.

-

See the Threading messages together article for more information.

-

Updating a message

-

Let’s say you have a bot which posts the status of a request. When that request changes, you’ll want to update the message to reflect it’s state.

-
response = client.chat_update(
-    channel="C0XXXXXX",
-    ts="1476746830.000003",
-    text="updates from your app! :tada:"
-)
-
-
-

See chat.update for formatting options and some special considerations when calling this with a bot user.

-

Deleting a message

-

Sometimes you need to delete things.

-
response = client.chat_delete(
-    channel="C0XXXXXX",
-    ts="1476745373.000002"
-)
-
-
-

See chat.delete for more info.

-

Emoji reactions

-

You can quickly respond to any message on Slack with an emoji reaction. Reactions can be used for any purpose: voting, checking off to-do items, showing excitement -β€” or just for fun.

-

This method adds a reaction (emoji) to an item (file, file comment, channel message, group message, or direct message). One of file, file_comment, or the combination of channel and timestamp must be specified.

-
response = client.reactions_add(
-    channel="C0XXXXXXX",
-    name="thumbsup",
-    timestamp="1234567890.123456"
-)
-
-
-

Removing an emoji reaction is basically the same format, but you’ll use reactions.remove instead of reactions.add

-
response = client.reactions_remove(
-    channel="C0XXXXXXX",
-    name="thumbsup",
-    timestamp="1234567890.123456"
-)
-
-
-

See reactions.add and reactions.remove for more info.

-
-
-
-

FilesΒΆ

-

Uploading files

-

You can upload files onto Slack and share the file with people in channels.

-
response = client.files_upload(
-    channels="C3UKJTQAC",
-    file="files.pdf",
-    title="Test upload"
-)
-
-
-

See files.upload for more info.

-

Adding a remote file

-

You can add a file information that is stored in an external storage, not in Slack.

-
response = client.files_remote_add(
-    external_id="the-all-hands-deck-12345",
-    external_url="https://{your domain}/files/the-all-hands-deck-12345",
-    title="The All-hands Deck",
-    preview_image="./preview.png" # will be displayed in channels
-)
-
-
-

See files.remote.add for more info.

-
-
-
-

ConversationsΒΆ

-

The Slack Conversations API provides your app with a unified interface to work with all the channel-like things encountered in Slack; public channels, private channels, direct messages, group direct messages, and our newest channel type, Shared Channels.

-

See Conversations API docs for more info.

-

Start a direct message

-

The conversations_open method opens either a 1:1 direct message with a single user or a a multi-person direct message, depending on the number of users supplied to the users parameter.

-

For public or private channels, use the conversations_create method.

-

Provide a users parameter as an array with 1 to 8 user IDs to open or resume a conversation. Providing only 1 ID will create a direct message. Providing more will create a new multi-party DM or resume an existing conversation.

-

Subsequent calls to conversations_open with the same set of users will return the already existing conversation.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_open(users=["W123456789", "U987654321"])
-
-
-

See conversations.open additional info.

-

Creating channels

-

Creates a new channel, either public or private. The name parameter is required, may contain numbers, letters, hyphens, and underscores, and must contain fewer than 21 characters. To make the channel private, set the option is_private parameter to True.

-
import os
-from slack_sdk import WebClient
-from time import time
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-channel_name = f"my-private-channel-{round(time())}"
-response = client.conversations_create(
-    name=channel_name,
-    is_private=True
-)
-channel_id = response["channel"]["id"]
-response = client.conversations_archive(channel=channel_id)
-
-
-

See conversations.create additional info.

-

Listing conversations

-

To get a list of all the conversations in a workspace, use conversations_list. By default, only public conversations are returned; use the types parameter specify which types of conversations you’re interested in (Note: types is a string of comma-separated values)

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_list()
-conversations = response["channels"]
-
-
-

Use the types parameter to request additional channels, including public_channel, private_channel, mpim, and im. This parameter is a string of comma-separated values.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_list(
-    types="public_channel, private_channel"
-)
-
-
-

See conversations.list for more info.

-

Archived channels are included by default. You can exclude them by passing exclude_archived=True to your request.

-
response = client.conversations_list(exclude_archived=True)
-
-
-

See conversations.list for more info.

-

Getting a conversation information

-

To retrieve a set of metadata about a channel (public, private, DM, or multi-party DM), use conversations_info. The channel parameter is required and must be a valid channel ID. The optional include_locale boolean parameter will return locale data, which may be useful if you wish to return localized responses. The include_num_members boolean parameter will return the number of people in a channel.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_info(
-    channel="C031415926",
-    include_num_members=1
-)
-
-
-

See conversations.info for more info.

-

Getting members of a conversation

-

To get a list of the members of a conversation, use conversations_members with the required channel parameter.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_members(channel="C16180339")
-user_ids = response["members"]
-
-
-

See conversations.members for more info.

-

Joining a conversation

-

Channels are the social hub of most Slack teams. Here’s how you hop into one:

-
response = client.conversations_join(channel="C0XXXXXXY")
-
-
-

If you are already in the channel, the response is slightly different. -already_in_channel will be true, and a limited channel object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user.

-

See conversations.join for more info.

-

Leaving a conversation

-

To leave a conversation, use conversations_leave with the required channel param containing the ID of the channel to leave.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-response = client.conversations_leave(channel="C27182818")
-
-
-

See conversations.leave for more info.

-
-
-
-

ModalsΒΆ

-

Opening a modal

-

Modals allow you to collect data from users and display dynamic information in a focused surface.

-

Modals use the same blocks that compose messages with the addition of an input block.

-
from slack_sdk.signature import SignatureVerifier
-signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"])
-
-from flask import Flask, request, make_response
-app = Flask(__name__)
-
-@app.route("/slack/events", methods=["POST"])
-def slack_app():
-    if not signature_verifier.is_valid_request(request.get_data(), request.headers):
-        return make_response("invalid request", 403)
-
-    if "payload" in request.form:
-        payload = json.loads(request.form["payload"])
-
-        if payload["type"] == "shortcut" \
-            and payload["callback_id"] == "open-modal-shortcut":
-            # Open a new modal by a global shortcut
-            try:
-                api_response = client.views_open(
-                    trigger_id=payload["trigger_id"],
-                    view={
-                        "type": "modal",
-                        "callback_id": "modal-id",
-                        "title": {
-                            "type": "plain_text",
-                            "text": "Awesome Modal"
-                        },
-                        "submit": {
-                            "type": "plain_text",
-                            "text": "Submit"
-                        },
-                        "blocks": [
-                            {
-                                "type": "input",
-                                "block_id": "b-id",
-                                "label": {
-                                    "type": "plain_text",
-                                    "text": "Input label",
-                                },
-                                "element": {
-                                    "action_id": "a-id",
-                                    "type": "plain_text_input",
-                                }
-                            }
-                        ]
-                    }
-                )
-                return make_response("", 200)
-            except SlackApiError as e:
-                code = e.response["error"]
-                return make_response(f"Failed to open a modal due to {code}", 200)
-
-        if payload["type"] == "view_submission" \
-            and payload["view"]["callback_id"] == "modal-id":
-            # Handle a data submission request from the modal
-            submitted_data = payload["view"]["state"]["values"]
-            print(submitted_data)    # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}}
-            return make_response("", 200)
-
-    return make_response("", 404)
-
-if __name__ == "__main__":
-    # export SLACK_SIGNING_SECRET=***
-    # export SLACK_BOT_TOKEN=xoxb-***
-    # export FLASK_ENV=development
-    # python3 app.py
-    app.run("localhost", 3000)
-
-
-

See views.open more details and additional parameters.

-

Also, to run the above example, the following Slack app configurations are required.

-
    -
  • Enable Interactivity with a valid Request URL: https://{your-public-domain}/slack/events

  • -
  • Add a global shortcut with the Callback ID: open-modal-shortcut

  • -
-

Updating and pushing modals

-

You can dynamically update a view inside of a modal by calling views.update and passing the view ID returned in the previous views.open call.

-
private_metadata = "any str data you want to store"
-response = client.views_update(
-    view_id=payload["view"]["id"],
-    hash=payload["view"]["hash"],
-    view={
-        "type": "modal",
-        "callback_id": "modal-id",
-        "private_metadata": private_metadata,
-        "title": {
-            "type": "plain_text",
-            "text": "Awesome Modal"
-        },
-        "submit": {
-            "type": "plain_text",
-            "text": "Submit"
-        },
-        "close": {
-            "type": "plain_text",
-            "text": "Cancel"
-        },
-        "blocks": [
-            {
-                "type": "input",
-                "block_id": "b-id",
-                "label": {
-                    "type": "plain_text",
-                    "text": "Input label",
-                },
-                "element": {
-                    "action_id": "a-id",
-                    "type": "plain_text_input",
-                }
-            }
-        ]
-    }
-)
-
-
-

See views.update for more info.

-

If you want to push a new view onto the modal instead of updating an existing view, reference the views.push documentation.

-
-
-
-

Rate LimitsΒΆ

-

When posting messages to a channel, Slack allows applications to send no more than one message per channel per second. We allow bursts over that limit for short periods. However, if your app continues to exceed the limit over a longer period of time it will be rate limited. Different API methods have other rate limits – be sure to check the limits and test that your application has a graceful fallback if it should hit those limits.

-

If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, a JSON object containing the number of calls you have been making, and a Retry-After header containing the number of seconds until you can retry.

-

Here’s a very basic example of how one might deal with rate limited requests.

-
import os
-import time
-from slack_sdk import WebClient
-from slack_sdk.errors import SlackApiError
-
-client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
-
-# Simple wrapper for sending a Slack message
-def send_slack_message(channel, message):
-    return client.chat_postMessage(
-        channel=channel,
-        text=message
-    )
-
-# Make the API call and save results to `response`
-channel = "#random"
-message = "Hello, from Python!"
-# Do until being rate limited
-while True:
-    try:
-        response = send_slack_message(channel, message)
-    except SlackApiError as e:
-        if e.response["error"] == "ratelimited":
-            # The `Retry-After` header will tell you how long to wait before retrying
-            delay = int(e.response.headers['Retry-After'])
-            print(f"Rate limited. Retrying in {delay} seconds")
-            time.sleep(delay)
-            response = send_slack_message(channel, message)
-        else:
-            # other errors
-            raise e
-
-
-

See the documentation on Rate Limiting for more info.

-
-
-

Calling any API methodsΒΆ

-

This library covers all the public endpoints as the methods in WebClient. That said, you may see a bit delay of the library release. When you’re in a hurry, you can directly use api_call method as below.

-
import os
-from slack_sdk import WebClient
-
-client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
-response = client.api_call(
-    api_method='chat.postMessage',
-    json={'channel': '#random','text': "Hello world!"}
-)
-assert response["message"]["text"] == "Hello world!"
-
-
-
-
-
-
-

AsyncWebClientΒΆ

-

All the API methods are available in asynchronous programming using the standard asyncio library. You use AsyncWebClient instead for it.

-

AsyncWebClient internally relies on AIOHTTP library but it is an optional dependency. So, to use this class, run pip install aiohttp beforehand.

-
import asyncio
-import os
-# requires: pip install aiohttp
-from slack_sdk.web.async_client import AsyncWebClient
-from slack_sdk.errors import SlackApiError
-
-client = AsyncWebClient(token=os.environ['SLACK_API_TOKEN'])
-
-# This must be an async method
-async def post_message():
-    try:
-        # Don't forget `await` keyword here
-        response = await client.chat_postMessage(
-            channel='#random',
-            text="Hello world!"
-        )
-        assert response["message"]["text"] == "Hello world!"
-    except SlackApiError as e:
-        assert e.response["ok"] is False
-        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
-        print(f"Got an error: {e.response['error']}")
-
-# This is the simplest way to run the async method
-# but you can go with any ways to run it
-asyncio.run(post_message())
-
-
-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/docs/webhook/index.html b/docs/webhook/index.html deleted file mode 100644 index 9e3915146..000000000 --- a/docs/webhook/index.html +++ /dev/null @@ -1,314 +0,0 @@ - - - - - - Webhook Client — Python Slack SDK - - - - - - - - - - - - - - - - - - -
- - - - - - - Python Slack SDK - - -
- - -
-
- - - - - -
- -
-
-

Webhook ClientΒΆ

-

You can use slack_sdk.webhook.WebhookClient for Incoming Webhooks and message responses using response_url in payloads.

-
-

Incoming WebhooksΒΆ

-

To use Incoming Webhooks, just calling WebhookClient(url)#send(payload) method works for you. The call posts a message in a channel associated with the webhook URL.

-
from slack_sdk.webhook import WebhookClient
-url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
-webhook = WebhookClient(url)
-
-response = webhook.send(text="Hello!")
-assert response.status_code == 200
-assert response.body == "ok"
-
-
-

It’s also possible to use blocks, richer message using Block Kit.

-
from slack_sdk.webhook import WebhookClient
-url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
-webhook = WebhookClient(url)
-response = webhook.send(
-    text="fallback",
-    blocks=[
-        {
-            "type": "section",
-            "text": {
-                "type": "mrkdwn",
-                "text": "You have a new request:\n*<fakeLink.toEmployeeProfile.com|Fred Enriquez - New device request>*"
-            }
-        }
-    ]
-)
-
-
-
-
-

response_urlΒΆ

-

User actions in channels generates a response_url and includes the URL in its payload. You can use WebhookClient to send a message via the response_url.

-
import os
-from slack_sdk.signature import SignatureVerifier
-signature_verifier = SignatureVerifier(
-    signing_secret=os.environ["SLACK_SIGNING_SECRET"]
-)
-
-from slack_sdk.webhook import WebhookClient
-
-from flask import Flask, request, make_response
-app = Flask(__name__)
-
-@app.route("/slack/events", methods=["POST"])
-def slack_app():
-    # Verify incoming requests from Slack
-    # https://api.slack.com/authentication/verifying-requests-from-slack
-    if not signature_verifier.is_valid(
-        body=request.get_data(),
-        timestamp=request.headers.get("X-Slack-Request-Timestamp"),
-        signature=request.headers.get("X-Slack-Signature")):
-        return make_response("invalid request", 403)
-
-    # Handle a slash command invocation
-    if "command" in request.form \
-        and request.form["command"] == "/reply-this":
-        response_url = request.form["response_url"]
-        text = request.form["text"]
-        webhook = WebhookClient(response_url)
-        # Send a reply in the channel
-        response = webhook.send(text=f"You said '{text}'")
-        # Acknowledge this request
-        return make_response("", 200)
-
-    return make_response("", 404)
-
-
-
-
-

AsyncWebhookClientΒΆ

-

The webhook client is available in asynchronous programming using the standard asyncio library, too. You use AsyncWebhookClient instead for it.

-

AsyncWebhookClient internally relies on AIOHTTP library but it is an optional dependency. So, to use this class, run pip install aiohttp beforehand.

-
import asyncio
-# requires: pip install aiohttp
-from slack_sdk.webhook.async_client import AsyncWebhookClient
-url = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
-
-async def send_message_via_webhook(url: str):
-    webhook = AsyncWebhookClient(url)
-    response = await webhook.send(text="Hello!")
-    assert response.status_code == 200
-    assert response.body == "ok"
-
-# This is the simplest way to run the async method
-# but you can go with any ways to run it
-asyncio.run(send_message_via_webhook(url))
-
-
-
-
- - -
-
-
- -
-
- -
-

- Β© 2020 Slack Technologies, Inc. and contributors -

-
- - - - - diff --git a/integration_tests/audit_logs/test_async_client.py b/integration_tests/audit_logs/test_async_client.py new file mode 100644 index 000000000..aae4888e3 --- /dev/null +++ b/integration_tests/audit_logs/test_async_client.py @@ -0,0 +1,44 @@ +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from integration_tests.helpers import async_test +from slack_sdk.audit_logs.async_client import AsyncAuditLogsClient + + +class TestAuditLogsClient(unittest.TestCase): + def setUp(self): + self.client = AsyncAuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) + + def tearDown(self): + pass + + @async_test + async def test_api_call(self): + api_response = await self.client.api_call(path="schemas") + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"schemas":[{""")) + self.assertIsNotNone(api_response.body.get("schemas")) + + @async_test + async def test_schemas(self): + api_response = await self.client.schemas() + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"schemas":[{""")) + self.assertIsNotNone(api_response.body.get("schemas")) + + @async_test + async def test_actions(self): + api_response = await self.client.actions() + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"actions":{""")) + self.assertIsNotNone(api_response.body.get("actions")) + + @async_test + async def test_logs(self): + api_response = await self.client.logs(action="user_login", limit=1) + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"entries":[{""")) + self.assertIsNotNone(api_response.body.get("entries")) diff --git a/integration_tests/audit_logs/test_client.py b/integration_tests/audit_logs/test_client.py new file mode 100644 index 000000000..fa9966039 --- /dev/null +++ b/integration_tests/audit_logs/test_client.py @@ -0,0 +1,39 @@ +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.audit_logs import AuditLogsClient + + +class TestAuditLogsClient(unittest.TestCase): + def setUp(self): + self.client = AuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) + + def tearDown(self): + pass + + def test_api_call(self): + api_response = self.client.api_call(path="schemas") + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"schemas":[{""")) + self.assertIsNotNone(api_response.body.get("schemas")) + + def test_schemas(self): + api_response = self.client.schemas() + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"schemas":[{""")) + self.assertIsNotNone(api_response.body.get("schemas")) + + def test_actions(self): + api_response = self.client.actions() + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"actions":{""")) + self.assertIsNotNone(api_response.body.get("actions")) + + def test_logs(self): + api_response = self.client.logs(action="user_login", limit=1) + self.assertEqual(200, api_response.status_code) + self.assertTrue(api_response.raw_body.startswith("""{"entries":[{""")) + self.assertIsNotNone(api_response.body.get("entries")) diff --git a/integration_tests/audit_logs/test_pagination.py b/integration_tests/audit_logs/test_pagination.py new file mode 100644 index 000000000..cdee8b178 --- /dev/null +++ b/integration_tests/audit_logs/test_pagination.py @@ -0,0 +1,27 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.audit_logs import AuditLogsClient + + +class TestAuditLogsClient(unittest.TestCase): + def setUp(self): + self.client = AuditLogsClient(token=os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN]) + + def tearDown(self): + pass + + def test_pagination(self): + call_count = 0 + response = None + ids = [] + while call_count < 10 and (response is None or response.status_code != 429): + cursor = response.body["response_metadata"]["next_cursor"] if response is not None else None + response = self.client.logs(action="user_login", limit=1, cursor=cursor) + ids += map(lambda v: v["id"], response.body.get("entries", [])) + call_count += 1 + self.assertGreaterEqual(len(set(ids)), 10) diff --git a/integration_tests/env_variable_names.py b/integration_tests/env_variable_names.py index 35e0f7c96..47deb1038 100644 --- a/integration_tests/env_variable_names.py +++ b/integration_tests/env_variable_names.py @@ -22,9 +22,18 @@ SLACK_SDK_TEST_GRID_WORKSPACE_USER_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_USER_TOKEN" SLACK_SDK_TEST_GRID_WORKSPACE_BOT_TOKEN = "SLACK_SDK_TEST_GRID_WORKSPACE_BOT_TOKEN" SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID = "SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID" +SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2 = "SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2" SLACK_SDK_TEST_GRID_TEAM_ID = "SLACK_SDK_TEST_GRID_TEAM_ID" +SLACK_SDK_TEST_GRID_TEAM_ID_2 = "SLACK_SDK_TEST_GRID_TEAM_ID_2" SLACK_SDK_TEST_GRID_USER_ID = "SLACK_SDK_TEST_GRID_USER_ID" +# The following user must be a full member, who is not a primary owner +SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH = "SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH" # Webhook SLACK_SDK_TEST_INCOMING_WEBHOOK_URL = "SLACK_SDK_TEST_INCOMING_WEBHOOK_URL" -SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME = "SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME" \ No newline at end of file +SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME = "SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME" + +# For Slack Connect shared tests +SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN" +SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN" +SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID = "SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID" diff --git a/integration_tests/helpers.py b/integration_tests/helpers.py index 35be07719..983df01b5 100644 --- a/integration_tests/helpers.py +++ b/integration_tests/helpers.py @@ -21,7 +21,6 @@ def is_not_specified() -> bool: module = inspect.getmodule(frame[0]) filepath: str = module.__file__ - # python setup.py integration_tests --test-target=web/test_issue_560.py + # ./scripts/run_integration_tests.sh web/test_issue_560.py test_target: str = sys.argv[1] # e.g., web/test_issue_560.py - return not test_target or \ - not filepath.endswith(test_target) + return not test_target or not filepath.endswith(test_target) diff --git a/integration_tests/rtm/test_issue_530.py b/integration_tests/rtm/test_issue_530.py index fdc3663f7..cd992b7c3 100644 --- a/integration_tests/rtm/test_issue_530.py +++ b/integration_tests/rtm/test_issue_530.py @@ -4,7 +4,7 @@ import unittest from integration_tests.helpers import async_test -from slack import RTMClient +from slack_sdk.rtm import RTMClient class TestRTMClient(unittest.TestCase): @@ -27,8 +27,9 @@ def test_issue_530(self): self.fail("Raising an error here was expected") except Exception as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {'ok': False, 'error': 'invalid_auth'}", str(e)) + "The request to the Slack API failed.\n" "The server responded with: {'ok': False, 'error': 'invalid_auth'}", + str(e), + ) finally: if not rtm_client._stopped: rtm_client.stop() @@ -41,8 +42,9 @@ async def test_issue_530_async(self): self.fail("Raising an error here was expected") except Exception as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {'ok': False, 'error': 'invalid_auth'}", str(e)) + "The request to the Slack API failed.\n" "The server responded with: {'ok': False, 'error': 'invalid_auth'}", + str(e), + ) finally: if not rtm_client._stopped: rtm_client.stop() diff --git a/integration_tests/rtm/test_issue_558.py b/integration_tests/rtm/test_issue_558.py index dcdb373e9..0e18bb48d 100644 --- a/integration_tests/rtm/test_issue_558.py +++ b/integration_tests/rtm/test_issue_558.py @@ -6,11 +6,13 @@ import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test, is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient class TestRTMClient(unittest.TestCase): @@ -45,8 +47,8 @@ async def process_reactions(**payload): self.reaction_count += 1 rtm = RTMClient(token=self.bot_token, run_async=True) - RTMClient.on(event='message', callback=process_messages) - RTMClient.on(event='reaction_added', callback=process_reactions) + RTMClient.on(event="message", callback=process_messages) + RTMClient.on(event="reaction_added", callback=process_reactions) web_client = WebClient(token=self.bot_token, run_async=True) message = await web_client.chat_postMessage(channel=channel_id, text=text) diff --git a/integration_tests/rtm/test_issue_569.py b/integration_tests/rtm/test_issue_569.py index 8355e1507..f2c1a6bd6 100644 --- a/integration_tests/rtm/test_issue_569.py +++ b/integration_tests/rtm/test_issue_569.py @@ -9,11 +9,14 @@ import psutil import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test, is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient +from slack_sdk.web.legacy_client import LegacyWebClient class TestRTMClient(unittest.TestCase): @@ -29,6 +32,7 @@ def setUp(self): self.bot_token = os.environ[SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN] if not hasattr(self, "cpu_monitor") or not TestRTMClient.cpu_monitor.is_alive(): + def run_cpu_monitor(self): self.logger.debug("Starting CPU monitor in another thread...") TestRTMClient.cpu_usage = 0 @@ -40,7 +44,7 @@ def run_cpu_monitor(self): TestRTMClient.cpu_usage = current_cpu_usage TestRTMClient.cpu_monitor = threading.Thread(target=run_cpu_monitor, args=[self]) - TestRTMClient.cpu_monitor.setDaemon(True) + TestRTMClient.cpu_monitor.daemon = True TestRTMClient.cpu_monitor.start() self.rtm_client = None @@ -56,7 +60,7 @@ def tearDown(self): @pytest.mark.skipif(condition=is_not_specified(), reason="To avoid rate_limited errors") def test_cpu_usage(self): self.rtm_client = RTMClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) - self.web_client = WebClient(token=self.bot_token, run_async=False) + self.web_client = WebClient(token=self.bot_token) self.call_count = 0 TestRTMClient.cpu_usage = 0 @@ -71,7 +75,7 @@ def send_reply(**payload): for i in range(0, 3): new_message = web_client.chat_postMessage( channel=event["channel"], - text=f"Current CPU usage: {TestRTMClient.cpu_usage} % (test_cpu_usage)" + text=f"Current CPU usage: {TestRTMClient.cpu_usage} % (test_cpu_usage)", ) self.logger.debug(new_message) self.call_count += 1 @@ -81,7 +85,7 @@ def connect(): self.rtm_client.start() rtm = threading.Thread(target=connect) - rtm.setDaemon(True) + rtm.daemon = True rtm.start() time.sleep(5) @@ -102,7 +106,7 @@ def connect(): @async_test async def test_cpu_usage_async(self): self.rtm_client = RTMClient(token=self.bot_token, run_async=True) - self.web_client = WebClient(token=self.bot_token, run_async=True) + self.web_client = LegacyWebClient(token=self.bot_token, run_async=True) self.call_count = 0 TestRTMClient.cpu_usage = 0 @@ -117,7 +121,7 @@ async def send_reply_async(**payload): for i in range(0, 3): new_message = await web_client.chat_postMessage( channel=event["channel"], - text=f"Current CPU usage: {TestRTMClient.cpu_usage} % (test_cpu_usage_async)" + text=f"Current CPU usage: {TestRTMClient.cpu_usage} % (test_cpu_usage_async)", ) self.logger.debug(new_message) self.call_count += 1 diff --git a/integration_tests/rtm/test_issue_605.py b/integration_tests/rtm/test_issue_605.py index 4f1a81985..68e3ce867 100644 --- a/integration_tests/rtm/test_issue_605.py +++ b/integration_tests/rtm/test_issue_605.py @@ -7,11 +7,13 @@ import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient class TestRTMClient(unittest.TestCase): @@ -45,7 +47,7 @@ def connect(): self.rtm_client.start() t = threading.Thread(target=connect) - t.setDaemon(True) + t.daemon = True try: t.start() self.assertFalse(self.called) @@ -62,7 +64,7 @@ def connect(): time.sleep(5) self.assertTrue(self.called) finally: - t.join(.3) + t.join(0.3) # --- a/slack/rtm/client.py # +++ b/slack/rtm/client.py diff --git a/integration_tests/rtm/test_issue_611.py b/integration_tests/rtm/test_issue_611.py index 35ce9f3b4..4df8de337 100644 --- a/integration_tests/rtm/test_issue_611.py +++ b/integration_tests/rtm/test_issue_611.py @@ -6,11 +6,13 @@ import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test, is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient class TestRTMClient(unittest.TestCase): @@ -48,8 +50,8 @@ async def process_reactions(**payload): self.reaction_count += 1 rtm = RTMClient(token=self.bot_token, run_async=True) - RTMClient.on(event='message', callback=process_messages) - RTMClient.on(event='reaction_added', callback=process_reactions) + RTMClient.on(event="message", callback=process_messages) + RTMClient.on(event="reaction_added", callback=process_reactions) web_client = WebClient(token=self.bot_token, run_async=True) message = await web_client.chat_postMessage(channel=channel_id, text=text) diff --git a/integration_tests/rtm/test_issue_631.py b/integration_tests/rtm/test_issue_631.py index e9e9aef51..0fe55a65c 100644 --- a/integration_tests/rtm/test_issue_631.py +++ b/integration_tests/rtm/test_issue_631.py @@ -9,11 +9,13 @@ import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test, is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient class TestRTMClient(unittest.TestCase): @@ -74,18 +76,14 @@ def test_issue_631_sharing_event_loop(self): @RTMClient.run_on(event="message") def send_reply(**payload): self.logger.debug(payload) - data = payload['data'] - web_client = payload['web_client'] + data = payload["data"] + web_client = payload["web_client"] try: if "text" in data and self.text in data["text"]: - channel_id = data['channel'] - thread_ts = data['ts'] - self.success = web_client.chat_postMessage( - channel=channel_id, - text="Thanks!", - thread_ts=thread_ts - ) + channel_id = data["channel"] + thread_ts = data["ts"] + self.success = web_client.chat_postMessage(channel=channel_id, text="Thanks!", thread_ts=thread_ts) except Exception as e: self.logger.error(traceback.format_exc()) raise e @@ -95,7 +93,7 @@ def connect(): self.rtm_client.start() t = threading.Thread(target=connect) - t.setDaemon(True) + t.daemon = True t.start() try: @@ -112,7 +110,7 @@ def connect(): time.sleep(5) self.assertIsNotNone(self.success) finally: - t.join(.3) + t.join(0.3) # Solution (2) for #631 @pytest.mark.skipif(condition=is_not_specified(), reason="this is just for reference") @@ -128,18 +126,14 @@ async def test_issue_631_sharing_event_loop_async(self): @RTMClient.run_on(event="message") async def send_reply(**payload): self.logger.debug(payload) - data = payload['data'] - web_client = payload['web_client'] + data = payload["data"] + web_client = payload["web_client"] try: if "text" in data and self.text in data["text"]: - channel_id = data['channel'] - thread_ts = data['ts'] - self.success = await web_client.chat_postMessage( - channel=channel_id, - text="Thanks!", - thread_ts=thread_ts - ) + channel_id = data["channel"] + thread_ts = data["ts"] + self.success = await web_client.chat_postMessage(channel=channel_id, text="Thanks!", thread_ts=thread_ts) except Exception as e: self.logger.error(traceback.format_exc()) raise e diff --git a/integration_tests/rtm/test_issue_701.py b/integration_tests/rtm/test_issue_701.py index b6fbae72b..793bab772 100644 --- a/integration_tests/rtm/test_issue_701.py +++ b/integration_tests/rtm/test_issue_701.py @@ -10,7 +10,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN from integration_tests.helpers import async_test, is_not_specified -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web import WebClient class TestRTMClient(unittest.TestCase): @@ -47,7 +48,7 @@ def connect(): self.rtm_client.start() rtm = threading.Thread(target=connect) - rtm.setDaemon(True) + rtm.daemon = True rtm.start() time.sleep(3) @@ -67,7 +68,7 @@ def sent_bulk_message(): senders = [] for sender_num in range(num_of_senders): sender = threading.Thread(target=sent_bulk_message) - sender.setDaemon(True) + sender.daemon = True sender.start() senders.append(sender) @@ -118,7 +119,7 @@ def sent_bulk_message(): senders = [] for sender_num in range(num_of_senders): sender = threading.Thread(target=sent_bulk_message) - sender.setDaemon(True) + sender.daemon = True sender.start() senders.append(sender) diff --git a/integration_tests/rtm/test_rtm_client.py b/integration_tests/rtm/test_rtm_client.py index 0a76d2c9d..b56b12ded 100644 --- a/integration_tests/rtm/test_rtm_client.py +++ b/integration_tests/rtm/test_rtm_client.py @@ -6,11 +6,13 @@ import time import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, \ - SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN, + SLACK_SDK_TEST_RTM_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import RTMClient, WebClient +from slack_sdk.rtm import RTMClient +from slack_sdk.web.legacy_client import LegacyWebClient class TestRTMClient(unittest.TestCase): @@ -36,23 +38,19 @@ def test_basic_operations(self): run_async=False, loop=asyncio.new_event_loop(), # TODO: this doesn't work without this ) - self.web_client = WebClient( - token=self.bot_token, - run_async=False, - loop=asyncio.new_event_loop(), # TODO: this doesn't work without this - ) + self.web_client = LegacyWebClient(token=self.bot_token) @RTMClient.run_on(event="message") def send_reply(**payload): self.logger.debug(payload) - self.sent_text = payload['data']['text'] + self.sent_text = payload["data"]["text"] def connect(): self.logger.debug("Starting RTM Client...") self.rtm_client.start() t = threading.Thread(target=connect) - t.setDaemon(True) + t.daemon = True t.start() try: @@ -66,18 +64,18 @@ def connect(): time.sleep(5) self.assertEqual(self.sent_text, text) finally: - t.join(.3) + t.join(0.3) @async_test async def test_basic_operations_async(self): self.sent_text: str = None self.rtm_client = RTMClient(token=self.bot_token, run_async=True) - self.async_web_client = WebClient(token=self.bot_token, run_async=True) + self.async_web_client = LegacyWebClient(token=self.bot_token, run_async=True) @RTMClient.run_on(event="message") async def send_reply(**payload): self.logger.debug(payload) - self.sent_text = payload['data']['text'] + self.sent_text = payload["data"]["text"] # intentionally not waiting here self.rtm_client.start() diff --git a/integration_tests/samples/basic_usage/calling_any_api_methods.py b/integration_tests/samples/basic_usage/calling_any_api_methods.py index 75fabcd81..bc545af39 100644 --- a/integration_tests/samples/basic_usage/calling_any_api_methods.py +++ b/integration_tests/samples/basic_usage/calling_any_api_methods.py @@ -1,22 +1,13 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/calling_any_api_methods.py import os -from slack import WebClient +from slack_sdk.web import WebClient -client = WebClient(token=os.environ['SLACK_API_TOKEN']) -response = client.api_call( - api_method='chat.postMessage', - json={'channel': '#random','text': "Hello world!"} -) -assert response["message"]["text"] == "Hello world!" \ No newline at end of file +client = WebClient(token=os.environ["SLACK_API_TOKEN"]) +response = client.api_call(api_method="chat.postMessage", json={"channel": "#random", "text": "Hello world!"}) +assert response["message"]["text"] == "Hello world!" diff --git a/integration_tests/samples/basic_usage/channels.py b/integration_tests/samples/basic_usage/channels.py index 962c7acd9..f7c1c9c41 100644 --- a/integration_tests/samples/basic_usage/channels.py +++ b/integration_tests/samples/basic_usage/channels.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/channels.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) diff --git a/integration_tests/samples/basic_usage/emoji_reactions.py b/integration_tests/samples/basic_usage/emoji_reactions.py index 52543ce84..03f11d266 100644 --- a/integration_tests/samples/basic_usage/emoji_reactions.py +++ b/integration_tests/samples/basic_usage/emoji_reactions.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/emoji_reactions.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) @@ -23,22 +17,11 @@ channel_id = "C0XXXXXX" user_id = "U0XXXXXXX" -response = client.chat_postMessage( - channel=channel_id, - text="Give me some reaction!" -) +response = client.chat_postMessage(channel=channel_id, text="Give me some reaction!") # Ensure the channel_id is not a name channel_id = response["channel"] ts = response["message"]["ts"] -response = client.reactions_add( - channel=channel_id, - name="thumbsup", - timestamp=ts -) - -response = client.reactions_remove( - channel=channel_id, - name="thumbsup", - timestamp=ts -) +response = client.reactions_add(channel=channel_id, name="thumbsup", timestamp=ts) + +response = client.reactions_remove(channel=channel_id, name="thumbsup", timestamp=ts) diff --git a/integration_tests/samples/basic_usage/rate_limits.py b/integration_tests/samples/basic_usage/rate_limits.py index 452eb075f..e0d947cbf 100644 --- a/integration_tests/samples/basic_usage/rate_limits.py +++ b/integration_tests/samples/basic_usage/rate_limits.py @@ -1,30 +1,21 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/rate_limits.py import os import time -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError client = WebClient(token=os.environ["SLACK_API_TOKEN"]) # Simple wrapper for sending a Slack message def send_slack_message(channel, message): - return client.chat_postMessage( - channel=channel, - text=message - ) + return client.chat_postMessage(channel=channel, text=message) # Make the API call and save results to `response` @@ -38,7 +29,7 @@ def send_slack_message(channel, message): except SlackApiError as e: if e.response["error"] == "ratelimited": # The `Retry-After` header will tell you how long to wait before retrying - delay = int(e.response.headers['Retry-After']) + delay = int(e.response.headers["Retry-After"]) print(f"Rate limited. Retrying in {delay} seconds") time.sleep(delay) response = send_slack_message(channel, message) diff --git a/integration_tests/samples/basic_usage/sending_a_message.py b/integration_tests/samples/basic_usage/sending_a_message.py index 1ac02a240..ed55ad00b 100644 --- a/integration_tests/samples/basic_usage/sending_a_message.py +++ b/integration_tests/samples/basic_usage/sending_a_message.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/sending_a_message.py import os -from slack import WebClient +from slack_sdk.web import WebClient slack_token = os.environ["SLACK_API_TOKEN"] client = WebClient(token=slack_token) @@ -24,20 +18,13 @@ channel_id = "C0XXXXXX" user_id = "U0XXXXXXX" -response = client.chat_postMessage( - channel=channel_id, - text="Hello from your app! :tada:" -) +response = client.chat_postMessage(channel=channel_id, text="Hello from your app! :tada:") # Ensure the channel_id is not a name channel_id = response["channel"] thread_ts = response["message"]["ts"] -response = client.chat_postEphemeral( - channel=channel_id, - user=user_id, - text="Hello silently from your app! :tada:" -) +response = client.chat_postEphemeral(channel=channel_id, user=user_id, text="Hello silently from your app! :tada:") response = client.chat_postMessage( channel=channel_id, @@ -46,68 +33,46 @@ "type": "section", "text": { "type": "mrkdwn", - "text": "Danny Torrence left the following review for your property:" - } + "text": "Danny Torrence left the following review for your property:", + }, }, { "type": "section", "text": { "type": "mrkdwn", - "text": " \n :star: \n Doors had too many axe holes, guest in room " + - "237 was far too rowdy, whole place felt stuck in the 1920s." + "text": " \n :star: \n Doors had too many axe holes, guest in room " + + "237 was far too rowdy, whole place felt stuck in the 1920s.", }, "accessory": { "type": "image", "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg", - "alt_text": "Haunted hotel image" - } + "alt_text": "Haunted hotel image", + }, }, { "type": "section", - "fields": [ - { - "type": "mrkdwn", - "text": "*Average Rating*\n1.0" - } - ] - } - ] + "fields": [{"type": "mrkdwn", "text": "*Average Rating*\n1.0"}], + }, + ], ) # Threading Messages -response = client.chat_postMessage( - channel=channel_id, - text="Hello from your app! :tada:", - thread_ts=thread_ts -) +response = client.chat_postMessage(channel=channel_id, text="Hello from your app! :tada:", thread_ts=thread_ts) response = client.chat_postMessage( channel=channel_id, text="Hello from your app! :tada:", thread_ts=thread_ts, - reply_broadcast=True + reply_broadcast=True, ) # Updating a message -response = client.chat_postMessage( - channel=channel_id, - text="To be modified :eyes:" -) +response = client.chat_postMessage(channel=channel_id, text="To be modified :eyes:") ts = response["message"]["ts"] -response = client.chat_update( - channel=channel_id, - ts=ts, - text="updates from your app! :tada:" -) +response = client.chat_update(channel=channel_id, ts=ts, text="updates from your app! :tada:") # Deleting a message -response = client.chat_postMessage( - channel=channel_id, - text="To be deleted :eyes:" -) +response = client.chat_postMessage(channel=channel_id, text="To be deleted :eyes:") ts = response["message"]["ts"] -response = client.chat_delete( - channel=channel_id, - ts=ts -) +response = client.chat_delete(channel=channel_id, ts=ts) diff --git a/integration_tests/samples/basic_usage/uploading_files.py b/integration_tests/samples/basic_usage/uploading_files.py index 97d0c9c62..7d0c828a5 100644 --- a/integration_tests/samples/basic_usage/uploading_files.py +++ b/integration_tests/samples/basic_usage/uploading_files.py @@ -1,22 +1,17 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # echo 'Hello world!' > tmp.txt # python3 integration_tests/samples/basic_usage/uploading_files.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) channels = ",".join(["#random"]) filepath = "./tmp.txt" response = client.files_upload(channels=channels, file=filepath) +response = client.files_upload_v2(channel=response.get("file").get("channels")[0], file=filepath) diff --git a/integration_tests/samples/basic_usage/users.py b/integration_tests/samples/basic_usage/users.py index fb05f426e..1446b32e6 100644 --- a/integration_tests/samples/basic_usage/users.py +++ b/integration_tests/samples/basic_usage/users.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/basic_usage/users.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) diff --git a/integration_tests/samples/basic_usage/views.py b/integration_tests/samples/basic_usage/views.py index 49ccbb2a5..ef791116e 100644 --- a/integration_tests/samples/basic_usage/views.py +++ b/integration_tests/samples/basic_usage/views.py @@ -1,11 +1,6 @@ -# ------------------ -# Only for running this script here import json import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) # --------------------- @@ -14,11 +9,11 @@ import os -from slack import WebClient -from slack.errors import SlackApiError -from slack.signature import SignatureVerifier +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier -client = WebClient(token=os.environ["SLACK_API_TOKEN"]) +client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) # --------------------- @@ -26,7 +21,7 @@ # --------------------- # pip3 install flask -from flask import Flask, request, make_response +from flask import Flask, request, make_response, jsonify app = Flask(__name__) @@ -39,8 +34,7 @@ def slack_app(): if "payload" in request.form: payload = json.loads(request.form["payload"]) - if payload["type"] == "shortcut" \ - and payload["callback_id"] == "open-modal-shortcut": + if payload["type"] == "shortcut" and payload["callback_id"] == "test-shortcut": # Open a new modal by a global shortcut try: api_response = client.views_open( @@ -48,18 +42,9 @@ def slack_app(): view={ "type": "modal", "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, "blocks": [ { "type": "input", @@ -71,22 +56,42 @@ def slack_app(): "element": { "action_id": "a-id", "type": "plain_text_input", - } + }, } - ] - } + ], + }, ) return make_response("", 200) except SlackApiError as e: code = e.response["error"] return make_response(f"Failed to open a modal due to {code}", 200) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - return make_response("", 200) + return make_response( + jsonify( + { + "response_action": "update", + "view": { + "type": "modal", + "title": {"type": "plain_text", "text": "Accepted"}, + "close": {"type": "plain_text", "text": "Close"}, + "blocks": [ + { + "type": "section", + "text": { + "type": "plain_text", + "text": "Thanks for submitting the data!", + }, + } + ], + }, + } + ), + 200, + ) return make_response("", 404) diff --git a/integration_tests/samples/basic_usage/views_2.py b/integration_tests/samples/basic_usage/views_2.py index af016a931..7ed4feea9 100644 --- a/integration_tests/samples/basic_usage/views_2.py +++ b/integration_tests/samples/basic_usage/views_2.py @@ -1,11 +1,6 @@ -# ------------------ -# Only for running this script here import json import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) # --------------------- @@ -14,15 +9,15 @@ import os -from slack import WebClient -from slack.errors import SlackApiError -from slack.signature import SignatureVerifier -from slack.web.classes.blocks import InputBlock -from slack.web.classes.elements import PlainTextInputElement -from slack.web.classes.objects import PlainTextObject -from slack.web.classes.views import View +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier +from slack_sdk.models.blocks import InputBlock, SectionBlock +from slack_sdk.models.blocks.block_elements import PlainTextInputElement +from slack_sdk.models.blocks.basic_components import PlainTextObject +from slack_sdk.models.views import View -client = WebClient(token=os.environ["SLACK_API_TOKEN"]) +client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) # --------------------- @@ -30,7 +25,7 @@ # --------------------- # pip3 install flask -from flask import Flask, request, make_response +from flask import Flask, request, make_response, jsonify app = Flask(__name__) @@ -42,8 +37,7 @@ def slack_app(): if "payload" in request.form: payload = json.loads(request.form["payload"]) - if payload["type"] == "shortcut" \ - and payload["callback_id"] == "open-modal-shortcut": + if payload["type"] == "shortcut" and payload["callback_id"] == "test-shortcut": # Open a new modal by a global shortcut try: view = View( @@ -56,9 +50,9 @@ def slack_app(): InputBlock( block_id="b-id", label=PlainTextObject(text="Input label"), - element=PlainTextInputElement(action_id="a-id") + element=PlainTextInputElement(action_id="a-id"), ) - ] + ], ) api_response = client.views_open( trigger_id=payload["trigger_id"], @@ -69,12 +63,30 @@ def slack_app(): code = e.response["error"] return make_response(f"Failed to open a modal due to {code}", 200) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - return make_response("", 200) + return make_response( + jsonify( + { + "response_action": "update", + "view": View( + type="modal", + callback_id="modal-id", + title=PlainTextObject(text="Accepted"), + close=PlainTextObject(text="Close"), + blocks=[ + SectionBlock( + block_id="b-id", + text=PlainTextObject(text="Thanks for submitting the data!"), + ) + ], + ).to_dict(), + } + ), + 200, + ) return make_response("", 404) diff --git a/integration_tests/samples/basic_usage/views_default_to_current_conversation.py b/integration_tests/samples/basic_usage/views_default_to_current_conversation.py index b3a682b2d..13cbd710a 100644 --- a/integration_tests/samples/basic_usage/views_default_to_current_conversation.py +++ b/integration_tests/samples/basic_usage/views_default_to_current_conversation.py @@ -1,11 +1,6 @@ -# ------------------ -# Only for running this script here import json import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) # --------------------- @@ -14,15 +9,18 @@ import os -from slack import WebClient -from slack.errors import SlackApiError -from slack.signature import SignatureVerifier -from slack.web.classes.blocks import InputBlock -from slack.web.classes.elements import ConversationMultiSelectElement, ConversationSelectElement -from slack.web.classes.objects import PlainTextObject -from slack.web.classes.views import View - -client = WebClient(token=os.environ["SLACK_API_TOKEN"]) +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier +from slack_sdk.models.blocks import InputBlock +from slack_sdk.models.blocks.block_elements import ( + ConversationMultiSelectElement, + ConversationSelectElement, +) +from slack_sdk.models.blocks.basic_components import PlainTextObject +from slack_sdk.models.views import View + +client = WebClient(token=os.environ["SLACK_BOT_TOKEN"]) signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) # --------------------- @@ -50,7 +48,7 @@ def open_modal(trigger_id: str): element=ConversationSelectElement( action_id="a", default_to_current_conversation=True, - ) + ), ), InputBlock( block_id="b-id-2", @@ -59,14 +57,11 @@ def open_modal(trigger_id: str): action_id="a", max_selected_items=2, default_to_current_conversation=True, - ) + ), ), - ] - ) - api_response = client.views_open( - trigger_id=trigger_id, - view=view + ], ) + api_response = client.views_open(trigger_id=trigger_id, view=view) return make_response("", 200) except SlackApiError as e: code = e.response["error"] @@ -78,21 +73,18 @@ def slack_app(): if not signature_verifier.is_valid_request(request.get_data(), request.headers): return make_response("invalid request", 403) - if "command" in request.form \ - and request.form["command"] == "/view": + if "command" in request.form and request.form["command"] == "/view": # Open a new modal by a slash command return open_modal(request.form["trigger_id"]) elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if payload["type"] == "shortcut" \ - and payload["callback_id"] == "open-modal-shortcut": + if payload["type"] == "shortcut" and payload["callback_id"] == "test-shortcut": # Open a new modal by a global shortcut return open_modal(payload["trigger_id"]) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": # Handle a data submission request from the modal submitted_data = payload["view"]["state"]["values"] print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} diff --git a/integration_tests/samples/conversations/create_private_channel.py b/integration_tests/samples/conversations/create_private_channel.py index 9cdbd5b74..4ab780b2b 100644 --- a/integration_tests/samples/conversations/create_private_channel.py +++ b/integration_tests/samples/conversations/create_private_channel.py @@ -1,33 +1,21 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/conversations/create_private_channel.py import os -from slack import WebClient +from slack_sdk.web import WebClient from time import time client = WebClient(token=os.environ["SLACK_API_TOKEN"]) channel_name = f"my-private-channel-{round(time())}" -response = client.conversations_create( - name=channel_name, - is_private=True -) +response = client.conversations_create(name=channel_name, is_private=True) channel_id = response["channel"]["id"] -response = client.conversations_info( - channel=channel_id, - include_num_members=1 # TODO: True -) +response = client.conversations_info(channel=channel_id, include_num_members=1) # TODO: True response = client.conversations_members(channel=channel_id) user_ids = response["members"] diff --git a/integration_tests/samples/conversations/list_conversations.py b/integration_tests/samples/conversations/list_conversations.py index b7f820982..19749f04d 100644 --- a/integration_tests/samples/conversations/list_conversations.py +++ b/integration_tests/samples/conversations/list_conversations.py @@ -1,30 +1,19 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/conversations/list_conversations.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) response = client.conversations_list() -response = client.conversations_list( - types="public_channel, private_channel" -) +response = client.conversations_list(types="public_channel, private_channel") channel_id = response["channels"][0]["id"] -response = client.conversations_info( - channel=channel_id, - include_num_members=1 # TODO: True -) +response = client.conversations_info(channel=channel_id, include_num_members=1) # TODO: True diff --git a/integration_tests/samples/conversations/open_dm.py b/integration_tests/samples/conversations/open_dm.py index 716b8696d..86786c885 100644 --- a/integration_tests/samples/conversations/open_dm.py +++ b/integration_tests/samples/conversations/open_dm.py @@ -1,29 +1,24 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/conversations/open_dm.py import os -from slack import WebClient +from slack_sdk.web import WebClient client = WebClient(token=os.environ["SLACK_API_TOKEN"]) all_users = client.users_list(limit=100)["members"] -joinable_only = lambda u: \ - u["id"] != "USLACKBOT" \ - and not u["is_bot"] \ - and not u["is_app_user"] \ - and not u["deleted"] \ - and not u["is_restricted"] \ +joinable_only = ( + lambda u: u["id"] != "USLACKBOT" + and not u["is_bot"] + and not u["is_app_user"] + and not u["deleted"] + and not u["is_restricted"] and not u["is_ultra_restricted"] +) users = filter(joinable_only, all_users) user_ids = list(map(lambda u: u["id"], users)) diff --git a/integration_tests/samples/issues/issue_497.py b/integration_tests/samples/issues/issue_497.py index 687f59d2a..7741c7ecb 100644 --- a/integration_tests/samples/issues/issue_497.py +++ b/integration_tests/samples/issues/issue_497.py @@ -1,13 +1,8 @@ -# ------------------ -# Only for running this script here import asyncio import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ + # --------------------- # Flask App @@ -21,17 +16,13 @@ import os -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError singleton_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=False) singleton_loop = asyncio.new_event_loop() -singleton_async_client = WebClient( - token=os.environ["SLACK_BOT_TOKEN"], - run_async=True, - loop=singleton_loop -) +singleton_async_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=True, loop=singleton_loop) # Fixed in 2.6.0: This doesn't work @@ -43,7 +34,7 @@ def singleton(): # until this completion, other simultaneous requests get "RuntimeError: This event loop is already running" response = singleton_client.chat_postMessage( channel="#random", - text="You used the singleton WebClient for posting this message!" + text="You used the singleton WebClient for posting this message!", ) return str(response) except SlackApiError as e: @@ -53,14 +44,8 @@ def singleton(): @app.route("/sync/per-request", methods=["GET"]) def per_request(): try: - client = WebClient( - token=os.environ["SLACK_BOT_TOKEN"], - run_async=False - ) - response = client.chat_postMessage( - channel="#random", - text="You used a new WebClient for posting this message!" - ) + client = WebClient(token=os.environ["SLACK_BOT_TOKEN"], run_async=False) + response = client.chat_postMessage(channel="#random", text="You used a new WebClient for posting this message!") return str(response) except SlackApiError as e: return make_response(str(e), 400) @@ -72,7 +57,7 @@ def singleton_async(): try: future = singleton_async_client.chat_postMessage( channel="#random", - text="You used the singleton WebClient for posting this message!" + text="You used the singleton WebClient for posting this message!", ) # blocking here!!! # as described at https://github.com/slackapi/python-slack-sdk/issues/497 @@ -92,11 +77,11 @@ def per_request_async(): async_client = WebClient( token=os.environ["SLACK_BOT_TOKEN"], run_async=True, - loop=loop_for_this_request + loop=loop_for_this_request, ) future = async_client.chat_postMessage( channel="#random", - text="You used the singleton WebClient for posting this message!" + text="You used the singleton WebClient for posting this message!", ) response = loop_for_this_request.run_until_complete(future) return str(response) diff --git a/integration_tests/samples/issues/issue_506.py b/integration_tests/samples/issues/issue_506.py index de6453885..b38b57ab4 100644 --- a/integration_tests/samples/issues/issue_506.py +++ b/integration_tests/samples/issues/issue_506.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/issues/issue_506.py import os -from slack import RTMClient +from slack_sdk.rtm import RTMClient logger = logging.getLogger(__name__) global_state = {} diff --git a/integration_tests/samples/issues/issue_522.py b/integration_tests/samples/issues/issue_522.py index 356d34b73..83a0bba9d 100644 --- a/integration_tests/samples/issues/issue_522.py +++ b/integration_tests/samples/issues/issue_522.py @@ -1,26 +1,17 @@ -# ------------------ -# Only for running this script here -import logging -import sys -from os.path import dirname - -sys.path.insert(1, f"{dirname(__file__)}/../../..") -logging.basicConfig(level=logging.DEBUG) -# ------------------ - # export SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN=xoxb-*** # python3 integration_tests/samples/issues/issue_522.py import asyncio import logging import os +import sys -import slack +from slack_sdk.rtm import RTMClient logging.basicConfig(level=logging.DEBUG) LOGGER = logging.getLogger(__name__) -token = os.environ['SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN'] +token = os.environ["SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN"] async def sleepy_count(name, sleep_for): @@ -31,7 +22,7 @@ async def sleepy_count(name, sleep_for): async def slack_client_and_sleeps(): # real-time-messaging Slack client - client = slack.RTMClient(token=token, run_async=True) + client = RTMClient(token=token, run_async=True) sleepy_count_task = asyncio.create_task(sleepy_count("first counter", 1)) sleepy_count_task2 = asyncio.create_task(sleepy_count("second counter", 3)) @@ -41,7 +32,7 @@ async def slack_client_and_sleeps(): async def slack_client(): # real-time-messaging Slack client - client = slack.RTMClient(token=token, run_async=True) + client = RTMClient(token=token, run_async=True) await asyncio.gather(client.start()) diff --git a/integration_tests/samples/issues/issue_690.py b/integration_tests/samples/issues/issue_690.py index fff4ca5a2..eadbce5f7 100644 --- a/integration_tests/samples/issues/issue_690.py +++ b/integration_tests/samples/issues/issue_690.py @@ -1,12 +1,6 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # --------------------- # Flask App @@ -24,9 +18,10 @@ @app.route("/slack/oauth/callback", methods=["GET"]) def endpoint(): code = request.args.get("code") + from slack_sdk.web import WebClient + from slack_sdk.errors import SlackApiError + try: - from slack import WebClient - from slack.errors import SlackApiError client = WebClient(token="") client_id = os.environ["SLACK_CLIENT_ID"] client_secret = os.environ["SLACK_CLIENT_SECRET"] diff --git a/integration_tests/samples/issues/issue_714.py b/integration_tests/samples/issues/issue_714.py index 150fdebf5..b7a7bd0c6 100644 --- a/integration_tests/samples/issues/issue_714.py +++ b/integration_tests/samples/issues/issue_714.py @@ -1,47 +1,37 @@ -# ------------------ -# Only for running this script here import asyncio import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ logger = logging.getLogger(__name__) import os -from slack import WebClient +from slack_sdk.web import WebClient # export HTTPS_PROXY=http://localhost:9000 client = WebClient(token=os.environ["SLACK_API_TOKEN"]) response = client.auth_test() logger.info(f"HTTPS_PROXY response: {response}") -client = WebClient( - token=os.environ["SLACK_API_TOKEN"], - proxy="http://localhost:9000" -) +client = WebClient(token=os.environ["SLACK_API_TOKEN"], proxy="http://localhost:9000") response = client.auth_test() logger.info(f"sync response: {response}") -client = WebClient( - token=os.environ["SLACK_API_TOKEN"], - proxy="localhost:9000" -) +client = WebClient(token=os.environ["SLACK_API_TOKEN"], proxy="localhost:9000") response = client.auth_test() logger.info(f"sync response: {response}") + async def async_call(): client = WebClient( token=os.environ["SLACK_API_TOKEN"], proxy="http://localhost:9000", - run_async=True + run_async=True, ) response = await client.auth_test() logger.info(f"async response: {response}") + asyncio.run(async_call()) # Terminal A: diff --git a/integration_tests/samples/issues/issue_838.py b/integration_tests/samples/issues/issue_838.py index 5cc41e68a..0c84b59ff 100644 --- a/integration_tests/samples/issues/issue_838.py +++ b/integration_tests/samples/issues/issue_838.py @@ -1,11 +1,6 @@ -# ------------------ -# Only for running this script here import json import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../..") logging.basicConfig(level=logging.DEBUG) # --------------------- @@ -14,10 +9,10 @@ import os -from slack import WebClient -from slack.signature import SignatureVerifier +from slack_sdk.web import WebClient +from slack_sdk.signature import SignatureVerifier -app_token_client = WebClient(token=os.environ["SLACK_APP_TOKEN"]) # xapp- +app_token_client = WebClient(token=os.environ["SLACK_APP_TOKEN"]) # xapp- signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) # --------------------- @@ -38,9 +33,7 @@ def slack_app(): if request.headers["content-type"] == "application/json": body = json.loads(request_body) - response = app_token_client.apps_event_authorizations_list( - event_context=body["event_context"] - ) + response = app_token_client.apps_event_authorizations_list(event_context=body["event_context"]) print(response) return make_response("", 200) diff --git a/integration_tests/samples/issues/issue_868.py b/integration_tests/samples/issues/issue_868.py index d78deaecd..d88700a5d 100644 --- a/integration_tests/samples/issues/issue_868.py +++ b/integration_tests/samples/issues/issue_868.py @@ -1,29 +1,23 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ def legacy(): - from slack.web.classes.blocks import SectionBlock - from slack.web.classes.objects import TextObject + from slack_sdk.models.blocks import SectionBlock + from slack_sdk.models.blocks.basic_components import TextObject fields = [] - fields.append(TextObject(text='...', type='mrkdwn')) - block = SectionBlock(text='', fields=fields) + fields.append(TextObject(text="...", type="mrkdwn")) + block = SectionBlock(text="", fields=fields) assert block is not None from slack_sdk.models.blocks import SectionBlock, TextObject fields = [] -fields.append(TextObject(text='...', type='mrkdwn')) -block = SectionBlock(text='', fields=fields) +fields.append(TextObject(text="...", type="mrkdwn")) +block = SectionBlock(text="", fields=fields) assert block is not None # @@ -33,4 +27,4 @@ def legacy(): # integration_tests/samples/issues/issue_868.py:26: error: Argument "fields" to "SectionBlock" has incompatible type "List[TextObject]"; expected "Optional[List[Union[str, Dict[Any, Any], TextObject]]]" # integration_tests/samples/issues/issue_868.py:26: note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance -# integration_tests/samples/issues/issue_868.py:26: note: Consider using "Sequence" instead, which is covariant \ No newline at end of file +# integration_tests/samples/issues/issue_868.py:26: note: Consider using "Sequence" instead, which is covariant diff --git a/integration_tests/samples/issues/issue_926.py b/integration_tests/samples/issues/issue_926.py new file mode 100644 index 000000000..ca893fc7e --- /dev/null +++ b/integration_tests/samples/issues/issue_926.py @@ -0,0 +1,23 @@ +import asyncio +import logging +import os + +from slack_sdk.socket_mode.aiohttp import SocketModeClient + +logging.basicConfig(level=logging.DEBUG) + + +async def main(): + client = SocketModeClient(app_token=os.environ["SLACK_APP_TOKEN"]) + await client.connect() + await asyncio.sleep(3) + await client.close() + + +if __name__ == "__main__": + asyncio.run(main()) + +# The issue: +# ERROR:asyncio:Unclosed client session +# client_session: +# INFO:slack_sdk.socket_mode.aiohttp:The session has been abandoned diff --git a/integration_tests/samples/oauth/oauth_v2.py b/integration_tests/samples/oauth/oauth_v2.py index af8cb51ac..c1c32d879 100644 --- a/integration_tests/samples/oauth/oauth_v2.py +++ b/integration_tests/samples/oauth/oauth_v2.py @@ -1,16 +1,7 @@ -# ------------------ -# Only for running this script here -import logging -import sys -from os.path import dirname - -sys.path.insert(1, f"{dirname(__file__)}/../../..") -logging.basicConfig(level=logging.DEBUG) -# ------------------ - # --------------------- # Flask App for Slack OAuth flow # --------------------- +import html # pip3 install flask from flask import Flask, request, make_response @@ -18,15 +9,16 @@ app = Flask(__name__) app.debug = True +import logging import os from slack_sdk.web import WebClient -from slack_sdk.oauth import AuthorizeUrlGenerator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer from slack_sdk.oauth.installation_store import FileInstallationStore, Installation from slack_sdk.oauth.state_store import FileOAuthStateStore client_id = os.environ["SLACK_CLIENT_ID"] client_secret = os.environ["SLACK_CLIENT_SECRET"] -scopes = ["app_mentions:read","chat:write"] +scopes = ["app_mentions:read", "chat:write"] user_scopes = ["search:read"] logger = logging.getLogger(__name__) @@ -39,13 +31,20 @@ scopes=scopes, user_scopes=user_scopes, ) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + @app.route("/slack/install", methods=["GET"]) def oauth_start(): state = state_store.issue() url = authorization_url_generator.generate(state) - return f'' \ - f'' + return ( + f'' + f'' + ) @app.route("/slack/oauth_redirect", methods=["GET"]) @@ -56,28 +55,32 @@ def oauth_callback(): if state_store.consume(state): code = request.args["code"] client = WebClient() # no prepared token needed for this app - oauth_response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code - ) + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise") or {} + is_enterprise_install = oauth_response.get("is_enterprise_install") installed_team = oauth_response.get("team") or {} installer = oauth_response.get("authed_user") or {} incoming_webhook = oauth_response.get("incoming_webhook") or {} + bot_token = oauth_response.get("access_token") # NOTE: oauth.v2.access doesn't include bot_id in response bot_id = None + enterprise_url = None if bot_token is not None: auth_test = client.auth_test(token=bot_token) bot_id = auth_test["bot_id"] + if is_enterprise_install is True: + enterprise_url = auth_test.get("url") installation = 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"), @@ -86,16 +89,24 @@ def oauth_callback(): user_token=installer.get("access_token"), user_scopes=installer.get("scope"), # comma-separated string 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"), ) installation_store.save(installation) - return "Thanks for installing this app!" + return redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) else: - return make_response(f"Try the installation again (the state value is already expired)", 400) + return redirect_page_renderer.render_failure_page("the state value is already expired") error = request.args["error"] if "error" in request.args else "" - return make_response(f"Something is wrong with the installation (error: {error})", 400) + return redirect_page_renderer.render_failure_page(error) # --------------------- @@ -109,16 +120,23 @@ def oauth_callback(): signing_secret = os.environ["SLACK_SIGNING_SECRET"] signature_verifier = SignatureVerifier(signing_secret=signing_secret) + @app.route("/slack/events", methods=["POST"]) def slack_app(): + data = request.get_data() if not signature_verifier.is_valid( - body=request.get_data(), + body=data, timestamp=request.headers.get("X-Slack-Request-Timestamp"), - signature=request.headers.get("X-Slack-Signature")): + signature=request.headers.get("X-Slack-Signature"), + ): return make_response("invalid request", 403) - if "command" in request.form \ - and request.form["command"] == "/open-modal": + if data and b"url_verification" in data: + body = json.loads(data) + if body.get("type") == "url_verification" and "challenge" in body: + return make_response(body["challenge"], 200) + + if "command" in request.form and request.form["command"] == "/open-modal": try: enterprise_id = request.form.get("enterprise_id") team_id = request.form["team_id"] @@ -137,18 +155,9 @@ def slack_app(): view={ "type": "modal", "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, "blocks": [ { "type": "input", @@ -160,10 +169,10 @@ def slack_app(): "element": { "action_id": "a-id", "type": "plain_text_input", - } + }, } - ] - } + ], + }, ) return make_response("", 200) except SlackApiError as e: @@ -172,8 +181,7 @@ def slack_app(): elif "payload" in request.form: payload = json.loads(request.form["payload"]) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": submitted_data = payload["view"]["state"]["values"] print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return make_response("", 200) @@ -191,4 +199,4 @@ def slack_app(): # python3 integration_tests/samples/oauth/oauth_v2.py # ngrok http 3000 - # https://{yours}.ngrok.io/slack/oauth/start + # https://{yours}.ngrok.io/slack/install diff --git a/integration_tests/samples/oauth/oauth_v2_async.py b/integration_tests/samples/oauth/oauth_v2_async.py index b561b98a9..588b0b5f0 100644 --- a/integration_tests/samples/oauth/oauth_v2_async.py +++ b/integration_tests/samples/oauth/oauth_v2_async.py @@ -1,25 +1,17 @@ -# ------------------ -# Only for running this script here -import logging -import sys -from os.path import dirname - -sys.path.insert(1, f"{dirname(__file__)}/../../..") -# ------------------ - # --------------------- # Sanic App for Slack OAuth flow # --------------------- - +import html +import logging import os from slack_sdk.web.async_client import AsyncWebClient -from slack_sdk.oauth import AuthorizeUrlGenerator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer from slack_sdk.oauth.installation_store import FileInstallationStore, Installation from slack_sdk.oauth.state_store import FileOAuthStateStore client_id = os.environ["SLACK_CLIENT_ID"] client_secret = os.environ["SLACK_CLIENT_SECRET"] -scopes = ["app_mentions:read","chat:write"] +scopes = ["app_mentions:read", "chat:write"] user_scopes = ["search:read"] logger = logging.getLogger(__name__) @@ -32,6 +24,10 @@ scopes=scopes, user_scopes=user_scopes, ) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) # https://sanicframework.org/ from sanic import Sanic @@ -48,8 +44,8 @@ async def oauth_start(req: Request): url = authorization_url_generator.generate(state) return HTTPResponse( status=200, - body=f'' \ - f'' + body=f'' + f'', ) @@ -61,14 +57,11 @@ async def oauth_callback(req: Request): if state_store.consume(state): code = req.args.get("code") client = AsyncWebClient() # no prepared token needed for this app - oauth_response = await client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - code=code - ) + oauth_response = await client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) logger.info(f"oauth.v2.access response: {oauth_response}") installed_enterprise = oauth_response.get("enterprise") or {} + is_enterprise_install = oauth_response.get("is_enterprise_install") installed_team = oauth_response.get("team") or {} installer = oauth_response.get("authed_user") or {} incoming_webhook = oauth_response.get("incoming_webhook") or {} @@ -93,22 +86,38 @@ async def oauth_callback(req: Request): incoming_webhook_url=incoming_webhook.get("url"), 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"), ) installation_store.save(installation) + html = redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) return HTTPResponse( status=200, - body="Thanks for installing this app!" + headers={ + "Content-Type": "text/html; charset=utf-8", + }, + body=html, ) else: + html = redirect_page_renderer.render_failure_page("the state value is already expired") return HTTPResponse( status=400, - body="Try the installation again (the state value is already expired)" + headers={ + "Content-Type": "text/html; charset=utf-8", + }, + body=html, ) - error = req.args["error"] if "error" in req.args else "" + error = req.args.get("error") if "error" in req.args else "" return HTTPResponse( status=400, - body=f"Something is wrong with the installation (error: {error})" + headers={"Content-Type": "text/html; charset=utf-8"}, + body=redirect_page_renderer.render_failure_page(error), ) @@ -123,19 +132,26 @@ async def oauth_callback(req: Request): signing_secret = os.environ["SLACK_SIGNING_SECRET"] signature_verifier = SignatureVerifier(signing_secret=signing_secret) + @app.post("/slack/events") async def slack_app(req: Request): + data = req.body.decode("utf-8") if not signature_verifier.is_valid( - body=req.body.decode("utf-8"), + body=data, timestamp=req.headers.get("X-Slack-Request-Timestamp"), - signature=req.headers.get("X-Slack-Signature")): + signature=req.headers.get("X-Slack-Signature"), + ): return HTTPResponse(status=403, body="invalid request") - if "command" in req.form \ - and req.form["command"] == "/open-modal": + if data and "url_verification" in data: + body = json.loads(data) + if body.get("type") == "url_verification" and "challenge" in body: + return HTTPResponse(status=200, body=body["challenge"]) + + if "command" in req.form and req.form.get("command") == "/open-modal": try: enterprise_id = req.form.get("enterprise_id") - team_id = req.form["team_id"] + team_id = req.form.get("team_id") bot = installation_store.find_bot( enterprise_id=enterprise_id, team_id=team_id, @@ -146,22 +162,13 @@ async def slack_app(req: Request): client = AsyncWebClient(token=bot_token) await client.views_open( - trigger_id=req.form["trigger_id"], + trigger_id=req.form.get("trigger_id"), view={ "type": "modal", "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, "blocks": [ { "type": "input", @@ -173,10 +180,10 @@ async def slack_app(req: Request): "element": { "action_id": "a-id", "type": "plain_text_input", - } + }, } - ] - } + ], + }, ) return HTTPResponse(status=200, body="") except SlackApiError as e: @@ -184,10 +191,9 @@ async def slack_app(req: Request): return HTTPResponse(status=200, body=f"Failed to open a modal due to {code}") elif "payload" in req.form: - payload = json.loads(req.form["payload"]) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": - submitted_data = payload["view"]["state"]["values"] + payload = json.loads(req.form.get("payload")) + if payload.get("type") == "view_submission" and payload.get("view").get("callback_id") == "modal-id": + submitted_data = payload.get("view").get("state").get("values") print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} return HTTPResponse(status=200, body="") @@ -195,9 +201,8 @@ async def slack_app(req: Request): if __name__ == "__main__": - # export SLACK_TEST_CLIENT_ID=123.123 - # export SLACK_TEST_CLIENT_SECRET=xxx - # export SLACK_TEST_REDIRECT_URI=https://{yours}.ngrok.io/slack/oauth/callback + # export SLACK_CLIENT_ID=123.123 + # export SLACK_CLIENT_SECRET=xxx # export SLACK_SIGNING_SECRET=*** app.run(host="0.0.0.0", port=3000) diff --git a/integration_tests/samples/oauth/oauth_v2_legacy.py b/integration_tests/samples/oauth/oauth_v2_legacy.py deleted file mode 100644 index 896b84bd4..000000000 --- a/integration_tests/samples/oauth/oauth_v2_legacy.py +++ /dev/null @@ -1,251 +0,0 @@ -# ------------------ -# Only for running this script here -import logging -import sys -from os.path import dirname - -sys.path.insert(1, f"{dirname(__file__)}/../../..") -logging.basicConfig(level=logging.DEBUG) -# ------------------ - -# --------------------- -# Flask App for Slack OAuth flow -# --------------------- - -# pip3 install flask -from flask import Flask, request, make_response - -app = Flask(__name__) -app.debug = True - -import os -from uuid import uuid4 -from slack_sdk import WebClient - -client_id = os.environ["SLACK_TEST_CLIENT_ID"] -client_secret = os.environ["SLACK_TEST_CLIENT_SECRET"] -redirect_uri = os.environ["SLACK_TEST_REDIRECT_URI"] -scopes = "app_mentions:read,chat:write" -user_scopes = "search:read" - -logger = logging.getLogger(__name__) - - -class StateService: - def __init__(self): - # no expiration implemented - self.state_values = [] - - def generate(self): - new_value = str(uuid4()) - self.state_values.append(new_value) - return new_value - - def consume(self, state) -> bool: - is_valid = state in self.state_values - if is_valid: - self.state_values.remove(state) - return is_valid - - -class Database: - def __init__(self): - self.tokens = {} - - def save(self, oauth_v2_response): - team_id = oauth_v2_response["team"]["id"] - installer = oauth_v2_response["authed_user"] - self.tokens[team_id] = { - "bot_token": oauth_v2_response["access_token"], - "bot_user_id": oauth_v2_response["bot_user_id"], - "user_id": installer["id"], - "user_token": installer["access_token"] if "access_token" in installer else None, - } - logger.debug(f"all rows: {list(self.tokens.keys())}") - - def find_bot_token(self, team_id: str) -> str: - logger.debug(f"all rows: {list(self.tokens.keys())}, team_id: {team_id}") - installation = self.tokens[team_id] if team_id in self.tokens else None - if installation: - return installation["bot_token"] - else: - return None - - -state_service = StateService() -database = Database() - - -@app.route("/slack/oauth/start", methods=["GET"]) -def oauth_start(): - state = state_service.generate() - return f'' \ - f'' - - -@app.route("/slack/oauth/callback", methods=["GET"]) -def oauth_callback(): - # Retrieve the auth code and state from the request params - if "code" in request.args: - state = request.args["state"] - if state_service.consume(state): - code = request.args["code"] - client = WebClient() # no prepared token needed for this app - response = client.oauth_v2_access( - client_id=client_id, - client_secret=client_secret, - redirect_uri=redirect_uri, - code=code - ) - logger.info(f"oauth.v2.access response: {response}") - database.save(response) - return "Thanks for installing this app!" - else: - return make_response(f"Try the installation again (the state value is already expired)", 400) - - error = request.args["error"] if "error" in request.args else "" - return make_response(f"Something is wrong with the installation (error: {error})", 400) - - -# --------------------- -# Flask App for Slack events -# --------------------- - -import hmac -import hashlib -from time import time -import json - - -def verify_slack_request( - signing_secret: str, - request_body: str, - timestamp: str, - signature: str) -> bool: - """Slack Request Verification - - For more information: https://github.com/slackapi/python-slack-events-api - """ - - if abs(time() - int(timestamp)) > 60 * 5: - return False - - if hasattr(hmac, "compare_digest"): - req = str.encode('v0:' + str(timestamp) + ':') + request_body - request_hash = 'v0=' + hmac.new( - str.encode(signing_secret), - req, hashlib.sha256 - ).hexdigest() - return hmac.compare_digest(request_hash, signature) - else: - # So, we'll compare the signatures explicitly - req = str.encode('v0:' + str(timestamp) + ':') + request_body - request_hash = 'v0=' + hmac.new( - str.encode(signing_secret), - req, hashlib.sha256 - ).hexdigest() - - if len(request_hash) != len(signature): - return False - result = 0 - if isinstance(request_hash, bytes) and isinstance(signature, bytes): - for x, y in zip(request_hash, signature): - result |= x ^ y - else: - for x, y in zip(request_hash, signature): - result |= ord(x) ^ ord(y) - return result == 0 - - -from slack_sdk.errors import SlackApiError - -signing_secret = os.environ["SLACK_SIGNING_SECRET"] - - -@app.route("/slack/events", methods=["POST"]) -def slack_app(): - if not verify_slack_request( - signing_secret=signing_secret, - request_body=request.get_data(), - timestamp=request.headers.get("X-Slack-Request-Timestamp"), - signature=request.headers.get("X-Slack-Signature")): - return make_response("invalid request", 403) - - if "command" in request.form \ - and request.form["command"] == "/do-something": - trigger_id = request.form["trigger_id"] - try: - team_id = request.form["team_id"] - bot_token = database.find_bot_token(team_id) - logger.debug(f"token: {bot_token}") - if not bot_token: - return make_response("Please install this app first!", 200) - - client = WebClient(token=bot_token) - response = client.views_open( - trigger_id=trigger_id, - view={ - "type": "modal", - "callback_id": "modal-id", - "title": { - "type": "plain_text", - "text": "Awesome Modal" - }, - "submit": { - "type": "plain_text", - "text": "Submit" - }, - "close": { - "type": "plain_text", - "text": "Cancel" - }, - "blocks": [ - { - "type": "input", - "block_id": "b-id", - "label": { - "type": "plain_text", - "text": "Input label", - }, - "element": { - "action_id": "a-id", - "type": "plain_text_input", - } - } - ] - } - ) - return make_response("", 200) - except SlackApiError as e: - code = e.response["error"] - return make_response(f"Failed to open a modal due to {code}", 200) - - elif "payload" in request.form: - payload = json.loads(request.form["payload"]) - if payload["type"] == "view_submission" \ - and payload["view"]["callback_id"] == "modal-id": - submitted_data = payload["view"]["state"]["values"] - print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} - return make_response("", 200) - - return make_response("", 404) - - -if __name__ == "__main__": - # export SLACK_TEST_CLIENT_ID=123.123 - # export SLACK_TEST_CLIENT_SECRET=xxx - # export SLACK_TEST_REDIRECT_URI=https://{yours}.ngrok.io/slack/oauth/callback - # export SLACK_SIGNING_SECRET=*** - # export FLASK_ENV=development - - app.run("localhost", 3000) - - # python3 integration_tests/samples/oauth/oauth_v2.py - # ngrok http 3000 - # https://{yours}.ngrok.io/slack/oauth/start diff --git a/integration_tests/samples/openid_connect/app_manifest.yml b/integration_tests/samples/openid_connect/app_manifest.yml new file mode 100644 index 000000000..12eae76fa --- /dev/null +++ b/integration_tests/samples/openid_connect/app_manifest.yml @@ -0,0 +1,22 @@ +_metadata: + major_version: 1 + minor_version: 1 +display_information: + name: openid-connect-app +features: + app_home: + home_tab_enabled: false + messages_tab_enabled: true + messages_tab_read_only_enabled: true +oauth_config: + redirect_urls: + - https://{your-domain}/slack/oauth_redirect + scopes: + user: + - openid + - email + - profile +settings: + org_deploy_enabled: false + socket_mode_enabled: false + token_rotation_enabled: false diff --git a/integration_tests/samples/openid_connect/flask_example.py b/integration_tests/samples/openid_connect/flask_example.py new file mode 100644 index 000000000..644ed31dd --- /dev/null +++ b/integration_tests/samples/openid_connect/flask_example.py @@ -0,0 +1,107 @@ +import json +import logging +import os +import jwt + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.DEBUG) + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +redirect_uri = os.environ["SLACK_REDIRECT_URI"] +scopes = ["openid", "email", "profile"] + +from slack_sdk.web import WebClient +from slack_sdk.oauth import OpenIDConnectAuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.state_store import FileOAuthStateStore + +state_store = FileOAuthStateStore(expiration_seconds=300) + +authorization_url_generator = OpenIDConnectAuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + redirect_uri=redirect_uri, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +from flask import Flask, request, make_response + +app = Flask(__name__) +app.debug = True + + +@app.route("/slack/install", methods=["GET"]) +def oauth_start(): + state = state_store.issue() + url = authorization_url_generator.generate(state=state) + return ( + '' + f'Sign in with Slack' + "" + ) + + +@app.route("/slack/oauth_redirect", methods=["GET"]) +def oauth_callback(): + # Retrieve the auth code and state from the request params + if "code" in request.args: + state = request.args["state"] + if state_store.consume(state): + code = request.args["code"] + try: + token_response = WebClient().openid_connect_token( + client_id=client_id, client_secret=client_secret, code=code + ) + logger.info(f"openid.connect.token response: {token_response}") + id_token = token_response.get("id_token") + claims = jwt.decode(id_token, options={"verify_signature": False}, algorithms=["RS256"]) + logger.info(f"claims (decoded id_token): {claims}") + + user_token = token_response.get("access_token") + user_info_response = WebClient(token=user_token).openid_connect_userInfo() + logger.info(f"openid.connect.userInfo response: {user_info_response}") + return f""" + + + + + +

OpenID Connect Claims

+
{json.dumps(claims, indent=2)}
+

openid.connect.userInfo response

+
{json.dumps(user_info_response.data, indent=2)}
+ + + """ + + except Exception: + logger.exception("Failed to perform openid.connect.token API call") + return redirect_page_renderer.render_failure_page("Failed to perform openid.connect.token API call") + else: + return redirect_page_renderer.render_failure_page("The state value is already expired") + + error = request.args["error"] if "error" in request.args else "" + return redirect_page_renderer.render_failure_page(error) + + +if __name__ == "__main__": + # export SLACK_CLIENT_ID=111.222 + # export SLACK_CLIENT_SECRET=xxx + # export FLASK_ENV=development + # export SLACK_REDIRECT_URI=https://{your-domain}/slack/oauth_redirect + # python3 integration_tests/samples/openid_connect/flask_example.py + + app.run("localhost", 3000) + + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/install diff --git a/integration_tests/samples/openid_connect/requirements.txt b/integration_tests/samples/openid_connect/requirements.txt new file mode 100644 index 000000000..c9aae7b20 --- /dev/null +++ b/integration_tests/samples/openid_connect/requirements.txt @@ -0,0 +1,5 @@ +slack-sdk +Flask>=2,<3 +pyjwt>=2.1,<3 +cryptography>=3.4,<4 +Sanic>=21.3 \ No newline at end of file diff --git a/integration_tests/samples/openid_connect/sanic_example.py b/integration_tests/samples/openid_connect/sanic_example.py new file mode 100644 index 000000000..a7d0f645e --- /dev/null +++ b/integration_tests/samples/openid_connect/sanic_example.py @@ -0,0 +1,128 @@ +import json +import jwt +import logging +import os + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.DEBUG) + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +redirect_uri = os.environ["SLACK_REDIRECT_URI"] +scopes = ["openid", "email", "profile"] + +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.oauth import OpenIDConnectAuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.state_store import FileOAuthStateStore + +state_store = FileOAuthStateStore(expiration_seconds=300) +authorization_url_generator = OpenIDConnectAuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + redirect_uri=redirect_uri, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +# https://sanicframework.org/ +from sanic import Sanic +from sanic.request import Request +from sanic.response import HTTPResponse + +app = Sanic("my-awesome-slack-app") + + +@app.get("/slack/install") +async def oauth_start(req: Request): + state = state_store.issue() + url = authorization_url_generator.generate(state) + response_body = ( + '' + f'Sign in with Slack' + "" + ) + return HTTPResponse( + status=200, + body=response_body, + ) + + +@app.get("/slack/oauth_redirect") +async def oauth_callback(req: Request): + # Retrieve the auth code and state from the request params + if "code" in req.args: + state = req.args.get("state") + if state_store.consume(state): + code = req.args.get("code") + try: + token_response = await AsyncWebClient().openid_connect_token( + client_id=client_id, client_secret=client_secret, code=code + ) + logger.info(f"openid.connect.token response: {token_response}") + id_token = token_response.get("id_token") + claims = jwt.decode(id_token, options={"verify_signature": False}, algorithms=["RS256"]) + logger.info(f"claims (decoded id_token): {claims}") + + user_token = token_response.get("access_token") + user_info_response = await AsyncWebClient(token=user_token).openid_connect_userInfo() + logger.info(f"openid.connect.userInfo response: {user_info_response}") + html = f""" + + + + + +

OpenID Connect Claims

+
{json.dumps(claims, indent=2)}
+

openid.connect.userInfo response

+
{json.dumps(user_info_response.data, indent=2)}
+ + + """ + return HTTPResponse( + status=200, + headers={ + "Content-Type": "text/html; charset=utf-8", + }, + body=html, + ) + + except Exception: + logger.exception("Failed to perform openid.connect.token API call") + html = redirect_page_renderer.render_failure_page("Failed to perform openid.connect.token API call") + return HTTPResponse( + status=400, + headers={"Content-Type": "text/html; charset=utf-8"}, + body=html, + ) + + else: + html = redirect_page_renderer.render_failure_page("The state value is already expired") + return HTTPResponse( + status=400, + headers={"Content-Type": "text/html; charset=utf-8"}, + body=html, + ) + + error = req.args.get("error") if "error" in req.args else "" + return HTTPResponse( + status=400, + headers={"Content-Type": "text/html; charset=utf-8"}, + body=redirect_page_renderer.render_failure_page(error), + ) + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) + # python3 integration_tests/samples/openid_connect/sanic_example.py + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/install diff --git a/integration_tests/samples/readme/async_function_in_framework.py b/integration_tests/samples/readme/async_function_in_framework.py index cface6b14..6b317462a 100644 --- a/integration_tests/samples/readme/async_function_in_framework.py +++ b/integration_tests/samples/readme/async_function_in_framework.py @@ -1,35 +1,23 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # pip3 install sanic # python3 integration_tests/samples/readme/async_function_in_framework.py import os -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.errors import SlackApiError -client = WebClient( - token=os.environ['SLACK_API_TOKEN'], - run_async=True # turn async mode on -) +client = AsyncWebClient(token=os.environ["SLACK_API_TOKEN"]) # Define this as an async function async def send_to_slack(channel, text): try: # Don't forget to have await as the client returns asyncio.Future - response = await client.chat_postMessage( - channel=channel, - text=text - ) + response = await client.chat_postMessage(channel=channel, text=text) assert response["message"]["text"] == text except SlackApiError as e: assert e.response["ok"] is False @@ -45,17 +33,17 @@ async def send_to_slack(channel, text): # e.g., http://localhost:3000/?text=foo&text=bar -@app.route('/') +@app.route("/") async def test(request): - text = 'Hello World!' - if 'text' in request.args: - text = "\t".join(request.args['text']) + text = "Hello World!" + if "text" in request.args: + text = "\t".join(request.args["text"]) try: await send_to_slack(channel="#random", text=text) - return json({'message': 'Done!'}) + return json({"message": "Done!"}) except SlackApiError as e: - return json({'message': f"Failed due to {e.response['error']}"}) + return json({"message": f"Failed due to {e.response['error']}"}) -if __name__ == '__main__': - app.run(host='0.0.0.0', port=3000) +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) diff --git a/integration_tests/samples/readme/async_script.py b/integration_tests/samples/readme/async_script.py index 5b40263c4..88ee6b500 100644 --- a/integration_tests/samples/readme/async_script.py +++ b/integration_tests/samples/readme/async_script.py @@ -1,29 +1,17 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/readme/async_script.py import asyncio import os -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.errors import SlackApiError -client = WebClient( - token=os.environ['SLACK_API_TOKEN'], - run_async=True -) -future = client.chat_postMessage( - channel='#random', - text="Hello world!" -) +client = AsyncWebClient(token=os.environ["SLACK_API_TOKEN"]) +future = client.chat_postMessage(channel="#random", text="Hello world!") loop = asyncio.get_event_loop() try: diff --git a/integration_tests/samples/readme/proxy.py b/integration_tests/samples/readme/proxy.py index 98cac5d2a..f667d007a 100644 --- a/integration_tests/samples/readme/proxy.py +++ b/integration_tests/samples/readme/proxy.py @@ -1,18 +1,12 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/readme/proxy.py import os -from slack import WebClient +from slack_sdk.web import WebClient from ssl import SSLContext sslcert = SSLContext() @@ -20,12 +14,6 @@ # proxy --port 9000 --log-level d proxyinfo = "http://localhost:9000" -client = WebClient( - token=os.environ['SLACK_API_TOKEN'], - ssl=sslcert, - proxy=proxyinfo -) -response = client.chat_postMessage( - channel="#random", - text="Hello World!") +client = WebClient(token=os.environ["SLACK_API_TOKEN"], ssl=sslcert, proxy=proxyinfo) +response = client.chat_postMessage(channel="#random", text="Hello World!") print(response) diff --git a/integration_tests/samples/readme/rtm_client_basics.py b/integration_tests/samples/readme/rtm_client_basics.py index 02117beaf..c97df1115 100644 --- a/integration_tests/samples/readme/rtm_client_basics.py +++ b/integration_tests/samples/readme/rtm_client_basics.py @@ -1,37 +1,27 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/readme/rtm_client_basics.py import os -from slack import RTMClient -from slack.errors import SlackApiError +from slack_sdk.rtm import RTMClient +from slack_sdk.errors import SlackApiError -@RTMClient.run_on(event='message') +@RTMClient.run_on(event="message") def say_hello(**payload): - data = payload['data'] - web_client = payload['web_client'] - rtm_client = payload['rtm_client'] - if 'text' in data and 'Hello' in data.get('text', []): - channel_id = data['channel'] - thread_ts = data['ts'] - user = data['user'] + data = payload["data"] + web_client = payload["web_client"] + rtm_client = payload["rtm_client"] + if "text" in data and "Hello" in data.get("text", []): + channel_id = data["channel"] + thread_ts = data["ts"] + user = data["user"] try: - response = web_client.chat_postMessage( - channel=channel_id, - text=f"Hi <@{user}>!", - thread_ts=thread_ts - ) + response = web_client.chat_postMessage(channel=channel_id, text=f"Hi <@{user}>!", thread_ts=thread_ts) except SlackApiError as e: # You will get a SlackApiError if "ok" is False assert e.response["ok"] is False diff --git a/integration_tests/samples/readme/sending_messages.py b/integration_tests/samples/readme/sending_messages.py index 8f1680050..86728df3d 100644 --- a/integration_tests/samples/readme/sending_messages.py +++ b/integration_tests/samples/readme/sending_messages.py @@ -1,26 +1,18 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # python3 integration_tests/samples/readme/sending_messages.py import os -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError -client = WebClient(token=os.environ['SLACK_API_TOKEN']) +client = WebClient(token=os.environ["SLACK_API_TOKEN"]) try: - response = client.chat_postMessage( - channel='#random', - text="Hello world!") + response = client.chat_postMessage(channel="#random", text="Hello world!") assert response["message"]["text"] == "Hello world!" except SlackApiError as e: # You will get a SlackApiError if "ok" is False diff --git a/integration_tests/samples/readme/uploading_files.py b/integration_tests/samples/readme/uploading_files.py index 6094b31ee..9767c1add 100644 --- a/integration_tests/samples/readme/uploading_files.py +++ b/integration_tests/samples/readme/uploading_files.py @@ -1,28 +1,20 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # export SLACK_API_TOKEN=xoxb-*** # echo 'Hello world!' > tmp.txt # python3 integration_tests/samples/readme/uploading_files.py import os -from slack import WebClient -from slack.errors import SlackApiError +from slack_sdk.web import WebClient +from slack_sdk.errors import SlackApiError -client = WebClient(token=os.environ['SLACK_API_TOKEN']) +client = WebClient(token=os.environ["SLACK_API_TOKEN"]) try: filepath = "./tmp.txt" - response = client.files_upload( - channels='#random', - file=filepath) + response = client.files_upload(channels="#random", file=filepath) assert response["file"] # the uploaded file except SlackApiError as e: # You will get a SlackApiError if "ok" is False diff --git a/integration_tests/samples/rtm_v2/rtm_v2_app.py b/integration_tests/samples/rtm_v2/rtm_v2_app.py new file mode 100644 index 000000000..f67f5e80a --- /dev/null +++ b/integration_tests/samples/rtm_v2/rtm_v2_app.py @@ -0,0 +1,33 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + format="%(asctime)s.%(msecs)03d %(levelname)s %(filename)s (%(lineno)s): %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) +logger = logging.getLogger(__name__) + +import os +from slack_sdk.rtm.v2 import RTMClient +from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN + +if __name__ == "__main__": + rtm = RTMClient( + token=os.environ.get(SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN), + trace_enabled=True, + all_message_trace_enabled=True, + ) + + @rtm.on("message") + def handle(client: RTMClient, event: dict): + client.web_client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + @rtm.on("*") + def handle(client: RTMClient, event: dict): + logger.info(event) + + rtm.start() diff --git a/integration_tests/samples/rtm_v2/rtm_v2_proxy_app.py b/integration_tests/samples/rtm_v2/rtm_v2_proxy_app.py new file mode 100644 index 000000000..0f8e5e8b9 --- /dev/null +++ b/integration_tests/samples/rtm_v2/rtm_v2_proxy_app.py @@ -0,0 +1,38 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + format="%(asctime)s.%(msecs)03d %(levelname)s %(filename)s (%(lineno)s): %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) +logger = logging.getLogger(__name__) + +import os +from slack_sdk.rtm.v2 import RTMClient +from integration_tests.env_variable_names import SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN + +# pip3 install proxy.py +# proxy --port 9000 --log-level d +proxy_url = "http://localhost:9000" + +if __name__ == "__main__": + rtm = RTMClient( + token=os.environ.get(SLACK_SDK_TEST_CLASSIC_APP_BOT_TOKEN), + trace_enabled=True, + all_message_trace_enabled=True, + proxy=proxy_url, + ) + + @rtm.on("message") + def handle(client: RTMClient, event: dict): + client.web_client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + @rtm.on("*") + def handle(client: RTMClient, event: dict): + logger.info(event) + + rtm.start() diff --git a/integration_tests/samples/scim/search_groups.py b/integration_tests/samples/scim/search_groups.py new file mode 100644 index 000000000..1819d4ffa --- /dev/null +++ b/integration_tests/samples/scim/search_groups.py @@ -0,0 +1,12 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from slack_sdk.scim import SCIMClient + +client = SCIMClient(token=os.environ["SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN"]) + +response = client.search_groups(start_index=1, count=2) +print("-----------------------") +print(response.groups) diff --git a/integration_tests/samples/scim/search_groups_async.py b/integration_tests/samples/scim/search_groups_async.py new file mode 100644 index 000000000..b66ca4112 --- /dev/null +++ b/integration_tests/samples/scim/search_groups_async.py @@ -0,0 +1,18 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import asyncio +import os +from slack_sdk.scim.async_client import AsyncSCIMClient + +client = AsyncSCIMClient(token=os.environ["SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN"]) + + +async def main(): + response = await client.search_groups(start_index=1, count=2) + print("-----------------------") + print(response.groups) + + +asyncio.run(main()) diff --git a/integration_tests/samples/scim/search_users.py b/integration_tests/samples/scim/search_users.py new file mode 100644 index 000000000..c0fb156de --- /dev/null +++ b/integration_tests/samples/scim/search_users.py @@ -0,0 +1,12 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from slack_sdk.scim import SCIMClient + +client = SCIMClient(token=os.environ["SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN"]) + +response = client.search_users(start_index=1, count=2) +print("-----------------------") +print(response.users) diff --git a/docs-v2/.nojekyll b/integration_tests/samples/socket_mode/__init__.py similarity index 100% rename from docs-v2/.nojekyll rename to integration_tests/samples/socket_mode/__init__.py diff --git a/integration_tests/samples/socket_mode/aiohttp_example.py b/integration_tests/samples/socket_mode/aiohttp_example.py new file mode 100644 index 000000000..37147dd3b --- /dev/null +++ b/integration_tests/samples/socket_mode/aiohttp_example.py @@ -0,0 +1,36 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import asyncio +import os +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.aiohttp import SocketModeClient + + +async def main(): + client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=AsyncWebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), + trace_enabled=True, + ) + + async def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + await client.send_socket_mode_response(response) + if req.payload["event"]["type"] == "message": + await client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + await client.connect() + await asyncio.sleep(float("inf")) + + +asyncio.run(main()) diff --git a/docs/.nojekyll b/integration_tests/samples/socket_mode/bolt_adapter/__init__.py similarity index 100% rename from docs/.nojekyll rename to integration_tests/samples/socket_mode/bolt_adapter/__init__.py diff --git a/integration_tests/samples/socket_mode/bolt_adapter/aiohttp.py b/integration_tests/samples/socket_mode/bolt_adapter/aiohttp.py new file mode 100644 index 000000000..3ea4e7695 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/aiohttp.py @@ -0,0 +1,58 @@ +import os +from time import time +from typing import Optional + +from slack_sdk.socket_mode.aiohttp import SocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_bolt import App +from .async_base_handler import AsyncBaseSocketModeHandler +from .async_internals import ( + send_async_response, + run_async_bolt_app, +) +from .internals import run_bolt_app +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.response import BoltResponse + + +class SocketModeHandler(AsyncBaseSocketModeHandler): + app: App # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: App, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + async def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = run_bolt_app(self.app, req) + await send_async_response(client, req, bolt_resp, start) + + +class AsyncSocketModeHandler(AsyncBaseSocketModeHandler): + app: AsyncApp # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: AsyncApp, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + async def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = await run_async_bolt_app(self.app, req) + await send_async_response(client, req, bolt_resp, start) diff --git a/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py b/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py new file mode 100644 index 000000000..36311318d --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/async_base_handler.py @@ -0,0 +1,34 @@ +import asyncio +import logging +from typing import Union + +from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_bolt import App +from slack_bolt.app.async_app import AsyncApp + + +class AsyncBaseSocketModeHandler: + app: Union[App, AsyncApp] # type: ignore + client: AsyncBaseSocketModeClient + + async def handle(self, client: AsyncBaseSocketModeClient, req: SocketModeRequest) -> None: + raise NotImplementedError() + + async def connect_async(self): + await self.client.connect() + + async def disconnect_async(self): + await self.client.disconnect() + + async def close_async(self): + await self.client.close() + + async def start_async(self): + await self.connect_async() + if self.app.logger.level > logging.INFO: + print("⚑️ Bolt app is running!") + else: + self.app.logger.info("⚑️ Bolt app is running!") + await asyncio.sleep(float("inf")) diff --git a/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py b/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py new file mode 100644 index 000000000..d80968050 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/async_internals.py @@ -0,0 +1,44 @@ +import json +import logging +from time import time + +from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.response import SocketModeResponse + +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.request.async_request import AsyncBoltRequest +from slack_bolt.response import BoltResponse + + +async def run_async_bolt_app(app: AsyncApp, req: SocketModeRequest): # type: ignore + bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload) + bolt_resp: BoltResponse = await app.async_dispatch(bolt_req) + return bolt_resp + + +async def send_async_response( + client: AsyncBaseSocketModeClient, + req: SocketModeRequest, + bolt_resp: BoltResponse, + start_time: float, +): + if bolt_resp.status == 200: + content_type = bolt_resp.headers.get("content-type", [""])[0] + if bolt_resp.body is None or len(bolt_resp.body) == 0: + await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id)) + elif content_type.startswith("application/json"): + dict_body = json.loads(bolt_resp.body) + await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)) + else: + await client.send_socket_mode_response( + SocketModeResponse( + envelope_id=req.envelope_id, + payload={"text": bolt_resp.body}, + ) + ) + if client.logger.level <= logging.DEBUG: + spent_time = int((time() - start_time) * 1000) + client.logger.debug(f"Response time: {spent_time} milliseconds") + else: + client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})") diff --git a/integration_tests/samples/socket_mode/bolt_adapter/base_handler.py b/integration_tests/samples/socket_mode/bolt_adapter/base_handler.py new file mode 100644 index 000000000..1cc6b2cc1 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/base_handler.py @@ -0,0 +1,32 @@ +import logging +from threading import Event + +from slack_sdk.socket_mode.client import BaseSocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_bolt import App + + +class BaseSocketModeHandler: + app: App # type: ignore + client: BaseSocketModeClient + + def handle(self, client: BaseSocketModeClient, req: SocketModeRequest) -> None: + raise NotImplementedError() + + def connect(self): + self.client.connect() + + def disconnect(self): + self.client.disconnect() + + def close(self): + self.client.close() + + def start(self): + self.connect() + if self.app.logger.level > logging.INFO: + print("⚑️ Bolt app is running!") + else: + self.app.logger.info("⚑️ Bolt app is running!") + Event().wait() diff --git a/integration_tests/samples/socket_mode/bolt_adapter/builtin.py b/integration_tests/samples/socket_mode/bolt_adapter/builtin.py new file mode 100644 index 000000000..06f014f59 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/builtin.py @@ -0,0 +1,32 @@ +import os +from time import time +from typing import Optional + +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.builtin import SocketModeClient + +from slack_bolt import App +from .base_handler import BaseSocketModeHandler +from .internals import run_bolt_app, send_response +from slack_bolt.response import BoltResponse + + +class SocketModeHandler(BaseSocketModeHandler): + app: App # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: App, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = run_bolt_app(self.app, req) + send_response(client, req, bolt_resp, start) diff --git a/integration_tests/samples/socket_mode/bolt_adapter/internals.py b/integration_tests/samples/socket_mode/bolt_adapter/internals.py new file mode 100644 index 000000000..065bb0204 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/internals.py @@ -0,0 +1,42 @@ +import json +import logging +from time import time + +from slack_sdk.socket_mode.client import BaseSocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.response import SocketModeResponse + +from slack_bolt.app import App +from slack_bolt.request import BoltRequest +from slack_bolt.response import BoltResponse + + +def run_bolt_app(app: App, req: SocketModeRequest): # type: ignore + bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload) + bolt_resp: BoltResponse = app.dispatch(bolt_req) + return bolt_resp + + +def send_response( + client: BaseSocketModeClient, + req: SocketModeRequest, + bolt_resp: BoltResponse, + start_time: float, +): + if bolt_resp.status == 200: + content_type = bolt_resp.headers.get("content-type", [""])[0] + if bolt_resp.body is None or len(bolt_resp.body) == 0: + client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id)) + elif content_type.startswith("application/json"): + dict_body = json.loads(bolt_resp.body) + client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)) + else: + client.send_socket_mode_response( + SocketModeResponse(envelope_id=req.envelope_id, payload={"text": bolt_resp.body}) + ) + + if client.logger.level <= logging.DEBUG: + spent_time = int((time() - start_time) * 1000) + client.logger.debug(f"Response time: {spent_time} milliseconds") + else: + client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})") diff --git a/integration_tests/samples/socket_mode/bolt_adapter/websocket_client.py b/integration_tests/samples/socket_mode/bolt_adapter/websocket_client.py new file mode 100644 index 000000000..850e534f4 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/websocket_client.py @@ -0,0 +1,32 @@ +import os +from time import time +from typing import Optional + +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.websocket_client import SocketModeClient + +from slack_bolt import App +from .base_handler import BaseSocketModeHandler +from .internals import run_bolt_app, send_response +from slack_bolt.response import BoltResponse + + +class SocketModeHandler(BaseSocketModeHandler): + app: App # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: App, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = run_bolt_app(self.app, req) + send_response(client, req, bolt_resp, start) diff --git a/integration_tests/samples/socket_mode/bolt_adapter/websockets.py b/integration_tests/samples/socket_mode/bolt_adapter/websockets.py new file mode 100644 index 000000000..2567014a6 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_adapter/websockets.py @@ -0,0 +1,58 @@ +import os +from time import time +from typing import Optional + +from slack_sdk.socket_mode.websockets import SocketModeClient +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_bolt import App +from .async_base_handler import AsyncBaseSocketModeHandler +from .async_internals import ( + send_async_response, + run_async_bolt_app, +) +from .internals import run_bolt_app +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.response import BoltResponse + + +class SocketModeHandler(AsyncBaseSocketModeHandler): + app: App # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: App, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + async def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = run_bolt_app(self.app, req) + await send_async_response(client, req, bolt_resp, start) + + +class AsyncSocketModeHandler(AsyncBaseSocketModeHandler): + app: AsyncApp # type: ignore + app_token: str + client: SocketModeClient + + def __init__( # type: ignore + self, + app: AsyncApp, # type: ignore + app_token: Optional[str] = None, + ): + self.app = app + self.app_token = app_token or os.environ["SLACK_APP_TOKEN"] + self.client = SocketModeClient(app_token=self.app_token) + self.client.socket_mode_request_listeners.append(self.handle) + + async def handle(self, client: SocketModeClient, req: SocketModeRequest) -> None: + start = time() + bolt_resp: BoltResponse = await run_async_bolt_app(self.app, req) + await send_async_response(client, req, bolt_resp, start) diff --git a/integration_tests/samples/socket_mode/bolt_aiohttp_async_example.py b/integration_tests/samples/socket_mode/bolt_aiohttp_async_example.py new file mode 100644 index 000000000..9c392e35f --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_aiohttp_async_example.py @@ -0,0 +1,49 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.context.async_context import AsyncBoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = AsyncApp(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +async def mention(context: AsyncBoltContext): + await context.say(":wave: Hi there!") + + +@app.event("message") +async def message(context: AsyncBoltContext, event: dict): + await context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +async def hello_command(ack, body): + user_id = body["user_id"] + await ack(f"Hi <@{user_id}>!") + + +async def main(): + from bolt_adapter.aiohttp import AsyncSocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + await AsyncSocketModeHandler(app, app_token).start_async() + + +if __name__ == "__main__": + import asyncio + + asyncio.run(main()) + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_aiohttp_example.py b/integration_tests/samples/socket_mode/bolt_aiohttp_example.py new file mode 100644 index 000000000..16d58f421 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_aiohttp_example.py @@ -0,0 +1,50 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = App(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +async def main(): + from bolt_adapter.aiohttp import SocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + await SocketModeHandler(app, app_token).start_async() + + +if __name__ == "__main__": + import asyncio + + asyncio.run(main()) + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_builtin_example.py b/integration_tests/samples/socket_mode/bolt_builtin_example.py new file mode 100644 index 000000000..319fdefed --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_builtin_example.py @@ -0,0 +1,44 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = App(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + from bolt_adapter.builtin import SocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + SocketModeHandler(app, app_token).start() + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_async_example.py b/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_async_example.py new file mode 100644 index 000000000..225d27e27 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_async_example.py @@ -0,0 +1,62 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.context.async_context import AsyncBoltContext +from slack_bolt.oauth.async_oauth_settings import AsyncOAuthSettings + +app = AsyncApp( + signing_secret=os.environ["SLACK_SIGNING_SECRET"], + oauth_settings=AsyncOAuthSettings( + client_id=os.environ["SLACK_CLIENT_ID"], + client_secret=os.environ["SLACK_CLIENT_SECRET"], + scopes=os.environ["SLACK_SCOPES"].split(","), + ), +) + + +@app.event("app_mention") +async def mention(context: AsyncBoltContext): + await context.say(":wave: Hi there!") + + +@app.event("message") +async def message(context: AsyncBoltContext, event: dict): + await context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +async def hello_command(ack, body): + user_id = body["user_id"] + await ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + import asyncio + from asyncio import Future + + async def socket_mode_runner(): + from bolt_adapter.aiohttp import AsyncSocketModeHandler + + app_token = os.environ.get("SLACK_APP_TOKEN") + await AsyncSocketModeHandler(app, app_token).connect_async() + await asyncio.sleep(float("inf")) + + _: Future = asyncio.ensure_future(socket_mode_runner()) + app.start() + + # export SLACK_APP_TOKEN= + # export SLACK_SIGNING_SECRET= + # export SLACK_CLIENT_ID= + # export SLACK_CLIENT_SECRET= + # export SLACK_SCOPES= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_example.py b/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_example.py new file mode 100644 index 000000000..7b19d1413 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_oauth_aiohttp_example.py @@ -0,0 +1,68 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext +from slack_bolt.oauth.oauth_settings import OAuthSettings + +app = App( + signing_secret=os.environ["SLACK_SIGNING_SECRET"], + oauth_settings=OAuthSettings( + client_id=os.environ["SLACK_CLIENT_ID"], + client_secret=os.environ["SLACK_CLIENT_SECRET"], + scopes=os.environ["SLACK_SCOPES"].split(","), + ), +) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + + def run_socket_mode_app(): + import asyncio + from bolt_adapter.aiohttp import AsyncSocketModeHandler + + async def socket_mode_app(): + app_token = os.environ.get("SLACK_APP_TOKEN") + await AsyncSocketModeHandler(app, app_token).connect_async() + await asyncio.sleep(float("inf")) + + asyncio.run(socket_mode_app()) + + from concurrent.futures.thread import ThreadPoolExecutor + + socket_mode_thread = ThreadPoolExecutor(1) + socket_mode_thread.submit(run_socket_mode_app) + + app.start() + + # export SLACK_APP_TOKEN= + # export SLACK_SIGNING_SECRET= + # export SLACK_CLIENT_ID= + # export SLACK_CLIENT_SECRET= + # export SLACK_SCOPES= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_oauth_builtin_example.py b/integration_tests/samples/socket_mode/bolt_oauth_builtin_example.py new file mode 100644 index 000000000..cf8574333 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_oauth_builtin_example.py @@ -0,0 +1,56 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext +from slack_bolt.oauth.oauth_settings import OAuthSettings + +app = App( + signing_secret=os.environ["SLACK_SIGNING_SECRET"], + oauth_settings=OAuthSettings( + client_id=os.environ["SLACK_CLIENT_ID"], + client_secret=os.environ["SLACK_CLIENT_SECRET"], + scopes=os.environ["SLACK_SCOPES"].split(","), + ), +) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + from bolt_adapter.builtin import SocketModeHandler + + app_token = os.environ.get("SLACK_APP_TOKEN") + SocketModeHandler(app, app_token).connect() + + app.start() + + # export SLACK_APP_TOKEN= + # export SLACK_SIGNING_SECRET= + # export SLACK_CLIENT_ID= + # export SLACK_CLIENT_SECRET= + # export SLACK_SCOPES= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_oauth_websocket_client_example.py b/integration_tests/samples/socket_mode/bolt_oauth_websocket_client_example.py new file mode 100644 index 000000000..74a78d3ad --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_oauth_websocket_client_example.py @@ -0,0 +1,56 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext +from slack_bolt.oauth.oauth_settings import OAuthSettings + +app = App( + signing_secret=os.environ["SLACK_SIGNING_SECRET"], + oauth_settings=OAuthSettings( + client_id=os.environ["SLACK_CLIENT_ID"], + client_secret=os.environ["SLACK_CLIENT_SECRET"], + scopes=os.environ["SLACK_SCOPES"].split(","), + ), +) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + from bolt_adapter.websocket_client import SocketModeHandler + + app_token = os.environ.get("SLACK_APP_TOKEN") + SocketModeHandler(app, app_token).connect() + + app.start() + + # export SLACK_APP_TOKEN= + # export SLACK_SIGNING_SECRET= + # export SLACK_CLIENT_ID= + # export SLACK_CLIENT_SECRET= + # export SLACK_SCOPES= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_websocket_client_example.py b/integration_tests/samples/socket_mode/bolt_websocket_client_example.py new file mode 100644 index 000000000..397fc4584 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_websocket_client_example.py @@ -0,0 +1,44 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = App(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +if __name__ == "__main__": + from bolt_adapter.websocket_client import SocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + SocketModeHandler(app, app_token).start() + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_websockets_async_example.py b/integration_tests/samples/socket_mode/bolt_websockets_async_example.py new file mode 100644 index 000000000..6db031d06 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_websockets_async_example.py @@ -0,0 +1,49 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from slack_bolt.app.async_app import AsyncApp +from slack_bolt.context.async_context import AsyncBoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = AsyncApp(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +async def mention(context: AsyncBoltContext): + await context.say(":wave: Hi there!") + + +@app.event("message") +async def message(context: AsyncBoltContext, event: dict): + await context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +async def hello_command(ack, body): + user_id = body["user_id"] + await ack(f"Hi <@{user_id}>!") + + +async def main(): + from bolt_adapter.websockets import AsyncSocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + await AsyncSocketModeHandler(app, app_token).start_async() + + +if __name__ == "__main__": + import asyncio + + asyncio.run(main()) + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/bolt_websockets_example.py b/integration_tests/samples/socket_mode/bolt_websockets_example.py new file mode 100644 index 000000000..04d8f7cc6 --- /dev/null +++ b/integration_tests/samples/socket_mode/bolt_websockets_example.py @@ -0,0 +1,50 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os + +from slack_bolt.app import App +from slack_bolt.context import BoltContext + +bot_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN") +app = App(signing_secret="will-be-removed-soon", token=bot_token) + + +@app.event("app_mention") +def mention(context: BoltContext): + context.say(":wave: Hi there!") + + +@app.event("message") +def message(context: BoltContext, event: dict): + context.client.reactions_add( + channel=event["channel"], + timestamp=event["ts"], + name="eyes", + ) + + +@app.command("/hello-socket-mode") +def hello_command(ack, body): + user_id = body["user_id"] + ack(f"Hi <@{user_id}>!") + + +async def main(): + from bolt_adapter.websockets import SocketModeHandler + + app_token = os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN") + await SocketModeHandler(app, app_token).start_async() + + +if __name__ == "__main__": + import asyncio + + asyncio.run(main()) + + # export SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN= + # export SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN= + # pip install .[optional] + # pip install slack_bolt + # python integration_tests/samples/socket_mode/{this file name}.py diff --git a/integration_tests/samples/socket_mode/builtin_example.py b/integration_tests/samples/socket_mode/builtin_example.py new file mode 100644 index 000000000..d4104238d --- /dev/null +++ b/integration_tests/samples/socket_mode/builtin_example.py @@ -0,0 +1,37 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + format="%(asctime)s.%(msecs)03d %(levelname)s %(pathname)s (%(lineno)s): %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode import SocketModeClient + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), + trace_enabled=True, + all_message_trace_enabled=True, +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/builtin_proxy_auth_example.py b/integration_tests/samples/socket_mode/builtin_proxy_auth_example.py new file mode 100644 index 000000000..be65ddba2 --- /dev/null +++ b/integration_tests/samples/socket_mode/builtin_proxy_auth_example.py @@ -0,0 +1,47 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + # format="%(asctime)s.%(msecs)03d %(levelname)s %(pathname)s (%(lineno)s): %(message)s", + # datefmt="%Y-%m-%d %H:%M:%S", +) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode import SocketModeClient + +# https://github.com/seratch/my-proxy-server +# go build && my-proxy-server -a -u user -p pass/word +proxy_url = "http://user:pass%2Fword@localhost:9000" + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient( + token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN"), + proxy=proxy_url, + ), + proxy=proxy_url, + # proxy="http://localhost:9000", + # proxy_headers={"Proxy-Authorization": "Basic dXNlcjpwYXNz"}, + trace_enabled=True, + all_message_trace_enabled=True, +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/builtin_proxy_env_variable_example.py b/integration_tests/samples/socket_mode/builtin_proxy_env_variable_example.py new file mode 100644 index 000000000..f564756e1 --- /dev/null +++ b/integration_tests/samples/socket_mode/builtin_proxy_env_variable_example.py @@ -0,0 +1,44 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + # format="%(asctime)s.%(msecs)03d %(levelname)s %(pathname)s (%(lineno)s): %(message)s", + # datefmt="%Y-%m-%d %H:%M:%S", +) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode import SocketModeClient + +# pip3 install proxy.py +# proxy --port 9000 --log-level d +os.environ["HTTPS_PROXY"] = "http://localhost:9000" + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient( + token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN"), + ), + proxy_headers={"Proxy-Authorization": "Basic dXNlcjpwYXNz"}, + trace_enabled=True, + all_message_trace_enabled=True, +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/builtin_proxy_example.py b/integration_tests/samples/socket_mode/builtin_proxy_example.py new file mode 100644 index 000000000..3160d7733 --- /dev/null +++ b/integration_tests/samples/socket_mode/builtin_proxy_example.py @@ -0,0 +1,45 @@ +import logging + +logging.basicConfig( + level=logging.DEBUG, + # format="%(asctime)s.%(msecs)03d %(levelname)s %(pathname)s (%(lineno)s): %(message)s", + # datefmt="%Y-%m-%d %H:%M:%S", +) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode import SocketModeClient + +# pip3 install proxy.py +# proxy --port 9000 --log-level d +proxy_url = "http://localhost:9000" + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient( + token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN"), + proxy=proxy_url, + ), + proxy=proxy_url, + trace_enabled=True, + all_message_trace_enabled=True, +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/websocket_client_example.py b/integration_tests/samples/socket_mode/websocket_client_example.py new file mode 100644 index 000000000..d14834efb --- /dev/null +++ b/integration_tests/samples/socket_mode/websocket_client_example.py @@ -0,0 +1,32 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.websocket_client import SocketModeClient + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), + trace_enabled=True, +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/websocket_client_proxy_example.py b/integration_tests/samples/socket_mode/websocket_client_proxy_example.py new file mode 100644 index 000000000..20126e3d9 --- /dev/null +++ b/integration_tests/samples/socket_mode/websocket_client_proxy_example.py @@ -0,0 +1,42 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import os +from threading import Event +from slack_sdk.web import WebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.websocket_client import SocketModeClient + +client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=WebClient( + token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN"), + # pip3 install proxy.py + # proxy --port 9000 --log-level d + proxy="http://localhost:9000", + ), + trace_enabled=True, + # pip3 install proxy.py + # proxy --port 9000 --log-level d + http_proxy_host="localhost", + http_proxy_port=9000, + http_proxy_auth=("user", "pass"), +) + +if __name__ == "__main__": + + def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + client.send_socket_mode_response(response) + client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + client.connect() + Event().wait() diff --git a/integration_tests/samples/socket_mode/websockets_example.py b/integration_tests/samples/socket_mode/websockets_example.py new file mode 100644 index 000000000..6129a8a42 --- /dev/null +++ b/integration_tests/samples/socket_mode/websockets_example.py @@ -0,0 +1,35 @@ +import logging + +logging.basicConfig(level=logging.DEBUG) + +import asyncio +import os +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.socket_mode.response import SocketModeResponse +from slack_sdk.socket_mode.request import SocketModeRequest +from slack_sdk.socket_mode.websockets import SocketModeClient + + +async def main(): + client = SocketModeClient( + app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"), + web_client=AsyncWebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")), + ) + + async def process(client: SocketModeClient, req: SocketModeRequest): + if req.type == "events_api": + response = SocketModeResponse(envelope_id=req.envelope_id) + await client.send_socket_mode_response(response) + + await client.web_client.reactions_add( + name="eyes", + channel=req.payload["event"]["channel"], + timestamp=req.payload["event"]["ts"], + ) + + client.socket_mode_request_listeners.append(process) + await client.connect() + await asyncio.sleep(float("inf")) + + +asyncio.run(main()) diff --git a/integration_tests/samples/token_rotation/.gitignore b/integration_tests/samples/token_rotation/.gitignore new file mode 100644 index 000000000..e6905a239 --- /dev/null +++ b/integration_tests/samples/token_rotation/.gitignore @@ -0,0 +1 @@ +.env* \ No newline at end of file diff --git a/integration_tests/samples/token_rotation/oauth.py b/integration_tests/samples/token_rotation/oauth.py new file mode 100644 index 000000000..4fb977244 --- /dev/null +++ b/integration_tests/samples/token_rotation/oauth.py @@ -0,0 +1,261 @@ +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +# pip3 install flask +from typing import Optional + +from integration_tests.samples.token_rotation.util import ( + parse_body, + extract_enterprise_id, + extract_user_id, + extract_team_id, + extract_is_enterprise_install, + extract_content_type, +) + +import logging +import os +from slack_sdk.web import WebClient +from slack_sdk.oauth.token_rotation import TokenRotator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.installation_store import FileInstallationStore, Installation +from slack_sdk.oauth.state_store import FileOAuthStateStore + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +scopes = ["app_mentions:read", "chat:write", "commands"] +user_scopes = ["search:read"] + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.DEBUG) + +state_store = FileOAuthStateStore(expiration_seconds=300) +installation_store = FileInstallationStore() +token_rotator = TokenRotator( + client_id=client_id, + client_secret=client_secret, +) + +# --------------------- +# Flask App for Slack events +# --------------------- + +import json +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier + +signing_secret = os.environ["SLACK_SIGNING_SECRET"] +signature_verifier = SignatureVerifier(signing_secret=signing_secret) + + +def rotate_tokens( + enterprise_id: Optional[str] = None, + team_id: Optional[str] = None, + user_id: Optional[str] = None, + is_enterprise_install: Optional[bool] = None, +): + installation = installation_store.find_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + is_enterprise_install=is_enterprise_install, + ) + if installation is not None: + updated_installation = token_rotator.perform_token_rotation( + installation=installation, + minutes_before_expiration=60 * 24 * 365, # one year for testing + ) + if updated_installation is not None: + installation_store.save(updated_installation) + + +from flask import Flask, request, make_response + +app = Flask(__name__) +app.debug = True + + +@app.route("/slack/events", methods=["POST"]) +def slack_app(): + if not signature_verifier.is_valid( + body=request.get_data(), + timestamp=request.headers.get("X-Slack-Request-Timestamp"), + signature=request.headers.get("X-Slack-Signature"), + ): + return make_response("invalid request", 403) + + raw_body = request.data.decode("utf-8") + body = parse_body(body=raw_body, content_type=extract_content_type(request.headers)) + rotate_tokens( + enterprise_id=extract_enterprise_id(body), + team_id=extract_team_id(body), + user_id=extract_user_id(body), + is_enterprise_install=extract_is_enterprise_install(body), + ) + + if "command" in request.form and request.form["command"] == "/token-rotation-modal": + try: + enterprise_id = request.form.get("enterprise_id") + team_id = request.form["team_id"] + bot = installation_store.find_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + bot_token = bot.bot_token if bot else None + if not bot_token: + return make_response("Please install this app first!", 200) + + client = WebClient(token=bot_token) + trigger_id = request.form["trigger_id"] + response = client.views_open( + trigger_id=trigger_id, + view={ + "type": "modal", + "callback_id": "modal-id", + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, + "blocks": [ + { + "type": "input", + "block_id": "b-id", + "label": { + "type": "plain_text", + "text": "Input label", + }, + "element": { + "action_id": "a-id", + "type": "plain_text_input", + }, + } + ], + }, + ) + return make_response("", 200) + except SlackApiError as e: + code = e.response["error"] + return make_response(f"Failed to open a modal due to {code}", 200) + + elif "payload" in request.form: + payload = json.loads(request.form["payload"]) + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": + submitted_data = payload["view"]["state"]["values"] + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + return make_response("", 200) + + else: + if raw_body.startswith("{"): + event_payload = json.loads(raw_body) + logger.info(f"Events API payload: {event_payload}") + if event_payload.get("type") == "url_verification": + return make_response(event_payload.get("challenge"), 200) + return make_response("", 200) + + return make_response("", 404) + + +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +authorization_url_generator = AuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + user_scopes=user_scopes, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +@app.route("/slack/install", methods=["GET"]) +def oauth_start(): + state = state_store.issue() + url = authorization_url_generator.generate(state) + return ( + '' + f'' + f'' + "" + ) + + +@app.route("/slack/oauth_redirect", methods=["GET"]) +def oauth_callback(): + # Retrieve the auth code and state from the request params + if "code" in request.args: + state = request.args["state"] + if state_store.consume(state): + code = request.args["code"] + client = WebClient() # no prepared token needed for this app + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) + logger.info(f"oauth.v2.access response: {oauth_response}") + + installed_enterprise = oauth_response.get("enterprise", {}) + is_enterprise_install = oauth_response.get("is_enterprise_install") + installed_team = oauth_response.get("team", {}) + installer = oauth_response.get("authed_user", {}) + incoming_webhook = oauth_response.get("incoming_webhook", {}) + + bot_token = oauth_response.get("access_token") + # NOTE: oauth.v2.access doesn't include bot_id in response + bot_id = None + enterprise_url = None + if bot_token is not None: + auth_test = client.auth_test(token=bot_token) + bot_id = auth_test["bot_id"] + if is_enterprise_install is True: + enterprise_url = auth_test.get("url") + + installation = 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"), # comma-separated string + bot_refresh_token=oauth_response.get("refresh_token"), + bot_token_expires_in=oauth_response.get("expires_in"), + user_id=installer.get("id"), + user_token=installer.get("access_token"), + user_scopes=installer.get("scope"), # comma-separated string + user_refresh_token=installer.get("refresh_token"), + user_token_expires_in=installer.get("expires_in"), + 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"), + ) + installation_store.save(installation) + return redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) + else: + return redirect_page_renderer.render_failure_page("the state value is already expired") + + error = request.args["error"] if "error" in request.args else "" + return redirect_page_renderer.render_failure_page(error) + + +if __name__ == "__main__": + # export SLACK_CLIENT_ID=123.123 + # export SLACK_CLIENT_SECRET=xxx + # export SLACK_SIGNING_SECRET=*** + # export FLASK_ENV=development + + app.run("localhost", 3000) + + # python3 integration_tests/samples/token_rotation/oauth.py + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/oauth/start diff --git a/integration_tests/samples/token_rotation/oauth_async.py b/integration_tests/samples/token_rotation/oauth_async.py new file mode 100644 index 000000000..319c718f9 --- /dev/null +++ b/integration_tests/samples/token_rotation/oauth_async.py @@ -0,0 +1,265 @@ +# --------------------- +# Sanic App for Slack OAuth flow +# --------------------- + +from typing import Optional + +from integration_tests.samples.token_rotation.util import ( + parse_body, + extract_enterprise_id, + extract_user_id, + extract_team_id, + extract_is_enterprise_install, + extract_content_type, +) + +import logging +import os +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.oauth.token_rotation.async_rotator import AsyncTokenRotator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.installation_store import FileInstallationStore, Installation +from slack_sdk.oauth.state_store import FileOAuthStateStore + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +scopes = ["app_mentions:read", "chat:write", "commands"] +user_scopes = ["search:read"] + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.DEBUG) + +state_store = FileOAuthStateStore(expiration_seconds=300) +installation_store = FileInstallationStore() +token_rotator = AsyncTokenRotator( + client_id=client_id, + client_secret=client_secret, +) + +# --------------------- +# Sanic App for Slack events +# --------------------- + +import json +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier + +signing_secret = os.environ["SLACK_SIGNING_SECRET"] +signature_verifier = SignatureVerifier(signing_secret=signing_secret) + + +async def rotate_tokens( + enterprise_id: Optional[str] = None, + team_id: Optional[str] = None, + user_id: Optional[str] = None, + is_enterprise_install: Optional[bool] = None, +): + installation = await installation_store.async_find_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + is_enterprise_install=is_enterprise_install, + ) + if installation is not None: + updated_installation = await token_rotator.perform_token_rotation( + installation=installation, + minutes_before_expiration=60 * 24 * 365, # one year for testing + ) + if updated_installation is not None: + await installation_store.async_save(updated_installation) + + +# https://sanicframework.org/ +from sanic import Sanic +from sanic.request import Request +from sanic.response import HTTPResponse + +app = Sanic("my-awesome-slack-app") + + +@app.post("/slack/events") +async def slack_app(req: Request): + if not signature_verifier.is_valid( + body=req.body.decode("utf-8"), + timestamp=req.headers.get("X-Slack-Request-Timestamp"), + signature=req.headers.get("X-Slack-Signature"), + ): + return HTTPResponse(status=403, body="invalid request") + + raw_body = req.body.decode("utf-8") + body = parse_body(body=raw_body, content_type=extract_content_type(req.headers)) + await rotate_tokens( + enterprise_id=extract_enterprise_id(body), + team_id=extract_team_id(body), + user_id=extract_user_id(body), + is_enterprise_install=extract_is_enterprise_install(body), + ) + + if "command" in req.form and req.form.get("command") == "/token-rotation-modal": + try: + enterprise_id = req.form.get("enterprise_id") + team_id = req.form.get("team_id") + bot = await installation_store.async_find_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + bot_token = bot.bot_token if bot else None + if not bot_token: + return HTTPResponse(status=200, body="Please install this app first!") + + client = AsyncWebClient(token=bot_token) + await client.views_open( + trigger_id=req.form.get("trigger_id"), + view={ + "type": "modal", + "callback_id": "modal-id", + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, + "blocks": [ + { + "type": "input", + "block_id": "b-id", + "label": { + "type": "plain_text", + "text": "Input label", + }, + "element": { + "action_id": "a-id", + "type": "plain_text_input", + }, + } + ], + }, + ) + return HTTPResponse(status=200, body="") + except SlackApiError as e: + code = e.response["error"] + return HTTPResponse(status=200, body=f"Failed to open a modal due to {code}") + + elif "payload" in req.form: + payload = json.loads(req.form.get("payload")) + if payload.get("type") == "view_submission" and payload.get("view").get("callback_id") == "modal-id": + submitted_data = payload.get("view").get("state").get("values") + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + return HTTPResponse(status=200, body="") + + else: + if raw_body.startswith("{"): + event_payload = json.loads(raw_body) + if event_payload.get("type") == "url_verification": + return HTTPResponse(status=200, body=event_payload.get("challenge")) + return HTTPResponse(status=200, body="") + + return HTTPResponse(status=404, body="Not found") + + +# --------------------- +# Sanic App for Slack OAuth flow +# --------------------- + +authorization_url_generator = AuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + user_scopes=user_scopes, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +@app.get("/slack/install") +async def oauth_start(req: Request): + state = state_store.issue() + url = authorization_url_generator.generate(state) + response_body = ( + '' + f'' + f'' + "" + ) + return HTTPResponse( + status=200, + body=response_body, + ) + + +@app.get("/slack/oauth_redirect") +async def oauth_callback(req: Request): + # Retrieve the auth code and state from the request params + if "code" in req.args: + state = req.args.get("state") + if state_store.consume(state): + code = req.args.get("code") + client = AsyncWebClient() # no prepared token needed for this app + oauth_response = await client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) + logger.info(f"oauth.v2.access response: {oauth_response}") + + installed_enterprise = oauth_response.get("enterprise") or {} + installed_team = oauth_response.get("team") or {} + installer = oauth_response.get("authed_user") or {} + incoming_webhook = oauth_response.get("incoming_webhook") or {} + bot_token = oauth_response.get("access_token") + # NOTE: oauth.v2.access doesn't include bot_id in response + bot_id = None + if bot_token is not None: + auth_test = await client.auth_test(token=bot_token) + bot_id = auth_test["bot_id"] + + installation = Installation( + app_id=oauth_response.get("app_id"), + enterprise_id=installed_enterprise.get("id"), + team_id=installed_team.get("id"), + bot_token=bot_token, + bot_id=bot_id, + bot_user_id=oauth_response.get("bot_user_id"), + bot_scopes=oauth_response.get("scope"), # comma-separated string + bot_refresh_token=oauth_response.get("refresh_token"), + bot_token_expires_in=oauth_response.get("expires_in"), + user_id=installer.get("id"), + user_token=installer.get("access_token"), + user_scopes=installer.get("scope"), # comma-separated string + user_refresh_token=installer.get("refresh_token"), + user_token_expires_in=installer.get("expires_in"), + incoming_webhook_url=incoming_webhook.get("url"), + incoming_webhook_channel_id=incoming_webhook.get("channel_id"), + incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), + ) + await installation_store.async_save(installation) + html = redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) + return HTTPResponse( + status=200, + headers={ + "Content-Type": "text/html; charset=utf-8", + }, + body=html, + ) + else: + html = redirect_page_renderer.render_failure_page("the state value is already expired") + return HTTPResponse( + status=400, + headers={ + "Content-Type": "text/html; charset=utf-8", + }, + body=html, + ) + + error = req.args.get("error") if "error" in req.args else "" + return HTTPResponse( + status=400, + headers={"Content-Type": "text/html; charset=utf-8"}, + body=redirect_page_renderer.render_failure_page(error), + ) + + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=3000) + # python3 integration_tests/samples/token_rotation/oauth_async.py + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/install diff --git a/integration_tests/samples/token_rotation/oauth_sqlalchemy.py b/integration_tests/samples/token_rotation/oauth_sqlalchemy.py new file mode 100644 index 000000000..df52beac7 --- /dev/null +++ b/integration_tests/samples/token_rotation/oauth_sqlalchemy.py @@ -0,0 +1,290 @@ +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +# pip3 install flask +from typing import Optional + +from integration_tests.samples.token_rotation.util import ( + parse_body, + extract_enterprise_id, + extract_user_id, + extract_team_id, + extract_is_enterprise_install, + extract_content_type, +) + +import logging +import os + +from slack_sdk.oauth.installation_store.sqlalchemy import SQLAlchemyInstallationStore +from slack_sdk.web import WebClient +from slack_sdk.oauth.token_rotation import TokenRotator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.installation_store import Installation +from slack_sdk.oauth.state_store.sqlalchemy import SQLAlchemyOAuthStateStore + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +scopes = ["app_mentions:read", "chat:write", "commands"] +user_scopes = ["search:read"] + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) +logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) + +import sqlalchemy +from sqlalchemy.engine import Engine + +database_url = "sqlite:///slackapp.db" +# database_url = "postgresql://localhost/slackapp" # pip install psycopg2 +engine: Engine = sqlalchemy.create_engine(database_url) + +installation_store = SQLAlchemyInstallationStore( + client_id=client_id, + engine=engine, + logger=logger, +) +token_rotator = TokenRotator( + client_id=client_id, + client_secret=client_secret, +) + +state_store = SQLAlchemyOAuthStateStore( + engine=engine, + logger=logger, + expiration_seconds=300, +) + +try: + engine.execute("select count(*) from slack_bots") +except Exception as e: + installation_store.metadata.create_all(engine) + +try: + engine.execute("select count(*) from slack_oauth_states") +except Exception as e: + state_store.metadata.create_all(engine) + +# --------------------- +# Flask App for Slack events +# --------------------- + +import json +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier + +signing_secret = os.environ["SLACK_SIGNING_SECRET"] +signature_verifier = SignatureVerifier(signing_secret=signing_secret) + + +def rotate_tokens( + enterprise_id: Optional[str] = None, + team_id: Optional[str] = None, + user_id: Optional[str] = None, + is_enterprise_install: Optional[bool] = None, +): + installation = installation_store.find_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + is_enterprise_install=is_enterprise_install, + ) + if installation is not None: + updated_installation = token_rotator.perform_token_rotation( + installation=installation, + minutes_before_expiration=60 * 24 * 365, # one year for testing + ) + if updated_installation is not None: + installation_store.save(updated_installation) + + +from flask import Flask, request, make_response + +app = Flask(__name__) +app.debug = True + + +@app.route("/slack/events", methods=["POST"]) +def slack_app(): + if not signature_verifier.is_valid( + body=request.get_data(), + timestamp=request.headers.get("X-Slack-Request-Timestamp"), + signature=request.headers.get("X-Slack-Signature"), + ): + return make_response("invalid request", 403) + + raw_body = request.data.decode("utf-8") + body = parse_body(body=raw_body, content_type=extract_content_type(request.headers)) + rotate_tokens( + enterprise_id=extract_enterprise_id(body), + team_id=extract_team_id(body), + user_id=extract_user_id(body), + is_enterprise_install=extract_is_enterprise_install(body), + ) + + if "command" in request.form and request.form["command"] == "/token-rotation-modal": + try: + enterprise_id = request.form.get("enterprise_id") + team_id = request.form["team_id"] + bot = installation_store.find_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + bot_token = bot.bot_token if bot else None + if not bot_token: + return make_response("Please install this app first!", 200) + + client = WebClient(token=bot_token) + trigger_id = request.form["trigger_id"] + response = client.views_open( + trigger_id=trigger_id, + view={ + "type": "modal", + "callback_id": "modal-id", + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, + "blocks": [ + { + "type": "input", + "block_id": "b-id", + "label": { + "type": "plain_text", + "text": "Input label", + }, + "element": { + "action_id": "a-id", + "type": "plain_text_input", + }, + } + ], + }, + ) + return make_response("", 200) + except SlackApiError as e: + code = e.response["error"] + return make_response(f"Failed to open a modal due to {code}", 200) + + elif "payload" in request.form: + payload = json.loads(request.form["payload"]) + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": + submitted_data = payload["view"]["state"]["values"] + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + return make_response("", 200) + + else: + if raw_body.startswith("{"): + event_payload = json.loads(raw_body) + logger.info(f"Events API payload: {event_payload}") + if event_payload.get("type") == "url_verification": + return make_response(event_payload.get("challenge"), 200) + return make_response("", 200) + + return make_response("", 404) + + +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +authorization_url_generator = AuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + user_scopes=user_scopes, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +@app.route("/slack/install", methods=["GET"]) +def oauth_start(): + state = state_store.issue() + url = authorization_url_generator.generate(state) + return ( + '' + f'' + f'' + "" + ) + + +@app.route("/slack/oauth_redirect", methods=["GET"]) +def oauth_callback(): + # Retrieve the auth code and state from the request params + if "code" in request.args: + state = request.args["state"] + if state_store.consume(state): + code = request.args["code"] + client = WebClient() # no prepared token needed for this app + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) + logger.info(f"oauth.v2.access response: {oauth_response}") + + installed_enterprise = oauth_response.get("enterprise", {}) + is_enterprise_install = oauth_response.get("is_enterprise_install") + installed_team = oauth_response.get("team", {}) + installer = oauth_response.get("authed_user", {}) + incoming_webhook = oauth_response.get("incoming_webhook", {}) + + bot_token = oauth_response.get("access_token") + # NOTE: oauth.v2.access doesn't include bot_id in response + bot_id = None + enterprise_url = None + if bot_token is not None: + auth_test = client.auth_test(token=bot_token) + bot_id = auth_test["bot_id"] + if is_enterprise_install is True: + enterprise_url = auth_test.get("url") + + installation = 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"), # comma-separated string + bot_refresh_token=oauth_response.get("refresh_token"), + bot_token_expires_in=oauth_response.get("expires_in"), + user_id=installer.get("id"), + user_token=installer.get("access_token"), + user_scopes=installer.get("scope"), # comma-separated string + user_refresh_token=installer.get("refresh_token"), + user_token_expires_in=installer.get("expires_in"), + 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"), + ) + installation_store.save(installation) + return redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) + else: + return redirect_page_renderer.render_failure_page("the state value is already expired") + + error = request.args["error"] if "error" in request.args else "" + return redirect_page_renderer.render_failure_page(error) + + +if __name__ == "__main__": + # export SLACK_CLIENT_ID=123.123 + # export SLACK_CLIENT_SECRET=xxx + # export SLACK_SIGNING_SECRET=*** + # export FLASK_ENV=development + + app.run("localhost", 3000) + + # python3 integration_tests/samples/token_rotation/oauth.py + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/oauth/start diff --git a/integration_tests/samples/token_rotation/oauth_sqlite3.py b/integration_tests/samples/token_rotation/oauth_sqlite3.py new file mode 100644 index 000000000..7b7acd989 --- /dev/null +++ b/integration_tests/samples/token_rotation/oauth_sqlite3.py @@ -0,0 +1,283 @@ +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +# pip3 install flask +from typing import Optional + +from integration_tests.samples.token_rotation.util import ( + parse_body, + extract_enterprise_id, + extract_user_id, + extract_team_id, + extract_is_enterprise_install, + extract_content_type, +) + +import logging +import os + +from slack_sdk.oauth.installation_store.sqlite3 import SQLite3InstallationStore +from slack_sdk.web import WebClient +from slack_sdk.oauth.token_rotation import TokenRotator +from slack_sdk.oauth import AuthorizeUrlGenerator, RedirectUriPageRenderer +from slack_sdk.oauth.installation_store import Installation +from slack_sdk.oauth.state_store.sqlite3 import SQLite3OAuthStateStore + +client_id = os.environ["SLACK_CLIENT_ID"] +client_secret = os.environ["SLACK_CLIENT_SECRET"] +scopes = ["app_mentions:read", "chat:write", "commands"] +user_scopes = ["search:read"] + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) +logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) + +import sqlalchemy +from sqlalchemy.engine import Engine + +database_url = "sqlite:///slackapp.db" +# database_url = "postgresql://localhost/slackapp" # pip install psycopg2 +engine: Engine = sqlalchemy.create_engine(database_url) + +installation_store = SQLite3InstallationStore( + database="test.db", + client_id=client_id, + logger=logger, +) +installation_store.init() + +token_rotator = TokenRotator( + client_id=client_id, + client_secret=client_secret, +) + +state_store = SQLite3OAuthStateStore( + database="test.db", + logger=logger, + expiration_seconds=300, +) +state_store.init() + +# --------------------- +# Flask App for Slack events +# --------------------- + +import json +from slack_sdk.errors import SlackApiError +from slack_sdk.signature import SignatureVerifier + +signing_secret = os.environ["SLACK_SIGNING_SECRET"] +signature_verifier = SignatureVerifier(signing_secret=signing_secret) + + +def rotate_tokens( + enterprise_id: Optional[str] = None, + team_id: Optional[str] = None, + user_id: Optional[str] = None, + is_enterprise_install: Optional[bool] = None, +): + installation = installation_store.find_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + is_enterprise_install=is_enterprise_install, + ) + if installation is not None: + updated_installation = token_rotator.perform_token_rotation( + installation=installation, + minutes_before_expiration=60 * 24 * 365, # one year for testing + ) + if updated_installation is not None: + installation_store.save(updated_installation) + + +from flask import Flask, request, make_response + +app = Flask(__name__) +app.debug = True + + +@app.route("/slack/events", methods=["POST"]) +def slack_app(): + if not signature_verifier.is_valid( + body=request.get_data(), + timestamp=request.headers.get("X-Slack-Request-Timestamp"), + signature=request.headers.get("X-Slack-Signature"), + ): + return make_response("invalid request", 403) + + raw_body = request.data.decode("utf-8") + body = parse_body(body=raw_body, content_type=extract_content_type(request.headers)) + rotate_tokens( + enterprise_id=extract_enterprise_id(body), + team_id=extract_team_id(body), + user_id=extract_user_id(body), + is_enterprise_install=extract_is_enterprise_install(body), + ) + + if "command" in request.form and request.form["command"] == "/token-rotation-modal": + try: + enterprise_id = request.form.get("enterprise_id") + team_id = request.form["team_id"] + bot = installation_store.find_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + bot_token = bot.bot_token if bot else None + if not bot_token: + return make_response("Please install this app first!", 200) + + client = WebClient(token=bot_token) + trigger_id = request.form["trigger_id"] + response = client.views_open( + trigger_id=trigger_id, + view={ + "type": "modal", + "callback_id": "modal-id", + "title": {"type": "plain_text", "text": "Awesome Modal"}, + "submit": {"type": "plain_text", "text": "Submit"}, + "close": {"type": "plain_text", "text": "Cancel"}, + "blocks": [ + { + "type": "input", + "block_id": "b-id", + "label": { + "type": "plain_text", + "text": "Input label", + }, + "element": { + "action_id": "a-id", + "type": "plain_text_input", + }, + } + ], + }, + ) + return make_response("", 200) + except SlackApiError as e: + code = e.response["error"] + return make_response(f"Failed to open a modal due to {code}", 200) + + elif "payload" in request.form: + payload = json.loads(request.form["payload"]) + if payload["type"] == "view_submission" and payload["view"]["callback_id"] == "modal-id": + submitted_data = payload["view"]["state"]["values"] + print(submitted_data) # {'b-id': {'a-id': {'type': 'plain_text_input', 'value': 'your input'}}} + return make_response("", 200) + + else: + if raw_body.startswith("{"): + event_payload = json.loads(raw_body) + logger.info(f"Events API payload: {event_payload}") + if event_payload.get("type") == "url_verification": + return make_response(event_payload.get("challenge"), 200) + return make_response("", 200) + + return make_response("", 404) + + +# --------------------- +# Flask App for Slack OAuth flow +# --------------------- + +authorization_url_generator = AuthorizeUrlGenerator( + client_id=client_id, + scopes=scopes, + user_scopes=user_scopes, +) +redirect_page_renderer = RedirectUriPageRenderer( + install_path="/slack/install", + redirect_uri_path="/slack/oauth_redirect", +) + + +@app.route("/slack/install", methods=["GET"]) +def oauth_start(): + state = state_store.issue() + url = authorization_url_generator.generate(state) + return ( + '' + f'' + f'' + "" + ) + + +@app.route("/slack/oauth_redirect", methods=["GET"]) +def oauth_callback(): + # Retrieve the auth code and state from the request params + if "code" in request.args: + state = request.args["state"] + if state_store.consume(state): + code = request.args["code"] + client = WebClient() # no prepared token needed for this app + oauth_response = client.oauth_v2_access(client_id=client_id, client_secret=client_secret, code=code) + logger.info(f"oauth.v2.access response: {oauth_response}") + + installed_enterprise = oauth_response.get("enterprise", {}) + is_enterprise_install = oauth_response.get("is_enterprise_install") + installed_team = oauth_response.get("team", {}) + installer = oauth_response.get("authed_user", {}) + incoming_webhook = oauth_response.get("incoming_webhook", {}) + + bot_token = oauth_response.get("access_token") + # NOTE: oauth.v2.access doesn't include bot_id in response + bot_id = None + enterprise_url = None + if bot_token is not None: + auth_test = client.auth_test(token=bot_token) + bot_id = auth_test["bot_id"] + if is_enterprise_install is True: + enterprise_url = auth_test.get("url") + + installation = 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"), # comma-separated string + bot_refresh_token=oauth_response.get("refresh_token"), + bot_token_expires_in=oauth_response.get("expires_in"), + user_id=installer.get("id"), + user_token=installer.get("access_token"), + user_scopes=installer.get("scope"), # comma-separated string + user_refresh_token=installer.get("refresh_token"), + user_token_expires_in=installer.get("expires_in"), + 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"), + ) + installation_store.save(installation) + return redirect_page_renderer.render_success_page( + app_id=installation.app_id, + team_id=installation.team_id, + is_enterprise_install=installation.is_enterprise_install, + enterprise_url=installation.enterprise_url, + ) + else: + return redirect_page_renderer.render_failure_page("the state value is already expired") + + error = request.args["error"] if "error" in request.args else "" + return redirect_page_renderer.render_failure_page(error) + + +if __name__ == "__main__": + # export SLACK_CLIENT_ID=123.123 + # export SLACK_CLIENT_SECRET=xxx + # export SLACK_SIGNING_SECRET=*** + # export FLASK_ENV=development + + app.run("localhost", 3000) + + # python3 integration_tests/samples/token_rotation/oauth_sqlite3.py + # ngrok http 3000 + # https://{yours}.ngrok.io/slack/oauth/start diff --git a/integration_tests/samples/token_rotation/util.py b/integration_tests/samples/token_rotation/util.py new file mode 100644 index 000000000..f0d201199 --- /dev/null +++ b/integration_tests/samples/token_rotation/util.py @@ -0,0 +1,88 @@ +import json +from typing import Optional, Dict, Any, Sequence +from urllib.parse import parse_qsl + + +def parse_body(body: str, content_type: Optional[str]) -> Dict[str, Any]: + if not body: + return {} + if (content_type is not None and content_type == "application/json") or body.startswith("{"): + return json.loads(body) + else: + if "payload" in body: # This is not JSON format yet + params = dict(parse_qsl(body)) + if params.get("payload") is not None: + return json.loads(params.get("payload")) + else: + return {} + else: + return dict(parse_qsl(body)) + + +def extract_is_enterprise_install(payload: Dict[str, Any]) -> Optional[bool]: + if "is_enterprise_install" in payload: + is_enterprise_install = payload.get("is_enterprise_install") + return is_enterprise_install is not None and (is_enterprise_install is True or is_enterprise_install == "true") + return False + + +def extract_enterprise_id(payload: Dict[str, Any]) -> Optional[str]: + if payload.get("enterprise") is not None: + org = payload.get("enterprise") + if isinstance(org, str): + return org + elif "id" in org: + return org.get("id") # type: ignore + if payload.get("authorizations") is not None and len(payload["authorizations"]) > 0: + # To make Events API handling functioning also for shared channels, + # we should use .authorizations[0].enterprise_id over .enterprise_id + return extract_enterprise_id(payload["authorizations"][0]) + if "enterprise_id" in payload: + return payload.get("enterprise_id") + if payload.get("team") is not None and "enterprise_id" in payload["team"]: + # In the case where the type is view_submission + return payload["team"].get("enterprise_id") + if payload.get("event") is not None: + return extract_enterprise_id(payload["event"]) + return None + + +def extract_team_id(payload: Dict[str, Any]) -> Optional[str]: + if payload.get("team") is not None: + team = payload.get("team") + if isinstance(team, str): + return team + elif team and "id" in team: + return team.get("id") + if payload.get("authorizations") is not None and len(payload["authorizations"]) > 0: + # To make Events API handling functioning also for shared channels, + # we should use .authorizations[0].team_id over .team_id + return extract_team_id(payload["authorizations"][0]) + if "team_id" in payload: + return payload.get("team_id") + if payload.get("event") is not None: + return extract_team_id(payload["event"]) + if payload.get("user") is not None: + return payload.get("user")["team_id"] + return None + + +def extract_user_id(payload: Dict[str, Any]) -> Optional[str]: + if payload.get("user") is not None: + user = payload.get("user") + if isinstance(user, str): + return user + elif "id" in user: + return user.get("id") # type: ignore + if "user_id" in payload: + return payload.get("user_id") + if payload.get("event") is not None: + return extract_user_id(payload["event"]) + return None + + +def extract_content_type(headers: Dict[str, Sequence[str]]) -> Optional[str]: + content_type: Optional[str] = headers.get("content-type", [None])[0] + if content_type: + return content_type.split(";")[0] + return None diff --git a/integration_tests/samples/workflows/steps_from_apps.py b/integration_tests/samples/workflows/steps_from_apps.py index 1ae446175..f77d6187a 100644 --- a/integration_tests/samples/workflows/steps_from_apps.py +++ b/integration_tests/samples/workflows/steps_from_apps.py @@ -1,12 +1,6 @@ -# ------------------ -# Only for running this script here import logging -import sys -from os.path import dirname -sys.path.insert(1, f"{dirname(__file__)}/../../..") logging.basicConfig(level=logging.DEBUG) -# ------------------ # --------------------- # Flask App for Slack OAuth flow @@ -14,8 +8,8 @@ import os import json -from slack import WebClient -from slack.signature import SignatureVerifier +from slack_sdk.web import WebClient +from slack_sdk.signature import SignatureVerifier logger = logging.getLogger(__name__) signature_verifier = SignatureVerifier(os.environ["SLACK_SIGNING_SECRET"]) @@ -26,6 +20,7 @@ # --------------------- from concurrent.futures.thread import ThreadPoolExecutor + executor = ThreadPoolExecutor(max_workers=5) # pip3 install flask @@ -34,6 +29,7 @@ app = Flask(__name__) app.debug = True + @app.route("/slack/events", methods=["POST"]) def slack_app(): request_body = request.get_data() @@ -59,7 +55,9 @@ def handle_step(): except Exception as err: client.workflows_stepFailed( workflow_step_execute_id=step["workflow_step_execute_id"], - error={"message": f"Something went wrong! ({err})", } + error={ + "message": f"Something went wrong! ({err})", + }, ) executor.submit(handle_step) @@ -128,8 +126,7 @@ def handle_step(): ) return make_response("", 200) - if body["type"] == "view_submission" \ - and body["view"]["callback_id"] == "copy_review_view": + if body["type"] == "view_submission" and body["view"]["callback_id"] == "copy_review_view": state_values = body["view"]["state"]["values"] client.workflows_updateStep( @@ -139,16 +136,18 @@ def handle_step(): "value": state_values["task_name_input"]["task_name"]["value"], }, "taskDescription": { - "value": state_values["task_description_input"]["task_description"][ - "value" - ], + "value": state_values["task_description_input"]["task_description"]["value"], }, "taskAuthorEmail": { "value": state_values["task_author_input"]["task_author"]["value"], }, }, outputs=[ - {"name": "taskName", "type": "text", "label": "Task Name", }, + { + "name": "taskName", + "type": "text", + "label": "Task Name", + }, { "name": "taskDescription", "type": "text", diff --git a/integration_tests/scim/test_scim_client_read.py b/integration_tests/scim/test_scim_client_read.py new file mode 100644 index 000000000..700dbceef --- /dev/null +++ b/integration_tests/scim/test_scim_client_read.py @@ -0,0 +1,74 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.scim import SCIMClient, SCIMResponse + + +class TestSCIMClient(unittest.TestCase): + def setUp(self): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.client: SCIMClient = SCIMClient(token=self.bot_token) + + def tearDown(self): + pass + + def test_api_call(self): + response: SCIMResponse = self.client.api_call( + http_verb="GET", path="Users", query_params={"startIndex": 1, "count": 1} + ) + self.assertIsNotNone(response) + + self.logger.info(response.snake_cased_body) + self.assertEqual(response.snake_cased_body["start_index"], 1) + self.assertIsNotNone(response.snake_cased_body["resources"][0]["id"]) + + def test_lookup_users(self): + search_result = self.client.search_users(start_index=1, count=1) + self.assertIsNotNone(search_result) + + self.logger.info(search_result.snake_cased_body) + self.assertEqual(search_result.snake_cased_body["start_index"], 1) + self.assertIsNotNone(search_result.snake_cased_body["resources"][0]["id"]) + self.assertEqual( + search_result.users[0].id, + search_result.snake_cased_body["resources"][0]["id"], + ) + + read_result = self.client.read_user(search_result.users[0].id) + self.assertIsNotNone(read_result) + self.logger.info(read_result.snake_cased_body) + self.assertEqual(read_result.user.id, search_result.users[0].id) + + def test_lookup_users_error(self): + # error + error_result = self.client.search_users(start_index=1, count=1, filter="foo") + self.assertEqual(error_result.errors.code, 400) + self.assertEqual(error_result.errors.description, "no_filters (is_aggregate_call=1)") + + def test_lookup_groups(self): + search_result = self.client.search_groups(start_index=1, count=1) + self.assertIsNotNone(search_result) + + self.logger.info(search_result.snake_cased_body) + self.assertEqual(search_result.snake_cased_body["start_index"], 1) + self.assertIsNotNone(search_result.snake_cased_body["resources"][0]["id"]) + self.assertEqual( + search_result.groups[0].id, + search_result.snake_cased_body["resources"][0]["id"], + ) + + read_result = self.client.read_group(search_result.groups[0].id) + self.assertIsNotNone(read_result) + self.logger.info(read_result.snake_cased_body) + self.assertEqual(read_result.group.id, search_result.groups[0].id) + + def test_lookup_groups_error(self): + # error + error_result = self.client.search_groups(start_index=1, count=-1, filter="foo") + self.assertEqual(error_result.errors.code, 400) + self.assertEqual(error_result.errors.description, "no_filters (is_aggregate_call=1)") diff --git a/integration_tests/scim/test_scim_client_write.py b/integration_tests/scim/test_scim_client_write.py new file mode 100644 index 000000000..bb598e003 --- /dev/null +++ b/integration_tests/scim/test_scim_client_write.py @@ -0,0 +1,125 @@ +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.scim import SCIMClient +from slack_sdk.scim.v1.group import Group, GroupMember +from slack_sdk.scim.v1.user import User, UserName, UserEmail + + +class TestSCIMClient(unittest.TestCase): + def setUp(self): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.client: SCIMClient = SCIMClient(token=self.bot_token) + + def tearDown(self): + pass + + def test_user_crud(self): + now = str(time.time())[:10] + user = User( + user_name=f"user_{now}", + name=UserName(given_name="Kaz", family_name="Sera"), + emails=[UserEmail(value=f"seratch+{now}@example.com")], + schemas=[ + "urn:scim:schemas:core:1.0", + # "urn:scim:schemas:extension:enterprise:1.0", + # "urn:scim:schemas:extension:slack:guest:1.0" + ], + # additional_fields={ + # "urn:scim:schemas:extension:slack:guest:1.0": { + # "type": "multi", + # "expiration": "2022-11-30T23:59:59Z" + # } + # } + ) + creation = self.client.create_user(user) + self.assertEqual(creation.status_code, 201) + + patch_result = self.client.patch_user( + id=creation.user.id, + partial_user=User( + user_name=f"user_{now}_2", + name=UserName(given_name="Kazuhiro", family_name="Sera"), + ), + ) + self.assertEqual(patch_result.status_code, 200) + + # Patch using dict + # snake_cased keys will be automatically converted to camelCase + patch_result_2 = self.client.patch_user( + id=creation.user.id, + partial_user={ + "user_name": f"user_{now}_3", + "name": { + "given_name": "Kaz", + "family_name": "Sera", + }, + }, + ) + self.assertEqual(patch_result_2.status_code, 200) + self.assertEqual(patch_result_2.user.user_name, f"user_{now}_3") + self.assertEqual(patch_result_2.user.name.given_name, "Kaz") + + # using camelCase also works + patch_result_3 = self.client.patch_user( + id=creation.user.id, + partial_user={ + "userName": f"user_{now}_4", + "name": { + "givenName": "Kazuhiro", + "familyName": "Sera", + }, + }, + ) + self.assertEqual(patch_result_3.status_code, 200) + self.assertEqual(patch_result_3.user.user_name, f"user_{now}_4") + self.assertEqual(patch_result_3.user.name.given_name, "Kazuhiro") + + updated_user = creation.user + updated_user.name = UserName(given_name="Foo", family_name="Bar") + update_result = self.client.update_user(user=updated_user) + self.assertEqual(update_result.status_code, 200) + + delete_result = self.client.delete_user(updated_user.id) + self.assertEqual(delete_result.status_code, 200) + + def test_group_crud(self): + now = str(time.time())[:10] + + user = User( + user_name=f"user_{now}", + name=UserName(given_name="Kaz", family_name="Sera"), + emails=[UserEmail(value=f"seratch+{now}@example.com")], + schemas=["urn:scim:schemas:core:1.0"], + ) + user_creation = self.client.create_user(user) + group = Group( + display_name=f"TestGroup_{now}", + members=[GroupMember(value=user_creation.user.id)], + ) + creation = self.client.create_group(group) + self.assertEqual(creation.status_code, 201) + + group = creation.group + + patch_result = self.client.patch_group( + id=group.id, + partial_group=Group( + display_name=f"Test Group{now}_2", + ), + ) + self.assertEqual(patch_result.status_code, 204) + + updated_group = group + updated_group.display_name = f"Test Group{now}_3" + update_result = self.client.update_group(updated_group) + self.assertEqual(update_result.status_code, 200) + + delete_result = self.client.delete_group(updated_group.id) + self.assertEqual(delete_result.status_code, 204) diff --git a/integration_tests/web/test_admin_analytics.py b/integration_tests/web/test_admin_analytics.py index 6270ed366..7b309d959 100644 --- a/integration_tests/web/test_admin_analytics.py +++ b/integration_tests/web/test_admin_analytics.py @@ -2,7 +2,9 @@ import os import unittest -from integration_tests.env_variable_names import SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) from integration_tests.helpers import async_test from slack_sdk.errors import SlackApiError from slack_sdk.web.legacy_client import LegacyWebClient @@ -23,17 +25,10 @@ def setUp(self): def tearDown(self): pass - def test_legacy(self): - client = self.legacy_client - - response = client.admin_analytics_getFile(date="2020-10-20", type="member") - self.assertTrue(isinstance(response.data, bytes)) - self.assertIsNotNone(response.data) - def test_sync(self): client = self.sync_client - response = client.admin_analytics_getFile(date="2020-10-20", type="member") + response = client.admin_analytics_getFile(date="2022-10-20", type="member") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) @@ -46,11 +41,25 @@ def test_sync_error(self): self.assertFalse(e.response["ok"]) self.assertEqual("file_not_yet_available", e.response["error"]) + def test_sync_public_channel(self): + client = self.sync_client + + response = client.admin_analytics_getFile(date="2022-10-20", type="public_channel") + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + + def test_sync_public_channel_medata_only(self): + client = self.sync_client + + response = client.admin_analytics_getFile(type="public_channel", metadata_only=True) + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + @async_test async def test_async(self): client = self.async_client - response = await client.admin_analytics_getFile(date="2020-10-20", type="member") + response = await client.admin_analytics_getFile(date="2022-10-20", type="member") self.assertTrue(isinstance(response.data, bytes)) self.assertIsNotNone(response.data) @@ -63,3 +72,43 @@ async def test_async_error(self): except SlackApiError as e: self.assertFalse(e.response["ok"]) self.assertEqual("file_not_yet_available", e.response["error"]) + + @async_test + async def test_async_public_channel(self): + client = self.async_client + + response = await client.admin_analytics_getFile(date="2022-10-20", type="public_channel") + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + + @async_test + async def test_async_public_channel_metadata_only(self): + client = self.async_client + + response = await client.admin_analytics_getFile( + type="public_channel", + metadata_only=True, + ) + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + + def test_legacy(self): + client = self.legacy_client + + response = client.admin_analytics_getFile(date="2022-10-20", type="member") + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + + def test_legacy_public_channel(self): + client = self.legacy_client + + response = client.admin_analytics_getFile(date="2022-10-20", type="public_channel") + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) + + def test_legacy_public_channel_metadata_only(self): + client = self.legacy_client + + response = client.admin_analytics_getFile(type="public_channel", metadata_only=True) + self.assertTrue(isinstance(response.data, bytes)) + self.assertIsNotNone(response.data) diff --git a/integration_tests/web/test_admin_auth_policy.py b/integration_tests/web/test_admin_auth_policy.py new file mode 100644 index 000000000..d83ad8c82 --- /dev/null +++ b/integration_tests/web/test_admin_auth_policy.py @@ -0,0 +1,70 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + self.user_ids = [os.environ[SLACK_SDK_TEST_GRID_USER_ID_ADMIN_AUTH]] + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + + list = client.admin_auth_policy_getEntities(policy_name="email_password", limit=3) + self.assertIsNotNone(list) + + assignment = client.admin_auth_policy_assignEntities( + entity_ids=self.user_ids, + policy_name="email_password", + entity_type="USER", + ) + self.assertIsNotNone(assignment) + self.assertEqual(list["entity_total_count"] + 1, assignment["entity_total_count"]) + + removal = client.admin_auth_policy_removeEntities( + entity_ids=self.user_ids, + policy_name="email_password", + entity_type="USER", + ) + self.assertIsNotNone(removal) + self.assertEqual(list["entity_total_count"], removal["entity_total_count"]) + + @async_test + async def test_async(self): + client = self.async_client + + list = await client.admin_auth_policy_getEntities(policy_name="email_password", limit=3) + self.assertIsNotNone(list) + + assignment = await client.admin_auth_policy_assignEntities( + entity_ids=self.user_ids, + policy_name="email_password", + entity_type="USER", + ) + self.assertIsNotNone(assignment) + self.assertEqual(list["entity_total_count"] + 1, assignment["entity_total_count"]) + + removal = await client.admin_auth_policy_removeEntities( + entity_ids=self.user_ids, + policy_name="email_password", + entity_type="USER", + ) + self.assertIsNotNone(removal) + self.assertEqual(list["entity_total_count"], removal["entity_total_count"]) diff --git a/integration_tests/web/test_admin_barriers.py b/integration_tests/web/test_admin_barriers.py new file mode 100644 index 000000000..b23591597 --- /dev/null +++ b/integration_tests/web/test_admin_barriers.py @@ -0,0 +1,77 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + + self.idp_usergroup_id1 = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] + self.idp_usergroup_id2 = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID_2] + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + + list = client.admin_barriers_list(limit=1000) + self.assertIsNotNone(list) + + for barrier in list["barriers"]: + client.admin_barriers_delete(barrier_id=barrier["id"]) + + creation = client.admin_barriers_create( + primary_usergroup_id=self.idp_usergroup_id1, + barriered_from_usergroup_ids=[self.idp_usergroup_id2], + restricted_subjects=["call", "im", "mpim"], + ) + self.assertIsNotNone(creation) + + modification = client.admin_barriers_update( + barrier_id=creation["barrier"]["id"], + primary_usergroup_id=self.idp_usergroup_id2, + barriered_from_usergroup_ids=[self.idp_usergroup_id1], + restricted_subjects=["call", "im", "mpim"], + ) + self.assertIsNotNone(modification) + + @async_test + async def test_async(self): + client = self.async_client + + list = await client.admin_barriers_list(limit=1000) + self.assertIsNotNone(list) + + for barrier in list["barriers"]: + await client.admin_barriers_delete(barrier_id=barrier["id"]) + + creation = await client.admin_barriers_create( + primary_usergroup_id=self.idp_usergroup_id1, + barriered_from_usergroup_ids=[self.idp_usergroup_id2], + restricted_subjects=["call", "im", "mpim"], + ) + self.assertIsNotNone(creation) + + modification = await client.admin_barriers_update( + barrier_id=creation["barrier"]["id"], + primary_usergroup_id=self.idp_usergroup_id2, + barriered_from_usergroup_ids=[self.idp_usergroup_id1], + restricted_subjects=["call", "im", "mpim"], + ) + self.assertIsNotNone(modification) diff --git a/integration_tests/web/test_admin_conversations.py b/integration_tests/web/test_admin_conversations.py index 06fccc460..95fc0060c 100644 --- a/integration_tests/web/test_admin_conversations.py +++ b/integration_tests/web/test_admin_conversations.py @@ -4,12 +4,15 @@ import time import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, SLACK_SDK_TEST_GRID_TEAM_ID, \ - SLACK_SDK_TEST_GRID_USER_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, + SLACK_SDK_TEST_GRID_USER_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -21,18 +24,14 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.org_admin_token, - run_async=False, - loop=asyncio.new_event_loop() - ) - self.async_client: WebClient = WebClient(token=self.org_admin_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_group_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] self.user_id = os.environ[SLACK_SDK_TEST_GRID_USER_ID] - self.channel_name = f'test-channel-{int(round(time.time() * 1000))}' - self.channel_rename = f'test-channel-renamed-{int(round(time.time() * 1000))}' + self.channel_name = f"test-channel-{int(round(time.time() * 1000))}" + self.channel_rename = f"test-channel-renamed-{int(round(time.time() * 1000))}" def tearDown(self): pass @@ -48,20 +47,30 @@ def test_sync(self): self.assertIsNotNone(conv_creation) created_channel_id = conv_creation.data["channel_id"] - self.assertIsNotNone(client.admin_conversations_invite( - channel_id=created_channel_id, - user_ids=[self.user_id], - )) - self.assertIsNotNone(client.admin_conversations_archive( - channel_id=created_channel_id, - )) - self.assertIsNotNone(client.admin_conversations_unarchive( - channel_id=created_channel_id, - )) - self.assertIsNotNone(client.admin_conversations_rename( - channel_id=created_channel_id, - name=self.channel_rename, - )) + self.assertIsNotNone(client.admin_conversations_lookup(last_message_activity_before=100, team_ids=[self.team_id])) + + self.assertIsNotNone( + client.admin_conversations_invite( + channel_id=created_channel_id, + user_ids=[self.user_id], + ) + ) + self.assertIsNotNone( + client.admin_conversations_archive( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + client.admin_conversations_unarchive( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + client.admin_conversations_rename( + channel_id=created_channel_id, + name=self.channel_rename, + ) + ) search_result = client.admin_conversations_search( limit=1, sort="member_count", @@ -70,34 +79,54 @@ def test_sync(self): self.assertIsNotNone(search_result.data["next_cursor"]) self.assertIsNotNone(search_result.data["conversations"]) - self.assertIsNotNone(client.admin_conversations_getConversationPrefs( - channel_id=created_channel_id, - )) - self.assertIsNotNone(client.admin_conversations_setConversationPrefs( - channel_id=created_channel_id, - prefs={}, - )) - - self.assertIsNotNone(client.admin_conversations_getTeams( - channel_id=created_channel_id, - )) - self.assertIsNotNone(client.admin_conversations_setTeams( - team_id=self.team_id, - channel_id=created_channel_id, - org_channel=True, - )) - time.sleep(2) # To avoid channel_not_found - self.assertIsNotNone(client.admin_conversations_convertToPrivate( - channel_id=created_channel_id, - )) - time.sleep(2) # To avoid internal_error - self.assertIsNotNone(client.admin_conversations_archive( - channel_id=created_channel_id, - )) - time.sleep(2) # To avoid internal_error - self.assertIsNotNone(client.admin_conversations_delete( - channel_id=created_channel_id, - )) + self.assertIsNotNone( + client.admin_conversations_getConversationPrefs( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + client.admin_conversations_setConversationPrefs( + channel_id=created_channel_id, + prefs={}, + ) + ) + + self.assertIsNotNone( + client.admin_conversations_getTeams( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + client.admin_conversations_setTeams( + team_id=self.team_id, + channel_id=created_channel_id, + org_channel=True, + ) + ) + time.sleep(2) # To avoid channel_not_found + self.assertIsNotNone( + client.admin_conversations_convertToPrivate( + channel_id=created_channel_id, + ) + ) + time.sleep(2) # To avoid internal_error + self.assertIsNotNone( + client.admin_conversations_convertToPublic( + channel_id=created_channel_id, + ) + ) + time.sleep(2) # To avoid internal_error + self.assertIsNotNone( + client.admin_conversations_archive( + channel_id=created_channel_id, + ) + ) + time.sleep(2) # To avoid internal_error + self.assertIsNotNone( + client.admin_conversations_delete( + channel_id=created_channel_id, + ) + ) @async_test async def test_async(self): @@ -113,47 +142,79 @@ async def test_async(self): self.assertIsNotNone(conv_creation) created_channel_id = conv_creation.data["channel_id"] - self.assertIsNotNone(await client.admin_conversations_invite( - channel_id=created_channel_id, - user_ids=[self.user_id], - )) - self.assertIsNotNone(await client.admin_conversations_archive( - channel_id=created_channel_id, - )) - self.assertIsNotNone(await client.admin_conversations_unarchive( - channel_id=created_channel_id, - )) - self.assertIsNotNone(await client.admin_conversations_rename( - channel_id=created_channel_id, - name=self.channel_rename, - )) + self.assertIsNotNone( + await client.admin_conversations_lookup(last_message_activity_before=100, team_ids=[self.team_id]) + ) + + self.assertIsNotNone( + await client.admin_conversations_invite( + channel_id=created_channel_id, + user_ids=[self.user_id], + ) + ) + self.assertIsNotNone( + await client.admin_conversations_archive( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_unarchive( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_rename( + channel_id=created_channel_id, + name=self.channel_rename, + ) + ) self.assertIsNotNone(await client.admin_conversations_search()) - self.assertIsNotNone(await client.admin_conversations_getConversationPrefs( - channel_id=created_channel_id, - )) - self.assertIsNotNone(await client.admin_conversations_setConversationPrefs( - channel_id=created_channel_id, - prefs={}, - )) - - self.assertIsNotNone(await client.admin_conversations_getTeams( - channel_id=created_channel_id, - )) - self.assertIsNotNone(await client.admin_conversations_setTeams( - team_id=self.team_id, - channel_id=created_channel_id, - org_channel=True, - )) - await asyncio.sleep(2) # To avoid channel_not_found - self.assertIsNotNone(await client.admin_conversations_convertToPrivate( - channel_id=created_channel_id, - )) - await asyncio.sleep(2) # To avoid internal_error - self.assertIsNotNone(await client.admin_conversations_archive( - channel_id=created_channel_id, - )) - await asyncio.sleep(2) # To avoid internal_error - self.assertIsNotNone(await client.admin_conversations_delete( - channel_id=created_channel_id, - )) + self.assertIsNotNone( + await client.admin_conversations_getConversationPrefs( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_setConversationPrefs( + channel_id=created_channel_id, + prefs={}, + ) + ) + + self.assertIsNotNone( + await client.admin_conversations_getTeams( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_setTeams( + team_id=self.team_id, + channel_id=created_channel_id, + org_channel=True, + ) + ) + await asyncio.sleep(2) # To avoid channel_not_found + self.assertIsNotNone( + await client.admin_conversations_convertToPrivate( + channel_id=created_channel_id, + ) + ) + await asyncio.sleep(2) # To avoid internal_error + self.assertIsNotNone( + await client.admin_conversations_convertToPublic( + channel_id=created_channel_id, + ) + ) + await asyncio.sleep(2) # To avoid internal_error + self.assertIsNotNone( + await client.admin_conversations_archive( + channel_id=created_channel_id, + ) + ) + await asyncio.sleep(2) # To avoid internal_error + self.assertIsNotNone( + await client.admin_conversations_delete( + channel_id=created_channel_id, + ) + ) diff --git a/integration_tests/web/test_admin_conversations_bulk.py b/integration_tests/web/test_admin_conversations_bulk.py new file mode 100644 index 000000000..20981d5b7 --- /dev/null +++ b/integration_tests/web/test_admin_conversations_bulk.py @@ -0,0 +1,148 @@ +import asyncio +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_TEAM_ID_2, + SLACK_SDK_TEST_GRID_TEAM_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient, SlackResponse +from slack_sdk.errors import SlackApiError +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + + self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] + self.team_id_2 = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID_2] + self.channel_name = f"test-channel-{int(round(time.time() * 1000))}" + + def tearDown(self): + pass + + def test_sync_move(self): + client = self.sync_client + + conv_creation = client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + _get_bulk_response( + client.admin_conversations_bulkMove, + channel_ids=[created_channel_id], + target_team_id=self.team_id_2, + ) + ) + + def test_sync(self): + client = self.sync_client + + conv_creation = client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + _get_bulk_response( + client.admin_conversations_bulkArchive, + channel_ids=[created_channel_id], + ) + ) + + self.assertIsNotNone( + _get_bulk_response( + client.admin_conversations_bulkDelete, + channel_ids=[created_channel_id], + ) + ) + + @async_test + async def test_async_move(self): + client = self.async_client + + conv_creation = await client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + await _get_async_bulk_response( + client.admin_conversations_bulkMove, + channel_ids=[created_channel_id], + target_team_id=self.team_id_2, + ) + ) + + @async_test + async def test_async(self): + client = self.async_client + + conv_creation = await client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + await _get_async_bulk_response( + client.admin_conversations_bulkArchive, + channel_ids=[created_channel_id], + ) + ) + + self.assertIsNotNone( + await _get_async_bulk_response( + client.admin_conversations_bulkDelete, + channel_ids=[created_channel_id], + ) + ) + + +async def _get_async_bulk_response(method, **kwargs) -> SlackResponse: + while True: + try: + return await method(**kwargs) + except SlackApiError as e: + if not _action_in_progress(e.response): + raise e + await asyncio.sleep(3) + + +def _get_bulk_response(method, **kwargs) -> SlackResponse: + while True: + try: + return method(**kwargs) + except SlackApiError as e: + if not _action_in_progress(e.response): + raise e + time.sleep(3) + + +def _action_in_progress(response: SlackResponse) -> bool: + if response.data.get("error", "") == "action_already_in_progress": + return True + return False diff --git a/integration_tests/web/test_admin_conversations_restrictAccess.py b/integration_tests/web/test_admin_conversations_restrictAccess.py index ab06387cc..97915abe5 100644 --- a/integration_tests/web/test_admin_conversations_restrictAccess.py +++ b/integration_tests/web/test_admin_conversations_restrictAccess.py @@ -4,11 +4,15 @@ import time import unittest -from integration_tests.env_variable_names import SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, SLACK_SDK_TEST_GRID_TEAM_ID, SLACK_SDK_TEST_WEB_TEST_USER_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -17,12 +21,8 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.org_admin_token, - run_async=False, - loop=asyncio.new_event_loop() - ) - self.async_client: WebClient = WebClient(token=self.org_admin_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_group_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] @@ -30,16 +30,22 @@ def setUp(self): if not hasattr(self, "channel_id"): team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] client = WebClient(token=team_admin_token) - # Only fetching private channels since admin.conversations.restrictAccess methods do not work for public channels + # Only fetching private channels since admin.conversations.restrictAccess methods + # do not work for public channels convs = client.conversations_list(exclude_archived=True, limit=100, types="private_channel") - self.channel_id = next((c["id"] for c in convs["channels"] if c["name"] != "general"), None) + self.channel_id = next( + (c["id"] for c in convs["channels"] if c["name"] != "general" and not c["is_ext_shared"]), + None, + ) if self.channel_id is None: millis = int(round(time.time() * 1000)) channel_name = f"private-test-channel-{millis}" self.channel_id = client.conversations_create( name=channel_name, is_private=True, - )["channel"]["id"] + )[ + "channel" + ]["id"] def tearDown(self): pass @@ -49,26 +55,19 @@ def test_sync(self): client = self.sync_client add_group = client.admin_conversations_restrictAccess_addGroup( - channel_id=self.channel_id, - group_id=self.idp_group_id, - team_id=self.team_id + channel_id=self.channel_id, group_id=self.idp_group_id, team_id=self.team_id ) self.assertIsNotNone(add_group) # To avoid rate limiting errors time.sleep(10) - list_groups = client.admin_conversations_restrictAccess_listGroups( - team_id=self.team_id, - channel_id=self.channel_id - ) + list_groups = client.admin_conversations_restrictAccess_listGroups(team_id=self.team_id, channel_id=self.channel_id) self.assertIsNotNone(list_groups) # To avoid rate limiting errors time.sleep(10) remove_group = client.admin_conversations_restrictAccess_removeGroup( - channel_id=self.channel_id, - group_id=self.idp_group_id, - team_id=self.team_id + channel_id=self.channel_id, group_id=self.idp_group_id, team_id=self.team_id ) self.assertIsNotNone(remove_group) # To avoid rate limiting errors @@ -81,27 +80,22 @@ async def test_async(self): client = self.async_client add_group = await client.admin_conversations_restrictAccess_addGroup( - channel_id=self.channel_id, - group_id=self.idp_group_id, - team_id=self.team_id + channel_id=self.channel_id, group_id=self.idp_group_id, team_id=self.team_id ) self.assertIsNotNone(add_group) # To avoid rate limiting errors await asyncio.sleep(10) list_groups = await client.admin_conversations_restrictAccess_listGroups( - team_id=self.team_id, - channel_id=self.channel_id + team_id=self.team_id, channel_id=self.channel_id ) self.assertIsNotNone(list_groups) # To avoid rate limiting errors await asyncio.sleep(10) remove_group = await client.admin_conversations_restrictAccess_removeGroup( - channel_id=self.channel_id, - group_id=self.idp_group_id, - team_id=self.team_id + channel_id=self.channel_id, group_id=self.idp_group_id, team_id=self.team_id ) self.assertIsNotNone(remove_group) # To avoid rate limiting errors - await asyncio.sleep(20) \ No newline at end of file + await asyncio.sleep(20) diff --git a/integration_tests/web/test_admin_conversations_retention.py b/integration_tests/web/test_admin_conversations_retention.py new file mode 100644 index 000000000..b2ceaadc0 --- /dev/null +++ b/integration_tests/web/test_admin_conversations_retention.py @@ -0,0 +1,102 @@ +import asyncio +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_TEAM_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + + self.channel_name = f"test-channel-{int(round(time.time() * 1000))}" + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + + conv_creation = client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + client.admin_conversations_setCustomRetention( + channel_id=created_channel_id, + duration_days=365, + ) + ) + self.assertIsNotNone( + client.admin_conversations_getCustomRetention( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + client.admin_conversations_removeCustomRetention( + channel_id=created_channel_id, + ) + ) + + time.sleep(2) # To avoid internal_error + self.assertIsNotNone( + client.admin_conversations_delete( + channel_id=created_channel_id, + ) + ) + + @async_test + async def test_async(self): + # await asyncio.sleep(seconds) are included to avoid rate limiting errors + + client = self.async_client + + conv_creation = await client.admin_conversations_create( + is_private=False, + name=self.channel_name, + team_id=self.team_id, + ) + self.assertIsNotNone(conv_creation) + created_channel_id = conv_creation.data["channel_id"] + + self.assertIsNotNone( + await client.admin_conversations_setCustomRetention( + channel_id=created_channel_id, + duration_days=365, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_getCustomRetention( + channel_id=created_channel_id, + ) + ) + self.assertIsNotNone( + await client.admin_conversations_removeCustomRetention( + channel_id=created_channel_id, + ) + ) + + await asyncio.sleep(2) # To avoid internal_error + self.assertIsNotNone( + await client.admin_conversations_delete( + channel_id=created_channel_id, + ) + ) diff --git a/integration_tests/web/test_admin_rate_limit_retries.py b/integration_tests/web/test_admin_rate_limit_retries.py new file mode 100644 index 000000000..86260720a --- /dev/null +++ b/integration_tests/web/test_admin_rate_limit_retries.py @@ -0,0 +1,42 @@ +import logging +import os +import unittest + +import pytest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from integration_tests.helpers import async_test, is_not_specified +from slack_sdk.http_retry import RateLimitErrorRetryHandler +from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.sync_client.retry_handlers.append(RateLimitErrorRetryHandler(max_retry_count=2)) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + self.async_client.retry_handlers.append(AsyncRateLimitErrorRetryHandler(max_retry_count=2)) + + def tearDown(self): + pass + + @pytest.mark.skipif(condition=is_not_specified(), reason="execution can take long") + def test_sync(self): + client = self.sync_client + for response in client.admin_users_session_list(limit=1): + self.assertIsNotNone(response.get("active_sessions")) + + @pytest.mark.skipif(condition=is_not_specified(), reason="execution can take long") + @async_test + async def test_async(self): + client = self.async_client + async for response in await client.admin_users_session_list(limit=1): + self.assertIsNotNone(response.get("active_sessions")) diff --git a/integration_tests/web/test_admin_roles.py b/integration_tests/web/test_admin_roles.py new file mode 100644 index 000000000..c9b79b01f --- /dev/null +++ b/integration_tests/web/test_admin_roles.py @@ -0,0 +1,38 @@ +import asyncio +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, + SLACK_SDK_TEST_GRID_USER_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + + def tearDown(self): + pass + + def test_sync(self): + client: WebClient = WebClient(token=self.org_admin_token) + list_response = client.admin_roles_listAssignments(role_ids=["Rl0A"], limit=3, sort_dir="DESC") + self.assertGreater(len(list_response.get("role_assignments", [])), 0) + # TODO tests for add/remove + + @async_test + async def test_async(self): + client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + list_response = await client.admin_roles_listAssignments(role_ids=["Rl0A"], limit=3, sort_dir="DESC") + self.assertGreater(len(list_response.get("role_assignments", [])), 0) + # TODO tests for add/remove diff --git a/integration_tests/web/test_admin_usergroups.py b/integration_tests/web/test_admin_usergroups.py index b1154a52f..2a845dc4d 100644 --- a/integration_tests/web/test_admin_usergroups.py +++ b/integration_tests/web/test_admin_usergroups.py @@ -3,11 +3,15 @@ import os import unittest -from integration_tests.env_variable_names import SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, SLACK_SDK_TEST_GRID_TEAM_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -16,19 +20,15 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.org_admin_token, - run_async=False, - loop=asyncio.new_event_loop() - ) - self.async_client: WebClient = WebClient(token=self.org_admin_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_ids"): team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] - client = WebClient(token=team_admin_token, run_async=False, loop=asyncio.new_event_loop()) + client = WebClient(token=team_admin_token) convs = client.conversations_list(exclude_archived=True, limit=100) self.channel_ids = [c["id"] for c in convs["channels"] if c["name"] == "general"] diff --git a/integration_tests/web/test_admin_users.py b/integration_tests/web/test_admin_users.py index 4b6715b45..317354a51 100644 --- a/integration_tests/web/test_admin_users.py +++ b/integration_tests/web/test_admin_users.py @@ -3,11 +3,15 @@ import os import unittest -from integration_tests.env_variable_names import SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, \ - SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, SLACK_SDK_TEST_GRID_TEAM_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -16,19 +20,15 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.org_admin_token, - run_async=False, - loop=asyncio.new_event_loop() - ) - self.async_client: WebClient = WebClient(token=self.org_admin_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] if not hasattr(self, "channel_ids"): team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] - client = WebClient(token=team_admin_token, run_async=False, loop=asyncio.new_event_loop()) + client = WebClient(token=team_admin_token) convs = client.conversations_list(exclude_archived=True, limit=100) self.channel_ids = [c["id"] for c in convs["channels"] if c["name"] == "general"] diff --git a/integration_tests/web/test_admin_users_session.py b/integration_tests/web/test_admin_users_session.py new file mode 100644 index 000000000..6dfa285c2 --- /dev/null +++ b/integration_tests/web/test_admin_users_session.py @@ -0,0 +1,43 @@ +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + def setUp(self): + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.client: WebClient = WebClient(token=self.org_admin_token) + + if not hasattr(self, "user_ids"): + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] + client = WebClient(token=team_admin_token) + users = client.users_list(exclude_archived=True, limit=50) + self.user_ids = [ + u["id"] + for u in users["members"] + if not u["is_bot"] + and not u["deleted"] + and not u["is_app_user"] + and not u["is_owner"] + and not u.get("is_stranger") + ][:3] + + def tearDown(self): + pass + + def test_reset(self): + response = self.client.admin_users_session_reset(user_id=self.user_ids[0]) + self.assertIsNone(response.get("error")) + + def test_resetBulk(self): + response = self.client.admin_users_session_resetBulk(user_ids=self.user_ids) + self.assertIsNone(response.get("error")) + + def test_resetBulk_str(self): + response = self.client.admin_users_session_resetBulk(user_ids=",".join(self.user_ids)) + self.assertIsNone(response.get("error")) diff --git a/integration_tests/web/test_admin_users_session_settings.py b/integration_tests/web/test_admin_users_session_settings.py new file mode 100644 index 000000000..0054ef3be --- /dev/null +++ b/integration_tests/web/test_admin_users_session_settings.py @@ -0,0 +1,60 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, + SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID, + SLACK_SDK_TEST_GRID_TEAM_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + + self.team_id = os.environ[SLACK_SDK_TEST_GRID_TEAM_ID] + self.idp_usergroup_id = os.environ[SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID] + + if not hasattr(self, "user_ids"): + team_admin_token = os.environ[SLACK_SDK_TEST_GRID_WORKSPACE_ADMIN_USER_TOKEN] + client = WebClient(token=team_admin_token) + users = client.users_list(exclude_archived=True, limit=50) + self.user_ids = [ + u["id"] + for u in users["members"] + if not u["is_bot"] + and not u["deleted"] + and not u["is_app_user"] + and not u["is_owner"] + and not u.get("is_stranger") + ][:3] + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + + response = client.admin_users_session_getSettings(user_ids=self.user_ids) + self.assertIsNotNone(response["session_settings"]) + client.admin_users_session_setSettings(user_ids=self.user_ids, duration=60 * 60 * 24 * 30) + client.admin_users_session_clearSettings(user_ids=self.user_ids) + + @async_test + async def test_async(self): + client = self.async_client + + response = await client.admin_users_session_getSettings(user_ids=self.user_ids) + self.assertIsNotNone(response["session_settings"]) + await client.admin_users_session_setSettings(user_ids=self.user_ids, duration=60 * 60 * 24 * 30) + await client.admin_users_session_clearSettings(user_ids=self.user_ids) diff --git a/integration_tests/web/test_admin_users_unsupportedVersions_export.py b/integration_tests/web/test_admin_users_unsupportedVersions_export.py new file mode 100644 index 000000000..2282ce427 --- /dev/null +++ b/integration_tests/web/test_admin_users_unsupportedVersions_export.py @@ -0,0 +1,35 @@ +import os +import unittest +import time + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN, +) +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + def setUp(self): + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.client: WebClient = WebClient(token=self.org_admin_token) + + def tearDown(self): + pass + + def test_no_args(self): + response = self.client.admin_users_unsupportedVersions_export() + self.assertIsNone(response.get("error")) + + def test_full_args(self): + response = self.client.admin_users_unsupportedVersions_export( + date_end_of_support=int(round(time.time())) + 60 * 60 * 24 * 120, + date_sessions_started=0, + ) + self.assertIsNone(response.get("error")) + + def test_full_args_str(self): + response = self.client.admin_users_unsupportedVersions_export( + date_end_of_support=str(int(round(time.time())) + 60 * 60 * 24 * 120), + date_sessions_started="0", + ) + self.assertIsNone(response.get("error")) diff --git a/integration_tests/web/test_app_manifest.py b/integration_tests/web/test_app_manifest.py new file mode 100644 index 000000000..10e2ec4f0 --- /dev/null +++ b/integration_tests/web/test_app_manifest.py @@ -0,0 +1,160 @@ +import os +import unittest + +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_operations(self): + token = os.environ["SLACK_SDK_TEST_TOOLING_TOKEN"] # xoxe.xoxp-... + client = WebClient(token) + client.apps_manifest_validate(manifest=STR_MANIFEST) + client.apps_manifest_validate(manifest=DICT_MANIFEST) + + response = client.apps_manifest_create(manifest=STR_MANIFEST) + app_id = response["app_id"] + try: + client.apps_manifest_update(app_id=app_id, manifest=DICT_MANIFEST) + client.apps_manifest_export(app_id=app_id) + finally: + client.apps_manifest_delete(app_id=app_id) + + +STR_MANIFEST = """{ + "display_information": { + "name": "manifest-sandbox" + }, + "features": { + "app_home": { + "home_tab_enabled": true, + "messages_tab_enabled": false, + "messages_tab_read_only_enabled": false + }, + "bot_user": { + "display_name": "manifest-sandbox", + "always_online": true + }, + "shortcuts": [ + { + "name": "message one", + "type": "message", + "callback_id": "m", + "description": "message" + }, + { + "name": "global one", + "type": "global", + "callback_id": "g", + "description": "global" + } + ], + "slash_commands": [ + { + "command": "/hey", + "url": "https://www.example.com/", + "description": "What's up?", + "usage_hint": "What's up?", + "should_escape": true + } + ], + "unfurl_domains": [ + "example.com" + ] + }, + "oauth_config": { + "redirect_urls": [ + "https://www.example.com/foo" + ], + "scopes": { + "user": [ + "search:read", + "channels:read", + "groups:read", + "mpim:read" + ], + "bot": [ + "commands", + "incoming-webhook", + "app_mentions:read", + "links:read" + ] + } + }, + "settings": { + "allowed_ip_address_ranges": [ + "123.123.123.123/32" + ], + "event_subscriptions": { + "request_url": "https://www.example.com/slack/events", + "user_events": [ + "member_joined_channel" + ], + "bot_events": [ + "app_mention", + "link_shared" + ] + }, + "interactivity": { + "is_enabled": true, + "request_url": "https://www.example.com/", + "message_menu_options_url": "https://www.example.com/" + }, + "org_deploy_enabled": true, + "socket_mode_enabled": false, + "token_rotation_enabled": true + } +} +""" + +DICT_MANIFEST = { + "display_information": {"name": "manifest-sandbox"}, + "features": { + "app_home": {"home_tab_enabled": True, "messages_tab_enabled": False, "messages_tab_read_only_enabled": False}, + "bot_user": {"display_name": "manifest-sandbox", "always_online": True}, + "shortcuts": [ + {"name": "message one", "type": "message", "callback_id": "m", "description": "message"}, + {"name": "global one", "type": "global", "callback_id": "g", "description": "global"}, + ], + "slash_commands": [ + { + "command": "/hey", + "url": "https://www.example.com/", + "description": "What's up?", + "usage_hint": "What's up?", + "should_escape": True, + } + ], + "unfurl_domains": ["example.com"], + }, + "oauth_config": { + "redirect_urls": ["https://www.example.com/foo"], + "scopes": { + "user": ["search:read", "channels:read", "groups:read", "mpim:read"], + "bot": ["commands", "incoming-webhook", "app_mentions:read", "links:read"], + }, + }, + "settings": { + "allowed_ip_address_ranges": ["123.123.123.123/32"], + "event_subscriptions": { + "request_url": "https://www.example.com/slack/events", + "user_events": ["member_joined_channel"], + "bot_events": ["app_mention", "link_shared"], + }, + "interactivity": { + "is_enabled": True, + "request_url": "https://www.example.com/", + "message_menu_options_url": "https://www.example.com/", + }, + "org_deploy_enabled": True, + "socket_mode_enabled": False, + "token_rotation_enabled": True, + }, +} diff --git a/integration_tests/web/test_async_web_client.py b/integration_tests/web/test_async_web_client.py index ecb0b454b..6785c59c9 100644 --- a/integration_tests/web/test_async_web_client.py +++ b/integration_tests/web/test_async_web_client.py @@ -2,12 +2,13 @@ import os import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import AsyncWebClient -from slack.web.async_base_client import AsyncSlackResponse +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.web.async_base_client import AsyncSlackResponse class TestAsyncWebClient(unittest.TestCase): @@ -67,18 +68,23 @@ async def test_basic_chat_operations_async(self): auth = await client.auth_test() self.assertIsNotNone(auth) - subdomain = auth["team"] + url = auth["url"] channel = self.channel_id - message = "This message was posted by ! " + \ - "(integration_tests/test_web_client.py #test_chat_operations)" + message = ( + "This message was posted by ! " + + "(integration_tests/test_web_client.py #test_chat_operations)" + ) new_message: AsyncSlackResponse = await client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] permalink = await client.chat_getPermalink(channel=channel, message_ts=ts) self.assertIsNotNone(permalink) - self.assertRegex(permalink["permalink"], f"https://{subdomain}.slack.com/archives/{channel}/.+") + self.assertRegex( + permalink["permalink"], + f"{url}archives/{channel}/.+", + ) new_reaction = await client.reactions_add(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(new_reaction) @@ -108,7 +114,11 @@ async def test_uploading_text_files_async(self): client = self.async_client file, filename = __file__, os.path.basename(__file__) upload = await client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename=filename, file=file) + channels=self.channel_id, + title="Good Old Slack Logo", + filename=filename, + file=file, + ) self.assertIsNotNone(upload) deletion = await client.files_delete(file=upload["file"]["id"]) @@ -120,7 +130,11 @@ async def test_uploading_binary_files_async(self): current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = await client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", file=file) + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) self.assertIsNotNone(upload) deletion = await client.files_delete(file=upload["file"]["id"]) diff --git a/integration_tests/web/test_bookmarks.py b/integration_tests/web/test_bookmarks.py new file mode 100644 index 000000000..8216055ad --- /dev/null +++ b/integration_tests/web/test_bookmarks.py @@ -0,0 +1,63 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestBookmarks(unittest.TestCase): + """Runs integration tests with real Slack API testing the bookmarks.* APIs""" + + def setUp(self): + if not hasattr(self, "logger"): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] + + def tearDown(self): + pass + + def test_adding_listing_editing_removing_bookmark(self): + client = self.sync_client + # create a new bookmark + bookmark = client.bookmarks_add( + channel_id=self.channel_id, + title="slack!", + type="link", + link="https://slack.com", + ) + self.assertIsNotNone(bookmark) + bookmark_id = bookmark["bookmark"]["id"] + # make sure we find the bookmark we just added + all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) + self.assertIsNotNone(all_bookmarks) + self.assertIsNotNone(next((b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None)) + # edit the bookmark + bookmark = client.bookmarks_edit( + bookmark_id=bookmark_id, + channel_id=self.channel_id, + title="slack api!", + type="link", + link="https://api.slack.com", + ) + self.assertIsNotNone(bookmark) + # make sure we find the edited bookmark we just added + all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) + self.assertIsNotNone(all_bookmarks) + edited_bookmark = next((b for b in all_bookmarks["bookmarks"] if b["id"] == bookmark_id), None) + self.assertIsNotNone(edited_bookmark) + self.assertEqual(edited_bookmark["title"], "slack api!") + # remove the bookmark + removed_bookmark = client.bookmarks_remove(bookmark_id=bookmark_id, channel_id=self.channel_id) + self.assertIsNotNone(removed_bookmark) + # make sure we cannot find the bookmark we just removed + all_bookmarks = client.bookmarks_list(channel_id=self.channel_id) + self.assertIsNotNone(all_bookmarks) + self.assertIsNone(next((b for b in all_bookmarks if b["id"] == bookmark_id), None)) diff --git a/integration_tests/web/test_calls.py b/integration_tests/web/test_calls.py index 03503252e..d285c03f0 100644 --- a/integration_tests/web/test_calls.py +++ b/integration_tests/web/test_calls.py @@ -5,8 +5,10 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test -from slack import WebClient -from slack.web.classes.blocks import CallBlock +from slack_sdk.web import WebClient +from slack_sdk.models.blocks import CallBlock +from slack_sdk.web.async_client import AsyncWebClient + class TestWebClient(unittest.TestCase): """Runs integration tests with real Slack API""" @@ -15,67 +17,76 @@ def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] self.sync_client: WebClient = WebClient(token=self.bot_token) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) def tearDown(self): pass def test_sync(self): client = self.sync_client - user_id = list(filter( - lambda u: not u["deleted"] and "bot_id" not in u, - client.users_list(limit=50)["members"] - ))[0]["id"] + user_id = list( + filter( + lambda u: not u["deleted"] and "bot_id" not in u, + client.users_list(limit=50)["members"], + ) + )[ + 0 + ]["id"] new_call = client.calls_add( external_unique_id=str(uuid.uuid4()), join_url="https://www.example.com/calls/12345", users=[ - { - "slack_id": user_id - }, + {"slack_id": user_id}, { "external_id": "anon-111", "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", "display_name": "anonymous user 1", - } - ] + }, + ], ) self.assertIsNotNone(new_call) call_id = new_call["call"]["id"] - channel_message = client.chat_postMessage(channel="#random", blocks=[ - { - "type": "call", - "call_id": call_id, - } - ]) + channel_message = client.chat_postMessage( + channel="#random", + blocks=[ + { + "type": "call", + "call_id": call_id, + } + ], + ) self.assertIsNotNone(channel_message) - channel_message = client.chat_postMessage(channel="#random", blocks=[ - CallBlock(call_id=call_id) - ]) + channel_message = client.chat_postMessage(channel="#random", blocks=[CallBlock(call_id=call_id)]) self.assertIsNotNone(channel_message) - call_info = client.calls_info(id = call_id) + call_info = client.calls_info(id=call_id) self.assertIsNotNone(call_info) - new_participants = client.calls_participants_add(id=call_id, users=[ - { - "external_id": "anon-222", - "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", - "display_name": "anonymous user 2", - } - ]) + new_participants = client.calls_participants_add( + id=call_id, + users=[ + { + "external_id": "anon-222", + "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", + "display_name": "anonymous user 2", + } + ], + ) self.assertIsNotNone(new_participants) - participants_removal = client.calls_participants_remove(id=call_id, users=[ - { - "external_id": "anon-222", - "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", - "display_name": "anonymous user 2", - } - ]) + participants_removal = client.calls_participants_remove( + id=call_id, + users=[ + { + "external_id": "anon-222", + "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", + "display_name": "anonymous user 2", + } + ], + ) self.assertIsNotNone(participants_removal) modified_call = client.calls_update(id=call_id, join_url="https://www.example.com/calls/99999") @@ -88,46 +99,47 @@ def test_sync(self): async def test_async(self): client = self.async_client users = await client.users_list(limit=50) - user_id = list(filter( - lambda u: not u["deleted"] and "bot_id" not in u, - users["members"] - ))[0]["id"] + user_id = list(filter(lambda u: not u["deleted"] and "bot_id" not in u, users["members"]))[0]["id"] new_call = await client.calls_add( external_unique_id=str(uuid.uuid4()), join_url="https://www.example.com/calls/12345", users=[ - { - "slack_id": user_id - }, + {"slack_id": user_id}, { "external_id": "anon-111", "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", "display_name": "anonymous user 1", - } - ] + }, + ], ) self.assertIsNotNone(new_call) call_id = new_call["call"]["id"] - channel_message = await client.chat_postMessage(channel="#random", blocks=[ - { - "type": "call", - "call_id": call_id, - } - ]) + channel_message = await client.chat_postMessage( + channel="#random", + blocks=[ + { + "type": "call", + "call_id": call_id, + } + ], + ) self.assertIsNotNone(channel_message) - call_info = await client.calls_info(id = call_id) + call_info = await client.calls_info(id=call_id) self.assertIsNotNone(call_info) - new_participants = await client.calls_participants_add(id=call_id, users=[ - { - "external_id": "anon-222", - "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", - "display_name": "anonymous user 2", - } - ]) + new_participants = await client.calls_participants_add( + id=call_id, + users=[ + { + "external_id": "anon-222", + "avatar_url": "https://assets.brandfolder.com/pmix53-32t4so-a6439g/original/slackbot.png", + "display_name": "anonymous user 2", + } + ], + ) self.assertIsNotNone(new_participants) modified_call = await client.calls_update(id=call_id, join_url="https://www.example.com/calls/99999") diff --git a/integration_tests/web/test_canvases.py b/integration_tests/web/test_canvases.py new file mode 100644 index 000000000..75e970f0f --- /dev/null +++ b/integration_tests/web/test_canvases.py @@ -0,0 +1,165 @@ +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + + # Channel canvas + new_channel = client.conversations_create(name=f"test-{str(time.time()).replace('.', '-')}") + channel_id = new_channel["channel"]["id"] + channel_canvas = client.conversations_canvases_create( + channel_id=channel_id, + document_content={ + "type": "markdown", + "markdown": """# My canvas + +## Hey + +What's up? + +- foo +- bar +""", + }, + ) + self.assertIsNone(channel_canvas.get("error")) + + # Standalone canvas + standalone_canvas = client.canvases_create( + title="My canvas", + document_content={ + "type": "markdown", + "markdown": """# My canvas + +## Hey + +What's up? + +- foo +- bar +""", + }, + ) + self.assertIsNone(standalone_canvas.get("error")) + canvas_id = standalone_canvas.get("canvas_id") + + sections = client.canvases_sections_lookup(canvas_id=canvas_id, criteria={"contains_text": "Hey"}) + section_id = sections["sections"][0]["id"] + + edit = client.canvases_edit( + canvas_id=canvas_id, + changes=[ + { + "operation": "replace", + "section_id": section_id, + "document_content": {"type": "markdown", "markdown": "## Hey Hey"}, + } + ], + ) + self.assertIsNone(edit.get("error")) + + user_id = client.auth_test()["user_id"] + access_set = client.canvases_access_set( + canvas_id=canvas_id, + access_level="write", + user_ids=[user_id], + ) + self.assertIsNone(access_set.get("error")) + + access_delete = client.canvases_access_delete(canvas_id=canvas_id, user_ids=[user_id]) + self.assertIsNone(access_delete.get("error")) + + delete = client.canvases_delete(canvas_id=canvas_id) + self.assertIsNone(delete.get("error")) + + @async_test + async def test_async(self): + client = self.async_client + + # Channel canvas + new_channel = await client.conversations_create(name=f"test-{str(time.time()).replace('.', '-')}") + channel_id = new_channel["channel"]["id"] + channel_canvas = await client.conversations_canvases_create( + channel_id=channel_id, + document_content={ + "type": "markdown", + "markdown": """# My canvas + +## Hey + +What's up? + +- foo +- bar +""", + }, + ) + self.assertIsNone(channel_canvas.get("error")) + + # Standalone canvas + standalone_canvas = await client.canvases_create( + title="My canvas", + document_content={ + "type": "markdown", + "markdown": """# My canvas + +## Hey + +What's up? + +- foo +- bar +""", + }, + ) + self.assertIsNone(standalone_canvas.get("error")) + canvas_id = standalone_canvas.get("canvas_id") + + sections = await client.canvases_sections_lookup(canvas_id=canvas_id, criteria={"contains_text": "Hey"}) + section_id = sections["sections"][0]["id"] + + edit = await client.canvases_edit( + canvas_id=canvas_id, + changes=[ + { + "operation": "replace", + "section_id": section_id, + "document_content": {"type": "markdown", "markdown": "## Hey Hey"}, + } + ], + ) + self.assertIsNone(edit.get("error")) + + user_id = (await client.auth_test())["user_id"] + access_set = await client.canvases_access_set( + canvas_id=canvas_id, + access_level="write", + user_ids=[user_id], + ) + self.assertIsNone(access_set.get("error")) + + access_delete = await client.canvases_access_delete(canvas_id=canvas_id, user_ids=[user_id]) + self.assertIsNone(access_delete.get("error")) + + delete = await client.canvases_delete(canvas_id=canvas_id) + self.assertIsNone(delete.get("error")) diff --git a/integration_tests/web/test_conversations_connect.py b/integration_tests/web/test_conversations_connect.py new file mode 100644 index 000000000..1d988946c --- /dev/null +++ b/integration_tests/web/test_conversations_connect.py @@ -0,0 +1,162 @@ +import logging +import os +import time +from typing import Optional +import unittest + +from slack_sdk.web.slack_response import SlackResponse +from slack_sdk.errors import SlackApiError +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN, + SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN, + SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with Slack API for conversations.* endpoints + To run, we use two workspace-level bot tokens, + one for the inviting workspace(list and send invites) another for the recipient + workspace (accept and approve) sent invites. Before being able to run this test suite, + we also need to have manually created a slack connect shared channel and added + these two bots as members first. See: https://docs.slack.dev/apis/slack-connect/ + + In addition to conversations.connect:* scopes, your sender bot token should have channels:manage scopes. + """ + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.sender_bot_token = os.environ[SLACK_SDK_TEST_CONNECT_INVITE_SENDER_BOT_TOKEN] + self.receiver_bot_token = os.environ[SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_TOKEN] + self.sender_sync_client: WebClient = WebClient(token=self.sender_bot_token) + self.sender_async_client: AsyncWebClient = AsyncWebClient(token=self.sender_bot_token) + self.receiver_sync_client: WebClient = WebClient(token=self.receiver_bot_token) + self.receiver_async_client: AsyncWebClient = AsyncWebClient(token=self.receiver_bot_token) + + def tearDown(self): + pass + + def test_sync(self): + sender = self.sender_sync_client + receiver = self.receiver_sync_client + channel_id: Optional[str] = None + + try: + auth_test: SlackResponse = receiver.auth_test() + self.assertIsNotNone(auth_test["team_id"]) + connect_team_id = auth_test["team_id"] + + # list senders pending connect invites + connect_invites: SlackResponse = sender.conversations_listConnectInvites() + self.assertIsNotNone(connect_invites["invites"]) + + # creates channel in sender workspace to share + unique_channel_name = str(int(time.time())) + "-shared" + new_channel: SlackResponse = sender.conversations_create(name=unique_channel_name) + self.assertIsNotNone(new_channel["channel"]) + self.assertIsNotNone(new_channel["channel"]["id"]) + channel_id = new_channel["channel"]["id"] + + # send an invite for sender's intended shared channel to receiver's bot user id + invite: SlackResponse = sender.conversations_inviteShared( + channel=new_channel["channel"]["id"], + user_ids=os.environ[SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID], + ) + self.assertIsNotNone(invite["invite_id"]) + + # receiver accept conversations invite via invite id + accepted: SlackResponse = receiver.conversations_acceptSharedInvite( + channel_name=unique_channel_name, + invite_id=invite["invite_id"], + ) + self.assertIsNone(accepted["error"]) + + # receiver attempt to approve invite already accepted by an admin level token should fail + self.assertRaises( + SlackApiError, + receiver.conversations_approveSharedInvite, + invite_id=invite["invite_id"], + ) + + sender_approval = sender.conversations_approveSharedInvite( + invite_id=invite["invite_id"], team_id=connect_team_id + ) + self.assertIsNone(sender_approval["error"]) + + downgrade = sender.conversations_externalInvitePermissions_set( + channel=channel_id, target_team=connect_team_id, action="downgrade" + ) + self.assertIsNone(downgrade["error"]) + + upgrade = sender.conversations_externalInvitePermissions_set( + channel=channel_id, target_team=connect_team_id, action="upgrade" + ) + self.assertIsNone(upgrade["error"]) + finally: + if channel_id is not None: + # clean up created channel + delete_channel: SlackResponse = sender.conversations_archive(channel=new_channel["channel"]["id"]) + self.assertIsNotNone(delete_channel) + + @async_test + async def test_async(self): + sender = self.sender_async_client + receiver = self.receiver_async_client + channel_id: Optional[str] = None + + try: + auth_test: SlackResponse = await receiver.auth_test() + self.assertIsNotNone(auth_test["team_id"]) + connect_team_id = auth_test["team_id"] + + # list senders pending connect invites + connect_invites: SlackResponse = await sender.conversations_listConnectInvites() + self.assertIsNotNone(connect_invites["invites"]) + + # creates channel in sender workspace to share + unique_channel_name = str(int(time.time())) + "-shared" + new_channel: SlackResponse = await sender.conversations_create(name=unique_channel_name) + self.assertIsNotNone(new_channel["channel"]) + self.assertIsNotNone(new_channel["channel"]["id"]) + channel_id = new_channel["channel"]["id"] + + # send an invite for sender's intended shared channel to receiver's bot user id + invite: SlackResponse = await sender.conversations_inviteShared( + channel=new_channel["channel"]["id"], + user_ids=os.environ[SLACK_SDK_TEST_CONNECT_INVITE_RECEIVER_BOT_USER_ID], + ) + self.assertIsNotNone(invite["invite_id"]) + + # receiver accept conversations invite via invite id + accepted: SlackResponse = await receiver.conversations_acceptSharedInvite( + channel_name=unique_channel_name, + invite_id=invite["invite_id"], + ) + self.assertIsNone(accepted["error"]) + + # receiver attempt to approve invite already accepted by an admin level token should fail + with self.assertRaises(SlackApiError): + await receiver.conversations_approveSharedInvite(invite_id=invite["invite_id"]) + + sender_approval = await sender.conversations_approveSharedInvite( + invite_id=invite["invite_id"], team_id=connect_team_id + ) + self.assertIsNone(sender_approval["error"]) + + downgrade = await sender.conversations_externalInvitePermissions_set( + channel=channel_id, target_team=connect_team_id, action="downgrade" + ) + self.assertIsNone(downgrade["error"]) + + upgrade = await sender.conversations_externalInvitePermissions_set( + channel=channel_id, target_team=connect_team_id, action="upgrade" + ) + self.assertIsNone(upgrade["error"]) + finally: + if channel_id is not None: + # clean up created channel + delete_channel: SlackResponse = await sender.conversations_archive(channel=new_channel["channel"]["id"]) + self.assertIsNotNone(delete_channel) diff --git a/integration_tests/web/test_files_upload_v2.py b/integration_tests/web/test_files_upload_v2.py new file mode 100644 index 000000000..4100051b4 --- /dev/null +++ b/integration_tests/web/test_files_upload_v2.py @@ -0,0 +1,224 @@ +import logging +import os +from pathlib import Path +import unittest +from io import BytesIO + +import pytest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) +from integration_tests.helpers import async_test +from slack_sdk.errors import SlackRequestError +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.web.legacy_client import LegacyWebClient + + +class TestWebClient_FilesUploads_V2(unittest.TestCase): + """Runs integration tests with real Slack API""" + + def setUp(self): + if not hasattr(self, "logger"): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.legacy_client: WebClient = LegacyWebClient(token=self.bot_token) + self.legacy_client_async: WebClient = LegacyWebClient(token=self.bot_token, run_async=True) + self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] + + def tearDown(self): + pass + + # ------------------------- + # file operations + + def test_uploading_text_files(self): + client = self.sync_client + file = __file__ + upload = client.files_upload_v2( + channels=self.channel_id, + file=file, + title="Test code", + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + def test_uploading_bytes_io(self): + client = self.sync_client + upload = client.files_upload_v2( + channels=self.channel_id, + file=BytesIO(bytearray("This is a test!", "utf-8")), + filename="test.txt", + title="Test code", + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + def test_uploading_text_files_path(self): + client = self.sync_client + file = __file__ + upload = client.files_upload_v2( + channel=self.channel_id, + file=Path(file), + title="Test code", + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + def test_uploading_multiple_files(self): + client = self.sync_client + file = __file__ + upload = client.files_upload_v2( + file_uploads=[ + { + "file": file, + "title": "Test code", + }, + { + "content": "Hi there!", + "title": "Text data", + "filename": "hi-there.txt", + }, + ], + channel=self.channel_id, + initial_comment="Here are files :wave:", + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + @async_test + async def test_uploading_text_files_async(self): + client = self.async_client + file, filename = __file__, os.path.basename(__file__) + upload = await client.files_upload_v2( + channels=self.channel_id, + title="Good Old Slack Logo", + filename=filename, + file=file, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = await client.files_delete(file=upload["file"]["id"]) + self.assertIsNotNone(deletion) + + @async_test + async def test_uploading_text_files_legacy_async(self): + client = self.legacy_client_async + file, filename = __file__, os.path.basename(__file__) + try: + await client.files_upload_v2( + channels=self.channel_id, + title="Good Old Slack Logo", + filename=filename, + file=file, + ) + pytest.fail("Raising SlackRequestError is expected here") + except SlackRequestError: + pass + + def test_uploading_binary_files(self): + client = self.sync_client + current_dir = os.path.dirname(__file__) + file = f"{current_dir}/../../tests/data/slack_logo.png" + upload = client.files_upload_v2( + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = client.files_delete(file=upload["file"]["id"]) + self.assertIsNotNone(deletion) + + def test_uploading_binary_files_as_content(self): + client = self.sync_client + current_dir = os.path.dirname(__file__) + file = f"{current_dir}/../../tests/data/slack_logo.png" + with open(file, "rb") as f: + content = f.read() + upload = client.files_upload_v2( + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + content=content, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = client.files_delete(file=upload["file"]["id"]) + self.assertIsNotNone(deletion) + + @async_test + async def test_uploading_binary_files_async(self): + client = self.async_client + current_dir = os.path.dirname(__file__) + file = f"{current_dir}/../../tests/data/slack_logo.png" + upload = await client.files_upload_v2( + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = await client.files_delete(file=upload["file"]["id"]) + self.assertIsNotNone(deletion) + + def test_uploading_file_with_token_param(self): + client = WebClient() + current_dir = os.path.dirname(__file__) + file = f"{current_dir}/../../tests/data/slack_logo.png" + upload = client.files_upload_v2( + token=self.bot_token, + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = client.files_delete( + token=self.bot_token, + file=upload["file"]["id"], + ) + self.assertIsNotNone(deletion) + + @async_test + async def test_uploading_file_with_token_param_async(self): + client = AsyncWebClient() + current_dir = os.path.dirname(__file__) + file = f"{current_dir}/../../tests/data/slack_logo.png" + upload = await client.files_upload_v2( + token=self.bot_token, + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) + self.assertIsNotNone(upload) + self.assertIsNotNone(upload.get("files")[0].get("id")) + self.assertIsNotNone(upload.get("files")[0].get("title")) + + deletion = await client.files_delete( + token=self.bot_token, + file=upload["file"]["id"], + ) + self.assertIsNotNone(deletion) diff --git a/integration_tests/web/test_issue_1053.py b/integration_tests/web/test_issue_1053.py new file mode 100644 index 000000000..607920efb --- /dev/null +++ b/integration_tests/web/test_issue_1053.py @@ -0,0 +1,46 @@ +import logging +import os +import time +import unittest + +from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API + + https://github.com/slackapi/python-slack-sdk/issues/1053 + """ + + def setUp(self): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + + def tearDown(self): + pass + + def test_issue_1053(self): + client: WebClient = WebClient(token=self.bot_token) + self_user_id = client.auth_test()["user_id"] + channel_name = f"test-channel-{str(time.time()).replace('.', '-')}" + channel_id = None + try: + creation = client.conversations_create(name=channel_name) + self.assertIsNone(creation.get("error")) + channel_id = creation["channel"]["id"] + user_ids = [ + u["id"] + for u in client.users_list(limit=100)["members"] + if u["id"] not in {"USLACKBOT", self_user_id} + and u.get("is_bot", False) is False + and u.get("is_app_user", False) is False + and u.get("is_restricted", False) is False + and u.get("is_ultra_restricted", False) is False + and u.get("is_email_confirmed", False) is True + ] + invitations = client.conversations_invite(channel=channel_id, users=user_ids) + self.assertIsNone(invitations.get("error")) + finally: + if channel_id is not None: + client.conversations_archive(channel=channel_id) diff --git a/integration_tests/web/test_issue_1143.py b/integration_tests/web/test_issue_1143.py new file mode 100644 index 000000000..850651439 --- /dev/null +++ b/integration_tests/web/test_issue_1143.py @@ -0,0 +1,41 @@ +import os +import unittest + +from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN +from integration_tests.helpers import async_test +from slack_sdk.errors import SlackApiError +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API + + export SLACK_SDK_TEST_BOT_TOKEN=xoxb-xxx + ./scripts/run_integration_tests.sh integration_tests/web/test_issue_1143.py + + https://github.com/slackapi/python-slack-sdk/issues/1143 + """ + + def setUp(self): + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + + def tearDown(self): + pass + + def test_backward_compatible_header(self): + client: WebClient = WebClient(token=self.bot_token) + try: + while True: + client.users_list() + except SlackApiError as e: + self.assertIsNotNone(e.response.headers["Retry-After"]) + + @async_test + async def test_backward_compatible_header_async(self): + client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + try: + while True: + await client.users_list() + except SlackApiError as e: + self.assertIsNotNone(e.response.headers["Retry-After"]) diff --git a/integration_tests/web/test_issue_1305.py b/integration_tests/web/test_issue_1305.py new file mode 100644 index 000000000..af002879f --- /dev/null +++ b/integration_tests/web/test_issue_1305.py @@ -0,0 +1,49 @@ +import asyncio +import os +import time +import unittest + +from integration_tests.env_variable_names import SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient + + +class TestWebClient(unittest.TestCase): + """Runs integration tests with real Slack API + + https://github.com/slackapi/python-slack-sdk/issues/1305 + """ + + def setUp(self): + self.org_admin_token = os.environ[SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN] + self.sync_client: WebClient = WebClient(token=self.org_admin_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.org_admin_token) + + def tearDown(self): + pass + + def test_sync(self): + client = self.sync_client + count = 0 + + for page in client.admin_conversations_search(limit=1): + count += len(page["conversations"]) + if count > 1: + break + time.sleep(1) + + self.assertGreater(count, 0) + + @async_test + async def test_async(self): + client = self.async_client + count = 0 + + async for page in await client.admin_conversations_search(limit=1): + count += len(page["conversations"]) + if count > 1: + break + await asyncio.sleep(1) + + self.assertGreater(count, 0) diff --git a/integration_tests/web/test_issue_378.py b/integration_tests/web/test_issue_378.py index 1a60a5f26..59b09a49d 100644 --- a/integration_tests/web/test_issue_378.py +++ b/integration_tests/web/test_issue_378.py @@ -5,7 +5,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_USER_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -17,8 +18,8 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.user_token = os.environ[SLACK_SDK_TEST_USER_TOKEN] - self.sync_client: WebClient = WebClient(token=self.user_token, run_async=False, loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.user_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.user_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.user_token) def tearDown(self): pass diff --git a/integration_tests/web/test_issue_480.py b/integration_tests/web/test_issue_480.py index 9fd0fb8d5..d3b2a95b9 100644 --- a/integration_tests/web/test_issue_480.py +++ b/integration_tests/web/test_issue_480.py @@ -6,7 +6,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_USER_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -17,8 +18,8 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.user_token = os.environ[SLACK_SDK_TEST_USER_TOKEN] - self.sync_client: WebClient = WebClient(token=self.user_token, run_async=False) - self.async_client: WebClient = WebClient(token=self.user_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.user_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.user_token) def tearDown(self): pass diff --git a/integration_tests/web/test_issue_560.py b/integration_tests/web/test_issue_560.py index 88669e968..259ebe9f6 100644 --- a/integration_tests/web/test_issue_560.py +++ b/integration_tests/web/test_issue_560.py @@ -4,7 +4,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -16,8 +17,8 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) def tearDown(self): pass diff --git a/integration_tests/web/test_issue_594.py b/integration_tests/web/test_issue_594.py index ca3e20736..024d941a3 100644 --- a/integration_tests/web/test_issue_594.py +++ b/integration_tests/web/test_issue_594.py @@ -4,11 +4,13 @@ import unittest from uuid import uuid4 -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, \ - SLACK_SDK_TEST_WEB_TEST_USER_ID -from slack import WebClient +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, + SLACK_SDK_TEST_WEB_TEST_USER_ID, +) +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -20,8 +22,8 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] self.user_id = os.environ[SLACK_SDK_TEST_WEB_TEST_USER_ID] @@ -38,8 +40,8 @@ def test_issue_594(self): external_id=external_id, external_url=external_url, title="Good Old Slack Logo", - indexable_file_contents="Good Old Slack Logo", - preview_image=image + indexable_file_contents="Good Old Slack Logo".encode("utf-8"), + preview_image=image, ) self.assertIsNotNone(creation) @@ -54,14 +56,14 @@ def test_issue_594(self): "type": "section", "text": { "type": "mrkdwn", - "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and " - } + "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and ", + }, }, { "type": "file", "external_id": external_id, "source": "remote", - } + }, ], ) self.assertIsNotNone(message) @@ -74,7 +76,9 @@ def test_no_preview_image(self): external_id=external_id, external_url=external_url, title="Slack (Wikipedia)", - indexable_file_contents="Slack is a proprietary business communication platform developed by Slack Technologies.", + indexable_file_contents="Slack is a proprietary business communication platform developed by Slack Technologies.".encode( + "utf-8" + ), ) self.assertIsNotNone(creation) @@ -89,14 +93,14 @@ def test_no_preview_image(self): "type": "section", "text": { "type": "mrkdwn", - "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and " - } + "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and ", + }, }, { "type": "file", "external_id": external_id, "source": "remote", - } + }, ], ) self.assertIsNotNone(message) diff --git a/integration_tests/web/test_issue_654.py b/integration_tests/web/test_issue_654.py index a49542ca5..c7e82454f 100644 --- a/integration_tests/web/test_issue_654.py +++ b/integration_tests/web/test_issue_654.py @@ -4,11 +4,13 @@ import os import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestIssue654(unittest.TestCase): @@ -21,17 +23,20 @@ def setUp(self): if not hasattr(self, "logger"): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False, - loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] def tearDown(self): pass def test_issue_654_files_upload(self): - client, logger, channel_ids = self.sync_client, self.logger, ",".join([self.channel_id]) - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + client, logger, channel_ids = ( + self.sync_client, + self.logger, + ",".join([self.channel_id]), + ) + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = client.files_upload( file=buff, @@ -47,8 +52,12 @@ def test_issue_654_files_upload(self): @async_test async def test_issue_654_files_upload_async(self): - client, logger, channel_ids = self.async_client, self.logger, ",".join([self.channel_id]) - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + client, logger, channel_ids = ( + self.async_client, + self.logger, + ",".join([self.channel_id]), + ) + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = await client.files_upload( file=buff, diff --git a/integration_tests/web/test_issue_670.py b/integration_tests/web/test_issue_670.py index 379526eef..f8be75895 100644 --- a/integration_tests/web/test_issue_670.py +++ b/integration_tests/web/test_issue_670.py @@ -6,7 +6,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -18,15 +19,15 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) def tearDown(self): pass def test_issue_670(self): client = self.sync_client - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = client.files_upload( file=buff, @@ -39,7 +40,7 @@ def test_issue_670(self): @async_test async def test_issue_670_async(self): client = self.async_client - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = await client.files_upload( file=buff, diff --git a/integration_tests/web/test_issue_672.py b/integration_tests/web/test_issue_672.py index 59ba823fb..2263c918e 100644 --- a/integration_tests/web/test_issue_672.py +++ b/integration_tests/web/test_issue_672.py @@ -3,11 +3,13 @@ import os import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -20,23 +22,24 @@ def setUp(self): if not hasattr(self, "logger"): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.bot_token, - run_async=False, - loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] def tearDown(self): pass def test_file_loading(self): - client, logger, channel_ids = self.sync_client, self.logger, ",".join([self.channel_id]) + client, logger, channel_ids = ( + self.sync_client, + self.logger, + ",".join([self.channel_id]), + ) upload = client.files_upload( file="tests/data/ζ—₯本θͺž.txt", filename="ζ—₯本θͺž.txt", filetype="text", - channels=channel_ids + channels=channel_ids, ) self.assertIsNotNone(upload) self.assertEqual("ζ—₯本θͺž.txt", upload["file"]["name"]) @@ -47,12 +50,16 @@ def test_file_loading(self): @async_test async def test_file_loading_async(self): - client, logger, channel_ids = self.async_client, self.logger, ",".join([self.channel_id]) + client, logger, channel_ids = ( + self.async_client, + self.logger, + ",".join([self.channel_id]), + ) upload = await client.files_upload( file="tests/data/ζ—₯本θͺž.txt", filename="ζ—₯本θͺž.txt", filetype="text", - channels=channel_ids + channels=channel_ids, ) logger.debug("File uploaded - %s", upload) self.assertIsNotNone(upload) @@ -63,12 +70,16 @@ async def test_file_loading_async(self): self.assertIsNotNone(deletion) def test_auto_filename_detection(self): - client, logger, channel_ids = self.sync_client, self.logger, ",".join([self.channel_id]) + client, logger, channel_ids = ( + self.sync_client, + self.logger, + ",".join([self.channel_id]), + ) upload = client.files_upload( file="tests/data/ζ—₯本θͺž.txt", # filename="ζ—₯本θͺž.txt", filetype="text", - channels=channel_ids + channels=channel_ids, ) self.assertIsNotNone(upload) self.assertEqual("ζ—₯本θͺž.txt", upload["file"]["name"]) @@ -79,12 +90,16 @@ def test_auto_filename_detection(self): @async_test async def test_auto_filename_detection_async(self): - client, logger, channel_ids = self.async_client, self.logger, ",".join([self.channel_id]) + client, logger, channel_ids = ( + self.async_client, + self.logger, + ",".join([self.channel_id]), + ) upload = await client.files_upload( file="tests/data/ζ—₯本θͺž.txt", # filename="ζ—₯本θͺž.txt", filetype="text", - channels=channel_ids + channels=channel_ids, ) logger.debug("File uploaded - %s", upload) self.assertIsNotNone(upload) diff --git a/integration_tests/web/test_issue_677.py b/integration_tests/web/test_issue_677.py index 2361f07dc..15e1eb286 100644 --- a/integration_tests/web/test_issue_677.py +++ b/integration_tests/web/test_issue_677.py @@ -4,12 +4,16 @@ import unittest from datetime import datetime -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient + +# NOTE: this one is not supported in v3 from slack.web.classes.objects import DateLink +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -22,11 +26,8 @@ def setUp(self): if not hasattr(self, "logger"): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient( - token=self.bot_token, - run_async=False, - loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] def tearDown(self): @@ -38,7 +39,7 @@ def test_date_link(self): date=datetime.now(), date_format="{date_long} {time}", fallback="fallback string", - link="https://www.example.com" + link="https://www.example.com", ) message = f"Here is a date link: {link}" response = client.chat_postMessage(channel=self.channel_id, text=message) @@ -55,7 +56,7 @@ async def test_date_link_async(self): date=datetime.now(), date_format="{date_long} {time}", fallback="fallback string", - link="https://www.example.com" + link="https://www.example.com", ) message = f"Here is a date link: {link}" response = await client.chat_postMessage(channel=self.channel_id, text=message) diff --git a/integration_tests/web/test_issue_714.py b/integration_tests/web/test_issue_714.py index 89da1d9ae..fbd2a9763 100644 --- a/integration_tests/web/test_issue_714.py +++ b/integration_tests/web/test_issue_714.py @@ -7,11 +7,11 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): - def setUp(self): self.proxy = "http://invalid-host:9999" self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] @@ -20,20 +20,12 @@ def tearDown(self): pass def test_proxy_failure(self): - client: WebClient = WebClient( - token=self.bot_token, - run_async=False, - proxy=self.proxy, - loop=asyncio.new_event_loop()) + client: WebClient = WebClient(token=self.bot_token, proxy=self.proxy) with self.assertRaises(URLError): client.auth_test() @async_test async def test_proxy_failure_async(self): - client: WebClient = WebClient( - token=self.bot_token, - proxy=self.proxy, - run_async=True - ) + client: AsyncWebClient = AsyncWebClient(token=self.bot_token, proxy=self.proxy) with self.assertRaises(ClientConnectorError): await client.auth_test() diff --git a/integration_tests/web/test_issue_728.py b/integration_tests/web/test_issue_728.py index ba1f258d1..080e1b988 100644 --- a/integration_tests/web/test_issue_728.py +++ b/integration_tests/web/test_issue_728.py @@ -1,11 +1,13 @@ import os import unittest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -22,7 +24,7 @@ def tearDown(self): pass def test_bytes_for_file_param(self): - client: WebClient = WebClient(token=self.bot_token, run_async=False) + client: WebClient = WebClient(token=self.bot_token) bytes = bytearray("This is a test", "utf-8") upload = client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) @@ -31,7 +33,7 @@ def test_bytes_for_file_param(self): @async_test async def test_bytes_for_file_param_async(self): - client: WebClient = WebClient(token=self.bot_token, run_async=True) + client: AsyncWebClient = AsyncWebClient(token=self.bot_token) bytes = bytearray("This is a test", "utf-8") upload = await client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) diff --git a/integration_tests/web/test_issue_770.py b/integration_tests/web/test_issue_770.py index 37478652d..d92395549 100644 --- a/integration_tests/web/test_issue_770.py +++ b/integration_tests/web/test_issue_770.py @@ -2,11 +2,13 @@ import unittest from io import BytesIO -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -14,7 +16,7 @@ class TestWebClient(unittest.TestCase): export SLACK_SDK_TEST_BOT_TOKEN=xoxb-xxx export SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID=C111 - python setup.py run_integration_tests --test-target integration_tests/web/test_issue_770.py + ./scripts/run_integration_tests.sh integration_tests/web/test_issue_770.py https://github.com/slackapi/python-slack-sdk/issues/770 """ @@ -27,7 +29,7 @@ def tearDown(self): pass def test_bytes_for_file_param_bytes(self): - client: WebClient = WebClient(token=self.bot_token, run_async=False) + client: WebClient = WebClient(token=self.bot_token) bytes = BytesIO(bytearray("This is a test (bytes)", "utf-8")).getvalue() upload = client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) @@ -36,7 +38,7 @@ def test_bytes_for_file_param_bytes(self): @async_test async def test_bytes_for_file_param_bytes_async(self): - client: WebClient = WebClient(token=self.bot_token, run_async=True) + client: AsyncWebClient = AsyncWebClient(token=self.bot_token) bytes = BytesIO(bytearray("This is a test (bytes)", "utf-8")).getvalue() upload = await client.files_upload(file=bytes, filename="test.txt", channels=self.channel_ids) self.assertIsNotNone(upload) diff --git a/integration_tests/web/test_issue_809.py b/integration_tests/web/test_issue_809.py index 4bd8db3a9..baa0123ba 100644 --- a/integration_tests/web/test_issue_809.py +++ b/integration_tests/web/test_issue_809.py @@ -6,7 +6,8 @@ from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN from integration_tests.helpers import async_test -from slack import WebClient +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient class TestWebClient(unittest.TestCase): @@ -18,15 +19,15 @@ class TestWebClient(unittest.TestCase): def setUp(self): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.sync_client: WebClient = WebClient(token=self.bot_token, run_async=False, loop=asyncio.new_event_loop()) - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) + self.sync_client: WebClient = WebClient(token=self.bot_token) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) def tearDown(self): pass def test_issue_809(self): client = self.sync_client - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = client.files_upload(file=buff) self.assertIsNotNone(upload) @@ -34,7 +35,7 @@ def test_issue_809(self): @async_test async def test_issue_809_async(self): client = self.async_client - buff = io.BytesIO(b'here is my data but not sure what is wrong.......') + buff = io.BytesIO(b"here is my data but not sure what is wrong.......") buff.seek(0) upload = await client.files_upload(file=buff) self.assertIsNotNone(upload) diff --git a/integration_tests/web/test_message_metadata.py b/integration_tests/web/test_message_metadata.py new file mode 100644 index 000000000..dc2626d27 --- /dev/null +++ b/integration_tests/web/test_message_metadata.py @@ -0,0 +1,244 @@ +import logging +import os +import time +import unittest +import json + +from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN +from slack_sdk.models.metadata import ( + Metadata, + EventAndEntityMetadata, + EntityMetadata, + ExternalRef, + EntityPayload, + EntityAttributes, + EntityTitle, + TaskEntityFields, + EntityStringField, + EntityTitle, + EntityAttributes, + EntityFullSizePreview, + TaskEntityFields, + EntityTypedField, + EntityStringField, + EntityTimestampField, + EntityEditSupport, + EntityEditTextConfig, + EntityCustomField, + EntityUserIDField, + ExternalRef, +) +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + def setUp(self): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + + def tearDown(self): + pass + + def test_publishing_message_metadata(self): + client: WebClient = WebClient(token=self.bot_token) + new_message = client.chat_postMessage( + channel="#random", + text="message with metadata", + metadata={ + "event_type": "procurement-task", + "event_payload": { + "id": "11111", + "amount": 5000, + "tags": ["foo", "bar", "baz"], + }, + }, + ) + self.assertIsNone(new_message.get("error")) + self.assertIsNotNone(new_message.get("message").get("metadata")) + + history = client.conversations_history( + channel=new_message.get("channel"), + limit=1, + include_all_metadata=True, + ) + self.assertIsNone(history.get("error")) + self.assertIsNotNone(history.get("messages")[0].get("metadata")) + + modification = client.chat_update( + channel=new_message.get("channel"), + ts=new_message.get("ts"), + text="message with metadata (modified)", + metadata={ + "event_type": "procurement-task", + "event_payload": { + "id": "11111", + "amount": 6000, + }, + }, + ) + self.assertIsNone(modification.get("error")) + self.assertIsNotNone(modification.get("message").get("metadata")) + + scheduled = client.chat_scheduleMessage( + channel=new_message.get("channel"), + post_at=int(time.time()) + 30, + text="message with metadata (scheduled)", + metadata={ + "event_type": "procurement-task", + "event_payload": { + "id": "11111", + "amount": 10, + }, + }, + ) + self.assertIsNone(scheduled.get("error")) + self.assertIsNotNone(scheduled.get("message").get("metadata")) + + def test_publishing_message_metadata_using_models(self): + client: WebClient = WebClient(token=self.bot_token) + new_message = client.chat_postMessage( + channel="#random", + text="message with metadata", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 5000, + "tags": ["foo", "bar", "baz"], + }, + ), + ) + self.assertIsNone(new_message.get("error")) + self.assertIsNotNone(new_message.get("message").get("metadata")) + + history = client.conversations_history( + channel=new_message.get("channel"), + limit=1, + include_all_metadata=True, + ) + self.assertIsNone(history.get("error")) + self.assertIsNotNone(history.get("messages")[0].get("metadata")) + + modification = client.chat_update( + channel=new_message.get("channel"), + ts=new_message.get("ts"), + text="message with metadata (modified)", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 6000, + }, + ), + ) + self.assertIsNone(modification.get("error")) + self.assertIsNotNone(modification.get("message").get("metadata")) + + scheduled = client.chat_scheduleMessage( + channel=new_message.get("channel"), + post_at=int(time.time()) + 30, + text="message with metadata (scheduled)", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 10, + }, + ), + ) + self.assertIsNone(scheduled.get("error")) + self.assertIsNotNone(scheduled.get("message").get("metadata")) + + def test_publishing_entity_metadata(self): + client: WebClient = WebClient(token=self.bot_token) + new_message = client.chat_postMessage( + channel="C014KLZN9M0", + text="Message with entity metadata", + metadata={ + "entities": [ + { + "entity_type": "slack#/entities/task", + "url": "https://abc.com/123", + "external_ref": {"id": "123"}, + "entity_payload": { + "attributes": {"title": {"text": "My task"}, "product_name": "We reference only"}, + "fields": { + "due_date": {"value": "2026-06-06", "type": "slack#/types/date", "edit": {"enabled": True}}, + "created_by": {"type": "slack#/types/user", "user": {"user_id": "U014KLZE350"}}, + "date_created": {"value": 1760629278}, + }, + "custom_fields": [ + { + "label": "img", + "key": "img", + "type": "slack#/types/image", + "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/korel-1YjNtFtJlMTaC26A/o.jpg", + } + ], + }, + } + ] + }, + ) + + self.assertIsNone(new_message.get("error")) + self.assertIsNone(new_message.get("warning")) + + def test_publishing_entity_metadata_using_models(self): + # Build the metadata + + title = EntityTitle(text="My title") + full_size_preview = EntityFullSizePreview( + is_supported=True, + preview_url="https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg", + mime_type="image/jpeg", + ) + attributes = EntityAttributes(title=title, product_name="My Product", full_size_preview=full_size_preview) + description = EntityStringField( + value="Description of the task.", + long=True, + edit=EntityEditSupport(enabled=True, text=EntityEditTextConfig(min_length=5, max_length=100)), + ) + due_date = EntityTypedField(value="2026-06-06", type="slack#/types/date", edit=EntityEditSupport(enabled=True)) + created_by = EntityTypedField( + type="slack#/types/user", + user=EntityUserIDField(user_id="USLACKBOT"), + ) + date_created = EntityTimestampField(value=1762450663, type="slack#/types/timestamp") + date_updated = EntityTimestampField(value=1762450663, type="slack#/types/timestamp") + fields = TaskEntityFields( + description=description, + due_date=due_date, + created_by=created_by, + date_created=date_created, + date_updated=date_updated, + ) + custom_fields = [] + custom_fields.append( + EntityCustomField( + label="My Image", + key="my-image", + type="slack#/types/image", + image_url="https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg", + ) + ) + entity = EntityPayload(attributes=attributes, fields=fields, custom_fields=custom_fields) + + client: WebClient = WebClient(token=self.bot_token) + new_message = client.chat_postMessage( + channel="#random", + text="Message with entity metadata", + metadata=EventAndEntityMetadata( + entities=[ + EntityMetadata( + entity_type="slack#/entities/task", + external_ref=ExternalRef(id="abc123"), + url="https://myappdomain.com", + entity_payload=entity, + ) + ] + ), + ) + + self.assertIsNone(new_message.get("error")) + self.assertIsNone(new_message.get("warning")) diff --git a/integration_tests/web/test_remote_file_replacement.py b/integration_tests/web/test_remote_file_replacement.py index 2b9a26a4a..2001b7c63 100644 --- a/integration_tests/web/test_remote_file_replacement.py +++ b/integration_tests/web/test_remote_file_replacement.py @@ -3,10 +3,11 @@ import unittest from uuid import uuid4 -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID -from slack import WebClient +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) +from slack_sdk.web import WebClient class TestWebClient(unittest.TestCase): @@ -22,7 +23,7 @@ def tearDown(self): pass def test_replacing_remote_file_blocks_in_a_message(self): - client: WebClient = WebClient(token=self.bot_token, run_async=False) + client: WebClient = WebClient(token=self.bot_token) current_dir = os.path.dirname(__file__) url = "https://www.example.com/slack-logo" @@ -31,7 +32,8 @@ def test_replacing_remote_file_blocks_in_a_message(self): external_id=external_id, external_url=url, title="Slack Logo", - preview_image=f"{current_dir}/../../tests/data/slack_logo.png" + indexable_file_contents="so many keywords!".encode("utf-8"), + preview_image=f"{current_dir}/../../tests/data/slack_logo.png", ) self.assertIsNotNone(remote_file_creation) @@ -41,16 +43,13 @@ def test_replacing_remote_file_blocks_in_a_message(self): blocks=[ { "type": "section", - "text": { - "type": "plain_text", - "text": "This is v1" - } + "text": {"type": "plain_text", "text": "This is v1"}, }, { "type": "file", "external_id": external_id, "source": "remote", - } + }, ], ) self.assertIsNotNone(new_message) @@ -63,7 +62,8 @@ def test_replacing_remote_file_blocks_in_a_message(self): external_id=external_id, external_url=url, title="Slack Logo", - preview_image=f"{current_dir}/../../tests/data/slack_logo_new.png" + indexable_file_contents="more and more keywords!".encode("utf-8"), + preview_image=f"{current_dir}/../../tests/data/slack_logo_new.png", ) self.assertIsNotNone(new_version) @@ -76,16 +76,13 @@ def test_replacing_remote_file_blocks_in_a_message(self): blocks=[ { "type": "section", - "text": { - "type": "plain_text", - "text": "This is v2" - } + "text": {"type": "plain_text", "text": "This is v2"}, }, { "type": "file", "external_id": external_id, "source": "remote", - } + }, ], ) self.assertIsNotNone(modification) diff --git a/integration_tests/web/test_slack_lists.py b/integration_tests/web/test_slack_lists.py new file mode 100644 index 000000000..6d813bffe --- /dev/null +++ b/integration_tests/web/test_slack_lists.py @@ -0,0 +1,88 @@ +import logging +import os +import unittest + +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, +) +from integration_tests.helpers import async_test +from slack_sdk.web import WebClient +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.models.blocks import RichTextBlock +from slack_sdk.models.blocks.block_elements import RichTextSection, RichTextText + + +class TestSlackLists(unittest.TestCase): + """Runs integration tests with real Slack API testing the slackLists.* APIs""" + + def setUp(self): + if not hasattr(self, "logger"): + self.logger = logging.getLogger(__name__) + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + self.sync_client: WebClient = WebClient(token=self.bot_token) + + def tearDown(self): + pass + + def test_create_list_with_dicts(self): + """Test creating a list with description_blocks as dicts""" + client = self.sync_client + + create_response = client.slackLists_create( + name="Test Sales Pipeline", + description_blocks=[ + { + "type": "rich_text", + "elements": [ + { + "type": "rich_text_section", + "elements": [{"type": "text", "text": "This is a test list for integration testing"}], + } + ], + } + ], + schema=[ + {"key": "deal_name", "name": "Deal Name", "type": "text", "is_primary_column": True}, + {"key": "amount", "name": "Amount", "type": "number", "options": {"format": "currency", "precision": 2}}, + ], + ) + + self.assertIsNotNone(create_response) + self.assertTrue(create_response["ok"]) + self.assertIn("list", create_response) + list_id = create_response["list"]["id"] + self.logger.info(f"βœ“ Created list with ID: {list_id}") + + def test_create_list_with_rich_text_blocks(self): + """Test creating a list with RichTextBlock objects""" + client = self.sync_client + + create_response = client.slackLists_create( + name="Test List with Rich Text Blocks", + description_blocks=[ + RichTextBlock( + elements=[RichTextSection(elements=[RichTextText(text="Created with RichTextBlock objects!")])] + ) + ], + schema=[{"key": "task_name", "name": "Task", "type": "text", "is_primary_column": True}], + ) + + self.assertIsNotNone(create_response) + self.assertTrue(create_response["ok"]) + list_id = create_response["list"]["id"] + self.logger.info(f"βœ“ Created list with RichTextBlocks, ID: {list_id}") + + @async_test + async def test_create_list_async(self): + """Test creating a list with async client""" + client = self.async_client + + create_response = await client.slackLists_create( + name="Async Test List", schema=[{"key": "item_name", "name": "Item", "type": "text", "is_primary_column": True}] + ) + + self.assertIsNotNone(create_response) + self.assertTrue(create_response["ok"]) + list_id = create_response["list"]["id"] + self.logger.info(f"βœ“ Created list asynchronously, ID: {list_id}") diff --git a/integration_tests/web/test_team.py b/integration_tests/web/test_team.py new file mode 100644 index 000000000..c560adc7b --- /dev/null +++ b/integration_tests/web/test_team.py @@ -0,0 +1,28 @@ +import os +import unittest + +from integration_tests.env_variable_names import SLACK_SDK_TEST_BOT_TOKEN +from slack_sdk.web import WebClient + + +class TestWebClient(unittest.TestCase): + def setUp(self): + self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + self.client: WebClient = WebClient(token=self.bot_token) + + def tearDown(self): + pass + + def test_team_billing_info(self): + response = self.client.team_billing_info() + self.assertIsNone(response.get("error")) + self.assertIsNotNone(response.get("plan")) + + def test_team_preferences_list(self): + response = self.client.team_preferences_list() + self.assertIsNone(response.get("error")) + self.assertIsNotNone(response.get("msg_edit_window_mins")) + self.assertIsNotNone(response.get("allow_message_deletion")) + self.assertIsNotNone(response.get("display_real_names")) + self.assertIsNotNone(response.get("disable_file_uploads")) + self.assertIsNotNone(response.get("who_can_post_general")) diff --git a/integration_tests/web/test_web_client.py b/integration_tests/web/test_web_client.py index c3e6858d7..21adbb569 100644 --- a/integration_tests/web/test_web_client.py +++ b/integration_tests/web/test_web_client.py @@ -5,12 +5,15 @@ import pytest -from integration_tests.env_variable_names import \ - SLACK_SDK_TEST_BOT_TOKEN, \ - SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_BOT_TOKEN, + SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID, +) from integration_tests.helpers import async_test, is_not_specified -from slack import WebClient -from slack.web.slack_response import SlackResponse +from slack_sdk.web import WebClient +from slack_sdk.web.slack_response import SlackResponse +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.web.legacy_client import LegacyWebClient class TestWebClient(unittest.TestCase): @@ -20,12 +23,8 @@ def setUp(self): if not hasattr(self, "logger"): self.logger = logging.getLogger(__name__) self.bot_token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - self.async_client: WebClient = WebClient(token=self.bot_token, run_async=True) - self.sync_client: WebClient = WebClient( - token=self.bot_token, - run_async=False, - loop=asyncio.new_event_loop(), # TODO: remove this - ) + self.async_client: AsyncWebClient = AsyncWebClient(token=self.bot_token) + self.sync_client: WebClient = WebClient(token=self.bot_token) self.channel_id = os.environ[SLACK_SDK_TEST_WEB_TEST_CHANNEL_ID] def tearDown(self): @@ -89,18 +88,23 @@ def test_basic_chat_operations(self): auth = client.auth_test() self.assertIsNotNone(auth) - subdomain = auth["team"] + url = auth["url"] channel = self.channel_id - message = "This message was posted by ! " + \ - "(integration_tests/test_web_client.py #test_chat_operations)" + message = ( + "This message was posted by ! " + + "(integration_tests/test_web_client.py #test_chat_operations)" + ) new_message: SlackResponse = client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] permalink = client.chat_getPermalink(channel=channel, message_ts=ts) self.assertIsNotNone(permalink) - self.assertRegex(permalink["permalink"], f"https://{subdomain}.slack.com/archives/{channel}/.+") + self.assertRegex( + permalink["permalink"], + f"{url}archives/{channel}/.+", + ) new_reaction = client.reactions_add(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(new_reaction) @@ -128,18 +132,23 @@ async def test_basic_chat_operations_async(self): auth = await client.auth_test() self.assertIsNotNone(auth) - subdomain = auth["team"] + url = auth["url"] channel = self.channel_id - message = "This message was posted by ! " + \ - "(integration_tests/test_web_client.py #test_chat_operations)" + message = ( + "This message was posted by ! " + + "(integration_tests/test_web_client.py #test_chat_operations)" + ) new_message: SlackResponse = await client.chat_postMessage(channel=channel, text=message) self.assertEqual(new_message["message"]["text"], message) ts = new_message["ts"] permalink = await client.chat_getPermalink(channel=channel, message_ts=ts) self.assertIsNotNone(permalink) - self.assertRegex(permalink["permalink"], f"https://{subdomain}.slack.com/archives/{channel}/.+") + self.assertRegex( + permalink["permalink"], + f"{url}archives/{channel}/.+", + ) new_reaction = await client.reactions_add(channel=channel, timestamp=ts, name="eyes") self.assertIsNotNone(new_reaction) @@ -178,7 +187,11 @@ async def test_uploading_text_files_async(self): client = self.async_client file, filename = __file__, os.path.basename(__file__) upload = await client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename=filename, file=file) + channels=self.channel_id, + title="Good Old Slack Logo", + filename=filename, + file=file, + ) self.assertIsNotNone(upload) deletion = await client.files_delete(file=upload["file"]["id"]) @@ -189,7 +202,11 @@ def test_uploading_binary_files(self): current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", file=file) + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) self.assertIsNotNone(upload) deletion = client.files_delete(file=upload["file"]["id"]) @@ -199,10 +216,14 @@ def test_uploading_binary_files_as_content(self): client = self.sync_client current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" - with open(file, 'rb') as f: + with open(file, "rb") as f: content = f.read() upload = client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", content=content) + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + content=content, + ) self.assertIsNotNone(upload) deletion = client.files_delete(file=upload["file"]["id"]) @@ -214,10 +235,14 @@ async def test_uploading_binary_files_async(self): current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = await client.files_upload( - channels=self.channel_id, title="Good Old Slack Logo", filename="slack_logo.png", file=file) + channels=self.channel_id, + title="Good Old Slack Logo", + filename="slack_logo.png", + file=file, + ) self.assertIsNotNone(upload) - deletion = client.files_delete(file=upload["file"]["id"]) + deletion = await client.files_delete(file=upload["file"]["id"]) self.assertIsNotNone(deletion) def test_uploading_file_with_token_param(self): @@ -241,7 +266,7 @@ def test_uploading_file_with_token_param(self): @async_test async def test_uploading_file_with_token_param_async(self): - client = WebClient(run_async=True) + client = AsyncWebClient() current_dir = os.path.dirname(__file__) file = f"{current_dir}/../../tests/data/slack_logo.png" upload = await client.files_upload( @@ -253,7 +278,7 @@ async def test_uploading_file_with_token_param_async(self): ) self.assertIsNotNone(upload) - deletion = client.files_delete( + deletion = await client.files_delete( token=self.bot_token, file=upload["file"]["id"], ) @@ -274,7 +299,7 @@ def test_pagination_with_iterator(self): self.assertGreater(fetched_count, 1) def test_pagination_with_iterator_use_sync_aiohttp(self): - client: WebClient = WebClient( + client: LegacyWebClient = LegacyWebClient( token=self.bot_token, run_async=False, use_sync_aiohttp=True, diff --git a/integration_tests/webhook/test_async_webhook.py b/integration_tests/webhook/test_async_webhook.py index b32ccc86d..8095c2fa1 100644 --- a/integration_tests/webhook/test_async_webhook.py +++ b/integration_tests/webhook/test_async_webhook.py @@ -1,22 +1,36 @@ import os +from tests.helpers import async_test import unittest +import time -from integration_tests.env_variable_names import SLACK_SDK_TEST_INCOMING_WEBHOOK_URL, \ - SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME, \ - SLACK_SDK_TEST_BOT_TOKEN -from integration_tests.helpers import async_test -from slack import AsyncWebClient -from slack import AsyncWebhookClient -from slack.web.classes.attachments import Attachment, AttachmentField -from slack.web.classes.blocks import SectionBlock, DividerBlock, ActionsBlock -from slack.web.classes.elements import ButtonElement -from slack.web.classes.objects import MarkdownTextObject, PlainTextObject +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_INCOMING_WEBHOOK_URL, + SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME, + SLACK_SDK_TEST_BOT_TOKEN, +) +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.webhook.async_client import AsyncWebhookClient +from slack_sdk.models.attachments import Attachment, AttachmentField +from slack_sdk.models.blocks import SectionBlock, DividerBlock, ActionsBlock +from slack_sdk.models.blocks.block_elements import ButtonElement +from slack_sdk.models.blocks.basic_components import MarkdownTextObject, PlainTextObject class TestAsyncWebhook(unittest.TestCase): - - def setUp(self): - pass + @async_test + async def setUp(self): + if not hasattr(self, "channel_id"): + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") + client = AsyncWebClient(token=token) + self.channel_id = None + async for resp in await client.conversations_list(limit=1000): + for c in resp["channels"]: + if c["name"] == channel_name: + self.channel_id = c["id"] + break + if self.channel_id is not None: + break def tearDown(self): pass @@ -30,22 +44,56 @@ async def test_webhook(self): self.assertEqual("ok", response.body) token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") client = AsyncWebClient(token=token) - channel_id = None - async for resp in await client.conversations_list(limit=10): - for c in resp["channels"]: - if c["name"] == channel_name: - channel_id = c["id"] - break - if channel_id is not None: - break - - history = await client.conversations_history(channel=channel_id, limit=1) + history = await client.conversations_history(channel=self.channel_id, limit=1) self.assertIsNotNone(history) actual_text = history["messages"][0]["text"] self.assertEqual("Hello!", actual_text) + @async_test + async def test_with_unfurls_off(self): + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + webhook = AsyncWebhookClient(url) + client = AsyncWebClient(token=token) + # send message that does not unfurl + response = await webhook.send( + text="", + unfurl_links=False, + unfurl_media=False, + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + # wait to allow Slack API to edit message with attachments + time.sleep(2) + history = await client.conversations_history(channel=self.channel_id, limit=1) + self.assertIsNotNone(history) + self.assertTrue("attachments" not in history["messages"][0]) + + @async_test + async def test_with_unfurls_on(self): + # Slack API rate limits unfurls of unique links so test will + # fail when repeated. For testing, either use a different URL + # for text option or delete existing attachments in webhook channel. + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + webhook = AsyncWebhookClient(url) + client = AsyncWebClient(token=token) + # send message that does unfurl + response = await webhook.send( + text="", + unfurl_links=True, + unfurl_media=True, + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + # wait to allow Slack API to edit message with attachments + time.sleep(2) + history = await client.conversations_history(channel=self.channel_id, limit=1) + self.assertIsNotNone(history) + # FIXME: when repeatedly running this test, the following assertion can fail + self.assertTrue("attachments" in history["messages"][0]) + @async_test async def test_with_blocks(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] @@ -60,7 +108,7 @@ async def test_with_blocks(self): PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), PlainTextObject(text="*this is plain_text text*", emoji=True), - ] + ], ), DividerBlock(), ActionsBlock( @@ -80,7 +128,7 @@ async def test_with_blocks(self): ), ], ), - ] + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -111,13 +159,10 @@ async def test_with_blocks_dict(self): { "type": "plain_text", "text": "*this is plain_text text*", - } - ] - }, - { - "type": "divider", - "block_id": "9SxG" + }, + ], }, + {"type": "divider", "block_id": "9SxG"}, { "type": "actions", "block_id": "avJ", @@ -130,7 +175,7 @@ async def test_with_blocks_dict(self): "text": "Create New Task", }, "style": "primary", - "value": "create_task" + "value": "create_task", }, { "type": "button", @@ -139,7 +184,7 @@ async def test_with_blocks_dict(self): "type": "plain_text", "text": "Create New Project", }, - "value": "create_project" + "value": "create_project", }, { "type": "button", @@ -148,11 +193,11 @@ async def test_with_blocks_dict(self): "type": "plain_text", "text": "Help", }, - "value": "help" - } - ] - } - ] + "value": "help", + }, + ], + }, + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -170,10 +215,7 @@ async def test_with_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -184,7 +226,7 @@ async def test_with_attachments(self): ts=123456789, markdown_in=["fields"], ) - ] + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -226,13 +268,25 @@ async def test_with_attachments_dict(self): { "title": "field_4_title", "value": "field_4_value", - } + }, ], - "mrkdwn_in": [ - "fields" - ] + "mrkdwn_in": ["fields"], } - ] + ], + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + + @async_test + async def test_metadata(self): + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + webhook = AsyncWebhookClient(url) + response = await webhook.send( + text="Hello with metadata", + metadata={ + "event_type": "foo", + "event_payload": {"foo": "bar"}, + }, ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) diff --git a/integration_tests/webhook/test_webhook.py b/integration_tests/webhook/test_webhook.py index 4c53d1e40..d1e55c6a0 100644 --- a/integration_tests/webhook/test_webhook.py +++ b/integration_tests/webhook/test_webhook.py @@ -1,21 +1,36 @@ import os import unittest +import time -from integration_tests.env_variable_names import SLACK_SDK_TEST_INCOMING_WEBHOOK_URL, \ - SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME, \ - SLACK_SDK_TEST_BOT_TOKEN -from slack import WebClient -from slack import WebhookClient -from slack.web.classes.attachments import Attachment, AttachmentField -from slack.web.classes.blocks import SectionBlock, DividerBlock, ActionsBlock -from slack.web.classes.elements import ButtonElement -from slack.web.classes.objects import MarkdownTextObject, PlainTextObject +import pytest +from integration_tests.env_variable_names import ( + SLACK_SDK_TEST_INCOMING_WEBHOOK_URL, + SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME, + SLACK_SDK_TEST_BOT_TOKEN, +) +from slack_sdk.web import WebClient +from slack_sdk.webhook import WebhookClient +from slack_sdk.models.attachments import Attachment, AttachmentField +from slack_sdk.models.blocks import SectionBlock, DividerBlock, ActionsBlock +from slack_sdk.models.blocks.block_elements import ButtonElement +from slack_sdk.models.blocks.basic_components import MarkdownTextObject, PlainTextObject -class TestWebhook(unittest.TestCase): +class TestWebhook(unittest.TestCase): def setUp(self): - pass + if not hasattr(self, "channel_id"): + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") + client = WebClient(token=token) + self.channel_id = None + for resp in client.conversations_list(limit=1000): + for c in resp["channels"]: + if c["name"] == channel_name: + self.channel_id = c["id"] + break + if self.channel_id is not None: + break def tearDown(self): pass @@ -28,22 +43,55 @@ def test_webhook(self): self.assertEqual("ok", response.body) token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] - channel_name = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_CHANNEL_NAME].replace("#", "") client = WebClient(token=token) - channel_id = None - for resp in client.conversations_list(limit=10): - for c in resp["channels"]: - if c["name"] == channel_name: - channel_id = c["id"] - break - if channel_id is not None: - break - - history = client.conversations_history(channel=channel_id, limit=1) + history = client.conversations_history(channel=self.channel_id, limit=1) self.assertIsNotNone(history) actual_text = history["messages"][0]["text"] self.assertEqual("Hello!", actual_text) + def test_with_unfurls_off(self): + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + webhook = WebhookClient(url) + client = WebClient(token=token) + # send message that does not unfurl + response = webhook.send( + text="", + unfurl_links=False, + unfurl_media=False, + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + # wait to allow Slack API to edit message with attachments + time.sleep(2) + history = client.conversations_history(channel=self.channel_id, limit=1) + self.assertIsNotNone(history) + self.assertTrue("attachments" not in history["messages"][0]) + + # FIXME: This test started failing as of August 5, 2021 + @pytest.mark.skip() + def test_with_unfurls_on(self): + # Slack API rate limits unfurls of unique links so test will + # fail when repeated. For testing, either use a different URL + # for text option or delete existing attachments in webhook channel. + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + token = os.environ[SLACK_SDK_TEST_BOT_TOKEN] + webhook = WebhookClient(url) + client = WebClient(token=token) + # send message that does unfurl + response = webhook.send( + text="", + unfurl_links=True, + unfurl_media=True, + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + # wait to allow Slack API to edit message with attachments + time.sleep(2) + history = client.conversations_history(channel=self.channel_id, limit=1) + self.assertIsNotNone(history) + self.assertTrue("attachments" in history["messages"][0]) + def test_with_blocks(self): url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] webhook = WebhookClient(url) @@ -57,7 +105,7 @@ def test_with_blocks(self): PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), PlainTextObject(text="*this is plain_text text*", emoji=True), - ] + ], ), DividerBlock(), ActionsBlock( @@ -77,7 +125,7 @@ def test_with_blocks(self): ), ], ), - ] + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -107,13 +155,10 @@ def test_with_blocks_dict(self): { "type": "plain_text", "text": "*this is plain_text text*", - } - ] - }, - { - "type": "divider", - "block_id": "9SxG" + }, + ], }, + {"type": "divider", "block_id": "9SxG"}, { "type": "actions", "block_id": "avJ", @@ -126,7 +171,7 @@ def test_with_blocks_dict(self): "text": "Create New Task", }, "style": "primary", - "value": "create_task" + "value": "create_task", }, { "type": "button", @@ -135,7 +180,7 @@ def test_with_blocks_dict(self): "type": "plain_text", "text": "Create New Project", }, - "value": "create_project" + "value": "create_project", }, { "type": "button", @@ -144,11 +189,11 @@ def test_with_blocks_dict(self): "type": "plain_text", "text": "Help", }, - "value": "help" - } - ] - } - ] + "value": "help", + }, + ], + }, + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -165,10 +210,7 @@ def test_with_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -179,7 +221,7 @@ def test_with_attachments(self): ts=123456789, markdown_in=["fields"], ) - ] + ], ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) @@ -220,13 +262,24 @@ def test_with_attachments_dict(self): { "title": "field_4_title", "value": "field_4_value", - } + }, ], - "mrkdwn_in": [ - "fields" - ] + "mrkdwn_in": ["fields"], } - ] + ], + ) + self.assertEqual(200, response.status_code) + self.assertEqual("ok", response.body) + + def test_metadata(self): + url = os.environ[SLACK_SDK_TEST_INCOMING_WEBHOOK_URL] + webhook = WebhookClient(url) + response = webhook.send( + text="Hello with metadata", + metadata={ + "event_type": "foo", + "event_payload": {"foo": "bar"}, + }, ) self.assertEqual(200, response.status_code) self.assertEqual("ok", response.body) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..37c6f3546 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,79 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "slack_sdk" +dynamic = ["version", "readme", "authors", "optional-dependencies"] +description = "The Slack API Platform SDK for Python" +license = { text = "MIT" } +requires-python = ">=3.7" +keywords = [ + "slack", + "slack-api", + "web-api", + "slack-rtm", + "websocket", + "chat", + "chatbot", + "chatops", +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Topic :: Communications :: Chat", + "Topic :: System :: Networking", + "Topic :: Office/Business", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] + + +[project.urls] +Documentation = "https://docs.slack.dev/tools/python-slack-sdk/" + +[tool.setuptools.packages.find] +include = ["slack*", "slack_sdk*"] + +[tool.setuptools.dynamic] +version = { attr = "slack_sdk.version.__version__" } +readme = { file = ["README.md"], content-type = "text/markdown" } +optional-dependencies.optional = { file = ["requirements/optional.txt"] } + +[tool.distutils.bdist_wheel] +universal = true + +[tool.black] +line-length = 125 + +[tool.pytest.ini_options] +testpaths = ["tests"] +log_file = "logs/pytest.log" +log_file_level = "DEBUG" +log_format = "%(asctime)s %(levelname)s %(message)s" +log_date_format = "%Y-%m-%d %H:%M:%S" +filterwarnings = [ + "ignore:\"@coroutine\" decorator is deprecated since Python 3.8, use \"async def\" instead:DeprecationWarning", + "ignore:The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.:DeprecationWarning", + "ignore:slack.* package is deprecated. Please use slack_sdk.* package instead.*:UserWarning", +] +asyncio_mode = "auto" + + +[tool.mypy] +files = "slack_sdk/" +exclude = ["slack_sdk/scim", "slack_sdk/rtm"] +force_union_syntax = true +warn_unused_ignores = true +enable_error_code = "ignore-without-code" diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index c1710c8ef..000000000 --- a/pytest.ini +++ /dev/null @@ -1,8 +0,0 @@ -[pytest] -log_file = logs/pytest.log -log_file_level = DEBUG -log_format = %(asctime)s %(levelname)s %(message)s -log_date_format = %Y-%m-%d %H:%M:%S -filterwarnings = - ignore:"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead:DeprecationWarning - ignore:The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.:DeprecationWarning \ No newline at end of file diff --git a/requirements/documentation.txt b/requirements/documentation.txt new file mode 100644 index 000000000..57304cb53 --- /dev/null +++ b/requirements/documentation.txt @@ -0,0 +1,2 @@ +docutils==0.22.4 +pdoc3==0.11.6 diff --git a/requirements/optional.txt b/requirements/optional.txt new file mode 100644 index 000000000..48c9a630d --- /dev/null +++ b/requirements/optional.txt @@ -0,0 +1,16 @@ +# pip install -r requirements/optional.txt +# async modules depend on aiohttp +aiodns>1.0 +# We recommend using 3.7.1+ for RTMClient +# https://github.com/slackapi/python-slack-sdk/issues/912 +aiohttp>=3.7.3,<4 +# used only under slack_sdk/*_store +boto3<=2 +# InstallationStore/OAuthStateStore +# Since v3.20, we no longer support SQLAlchemy 1.3 or older. +# If you need to use a legacy version, please add our v3.19.5 code to your project. +SQLAlchemy>=1.4,<3 +# Socket Mode +# websockets 9 is not compatible with Python 3.10 +websockets>=9.1,<16 +websocket-client>=1,<2 diff --git a/requirements/testing.txt b/requirements/testing.txt new file mode 100644 index 000000000..9e1a3fd67 --- /dev/null +++ b/requirements/testing.txt @@ -0,0 +1,14 @@ +# pip install -r requirements/testing.txt +aiohttp<4 # used for a WebSocket server mock +pytest>=7.0.1,<9 +pytest-asyncio<2 # for async +pytest-cov>=2,<8 +click==8.0.4 # black is affected by https://github.com/pallets/click/issues/2225 +psutil>=6.0.0,<8 +# used only under slack_sdk/*_store +boto3<=2 +# For AWS tests +moto>=4.0.13,<6 +# For AsyncSQLAlchemy tests +greenlet<=4 +aiosqlite<=1 diff --git a/requirements/tools.txt b/requirements/tools.txt new file mode 100644 index 000000000..39946a86d --- /dev/null +++ b/requirements/tools.txt @@ -0,0 +1,7 @@ +mypy<=1.19.0; +# while flake8 5.x have issues with Python 3.12, flake8 6.x requires Python >= 3.8.1, +# so 5.x should be kept in order to stay compatible with Python 3.7/3.8 +flake8>=5.0.4,<8 +# Don't change this version without running CI builds; +# The latest version may not be available for older Python runtime +black==24.3.0; diff --git a/scripts/build_pypi_package.sh b/scripts/build_pypi_package.sh new file mode 100755 index 000000000..76b3e8e41 --- /dev/null +++ b/scripts/build_pypi_package.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +script_dir=`dirname $0` +cd ${script_dir}/.. +rm -rf ./slack_sdk.egg-info + +pip install -U pip && \ + pip install -U twine build && \ + rm -rf dist/ build/ slack_sdk.egg-info/ && \ + python -m build --sdist --wheel && \ + twine check dist/* diff --git a/scripts/codegen.py b/scripts/codegen.py new file mode 100644 index 000000000..3633faf35 --- /dev/null +++ b/scripts/codegen.py @@ -0,0 +1,153 @@ +import argparse +import sys + +parser = argparse.ArgumentParser() +parser.add_argument("-p", "--path", help="Path to the project source code.", type=str) +if len(sys.argv) == 1: + parser.print_help(sys.stderr) + sys.exit(1) +args = parser.parse_args() + +header = ( + "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" + "#\n" + "# *** DO NOT EDIT THIS FILE ***\n" + "#\n" + "# 1) Modify slack_sdk/web/client.py\n" + "# 2) Run `python scripts/codegen.py`\n" + "# 3) Run `black slack_sdk/`\n" + "#\n" + "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" + "\n" +) + +with open(f"{args.path}/slack_sdk/web/client.py", "r") as original: + source = original.read() + import re + + async_source = header + source + async_source = re.sub(" def ", " async def ", async_source) + async_source = re.sub("from asyncio import Future\n", "", async_source) + async_source = re.sub(r"return self.api_call\(", "return await self.api_call(", async_source) + async_source = re.sub("-> SlackResponse", "-> AsyncSlackResponse", async_source) + async_source = re.sub( + "from .base_client import BaseClient, SlackResponse", + "from .async_base_client import AsyncBaseClient, AsyncSlackResponse", + async_source, + ) + async_source = re.sub( + r"class WebClient\(BaseClient\):", + "class AsyncWebClient(AsyncBaseClient):", + async_source, + ) + async_source = re.sub( + "from slack_sdk import WebClient", + "from slack_sdk.web.async_client import AsyncWebClient", + async_source, + ) + async_source = re.sub(r"= WebClient\(", "= AsyncWebClient(", async_source) + async_source = re.sub( + "from slack_sdk.web.chat_stream import ChatStream", + "from slack_sdk.web.async_chat_stream import AsyncChatStream", + async_source, + ) + async_source = re.sub(r"ChatStream:", "AsyncChatStream:", async_source) + async_source = re.sub(r"ChatStream\(", "AsyncChatStream(", async_source) + async_source = re.sub( + r" client.chat_stream\(", + " await client.chat_stream(", + async_source, + ) + async_source = re.sub( + r" streamer.append\(", + " await streamer.append(", + async_source, + ) + async_source = re.sub( + r" streamer.stop\(", + " await streamer.stop(", + async_source, + ) + async_source = re.sub( + r" self.files_getUploadURLExternal\(", + " await self.files_getUploadURLExternal(", + async_source, + ) + async_source = re.sub( + r" self._upload_file\(", + " await self._upload_file(", + async_source, + ) + async_source = re.sub( + r" self.files_completeUploadExternal\(", + " await self.files_completeUploadExternal(", + async_source, + ) + async_source = re.sub( + r" self.files_info\(", + " await self.files_info(", + async_source, + ) + async_source = re.sub( + "_attach_full_file_metadata", + "_attach_full_file_metadata_async", + async_source, + ) + async_source = re.sub( + r" _attach_full_file_metadata_async\(", + " await _attach_full_file_metadata_async(", + async_source, + ) + with open(f"{args.path}/slack_sdk/web/async_client.py", "w") as output: + output.write(async_source) + + legacy_source = header + "from asyncio import Future\n" + source + legacy_source = re.sub("-> SlackResponse", "-> Union[Future, SlackResponse]", legacy_source) + legacy_source = re.sub( + "from .base_client import BaseClient, SlackResponse", + "from .legacy_base_client import LegacyBaseClient, SlackResponse", + legacy_source, + ) + legacy_source = re.sub( + r"class WebClient\(BaseClient\):", + "class LegacyWebClient(LegacyBaseClient):", + legacy_source, + ) + legacy_source = re.sub( + "from slack_sdk import WebClient", + "from slack_sdk.web.legacy_client import LegacyWebClient", + legacy_source, + ) + legacy_source = re.sub(r"= WebClient\(", "= LegacyWebClient(", legacy_source) + legacy_source = re.sub(r"^from slack_sdk.web.chat_stream import ChatStream\n", "", legacy_source, flags=re.MULTILINE) + legacy_source = re.sub(r"(?s)def chat_stream.*?(?=def)", "", legacy_source) + with open(f"{args.path}/slack_sdk/web/legacy_client.py", "w") as output: + output.write(legacy_source) + +with open(f"{args.path}/slack_sdk/web/chat_stream.py", "r") as original: + source = original.read() + import re + + async_source = header + source + async_source = re.sub( + "from slack_sdk.web.slack_response import SlackResponse", + "from slack_sdk.web.async_slack_response import AsyncSlackResponse", + async_source, + ) + async_source = re.sub( + r"from slack_sdk import WebClient", + "from slack_sdk.web.async_client import AsyncWebClient", + async_source, + ) + async_source = re.sub("class ChatStream", "class AsyncChatStream", async_source) + async_source = re.sub('"WebClient"', '"AsyncWebClient"', async_source) + async_source = re.sub(r"Optional\[SlackResponse\]", "Optional[AsyncSlackResponse]", async_source) + async_source = re.sub(r"SlackResponse ", "AsyncSlackResponse ", async_source) + async_source = re.sub(r"SlackResponse:", "AsyncSlackResponse:", async_source) + async_source = re.sub(r"def append\(", "async def append(", async_source) + async_source = re.sub(r"def stop\(", "async def stop(", async_source) + async_source = re.sub(r"def _flush_buffer\(", "async def _flush_buffer(", async_source) + async_source = re.sub("self._client.chat_", "await self._client.chat_", async_source) + async_source = re.sub("self._flush_buffer", "await self._flush_buffer", async_source) + with open(f"{args.path}/slack_sdk/web/async_chat_stream.py", "w") as output: + output.write(async_source) diff --git a/scripts/deploy_to_prod_pypi_org.sh b/scripts/deploy_to_prod_pypi_org.sh deleted file mode 100755 index 4b15fef2c..000000000 --- a/scripts/deploy_to_prod_pypi_org.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -python setup.py upload diff --git a/scripts/deploy_to_test_pypi.sh b/scripts/deploy_to_test_pypi.sh new file mode 100755 index 000000000..54ed0e04b --- /dev/null +++ b/scripts/deploy_to_test_pypi.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +script_dir=`dirname $0` +cd ${script_dir}/.. +rm -rf ./slack_sdk.egg-info + +pip install -U pip && \ + pip install -U twine build && \ + rm -rf dist/ build/ slack_sdk.egg-info/ && \ + python -m build --sdist --wheel && \ + twine check dist/* && \ + twine upload --repository testpypi dist/* diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100755 index 000000000..56ca68077 --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,13 @@ +#!/bin/bash +# ./scripts/format.sh + +script_dir=`dirname $0` +cd ${script_dir}/.. + +if [[ "$1" != "--no-install" ]]; then + export PIP_REQUIRE_VIRTUALENV=1 + pip install -U pip + pip install -U -r requirements/tools.txt +fi + +black slack/ slack_sdk/ tests/ integration_tests/ diff --git a/scripts/generate_api_docs.sh b/scripts/generate_api_docs.sh new file mode 100755 index 000000000..c2bb260ab --- /dev/null +++ b/scripts/generate_api_docs.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Generate API documents from the latest source code + +script_dir=`dirname $0` +cd ${script_dir}/.. + +pip install -U -r requirements/documentation.txt +pip install -U -r requirements/optional.txt + +rm -rf docs/reference + +HOME="\$HOME" pdoc slack_sdk --html -o docs/reference +cp -R docs/reference/slack_sdk/* docs/reference/ +rm -rf docs/reference/slack_sdk + +open docs/reference/index.html diff --git a/scripts/lint.sh b/scripts/lint.sh new file mode 100755 index 000000000..8fac67888 --- /dev/null +++ b/scripts/lint.sh @@ -0,0 +1,14 @@ + +#!/bin/bash +# ./scripts/lint.sh + +script_dir=`dirname $0` +cd ${script_dir}/.. + +if [[ "$1" != "--no-install" ]]; then + pip install -U pip + pip install -U -r requirements/tools.txt +fi + +black --check slack/ slack_sdk/ tests/ integration_tests/ +flake8 slack/ slack_sdk/ diff --git a/scripts/run_integration_tests.sh b/scripts/run_integration_tests.sh index 99103afda..1a6f254cb 100755 --- a/scripts/run_integration_tests.sh +++ b/scripts/run_integration_tests.sh @@ -3,19 +3,18 @@ # all: ./scripts/run_integration_tests.sh # single: ./scripts/run_integration_tests.sh integration_tests/web/test_async_web_client.py +set -e + script_dir=`dirname $0` cd ${script_dir}/.. -test_target="$1" -python_version=`python --version | awk '{print $2}'` +pip install -U pip +pip install -U -r requirements/testing.txt \ + -U -r requirements/optional.txt \ + -U -r requirements/tools.txt + +echo "Generating code ..." && python scripts/codegen.py --path . +echo "Running black (code formatter) ..." && ./scripts/format.sh --no-install -if [[ $test_target != "" ]] -then - black slack_sdk/ slack/ tests/ && \ - python setup.py codegen && \ - python setup.py integration_tests --test-target $1 -else - black slack_sdk/ slack/ tests/ && \ - python setup.py codegen && \ - python setup.py integration_tests -fi +test_target="${1:-tests/integration_tests/}" +PYTHONPATH=$PWD:$PYTHONPATH pytest $test_target diff --git a/scripts/run_mypy.sh b/scripts/run_mypy.sh new file mode 100755 index 000000000..cc1146f15 --- /dev/null +++ b/scripts/run_mypy.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# ./scripts/run_mypy.sh + +set -e + +script_dir=$(dirname $0) +cd ${script_dir}/.. + +pip install -U pip setuptools wheel +pip install -U -r requirements/testing.txt \ + -U -r requirements/optional.txt \ + -U -r requirements/tools.txt + +mypy --config-file pyproject.toml diff --git a/scripts/run_unit_tests.sh b/scripts/run_unit_tests.sh index f8f28a793..c8ab0af78 100755 --- a/scripts/run_unit_tests.sh +++ b/scripts/run_unit_tests.sh @@ -3,19 +3,19 @@ # all: ./scripts/run_unit_tests.sh # single: ./scripts/run_unit_tests.sh tests/slack_sdk_async/web/test_web_client_coverage.py +set -e + script_dir=`dirname $0` cd ${script_dir}/.. -test_target="$1" -python_version=`python --version | awk '{print $2}'` +pip install -U pip +pip install -U -r requirements/testing.txt \ + -U -r requirements/optional.txt \ + -U -r requirements/tools.txt + +echo "Generating code ..." && python scripts/codegen.py --path . +echo "Running black (code formatter) ..." && ./scripts/format.sh --no-install -if [[ $test_target != "" ]] -then - black slack_sdk/ slack/ tests/ && \ - python setup.py codegen && \ - python setup.py unit_tests --test-target $1 -else - black slack_sdk/ slack/ tests/ && \ - python setup.py codegen && \ - python setup.py unit_tests -fi +echo "Running tests ..." +test_target="${1:-tests/}" +PYTHONPATH=$PWD:$PYTHONPATH pytest $test_target diff --git a/scripts/run_validation.sh b/scripts/run_validation.sh index 8f7f432e4..366f0d321 100755 --- a/scripts/run_validation.sh +++ b/scripts/run_validation.sh @@ -1,8 +1,21 @@ #!/bin/bash -# ./scripts/run_validation.sh +# all: ./scripts/run_validation.sh +# single: ./scripts/run_validation.sh tests/slack_sdk_async/web/test_web_client_coverage.py + +set -e script_dir=`dirname $0` cd ${script_dir}/.. -black slack_sdk/ slack/ tests/ && \ - python setup.py codegen && \ - python setup.py validate + +pip install -U -r requirements/testing.txt \ + -U -r requirements/optional.txt \ + -U -r requirements/tools.txt + +echo "Generating code ..." && python scripts/codegen.py --path . +echo "Running black (code formatter) ..." && ./scripts/format.sh --no-install + +echo "Running linting checks ..." && ./scripts/lint.sh --no-install + +echo "Running tests with coverage reporting ..." +test_target="${1:-tests/}" +PYTHONPATH=$PWD:$PYTHONPATH pytest --cov-report=xml --cov=slack_sdk/ $test_target diff --git a/scripts/uninstall_all.sh b/scripts/uninstall_all.sh new file mode 100755 index 000000000..71a1e51f6 --- /dev/null +++ b/scripts/uninstall_all.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# remove slack-sdk without a version specifier so that local builds are cleaned up +pip uninstall -y slack-sdk +# collect all installed packages +PACKAGES=$(pip freeze | grep -v "^-e" | sed 's/@.*//' | sed 's/\=\=.*//') +# uninstall packages without exiting on a failure +for package in $PACKAGES; do + pip uninstall -y $package +done diff --git a/setup.cfg b/setup.cfg index b7e478982..384126b63 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,5 @@ -[aliases] -test=pytest +; Legacy package configuration, prefer pyproject.toml over setup.cfg or setup.py +[metadata] +url=https://github.com/slackapi/python-slack-sdk +author=Slack Technologies, LLC +author_email=opensource@slack.com diff --git a/setup.py b/setup.py deleted file mode 100644 index eb94561d4..000000000 --- a/setup.py +++ /dev/null @@ -1,315 +0,0 @@ -# -*- coding: utf-8 -*- -import codecs -import os -import subprocess -import sys -from shutil import rmtree - -from setuptools import setup, find_packages, Command - -here = os.path.abspath(os.path.dirname(__file__)) - -__version__ = None -exec(open(f"{here}/slack_sdk/version.py").read()) - -long_description = "" -with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as readme: - long_description = readme.read() - -validate_dependencies = [ - "pytest>=5.4,<6", - "pytest-asyncio<1", # for async - "pytest-cov>=2,<3", - "codecov>=2,<3", - "flake8>=3,<4", - "black==19.10b0", - "psutil>=5,<6", - "databases>=0.3", -] -codegen_dependencies = [ - "black==19.10b0", -] - -needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv) -pytest_runner = ["pytest-runner"] if needs_pytest else [] - - -class BaseCommand(Command): - user_options = [] - - @staticmethod - def status(s): - """Prints things in bold.""" - print("\033[1m{0}\033[0m".format(s)) - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def _run(self, s, command): - try: - self.status(s + "\n" + " ".join(command)) - subprocess.check_call(command) - except subprocess.CalledProcessError as error: - sys.exit(error.returncode) - - -class UploadCommand(BaseCommand): - """Support setup.py upload. Thanks @kennethreitz!""" - - description = "Build and publish the package." - - def run(self): - self._run( - "Installing upload dependencies ...", - [sys.executable, "-m", "pip", "install", "wheel"], - ) - try: - self.status("Removing previous builds ...") - rmtree(os.path.join(here, "dist")) - rmtree(os.path.join(here, "build")) - except OSError: - pass - - self._run( - "Building Source and Wheel (universal) distribution ...", - [sys.executable, "setup.py", "sdist", "bdist_wheel", "--universal"], - ) - self._run( - "Installing Twine dependency ...", - [sys.executable, "-m", "pip", "install", "twine"], - ) - self._run( - "Uploading the package to PyPI via Twine ...", - [sys.executable, "-m", "twine", "upload", "dist/*"], - ) - - -class CodegenCommand(BaseCommand): - def run(self): - self._run( - "Installing required dependencies ...", - [sys.executable, "-m", "pip", "install"] + codegen_dependencies, - ) - - header = ( - "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" - "#\n" - "# *** DO NOT EDIT THIS FILE ***\n" - "#\n" - "# 1) Modify slack_sdk/web/client.py\n" - "# 2) Run `python setup.py codegen`\n" - "#\n" - "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" - "\n" - ) - with open(f"{here}/slack_sdk/web/client.py", "r") as original: - source = original.read() - import re - - async_source = header + source - async_source = re.sub(" def ", " async def ", async_source) - async_source = re.sub("from asyncio import Future\n", "", async_source) - async_source = re.sub( - "return self.api_call\(", "return await self.api_call(", async_source - ) - async_source = re.sub( - "-> SlackResponse", "-> AsyncSlackResponse", async_source - ) - async_source = re.sub( - "from .base_client import BaseClient, SlackResponse", - "from .async_base_client import AsyncBaseClient, AsyncSlackResponse", - async_source, - ) - # from slack_sdk import WebClient - async_source = re.sub( - "class WebClient\(BaseClient\):", - "class AsyncWebClient(AsyncBaseClient):", - async_source, - ) - async_source = re.sub( - "from slack_sdk import WebClient", - "from slack_sdk.web.async_client import AsyncWebClient", - async_source, - ) - async_source = re.sub("= WebClient\(", "= AsyncWebClient(", async_source) - with open(f"{here}/slack_sdk/web/async_client.py", "w") as output: - output.write(async_source) - - legacy_source = header + "from asyncio import Future\n" + source - legacy_source = re.sub( - "-> SlackResponse", "-> Union[Future, SlackResponse]", legacy_source - ) - legacy_source = re.sub( - "from .base_client import BaseClient, SlackResponse", - "from .legacy_base_client import LegacyBaseClient, SlackResponse", - legacy_source, - ) - legacy_source = re.sub( - "class WebClient\(BaseClient\):", - "class LegacyWebClient(LegacyBaseClient):", - legacy_source, - ) - legacy_source = re.sub( - "from slack_sdk import WebClient", - "from slack_sdk.web.legacy_client import LegacyWebClient", - legacy_source, - ) - legacy_source = re.sub("= WebClient\(", "= LegacyWebClient(", legacy_source) - with open(f"{here}/slack_sdk/web/legacy_client.py", "w") as output: - output.write(legacy_source) - - self._run( - "Running black (code formatter) ... ", - [sys.executable, "-m", "black", f"{here}/slack_sdk"], - ) - - -class ValidateCommand(BaseCommand): - """Support setup.py validate.""" - - description = "Run Python static code analyzer (flake8), formatter (black) and unit tests (pytest)." - - user_options = [("test-target=", "i", "tests/{test-target}")] - - def initialize_options(self): - self.test_target = "" - - def run(self): - self._run( - "Installing test dependencies ...", - [sys.executable, "-m", "pip", "install"] + validate_dependencies, - ) - self._run("Running black ...", [sys.executable, "-m", "black", f"{here}/slack"]) - self._run( - "Running black ...", [sys.executable, "-m", "black", f"{here}/slack_sdk"] - ) - self._run( - "Running flake8 for legacy packages ...", [sys.executable, "-m", "flake8", f"{here}/slack"] - ) - self._run( - "Running flake8 for slack_sdk package ...", [sys.executable, "-m", "flake8", f"{here}/slack_sdk"] - ) - - target = self.test_target.replace("tests/", "", 1) - self._run( - "Running unit tests ...", - [ - sys.executable, - "-m", - "pytest", - "--cov-report=xml", - f"--cov={here}/slack_sdk", - f"tests/{target}", - ], - ) - - -class UnitTestsCommand(BaseCommand): - """Support setup.py validate.""" - - description = "Run unit tests (pytest)." - user_options = [("test-target=", "i", "tests/{test-target}")] - - def initialize_options(self): - self.test_target = "" - - def run(self): - target = self.test_target.replace("tests/", "", 1) - self._run( - "Running unit tests ...", - [sys.executable, "-m", "pytest", f"tests/{target}",], - ) - - -class IntegrationTestsCommand(BaseCommand): - """Support setup.py run_integration_tests""" - - description = "Run integration tests (pytest)." - - user_options = [ - ("test-target=", "i", "integration_tests/{test-target}"), - ] - - def initialize_options(self): - self.test_target = "" - self.legacy = "" - - def run(self): - target = self.test_target.replace("integration_tests/", "", 1) - path = f"integration_tests/{target}" - self._run( - "Running integration tests ...", [sys.executable, "-m", "pytest", path,], - ) - - -setup( - name="slack_sdk", - version=__version__, - description="The Slack API Platform SDK for Python", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/slackapi/python-slack-sdk", - author="Slack Technologies, Inc.", - author_email="opensource@slack.com", - python_requires=">=3.6.0", - include_package_data=True, - license="MIT", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Topic :: Communications :: Chat", - "Topic :: System :: Networking", - "Topic :: Office/Business", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - ], - keywords="slack slack-api web-api slack-rtm websocket chat chatbot chatops", - packages=find_packages( - exclude=[ - "docs", - "docs-src", - "docs-v2", - "docs-src-v2", - "docs-v3", - "docs-src-v3", - "integration_tests", - "integration_tests_legacy", - "tests", - "tests.*", - "tutorial", - ] - ), - install_requires=[], - extras_require={ - # pip install -e ".[testing]" - "testing": validate_dependencies, - # pip install -e ".[optional]" - "optional": [ - # async modules depend on aiohttp - "aiodns>1.0", - "aiohttp>=3,<4", - # used only under slack_sdk/*_store - "boto3<=2", - # InstallationStore/OAuthStateStore - "SQLAlchemy>=1,<2", - ], - }, - setup_requires=pytest_runner, - test_suite="tests", - tests_require=validate_dependencies, - cmdclass={ - "upload": UploadCommand, - "codegen": CodegenCommand, - "validate": ValidateCommand, - "unit_tests": UnitTestsCommand, - "integration_tests": IntegrationTestsCommand, - }, -) diff --git a/slack/deprecation.py b/slack/deprecation.py index 996a7e562..8c5e8207b 100644 --- a/slack/deprecation.py +++ b/slack/deprecation.py @@ -3,14 +3,12 @@ def show_message(old: str, new: str) -> None: - skip_deprecation = os.environ.get( - "SLACKCLIENT_SKIP_DEPRECATION" - ) # for unit tests etc. + skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if skip_deprecation: return message = ( f"{old} package is deprecated. Please use {new} package instead. " - "For more info, go to https://slack.dev/python-slack-sdk/v3-migration/" + "For more info, go to https://docs.slack.dev/tools/python-slack-sdk/v3-migration/" ) warnings.warn(message) diff --git a/slack/signature/verifier.py b/slack/signature/verifier.py index e42ca6011..da9c6ef5e 100644 --- a/slack/signature/verifier.py +++ b/slack/signature/verifier.py @@ -17,13 +17,15 @@ def __init__(self, signing_secret: str, clock: Clock = Clock()): Slack signs its requests using a secret that's unique to your app. With the help of signing secrets, your app can more confidently verify whether requests from us are authentic. - https://api.slack.com/authentication/verifying-requests-from-slack + https://docs.slack.dev/authentication/verifying-requests-from-slack/ """ self.signing_secret = signing_secret self.clock = clock def is_valid_request( - self, body: Union[str, bytes], headers: Dict[str, str], + self, + body: Union[str, bytes], + headers: Dict[str, str], ) -> bool: """Verifies if the given signature is valid""" if headers is None: @@ -36,7 +38,10 @@ def is_valid_request( ) def is_valid( - self, body: Union[str, bytes], timestamp: str, signature: str, + self, + body: Union[str, bytes], + timestamp: str, + signature: str, ) -> bool: """Verifies if the given signature is valid""" if timestamp is None or signature is None: @@ -50,9 +55,7 @@ def is_valid( return False return hmac.compare_digest(calculated_signature, signature) - def generate_signature( - self, *, timestamp: str, body: Union[str, bytes] - ) -> Optional[str]: + def generate_signature(self, *, timestamp: str, body: Union[str, bytes]) -> Optional[str]: """Generates a signature""" if timestamp is None: return None diff --git a/slack/web/async_base_client.py b/slack/web/async_base_client.py index 514aaae82..c0cc3f962 100644 --- a/slack/web/async_base_client.py +++ b/slack/web/async_base_client.py @@ -17,7 +17,7 @@ class AsyncBaseClient: - BASE_URL = "https://www.slack.com/api/" + BASE_URL = "https://slack.com/api/" def __init__( self, @@ -41,9 +41,7 @@ def __init__( # https://github.com/slackapi/python-slack-sdk/issues/738 self.trust_env_in_session = trust_env_in_session self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self._logger = logging.getLogger(__name__) async def api_call( # skipcq: PYL-R1710 @@ -111,12 +109,12 @@ async def api_call( # skipcq: PYL-R1710 show_2020_01_deprecation(api_method) return await self._send( - http_verb=http_verb, api_url=api_url, req_args=req_args, + http_verb=http_verb, + api_url=api_url, + req_args=req_args, ) - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> AsyncSlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> AsyncSlackResponse: """Sends the request out for transmission. Args: @@ -139,9 +137,7 @@ async def _send( # True/False -> "1"/"0" req_args["params"] = convert_bool_to_0_or_1(req_args["params"]) - res = await self._request( - http_verb=http_verb, api_url=api_url, req_args=req_args - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() diff --git a/slack/web/async_client.py b/slack/web/async_client.py index 06aeae240..7258c5eb2 100644 --- a/slack/web/async_client.py +++ b/slack/web/async_client.py @@ -3,7 +3,8 @@ # *** DO NOT EDIT THIS FILE *** # # 1) Modify slack/web/client.py -# 2) Run `python setup.py validate` +# 2) Run `python scripts/codegen.py` +# 3) Run `black slack_sdk/` # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! diff --git a/slack/web/async_internal_utils.py b/slack/web/async_internal_utils.py index ccad1abf7..1148dc9e7 100644 --- a/slack/web/async_internal_utils.py +++ b/slack/web/async_internal_utils.py @@ -32,7 +32,7 @@ def _get_url(base_url: str, api_method: str) -> str: Returns: The absolute API URL. - e.g. 'https://www.slack.com/api/chat.postMessage' + e.g. 'https://slack.com/api/chat.postMessage' """ return urljoin(base_url, api_method) @@ -56,7 +56,7 @@ def _get_headers( e.g. { 'Content-Type': 'application/json;charset=utf-8', 'Authorization': 'Bearer xoxb-1234-1243', - 'User-Agent': 'Python/3.6.8 slack/2.1.0 Darwin/17.7.0' + 'User-Agent': 'Python/3.7.17 slack/2.1.0 Darwin/17.7.0' } """ final_headers = { @@ -183,9 +183,7 @@ async def _request_with_session( try: data = await res.json() except aiohttp.ContentTypeError: - logger.debug( - f"No response data returned from the following API call: {api_url}." - ) + logger.debug(f"No response data returned from the following API call: {api_url}.") except json.decoder.JSONDecodeError as e: message = f"Failed to parse the response body: {str(e)}" raise SlackApiError(message, res) diff --git a/slack/web/async_slack_response.py b/slack/web/async_slack_response.py index 462b7d2dc..150bc519e 100644 --- a/slack/web/async_slack_response.py +++ b/slack/web/async_slack_response.py @@ -74,8 +74,13 @@ def __init__( def __str__(self): """Return the Response data if object is converted to a string.""" + if isinstance(self.data, bytes): + raise ValueError("As the response.data is binary data, this operation is unsupported") return f"{self.data}" + def __contains__(self, key: str) -> bool: + return self.get(key) is not None + def __getitem__(self, key): """Retrieves any key from the data store. @@ -87,6 +92,10 @@ def __getitem__(self, key): Returns: The value from data or None. """ + if isinstance(self.data, bytes): + raise ValueError("As the response.data is binary data, this operation is unsupported") + if self.data is None: + raise ValueError("As the response.data is empty, this operation is unsupported") return self.data.get(key, None) def __aiter__(self): @@ -133,7 +142,9 @@ async def __anext__(self): self.req_args.update({"params": params}) response = await self._client._request( # skipcq: PYL-W0212 - http_verb=self.http_verb, api_url=self.api_url, req_args=self.req_args, + http_verb=self.http_verb, + api_url=self.api_url, + req_args=self.req_args, ) self.data = response["data"] @@ -154,6 +165,10 @@ def get(self, key, default=None): Returns: The value from data or the specified default. """ + if isinstance(self.data, bytes): + raise ValueError("As the response.data is binary data, this operation is unsupported") + if self.data is None: + return None return self.data.get(key, default) def validate(self): @@ -166,13 +181,6 @@ def validate(self): Raises: SlackApiError: The request to the Slack API failed. """ - if self._logger.level <= logging.DEBUG: - self._logger.debug( - "Received the following response - " - f"status: {self.status_code}, " - f"headers: {dict(self.headers)}, " - f"body: {self.data}" - ) if self.status_code == 200 and self.data and self.data.get("ok", False): return self msg = "The request to the Slack API failed." diff --git a/slack/web/base_client.py b/slack/web/base_client.py index 26778e6c0..28f597411 100644 --- a/slack/web/base_client.py +++ b/slack/web/base_client.py @@ -37,7 +37,7 @@ class BaseClient: - BASE_URL = "https://www.slack.com/api/" + BASE_URL = "https://slack.com/api/" def __init__( self, @@ -63,9 +63,7 @@ def __init__( self.use_sync_aiohttp = use_sync_aiohttp self.session = session self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self._logger = logging.getLogger(__name__) self._event_loop = loop @@ -153,9 +151,7 @@ def api_call( # skipcq: PYL-R1710 # aiohttp based async WebClient # ================================================================= - async def _send( - self, http_verb: str, api_url: str, req_args: dict - ) -> SlackResponse: + async def _send(self, http_verb: str, api_url: str, req_args: dict) -> SlackResponse: """Sends the request out for transmission. Args: @@ -178,9 +174,7 @@ async def _send( # True/False -> "1"/"0" req_args["params"] = convert_bool_to_0_or_1(req_args["params"]) - res = await self._request( - http_verb=http_verb, api_url=api_url, req_args=req_args - ) + res = await self._request(http_verb=http_verb, api_url=api_url, req_args=req_args) finally: for f in open_files: f.close() @@ -219,18 +213,14 @@ def _sync_send(self, api_url, req_args) -> SlackResponse: _json = req_args["json"] if "json" in req_args else None headers = req_args["headers"] if "headers" in req_args else None token = params.get("token") if params and "token" in params else None - auth = ( - req_args["auth"] if "auth" in req_args else None - ) # Basic Auth for oauth.v2.access / oauth.access + auth = req_args["auth"] if "auth" in req_args else None # Basic Auth for oauth.v2.access / oauth.access if auth is not None: if isinstance(auth, BasicAuth): headers["Authorization"] = auth.encode() elif isinstance(auth, str): headers["Authorization"] = auth else: - self._logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self._logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") body_params = {} if params: @@ -274,19 +264,6 @@ def _urllib_api_call( files: Dict[str, io.BytesIO] = {}, additional_headers: Dict[str, str] = {}, ) -> SlackResponse: - """Performs a Slack API request and returns the result. - - :param token: Slack API Token (either bot token or user token) - :param url: a complete URL (e.g., https://www.slack.com/api/chat.postMessage) - :param query_params: query string - :param json_body: json data structure (it's still a dict at this point), - if you give this argument, body_params and files will be skipped - :param body_params: form params - :param files: files to upload - :param additional_headers: request headers to append - :return: API response - """ - files_to_close: List[BinaryIO] = [] try: # True/False -> "1"/"0" @@ -298,15 +275,9 @@ def _urllib_api_call( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } - - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in additional_headers.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} + + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in additional_headers.items()} self._logger.debug( f"Sending a request - url: {url}, " f"query_params: {convert_params(query_params)}, " @@ -381,19 +352,7 @@ def convert_params(values: dict) -> dict: if not f.closed: f.close() - def _perform_urllib_http_request( - self, *, url: str, args: Dict[str, Dict[str, any]] - ) -> Dict[str, any]: - """Performs an HTTP request and parses the response. - - :param url: a complete URL (e.g., https://www.slack.com/api/chat.postMessage) - :param args: args has "headers", "data", "params", and "json" - "headers": Dict[str, str] - "data": Dict[str, any] - "params": Dict[str, str], - "json": Dict[str, any], - :return: dict {status: int, headers: Headers, body: str} - """ + def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, any]]) -> Dict[str, any]: headers = args["headers"] if args["json"]: body = json.dumps(args["json"]) @@ -410,16 +369,10 @@ def _perform_urllib_http_request( filename = "Uploaded file" name_attr = getattr(value, "name", None) if name_attr: - filename = ( - name_attr.decode("utf-8") - if isinstance(name_attr, bytes) - else name_attr - ) + filename = name_attr.decode("utf-8") if isinstance(name_attr, bytes) else name_attr if "filename" in data: filename = data["filename"] - mimetype = ( - mimetypes.guess_type(filename)[0] or "application/octet-stream" - ) + mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream" title = ( f'\r\nContent-Disposition: form-data; name="{key}"; filename="{filename}"\r\n' + f"Content-Type: {mimetype}\r\n" @@ -463,18 +416,14 @@ def _perform_urllib_http_request( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset = resp.headers.get_content_charset() or "utf-8" body: str = resp.read().decode(charset) # read the response body here return {"status": resp.code, "headers": resp.headers, "body": body} @@ -513,9 +462,7 @@ def _build_urllib_request_headers( # ================================================================= @staticmethod - def validate_slack_signature( - *, signing_secret: str, data: str, timestamp: str, signature: str - ) -> bool: + def validate_slack_signature(*, signing_secret: str, data: str, timestamp: str, signature: str) -> bool: """ Slack creates a unique string for your app and shares it with you. Verify requests from Slack with confidence by verifying signatures using your @@ -525,7 +472,7 @@ def validate_slack_signature( header. The signature is created by combining the signing secret with the body of the request we're sending using a standard HMAC-SHA256 keyed hash. - https://api.slack.com/docs/verifying-requests-from-slack#how_to_make_a_request_signature_in_4_easy_steps__an_overview + https://docs.slack.dev/authentication/verifying-requests-from-slack/ Args: signing_secret: Your application's signing secret, available in the diff --git a/slack/web/classes/actions.py b/slack/web/classes/actions.py index b22543e3e..6f2ded52d 100644 --- a/slack/web/classes/actions.py +++ b/slack/web/classes/actions.py @@ -6,7 +6,7 @@ from slack_sdk.models.attachments import ActionExternalSelector # noqa from slack_sdk.models.attachments import ActionLinkButton # noqa from slack_sdk.models.attachments import ActionUserSelector # noqa -from slack_sdk.models.dialoags import ActionStaticSelector # noqa +from slack_sdk.models.dialogs import ActionStaticSelector # noqa from slack import deprecation diff --git a/slack/web/classes/dialog_elements.py b/slack/web/classes/dialog_elements.py index a9e01d190..00b3126d7 100644 --- a/slack/web/classes/dialog_elements.py +++ b/slack/web/classes/dialog_elements.py @@ -1,13 +1,13 @@ -from slack_sdk.models.dialoags import AbstractDialogSelector # noqa -from slack_sdk.models.dialoags import DialogChannelSelector # noqa -from slack_sdk.models.dialoags import DialogConversationSelector # noqa -from slack_sdk.models.dialoags import DialogExternalSelector # noqa -from slack_sdk.models.dialoags import DialogStaticSelector # noqa -from slack_sdk.models.dialoags import DialogTextArea # noqa -from slack_sdk.models.dialoags import DialogTextComponent # noqa -from slack_sdk.models.dialoags import DialogTextField # noqa -from slack_sdk.models.dialoags import DialogUserSelector # noqa -from slack_sdk.models.dialoags import TextElementSubtypes # noqa +from slack_sdk.models.dialogs import AbstractDialogSelector # noqa +from slack_sdk.models.dialogs import DialogChannelSelector # noqa +from slack_sdk.models.dialogs import DialogConversationSelector # noqa +from slack_sdk.models.dialogs import DialogExternalSelector # noqa +from slack_sdk.models.dialogs import DialogStaticSelector # noqa +from slack_sdk.models.dialogs import DialogTextArea # noqa +from slack_sdk.models.dialogs import DialogTextComponent # noqa +from slack_sdk.models.dialogs import DialogTextField # noqa +from slack_sdk.models.dialogs import DialogUserSelector # noqa +from slack_sdk.models.dialogs import TextElementSubtypes # noqa from slack import deprecation diff --git a/slack/web/classes/dialogs.py b/slack/web/classes/dialogs.py index fe51f01b4..7e6d1cbd2 100644 --- a/slack/web/classes/dialogs.py +++ b/slack/web/classes/dialogs.py @@ -1,4 +1,4 @@ -from slack_sdk.models.dialoags import DialogBuilder # noqa +from slack_sdk.models.dialogs import DialogBuilder # noqa from slack import deprecation diff --git a/slack/web/classes/elements.py b/slack/web/classes/elements.py index ce2671f4e..fbe4b801e 100644 --- a/slack/web/classes/elements.py +++ b/slack/web/classes/elements.py @@ -7,6 +7,7 @@ from slack_sdk.models.blocks import ConversationMultiSelectElement # noqa from slack_sdk.models.blocks import ConversationSelectElement # noqa from slack_sdk.models.blocks import DatePickerElement # noqa +from slack_sdk.models.blocks import DateTimePickerElement # noqa from slack_sdk.models.blocks import ExternalDataMultiSelectElement # noqa from slack_sdk.models.blocks import ExternalDataSelectElement # noqa from slack_sdk.models.blocks import ImageElement # noqa @@ -15,6 +16,9 @@ from slack_sdk.models.blocks import LinkButtonElement # noqa from slack_sdk.models.blocks import OverflowMenuElement # noqa from slack_sdk.models.blocks import PlainTextInputElement # noqa +from slack_sdk.models.blocks import EmailInputElement # noqa +from slack_sdk.models.blocks import UrlInputElement # noqa +from slack_sdk.models.blocks import NumberInputElement # noqa from slack_sdk.models.blocks import RadioButtonsElement # noqa from slack_sdk.models.blocks import SelectElement # noqa from slack_sdk.models.blocks import StaticMultiSelectElement # noqa diff --git a/slack/web/classes/interactions.py b/slack/web/classes/interactions.py index fe5b0481c..f4d871efa 100644 --- a/slack/web/classes/interactions.py +++ b/slack/web/classes/interactions.py @@ -42,9 +42,7 @@ def __init__(self, event: dict): super().__init__(event) self.user = IDNamePair(event["user"]["id"], event["user"]["username"]) self.team: IDNamePair = IDNamePair(event["team"]["id"], event["team"]["domain"]) - self.channel: IDNamePair = IDNamePair( - event["channel"]["id"], event["channel"]["name"] - ) + self.channel: IDNamePair = IDNamePair(event["channel"]["id"], event["channel"]["name"]) self.event_type = event["type"] self.message_ts = event["message"]["ts"] self.trigger_id = event["trigger_id"] @@ -92,9 +90,7 @@ def require_any(self, requirements: List[str]) -> dict: Args: requirements: List of required dialog components, by name """ - if any( # skipcq: PYL-R1705 - self.submission.get(requirement, "") for requirement in requirements - ): + if any(self.submission.get(requirement, "") for requirement in requirements): # skipcq: PYL-R1705 return {} else: errors = [] diff --git a/slack/web/deprecation.py b/slack/web/deprecation.py index 7781e0bfc..059bf149f 100644 --- a/slack/web/deprecation.py +++ b/slack/web/deprecation.py @@ -1,7 +1,7 @@ import os import warnings -# https://api.slack.com/changelog/2020-01-deprecating-antecedents-to-the-conversations-api +# https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/ deprecated_method_prefixes_2020_01 = [ "channels.", "groups.", @@ -14,23 +14,17 @@ def show_2020_01_deprecation(method_name: str): """Prints a warning if the given method is deprecated""" - skip_deprecation = os.environ.get( - "SLACKCLIENT_SKIP_DEPRECATION" - ) # for unit tests etc. + skip_deprecation = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. if skip_deprecation: return if not method_name: return - matched_prefixes = [ - prefix - for prefix in deprecated_method_prefixes_2020_01 - if method_name.startswith(prefix) - ] + matched_prefixes = [prefix for prefix in deprecated_method_prefixes_2020_01 if method_name.startswith(prefix)] if len(matched_prefixes) > 0: message = ( f"{method_name} is deprecated. Please use the Conversations API instead. " "For more info, go to " - "https://api.slack.com/changelog/2020-01-deprecating-antecedents-to-the-conversations-api" + "https://docs.slack.dev/changelog/2020-01-deprecating-antecedents-to-the-conversations-api/" ) warnings.warn(message) diff --git a/slack/webhook/async_client.py b/slack/webhook/async_client.py index 3a50dbdac..31310c96f 100644 --- a/slack/webhook/async_client.py +++ b/slack/webhook/async_client.py @@ -27,16 +27,6 @@ def __init__( auth: Optional[BasicAuth] = None, default_headers: Optional[Dict[str, str]] = None, ): - """API client for Incoming Webhooks and response_url - :param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX) - :param timeout: request timeout (in seconds) - :param ssl: ssl.SSLContext to use for requests - :param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000) - :param session: a complete aiohttp.ClientSession - :param trust_env_in_session: True/False for aiohttp.ClientSession - :param auth: Basic auth info for aiohttp.ClientSession - :param default_headers: request headers to add to all requests - """ self.url = url self.timeout = timeout self.ssl = ssl @@ -56,12 +46,15 @@ async def send( headers: Optional[Dict[str, str]] = None, ) -> WebhookResponse: """Performs a Slack API request and returns the result. - :param text: the text message (even when having blocks, setting this as well is recommended as it works as fallback) - :param attachments: a collection of attachments - :param blocks: a collection of Block Kit UI components - :param response_type: the type of message (either 'in_channel' or 'ephemeral') - :param headers: request headers to append only for this request - :return: API response + + Args: + text: The text message (even when having blocks, setting this as well is recommended as it works as fallback) + attachments: A collection of attachments + blocks: A collection of Block Kit UI components + response_type: The type of message (either 'in_channel' or 'ephemeral') + headers: Request headers to append only for this request + Returns: + Webhook response """ return await self.send_dict( body={ @@ -73,36 +66,18 @@ async def send( headers=headers, ) - async def send_dict( - self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: - """Performs a Slack API request and returns the result. - :param body: json data structure (it's still a dict at this point), - if you give this argument, body_params and files will be skipped - :param headers: request headers to append only for this request - :return: API response - """ + async def send_dict(self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: return await self._perform_http_request( body=_build_body(body), headers=_build_request_headers(self.default_headers, headers), ) - async def _perform_http_request( - self, *, body: Dict[str, any], headers: Dict[str, str] - ) -> WebhookResponse: - """Performs an HTTP request and parses the response. - :param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX) - :param body: request body data - :param headers: complete set of request headers - :return: API response - """ + async def _perform_http_request(self, *, body: Dict[str, any], headers: Dict[str, str]) -> WebhookResponse: body = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {body}, headers: {headers}") session: Optional[ClientSession] = None use_running_session = self.session and not self.session.closed if use_running_session: @@ -126,9 +101,7 @@ async def _perform_http_request( try: response_body = await res.text() except aiohttp.ContentTypeError: - self._logger.debug( - f"No response data returned from the following API call: {self.url}." - ) + self._logger.debug(f"No response data returned from the following API call: {self.url}.") except json.decoder.JSONDecodeError as e: message = f"Failed to parse the response body: {str(e)}" raise SlackApiError(message, res) diff --git a/slack/webhook/client.py b/slack/webhook/client.py index f727c3080..7d39c03df 100644 --- a/slack/webhook/client.py +++ b/slack/webhook/client.py @@ -25,13 +25,6 @@ def __init__( proxy: Optional[str] = None, default_headers: Optional[Dict[str, str]] = None, ): - """API client for Incoming Webhooks and response_url - :param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX) - :param timeout: request timeout (in seconds) - :param ssl: ssl.SSLContext to use for requests - :param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000) - :param default_headers: request headers to add to all requests - """ self.url = url self.timeout = timeout self.ssl = ssl @@ -47,14 +40,6 @@ def send( response_type: Optional[str] = None, headers: Optional[Dict[str, str]] = None, ) -> WebhookResponse: - """Performs a Slack API request and returns the result. - :param text: the text message (even when having blocks, setting this as well is recommended as it works as fallback) - :param attachments: a collection of attachments - :param blocks: a collection of Block Kit UI components - :param response_type: the type of message (either 'in_channel' or 'ephemeral') - :param headers: request headers to append only for this request - :return: API response - """ return self.send_dict( body={ "text": text, @@ -65,44 +50,24 @@ def send( headers=headers, ) - def send_dict( - self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None - ) -> WebhookResponse: - """Performs a Slack API request and returns the result. - :param body: json data structure (it's still a dict at this point), - if you give this argument, body_params and files will be skipped - :param headers: request headers to append only for this request - :return: API response - """ + def send_dict(self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None) -> WebhookResponse: return self._perform_http_request( body=_build_body(body), headers=_build_request_headers(self.default_headers, headers), ) - def _perform_http_request( - self, *, body: Dict[str, any], headers: Dict[str, str] - ) -> WebhookResponse: - """Performs an HTTP request and parses the response. - :param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX) - :param body: request body data - :param headers: complete set of request headers - :return: API response - """ + def _perform_http_request(self, *, body: Dict[str, any], headers: Dict[str, str]) -> WebhookResponse: body = json.dumps(body) headers["Content-Type"] = "application/json;charset=utf-8" if self.logger.level <= logging.DEBUG: - self.logger.debug( - f"Sending a request - url: {self.url}, body: {body}, headers: {headers}" - ) + self.logger.debug(f"Sending a request - url: {self.url}, body: {body}, headers: {headers}") try: url = self.url opener: Optional[OpenerDirector] = None # for security (BAN-B310) if url.lower().startswith("http"): - req = Request( - method="POST", url=url, data=body.encode("utf-8"), headers=headers - ) + req = Request(method="POST", url=url, data=body.encode("utf-8"), headers=headers) if self.proxy is not None: if isinstance(self.proxy, str): opener = urllib.request.build_opener( @@ -110,9 +75,7 @@ def _perform_http_request( HTTPSHandler(context=self.ssl), ) else: - raise SlackRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") else: raise SlackRequestError(f"Invalid URL detected: {url}") @@ -121,9 +84,7 @@ def _perform_http_request( if opener: resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310 else: - resp = urlopen( # skipcq: BAN-B310 - req, context=self.ssl, timeout=self.timeout - ) + resp = urlopen(req, context=self.ssl, timeout=self.timeout) # skipcq: BAN-B310 charset: str = resp.headers.get_content_charset() or "utf-8" response_body: str = resp.read().decode(charset) resp = WebhookResponse( @@ -139,7 +100,10 @@ def _perform_http_request( charset = e.headers.get_content_charset() or "utf-8" body: str = e.read().decode(charset) # read the response body here resp = WebhookResponse( - url=url, status_code=e.code, body=body, headers=e.headers, + url=url, + status_code=e.code, + body=body, + headers=e.headers, ) if e.code == 429: # for backward-compatibility with WebClient (v.2.5.0 or older) diff --git a/slack/webhook/internal_utils.py b/slack/webhook/internal_utils.py index 2dfdd6d5a..ea21e88e2 100644 --- a/slack/webhook/internal_utils.py +++ b/slack/webhook/internal_utils.py @@ -14,7 +14,8 @@ def _build_body(original_body: Dict[str, any]) -> Dict[str, any]: def _build_request_headers( - default_headers: Dict[str, str], additional_headers: Optional[Dict[str, str]], + default_headers: Dict[str, str], + additional_headers: Optional[Dict[str, str]], ) -> Dict[str, str]: if additional_headers is None: return {} diff --git a/slack/webhook/webhook_response.py b/slack/webhook/webhook_response.py index b2a016af9..5da6b8086 100644 --- a/slack/webhook/webhook_response.py +++ b/slack/webhook/webhook_response.py @@ -1,6 +1,11 @@ class WebhookResponse: def __init__( - self, *, url: str, status_code: int, body: str, headers: dict, + self, + *, + url: str, + status_code: int, + body: str, + headers: dict, ): self.api_url = url self.status_code = status_code diff --git a/slack_sdk/__init__.py b/slack_sdk/__init__.py index 59ba2d96b..b5204e3e3 100644 --- a/slack_sdk/__init__.py +++ b/slack_sdk/__init__.py @@ -1,9 +1,54 @@ +""" +* The SDK website: https://docs.slack.dev/tools/python-slack-sdk +* PyPI package: https://pypi.org/project/slack-sdk/ + +Here is the list of key modules in this SDK: + +#### Web API Client + +* Web API client: `slack_sdk.web.client` +* asyncio-based Web API client: `slack_sdk.web.async_client` + +#### Webhook / response_url Client + +* Webhook client: `slack_sdk.webhook.client` +* asyncio-based Webhook client: `slack_sdk.webhook.async_client` + +#### Socket Mode Client + +* The built-in Socket Mode client: `slack_sdk.socket_mode.builtin.client` +* [aiohttp](https://pypi.org/project/aiohttp/) based client: `slack_sdk.socket_mode.aiohttp` +* [websocket_client](https://pypi.org/project/websocket-client/) based client: `slack_sdk.socket_mode.websocket_client` +* [websockets](https://pypi.org/project/websockets/) based client: `slack_sdk.socket_mode.websockets` + +#### OAuth + +* `slack_sdk.oauth.installation_store.installation_store` +* `slack_sdk.oauth.state_store` + +#### Audit Logs API Client + +* `slack_sdk.audit_logs.v1.client` +* `slack_sdk.audit_logs.v1.async_client` + +#### SCIM API Client + +* `slack_sdk.scim.v1.client` +* `slack_sdk.scim.v1.async_client` + +""" + import logging from logging import NullHandler -# from .rtm import RTMClient # noqa -from .web import WebClient # noqa -from .webhook import WebhookClient # noqa +# from .rtm import RTMClient +from .web import WebClient +from .webhook import WebhookClient + +__all__ = [ + "WebClient", + "WebhookClient", +] # Set default logging handler to avoid "No handler found" warnings. logging.getLogger(__name__).addHandler(NullHandler()) diff --git a/slack_sdk/aiohttp_version_checker.py b/slack_sdk/aiohttp_version_checker.py new file mode 100644 index 000000000..1eff14efa --- /dev/null +++ b/slack_sdk/aiohttp_version_checker.py @@ -0,0 +1,24 @@ +"""Internal module for checking aiohttp compatibility of async modules""" + +import logging +from typing import Callable + + +def _print_warning_log(message: str) -> None: + logging.getLogger(__name__).warning(message) + + +def validate_aiohttp_version( + aiohttp_version: str, + print_warning: Callable[[str], None] = _print_warning_log, +): + if aiohttp_version is not None: + elements = aiohttp_version.split(".") + if len(elements) >= 3: + # patch version can be a non-numeric value + major, minor, patch = int(elements[0]), int(elements[1]), elements[2] + if major <= 2 or (major == 3 and (minor == 6 or (minor == 7 and patch == "0"))): + print_warning( + "We highly recommend upgrading aiohttp to 3.7.3 or higher versions." + "An older version of the library may not work with the Slack server-side in the future." + ) diff --git a/slack_sdk/audit_logs/__init__.py b/slack_sdk/audit_logs/__init__.py new file mode 100644 index 000000000..f8a7a2a91 --- /dev/null +++ b/slack_sdk/audit_logs/__init__.py @@ -0,0 +1,12 @@ +"""Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization. + +Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details. +""" + +from .v1.client import AuditLogsClient +from .v1.response import AuditLogsResponse + +__all__ = [ + "AuditLogsClient", + "AuditLogsResponse", +] diff --git a/slack_sdk/audit_logs/async_client.py b/slack_sdk/audit_logs/async_client.py new file mode 100644 index 000000000..3e606fb5f --- /dev/null +++ b/slack_sdk/audit_logs/async_client.py @@ -0,0 +1,5 @@ +from .v1.async_client import AsyncAuditLogsClient + +__all__ = [ + "AsyncAuditLogsClient", +] diff --git a/slack_sdk/audit_logs/v1/__init__.py b/slack_sdk/audit_logs/v1/__init__.py new file mode 100644 index 000000000..9d03c76ce --- /dev/null +++ b/slack_sdk/audit_logs/v1/__init__.py @@ -0,0 +1,4 @@ +"""Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization. + +Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details. +""" diff --git a/slack_sdk/audit_logs/v1/async_client.py b/slack_sdk/audit_logs/v1/async_client.py new file mode 100644 index 000000000..7de8fd5b2 --- /dev/null +++ b/slack_sdk/audit_logs/v1/async_client.py @@ -0,0 +1,361 @@ +"""Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization. + +Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details. +""" + +import json +import logging +from ssl import SSLContext +from typing import Any, List +from typing import Dict, Optional + +import aiohttp +from aiohttp import BasicAuth, ClientSession + +from slack_sdk.errors import SlackApiError +from .internal_utils import ( + _build_request_headers, + _debug_log_response, + get_user_agent, +) +from .response import AuditLogsResponse +from slack_sdk.http_retry.async_handler import AsyncRetryHandler +from slack_sdk.http_retry.builtin_async_handlers import async_default_handlers +from slack_sdk.http_retry.request import HttpRequest as RetryHttpRequest +from slack_sdk.http_retry.response import HttpResponse as RetryHttpResponse +from slack_sdk.http_retry.state import RetryState +from ...proxy_env_variable_loader import load_http_proxy_from_env + + +class AsyncAuditLogsClient: + BASE_URL = "https://api.slack.com/audit/v1/" + + token: str + timeout: int + ssl: Optional[SSLContext] + proxy: Optional[str] + base_url: str + session: Optional[ClientSession] + trust_env_in_session: bool + auth: Optional[BasicAuth] + default_headers: Dict[str, str] + logger: logging.Logger + retry_handlers: List[AsyncRetryHandler] + + def __init__( + self, + token: str, + timeout: int = 30, + ssl: Optional[SSLContext] = None, + proxy: Optional[str] = None, + base_url: str = BASE_URL, + session: Optional[ClientSession] = None, + trust_env_in_session: bool = False, + auth: Optional[BasicAuth] = None, + default_headers: Optional[Dict[str, str]] = None, + user_agent_prefix: Optional[str] = None, + user_agent_suffix: Optional[str] = None, + logger: Optional[logging.Logger] = None, + retry_handlers: Optional[List[AsyncRetryHandler]] = None, + ): + """API client for Audit Logs API + See https://docs.slack.dev/admins/audit-logs-api/ for more details + + Args: + token: An admin user's token, which starts with `xoxp-` + timeout: Request timeout (in seconds) + ssl: `ssl.SSLContext` to use for requests + proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`) + base_url: The base URL for API calls + session: `aiohttp.ClientSession` instance + trust_env_in_session: True/False for `aiohttp.ClientSession` + auth: Basic auth info for `aiohttp.ClientSession` + default_headers: Request headers to add to all requests + user_agent_prefix: Prefix for User-Agent header value + user_agent_suffix: Suffix for User-Agent header value + logger: Custom logger + retry_handlers: Retry handlers + """ + self.token = token + self.timeout = timeout + self.ssl = ssl + self.proxy = proxy + self.base_url = base_url + self.session = session + self.trust_env_in_session = trust_env_in_session + self.auth = auth + self.default_headers = default_headers if default_headers else {} + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) + self.logger = logger if logger is not None else logging.getLogger(__name__) + self.retry_handlers = retry_handlers if retry_handlers is not None else async_default_handlers() + + if self.proxy is None or len(self.proxy.strip()) == 0: + env_variable = load_http_proxy_from_env(self.logger) + if env_variable is not None: + self.proxy = env_variable + + async def schemas( + self, + *, + query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """Returns information about the kind of objects which the Audit Logs API + returns as a list of all objects and a short description. + Authentication not required. + + Args: + query_params: Set any values if you want to add query params + headers: Additional request headers + Returns: + API response + """ + return await self.api_call( + path="schemas", + query_params=query_params, + headers=headers, + ) + + async def actions( + self, + *, + query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """Returns information about the kind of actions that the Audit Logs API + returns as a list of all actions and a short description of each. + Authentication not required. + + Args: + query_params: Set any values if you want to add query params + headers: Additional request headers + + Returns: + API response + """ + return await self.api_call( + path="actions", + query_params=query_params, + headers=headers, + ) + + async def logs( + self, + *, + latest: Optional[int] = None, + oldest: Optional[int] = None, + limit: Optional[int] = None, + action: Optional[str] = None, + actor: Optional[str] = None, + entity: Optional[str] = None, + cursor: Optional[str] = None, + additional_query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """This is the primary endpoint for retrieving actual audit events from your organization. + It will return a list of actions that have occurred on the installed workspace or grid organization. + Authentication required. + + The following filters can be applied in order to narrow the range of actions returned. + Filters are added as query string parameters and can be combined together. + Multiple filter parameters are additive (a boolean AND) and are separated + with an ampersand (&) in the query string. Filtering is entirely optional. + + Args: + latest: Unix timestamp of the most recent audit event to include (inclusive). + oldest: Unix timestamp of the least recent audit event to include (inclusive). + Data is not available prior to March 2018. + limit: Number of results to optimistically return, maximum 9999. + action: Name of the action. + actor: User ID who initiated the action. + entity: ID of the target entity of the action (such as a channel, workspace, organization, file). + cursor: The next page cursor of pagination + additional_query_params: Add anything else if you need to use the ones this library does not support + headers: Additional request headers + + Returns: + API response + """ + query_params = { + "latest": latest, + "oldest": oldest, + "limit": limit, + "action": action, + "actor": actor, + "entity": entity, + "cursor": cursor, + } + if additional_query_params is not None: + query_params.update(additional_query_params) + query_params = {k: v for k, v in query_params.items() if v is not None} + return await self.api_call( + path="logs", + query_params=query_params, + headers=headers, + ) + + async def api_call( + self, + *, + http_verb: str = "GET", + path: str, + query_params: Optional[Dict[str, Any]] = None, + body_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + url = f"{self.base_url}{path}" + return await self._perform_http_request( + http_verb=http_verb, + url=url, + query_params=query_params, + body_params=body_params, + headers=_build_request_headers( + token=self.token, + default_headers=self.default_headers, + additional_headers=headers, + ), + ) + + async def _perform_http_request( + self, + *, + http_verb: str, + url: str, + query_params: Optional[Dict[str, Any]], + body_params: Optional[Dict[str, Any]], + headers: Dict[str, str], + ) -> AuditLogsResponse: + if body_params is not None: + body_params = json.dumps(body_params) # type: ignore[assignment] + headers["Content-Type"] = "application/json;charset=utf-8" + + session: Optional[ClientSession] = None + use_running_session = self.session and not self.session.closed + if use_running_session: + session = self.session + else: + session = aiohttp.ClientSession( + timeout=aiohttp.ClientTimeout(total=self.timeout), + auth=self.auth, + trust_env=self.trust_env_in_session, + ) + + last_error = None + resp: Optional[AuditLogsResponse] = None + try: + request_kwargs = { + "headers": headers, + "params": query_params, + "data": body_params, + "ssl": self.ssl, + "proxy": self.proxy, + } + retry_request = RetryHttpRequest( + method=http_verb, + url=url, + headers=headers, # type: ignore[arg-type] + body_params=body_params, + ) + + retry_state = RetryState() + counter_for_safety = 0 + while counter_for_safety < 100: + counter_for_safety += 1 + # If this is a retry, the next try started here. We can reset the flag. + retry_state.next_attempt_requested = False + retry_response: Optional[RetryHttpResponse] = None + response_body = "" + + if self.logger.level <= logging.DEBUG: + headers_for_logging = { + k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items() + } + self.logger.debug( + f"Sending a request - " + f"url: {url}, " + f"params: {query_params}, " + f"body: {body_params}, " + f"headers: {headers_for_logging}" + ) + + try: + async with session.request(http_verb, url, **request_kwargs) as res: # type: ignore[arg-type, union-attr] # noqa: E501 + try: + response_body = await res.text() + retry_response = RetryHttpResponse( + status_code=res.status, + headers=res.headers, # type: ignore[arg-type] + data=response_body.encode("utf-8") if response_body is not None else None, + ) + except aiohttp.ContentTypeError: + self.logger.debug(f"No response data returned from the following API call: {url}.") + retry_response = RetryHttpResponse( + status_code=res.status, + headers=res.headers, # type: ignore[arg-type] + ) + except json.decoder.JSONDecodeError as e: + message = f"Failed to parse the response body: {str(e)}" + raise SlackApiError(message, res) + + if res.status == 429: + for handler in self.retry_handlers: + if await handler.can_retry_async( + state=retry_state, + request=retry_request, + response=retry_response, + ): + if self.logger.level <= logging.DEBUG: + self.logger.info( + f"A retry handler found: {type(handler).__name__} " + f"for {http_verb} {url} - rate_limited" + ) + await handler.prepare_for_next_attempt_async( + state=retry_state, + request=retry_request, + response=retry_response, + ) + break + + if retry_state.next_attempt_requested is False: + resp = AuditLogsResponse( + url=url, + status_code=res.status, + raw_body=response_body, + headers=res.headers, # type: ignore[arg-type] + ) + _debug_log_response(self.logger, resp) + return resp + + except Exception as e: + last_error = e + for handler in self.retry_handlers: + if await handler.can_retry_async( + state=retry_state, + request=retry_request, + response=retry_response, + error=e, + ): + if self.logger.level <= logging.DEBUG: + self.logger.info( + f"A retry handler found: {type(handler).__name__} " f"for {http_verb} {url} - {e}" + ) + await handler.prepare_for_next_attempt_async( + state=retry_state, + request=retry_request, + response=retry_response, + error=e, + ) + break + + if retry_state.next_attempt_requested is False: + raise last_error + + if resp is not None: + return resp + raise last_error # type: ignore[misc] + + finally: + if not use_running_session: + await session.close() # type: ignore[union-attr] + + return resp diff --git a/slack_sdk/audit_logs/v1/client.py b/slack_sdk/audit_logs/v1/client.py new file mode 100644 index 000000000..704b872fa --- /dev/null +++ b/slack_sdk/audit_logs/v1/client.py @@ -0,0 +1,362 @@ +"""Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization. + +Refer to https://docs.slack.dev/tools/python-slack-sdk/audit-logs for details. +""" + +import json +import logging +import urllib +from http.client import HTTPResponse +from ssl import SSLContext +from typing import Dict, Optional, List, Any +from urllib.error import HTTPError +from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler + +from slack_sdk.errors import SlackRequestError +from .internal_utils import ( + _build_query, + _build_request_headers, + _debug_log_response, + get_user_agent, +) +from .response import AuditLogsResponse +from slack_sdk.http_retry import default_retry_handlers +from slack_sdk.http_retry.handler import RetryHandler +from slack_sdk.http_retry.request import HttpRequest as RetryHttpRequest +from slack_sdk.http_retry.response import HttpResponse as RetryHttpResponse +from slack_sdk.http_retry.state import RetryState +from ...proxy_env_variable_loader import load_http_proxy_from_env + + +class AuditLogsClient: + BASE_URL = "https://api.slack.com/audit/v1/" + + token: str + timeout: int + ssl: Optional[SSLContext] + proxy: Optional[str] + base_url: str + default_headers: Dict[str, str] + logger: logging.Logger + retry_handlers: List[RetryHandler] + + def __init__( + self, + token: str, + timeout: int = 30, + ssl: Optional[SSLContext] = None, + proxy: Optional[str] = None, + base_url: str = BASE_URL, + default_headers: Optional[Dict[str, str]] = None, + user_agent_prefix: Optional[str] = None, + user_agent_suffix: Optional[str] = None, + logger: Optional[logging.Logger] = None, + retry_handlers: Optional[List[RetryHandler]] = None, + ): + """API client for Audit Logs API + See https://docs.slack.dev/admins/audit-logs-api/ for more details + + Args: + token: An admin user's token, which starts with `xoxp-` + timeout: Request timeout (in seconds) + ssl: `ssl.SSLContext` to use for requests + proxy: Proxy URL (e.g., `localhost:9000`, `http://localhost:9000`) + base_url: The base URL for API calls + default_headers: Request headers to add to all requests + user_agent_prefix: Prefix for User-Agent header value + user_agent_suffix: Suffix for User-Agent header value + logger: Custom logger + retry_handlers: Retry handlers + """ + self.token = token + self.timeout = timeout + self.ssl = ssl + self.proxy = proxy + self.base_url = base_url + self.default_headers = default_headers if default_headers else {} + self.default_headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) + self.logger = logger if logger is not None else logging.getLogger(__name__) + self.retry_handlers = retry_handlers if retry_handlers is not None else default_retry_handlers() + + if self.proxy is None or len(self.proxy.strip()) == 0: + env_variable = load_http_proxy_from_env(self.logger) + if env_variable is not None: + self.proxy = env_variable + + def schemas( + self, + *, + query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """Returns information about the kind of objects which the Audit Logs API + returns as a list of all objects and a short description. + Authentication not required. + + Args: + query_params: Set any values if you want to add query params + headers: Additional request headers + Returns: + API response + """ + return self.api_call( + path="schemas", + query_params=query_params, + headers=headers, + ) + + def actions( + self, + *, + query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """Returns information about the kind of actions that the Audit Logs API + returns as a list of all actions and a short description of each. + Authentication not required. + + Args: + query_params: Set any values if you want to add query params + headers: Additional request headers + + Returns: + API response + """ + return self.api_call( + path="actions", + query_params=query_params, + headers=headers, + ) + + def logs( + self, + *, + latest: Optional[int] = None, + oldest: Optional[int] = None, + limit: Optional[int] = None, + action: Optional[str] = None, + actor: Optional[str] = None, + entity: Optional[str] = None, + cursor: Optional[str] = None, + additional_query_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """This is the primary endpoint for retrieving actual audit events from your organization. + It will return a list of actions that have occurred on the installed workspace or grid organization. + Authentication required. + + The following filters can be applied in order to narrow the range of actions returned. + Filters are added as query string parameters and can be combined together. + Multiple filter parameters are additive (a boolean AND) and are separated + with an ampersand (&) in the query string. Filtering is entirely optional. + + Args: + latest: Unix timestamp of the most recent audit event to include (inclusive). + oldest: Unix timestamp of the least recent audit event to include (inclusive). + Data is not available prior to March 2018. + limit: Number of results to optimistically return, maximum 9999. + action: Name of the action. + actor: User ID who initiated the action. + entity: ID of the target entity of the action (such as a channel, workspace, organization, file). + cursor: The next page cursor of pagination + additional_query_params: Add anything else if you need to use the ones this library does not support + headers: Additional request headers + + Returns: + API response + """ + query_params = { + "latest": latest, + "oldest": oldest, + "limit": limit, + "action": action, + "actor": actor, + "entity": entity, + "cursor": cursor, + } + if additional_query_params is not None: + query_params.update(additional_query_params) + query_params = {k: v for k, v in query_params.items() if v is not None} + return self.api_call( + path="logs", + query_params=query_params, + headers=headers, + ) + + def api_call( + self, + *, + http_verb: str = "GET", + path: str, + query_params: Optional[Dict[str, Any]] = None, + body_params: Optional[Dict[str, Any]] = None, + headers: Optional[Dict[str, str]] = None, + ) -> AuditLogsResponse: + """Performs a Slack API request and returns the result.""" + url = f"{self.base_url}{path}" + query = _build_query(query_params) + if len(query) > 0: + url += f"?{query}" + + return self._perform_http_request( + http_verb=http_verb, + url=url, + body=body_params, + headers=_build_request_headers( + token=self.token, + default_headers=self.default_headers, + additional_headers=headers, + ), + ) + + def _perform_http_request( + self, + *, + http_verb: str = "GET", + url: str, + body: Optional[Dict[str, Any]] = None, + headers: Dict[str, str], + ) -> AuditLogsResponse: + if body is not None: + body = json.dumps(body) # type: ignore[assignment] + headers["Content-Type"] = "application/json;charset=utf-8" + + if self.logger.level <= logging.DEBUG: + headers_for_logging = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()} + self.logger.debug(f"Sending a request - url: {url}, body: {body}, headers: {headers_for_logging}") + + # NOTE: Intentionally ignore the `http_verb` here + # Slack APIs accepts any API method requests with POST methods + req = Request( + method=http_verb, + url=url, + data=body.encode("utf-8") if body is not None else None, # type: ignore[attr-defined] + headers=headers, + ) + resp = None + last_error = None + + retry_state = RetryState() + counter_for_safety = 0 + while counter_for_safety < 100: + counter_for_safety += 1 + # If this is a retry, the next try started here. We can reset the flag. + retry_state.next_attempt_requested = False + + try: + resp = self._perform_http_request_internal(url, req) + # The resp is a 200 OK response + return resp + + except HTTPError as e: + # read the response body here + charset = e.headers.get_content_charset() or "utf-8" + response_body: str = e.read().decode(charset) + # As adding new values to HTTPError#headers can be ignored, building a new dict object here + response_headers = dict(e.headers.items()) + resp = AuditLogsResponse( + url=url, + status_code=e.code, + raw_body=response_body, + headers=response_headers, + ) + if e.code == 429: + # for backward-compatibility with WebClient (v.2.5.0 or older) + if "retry-after" not in resp.headers and "Retry-After" in resp.headers: + resp.headers["retry-after"] = resp.headers["Retry-After"] + if "Retry-After" not in resp.headers and "retry-after" in resp.headers: + resp.headers["Retry-After"] = resp.headers["retry-after"] + _debug_log_response(self.logger, resp) + + # Try to find a retry handler for this error + retry_request = RetryHttpRequest.from_urllib_http_request(req) + retry_response = RetryHttpResponse( + status_code=e.code, + headers={k: [v] for k, v in e.headers.items()}, + data=response_body.encode("utf-8") if response_body is not None else None, + ) + for handler in self.retry_handlers: + if handler.can_retry( + state=retry_state, + request=retry_request, + response=retry_response, + error=e, + ): + if self.logger.level <= logging.DEBUG: + self.logger.info( + f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {e}" + ) + handler.prepare_for_next_attempt( + state=retry_state, + request=retry_request, + response=retry_response, + error=e, + ) + break + + if retry_state.next_attempt_requested is False: + return resp + + except Exception as err: + last_error = err + self.logger.error(f"Failed to send a request to Slack API server: {err}") + + # Try to find a retry handler for this error + retry_request = RetryHttpRequest.from_urllib_http_request(req) + for handler in self.retry_handlers: + if handler.can_retry( + state=retry_state, + request=retry_request, + response=None, + error=err, + ): + if self.logger.level <= logging.DEBUG: + self.logger.info( + f"A retry handler found: {type(handler).__name__} for {req.method} {req.full_url} - {err}" + ) + handler.prepare_for_next_attempt( + state=retry_state, + request=retry_request, + response=None, + error=err, + ) + self.logger.info(f"Going to retry the same request: {req.method} {req.full_url}") + break + + if retry_state.next_attempt_requested is False: + raise err + + if resp is not None: + return resp + raise last_error # type: ignore[misc] + + def _perform_http_request_internal(self, url: str, req: Request) -> AuditLogsResponse: + opener: Optional[OpenerDirector] = None + # for security (BAN-B310) + if url.lower().startswith("http"): + if self.proxy is not None: + if isinstance(self.proxy, str): + opener = urllib.request.build_opener( + ProxyHandler({"http": self.proxy, "https": self.proxy}), + HTTPSHandler(context=self.ssl), + ) + else: + raise SlackRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") + else: + raise SlackRequestError(f"Invalid URL detected: {url}") + + http_resp: HTTPResponse + if opener: + http_resp = opener.open(req, timeout=self.timeout) + else: + http_resp = urlopen(req, context=self.ssl, timeout=self.timeout) + charset: str = http_resp.headers.get_content_charset() or "utf-8" + response_body: str = http_resp.read().decode(charset) + resp = AuditLogsResponse( + url=url, + status_code=http_resp.status, + raw_body=response_body, + headers=http_resp.headers, # type: ignore[arg-type] + ) + _debug_log_response(self.logger, resp) + return resp diff --git a/slack_sdk/audit_logs/v1/internal_utils.py b/slack_sdk/audit_logs/v1/internal_utils.py new file mode 100644 index 000000000..c4521c7eb --- /dev/null +++ b/slack_sdk/audit_logs/v1/internal_utils.py @@ -0,0 +1,40 @@ +import logging +from typing import Optional, Dict, Any +from urllib.parse import quote + +from slack_sdk.web.internal_utils import get_user_agent +from .response import AuditLogsResponse + + +def _build_query(params: Optional[Dict[str, Any]]) -> str: + if params is not None and len(params) > 0: + return "&".join({f"{quote(str(k))}={quote(str(v))}" for k, v in params.items() if v is not None}) + return "" + + +def _build_request_headers( + token: str, + default_headers: Dict[str, str], + additional_headers: Optional[Dict[str, str]], +) -> Dict[str, str]: + request_headers = { + "Content-Type": "application/json;charset=utf-8", + "Authorization": f"Bearer {token}", + } + if default_headers is None or "User-Agent" not in default_headers: + request_headers["User-Agent"] = get_user_agent() + if default_headers is not None: + request_headers.update(default_headers) + if additional_headers is not None: + request_headers.update(additional_headers) + return request_headers + + +def _debug_log_response(logger, resp: AuditLogsResponse) -> None: + if logger.level <= logging.DEBUG: + logger.debug( + "Received the following response - " + f"status: {resp.status_code}, " + f"headers: {(dict(resp.headers))}, " + f"body: {resp.raw_body}" + ) diff --git a/slack_sdk/audit_logs/v1/logs.py b/slack_sdk/audit_logs/v1/logs.py new file mode 100644 index 000000000..6ace8f8ba --- /dev/null +++ b/slack_sdk/audit_logs/v1/logs.py @@ -0,0 +1,1246 @@ +import json +from typing import Optional, List, Union, Any, Dict + + +class App: + id: Optional[str] + name: Optional[str] + is_distributed: Optional[bool] + is_directory_approved: Optional[bool] + is_workflow_app: Optional[bool] + scopes: Optional[List[str]] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + is_distributed: Optional[bool] = None, + is_directory_approved: Optional[bool] = None, + is_workflow_app: Optional[bool] = None, + scopes: Optional[List[str]] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.is_distributed = is_distributed + self.is_directory_approved = is_directory_approved + self.is_workflow_app = is_workflow_app + self.scopes = scopes + self.unknown_fields = kwargs + + +class User: + id: Optional[str] + name: Optional[str] + email: Optional[str] + team: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + email: Optional[str] = None, + team: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.email = email + self.team = team + self.unknown_fields = kwargs + + +class Actor: + type: Optional[str] + user: Optional[User] + unknown_fields: Dict[str, Any] + + def __init__( + self, + type: Optional[str] = None, + user: Optional[Union[User, Dict[str, Any]]] = None, + **kwargs, + ) -> None: + self.type = type + self.user = User(**user) if isinstance(user, dict) else user + self.unknown_fields = kwargs + + +class Location: + type: Optional[str] + id: Optional[str] + name: Optional[str] + domain: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + type: Optional[str] = None, + id: Optional[str] = None, + name: Optional[str] = None, + domain: Optional[str] = None, + **kwargs, + ) -> None: + self.type = type + self.id = id + self.name = name + self.domain = domain + self.unknown_fields = kwargs + + +class Context: + location: Optional[Location] + ua: Optional[str] + ip_address: Optional[str] + session_id: Optional[str] + app: Optional[App] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + location: Optional[Union[Location, Dict[str, Any]]] = None, + ua: Optional[str] = None, + ip_address: Optional[str] = None, + session_id: Optional[str] = None, + app: Optional[Union[App, Dict[str, Any]]] = None, + **kwargs, + ) -> None: + self.location = Location(**location) if isinstance(location, dict) else location + self.ua = ua + self.ip_address = ip_address + self.session_id = session_id + self.app = App(**app) if isinstance(app, dict) else app + self.unknown_fields = kwargs + + +class RetentionPolicy: + type: Optional[str] + duration_days: Optional[int] + + def __init__( + self, + *, + type: Optional[str] = None, + duration_days: Optional[int] = None, + **kwargs, + ) -> None: + self.type = type + self.duration_days = duration_days + self.unknown_fields = kwargs + + +class ConversationPref: + type: Optional[List[str]] + user: Optional[List[str]] + + def __init__( + self, + *, + type: Optional[List[str]] = None, + user: Optional[List[str]] = None, + **kwargs, + ) -> None: + self.type = type + self.user = user + self.unknown_fields = kwargs + + +class FeatureEnablement: + enabled: Optional[bool] + + def __init__( + self, + *, + enabled: Optional[bool] = None, + **kwargs, + ) -> None: + self.enabled = enabled + self.unknown_fields = kwargs + + +class SharedWith: + channel_id: Optional[str] + access_level: Optional[str] + + def __init__( + self, + *, + channel_id: Optional[str] = None, + access_level: Optional[str] = None, + **kwargs, + ) -> None: + self.channel_id = channel_id + self.access_level = access_level + self.unknown_fields = kwargs + + +class Profile: + real_name: Optional[str] + first_name: Optional[str] + last_name: Optional[str] + display_name: Optional[str] + image_original: Optional[str] + image_24: Optional[str] + image_32: Optional[str] + image_48: Optional[str] + image_72: Optional[str] + image_192: Optional[str] + image_512: Optional[str] + image_1024: Optional[str] + + def __init__( + self, + *, + real_name: Optional[str] = None, + first_name: Optional[str] = None, + last_name: Optional[str] = None, + display_name: Optional[str] = None, + image_original: Optional[str] = None, + image_24: Optional[str] = None, + image_32: Optional[str] = None, + image_48: Optional[str] = None, + image_72: Optional[str] = None, + image_192: Optional[str] = None, + image_512: Optional[str] = None, + image_1024: Optional[str] = None, + **kwargs, + ) -> None: + self.real_name = real_name + self.first_name = first_name + self.last_name = last_name + self.display_name = display_name + self.image_original = image_original + self.image_24 = image_24 + self.image_32 = image_32 + self.image_48 = image_48 + self.image_72 = image_72 + self.image_192 = image_192 + self.image_512 = image_512 + self.image_1024 = image_1024 + + +class SpaceFileId: + payload: Optional[str] + + def __init__( + self, + *, + payload: Optional[str] = None, + **kwargs, + ) -> None: + self.payload = payload + + +class AttributeItems: + type: Optional[str] + + def __init__( + self, + *, + type: Optional[str] = None, + **kwargs, + ) -> None: + self.type = type + + +class Attribute: + name: Optional[str] + type: Optional[str] + items: Optional[AttributeItems] + + def __init__( + self, + *, + name: Optional[str] = None, + type: Optional[str] = None, + items: Optional[AttributeItems] = None, + **kwargs, + ) -> None: + self.name = name + self.type = type + self.items = items + + +class AAARuleActionResolution: + value: Optional[str] + + def __init__( + self, + *, + value: Optional[str] = None, + **kwargs, + ) -> None: + self.value = value + + +class AAARuleActionNotify: + entity_type: Optional[str] + + def __init__( + self, + *, + entity_type: Optional[str] = None, + **kwargs, + ) -> None: + self.entity_type = entity_type + + +class AAARuleAction: + resolution: Optional[AAARuleActionResolution] + notify: Optional[List[AAARuleActionNotify]] + + def __init__( + self, + *, + resolution: Optional[Union[Dict[str, Any], AAARuleActionResolution]] = None, + notify: Optional[List[Union[Dict[str, Any], AAARuleActionNotify]]] = None, + **kwargs, + ) -> None: + self.resolution = ( + resolution + if resolution is None or isinstance(resolution, AAARuleActionResolution) + else AAARuleActionResolution(**resolution) + ) + self.notify = None + if notify is not None: + self.notify = [] + for a in notify: + if isinstance(a, dict): + self.notify.append(AAARuleActionNotify(**a)) + else: + self.notify.append(a) + + +class AAARuleConditionValue: + field: Optional[str] + values: Optional[List[str]] + datatype: Optional[str] + operator: Optional[str] + + def __init__( + self, + *, + field: Optional[str] = None, + values: Optional[List[str]] = None, + datatype: Optional[str] = None, + operator: Optional[str] = None, + **kwargs, + ) -> None: + self.field = field + self.values = values + self.datatype = datatype + self.operator = operator + + +class AAARuleCondition: + datatype: Optional[str] + operator: Optional[str] + values: Optional[List[AAARuleConditionValue]] + entity_type: Optional[str] + + def __init__( + self, + *, + datatype: Optional[str] = None, + operator: Optional[str] = None, + values: Optional[List[Union[Dict[str, Any], AAARuleConditionValue]]] = None, + entity_type: Optional[str] = None, + **kwargs, + ) -> None: + self.datatype = datatype + self.operator = operator + self.values = None + if values is not None: + self.values = [] + for a in values: + if isinstance(a, dict): + self.values.append(AAARuleConditionValue(**a)) + else: + self.values.append(a) + self.entity_type = entity_type + + +class AAARule: + id: Optional[str] + team_id: Optional[str] + title: Optional[str] + action: Optional[AAARuleAction] + condition: Optional[AAARuleCondition] + + def __init__( + self, + *, + id: Optional[str] = None, + team_id: Optional[str] = None, + title: Optional[str] = None, + action: Optional[Union[Dict[str, Any], AAARuleAction]] = None, + condition: Optional[Union[Dict[str, Any], AAARuleCondition]] = None, + **kwargs, + ) -> None: + self.id = id + self.team_id = team_id + self.title = title + self.action = action if action is None or isinstance(action, AAARuleAction) else AAARuleAction(**action) + self.condition = ( + condition if condition is None or isinstance(condition, AAARuleCondition) else AAARuleCondition(**condition) + ) + + +class AAARequest: + id: Optional[str] + team_id: Optional[str] + + def __init__( + self, + *, + id: Optional[str] = None, + team_id: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.team_id = team_id + + +class Details: + name: Optional[str] + new_value: Optional[Union[str, List[str], Dict[str, Any]]] + previous_value: Optional[Union[str, List[str], Dict[str, Any]]] + expires_on: Optional[int] + mobile_only: Optional[bool] + web_only: Optional[bool] + non_sso_only: Optional[bool] + type: Optional[str] + is_workflow: Optional[bool] + inviter: Optional[User] + kicker: Optional[User] + shared_to: Optional[str] + reason: Optional[str] + origin_team: Optional[str] + target_team: Optional[str] + is_internal_integration: Optional[bool] + cleared_resolution: Optional[str] + app_owner_id: Optional[str] + bot_scopes: Optional[List[str]] + new_scopes: Optional[List[str]] + previous_scopes: Optional[List[str]] + granular_bot_token: Optional[bool] + scopes: Optional[List[str]] + scopes_bot: Optional[List[str]] + resolution: Optional[str] + app_previously_resolved: Optional[bool] + admin_app_id: Optional[str] + bot_id: Optional[str] + installer_user_id: Optional[str] + approver_id: Optional[str] + approval_type: Optional[str] + app_previously_approved: Optional[bool] + old_scopes: Optional[List[str]] + channels: Optional[List[str]] + permissions: Optional[List[Dict[str, Any]]] + new_version_id: Optional[str] + trigger: Optional[str] + export_type: Optional[str] + export_start_ts: Optional[str] + export_end_ts: Optional[str] + barrier_id: Optional[str] + primary_usergroup_id: Optional[str] + barriered_from_usergroup_ids: Optional[List[str]] + restricted_subjects: Optional[List[str]] + duration: Optional[int] + desktop_app_browser_quit: Optional[bool] + invite_id: Optional[str] + external_organization_id: Optional[str] + external_organization_name: Optional[str] + external_user_id: Optional[str] + external_user_email: Optional[str] + channel_id: Optional[str] + added_team_id: Optional[str] + unknown_fields: Dict[str, Any] + is_token_rotation_enabled_app: Optional[bool] + old_retention_policy: Optional[RetentionPolicy] + new_retention_policy: Optional[RetentionPolicy] + who_can_post: Optional[ConversationPref] + can_thread: Optional[ConversationPref] + is_external_limited: Optional[bool] + exporting_team_id: Optional[int] + session_search_start: Optional[int] + deprecation_search_end: Optional[int] + is_error: Optional[bool] + creator: Optional[str] + team: Optional[str] + app_id: Optional[str] + enable_at_here: Optional[FeatureEnablement] + enable_at_channel: Optional[FeatureEnablement] + can_huddle: Optional[FeatureEnablement] + url_private: Optional[str] + shared_with: Optional[SharedWith] + initiated_by: Optional[str] + source_team: Optional[str] + destination_team: Optional[str] + succeeded_users: Optional[List[str]] + failed_users: Optional[List[str]] + enterprise: Optional[str] + subteam: Optional[str] + action: Optional[str] + idp_group_member_count: Optional[int] + workspace_member_count: Optional[int] + added_user_count: Optional[int] + added_user_error_count: Optional[int] + reactivated_user_count: Optional[int] + removed_user_count: Optional[int] + removed_user_error_count: Optional[int] + total_removal_count: Optional[int] + is_flagged: Optional[str] + target_user: Optional[str] + idp_config_id: Optional[str] + config_type: Optional[str] + idp_entity_id_hash: Optional[str] + label: Optional[str] + previous_profile: Optional[Profile] + new_profile: Optional[Profile] + target_user_id: Optional[str] + space_file_id: Optional[SpaceFileId] + target_entity: Optional[str] + target_entity_id: Optional[str] + changed_permissions: Optional[List[str]] + datastore_name: Optional[str] + attributes: Optional[List[Attribute]] + channel: Optional[str] + entity_type: Optional[str] + actor: Optional[str] + access_level: Optional[str] + functions: Optional[List[str]] + workflows: Optional[List[str]] + datastores: Optional[List[str]] + permissions_updated: Optional[bool] + matched_rule: Optional[AAARule] + request: Optional[AAARequest] + rules_checked: Optional[List[AAARule]] + disconnecting_team: Optional[str] + is_channel_canvas: Optional[bool] + linked_channel_id: Optional[str] + column_id: Optional[str] + row_id: Optional[str] + cell_date_updated: Optional[int] + view_id: Optional[str] + user: Optional[str] + + def __init__( + self, + *, + name: Optional[str] = None, + new_value: Optional[Union[str, List[str], Dict[str, Any]]] = None, + previous_value: Optional[Union[str, List[str], Dict[str, Any]]] = None, + expires_on: Optional[int] = None, + mobile_only: Optional[bool] = None, + web_only: Optional[bool] = None, + non_sso_only: Optional[bool] = None, + type: Optional[str] = None, + is_workflow: Optional[bool] = None, + inviter: Optional[Union[Dict[str, Any], User]] = None, + kicker: Optional[Union[Dict[str, Any], User]] = None, + shared_to: Optional[str] = None, + reason: Optional[str] = None, + origin_team: Optional[str] = None, + target_team: Optional[str] = None, + is_internal_integration: Optional[bool] = None, + cleared_resolution: Optional[str] = None, + app_owner_id: Optional[str] = None, + bot_scopes: Optional[List[str]] = None, + new_scopes: Optional[List[str]] = None, + previous_scopes: Optional[List[str]] = None, + granular_bot_token: Optional[bool] = None, + scopes: Optional[List[str]] = None, + scopes_bot: Optional[List[str]] = None, + resolution: Optional[str] = None, + app_previously_resolved: Optional[bool] = None, + admin_app_id: Optional[str] = None, + bot_id: Optional[str] = None, + installer_user_id: Optional[str] = None, + approver_id: Optional[str] = None, + approval_type: Optional[str] = None, + app_previously_approved: Optional[bool] = None, + old_scopes: Optional[List[str]] = None, + channels: Optional[List[str]] = None, + permissions: Optional[List[Dict[str, Any]]] = None, + new_version_id: Optional[str] = None, + trigger: Optional[str] = None, + export_type: Optional[str] = None, + export_start_ts: Optional[str] = None, + export_end_ts: Optional[str] = None, + barrier_id: Optional[str] = None, + primary_usergroup_id: Optional[str] = None, + barriered_from_usergroup_ids: Optional[List[str]] = None, + restricted_subjects: Optional[List[str]] = None, + duration: Optional[int] = None, + desktop_app_browser_quit: Optional[bool] = None, + invite_id: Optional[str] = None, + external_organization_id: Optional[str] = None, + external_organization_name: Optional[str] = None, + external_user_id: Optional[str] = None, + external_user_email: Optional[str] = None, + channel_id: Optional[str] = None, + added_team_id: Optional[str] = None, + is_token_rotation_enabled_app: Optional[bool] = None, + old_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None, + new_retention_policy: Optional[Union[Dict[str, Any], RetentionPolicy]] = None, + who_can_post: Optional[Union[Dict[str, List[str]], ConversationPref]] = None, + can_thread: Optional[Union[Dict[str, List[str]], ConversationPref]] = None, + is_external_limited: Optional[bool] = None, + exporting_team_id: Optional[int] = None, + session_search_start: Optional[int] = None, + deprecation_search_end: Optional[int] = None, + is_error: Optional[bool] = None, + creator: Optional[str] = None, + team: Optional[str] = None, + app_id: Optional[str] = None, + enable_at_here: Optional[Union[Dict[str, Any], FeatureEnablement]] = None, + enable_at_channel: Optional[Union[Dict[str, Any], FeatureEnablement]] = None, + can_huddle: Optional[Union[Dict[str, Any], FeatureEnablement]] = None, + url_private: Optional[str] = None, + shared_with: Optional[Union[Dict[str, Any], SharedWith]] = None, + initiated_by: Optional[str] = None, + source_team: Optional[str] = None, + destination_team: Optional[str] = None, + succeeded_users: Optional[Union[List[str], str]] = None, + failed_users: Optional[Union[List[str], str]] = None, + enterprise: Optional[str] = None, + subteam: Optional[str] = None, + action: Optional[str] = None, + idp_group_member_count: Optional[int] = None, + workspace_member_count: Optional[int] = None, + added_user_count: Optional[int] = None, + added_user_error_count: Optional[int] = None, + reactivated_user_count: Optional[int] = None, + removed_user_count: Optional[int] = None, + removed_user_error_count: Optional[int] = None, + total_removal_count: Optional[int] = None, + is_flagged: Optional[str] = None, + target_user: Optional[str] = None, + idp_config_id: Optional[str] = None, + config_type: Optional[str] = None, + idp_entity_id_hash: Optional[str] = None, + label: Optional[str] = None, + previous_profile: Optional[Union[Dict[str, Any], Profile]] = None, + new_profile: Optional[Union[Dict[str, Any], Profile]] = None, + target_user_id: Optional[str] = None, + space_file_id: Optional[Union[Dict[str, Any], SpaceFileId]] = None, + target_entity: Optional[str] = None, + target_entity_id: Optional[str] = None, + changed_permissions: Optional[List[str]] = None, + datastore_name: Optional[str] = None, + attributes: Optional[List[Union[Dict[str, str], Attribute]]] = None, + channel: Optional[str] = None, + entity_type: Optional[str] = None, + actor: Optional[str] = None, + access_level: Optional[str] = None, + functions: Optional[List[str]] = None, + workflows: Optional[List[str]] = None, + datastores: Optional[List[str]] = None, + permissions_updated: Optional[bool] = None, + matched_rule: Optional[Union[Dict[str, Any], AAARule]] = None, + request: Optional[Union[Dict[str, Any], AAARequest]] = None, + rules_checked: Optional[List[Union[Dict[str, Any], AAARule]]] = None, + disconnecting_team: Optional[str] = None, + is_channel_canvas: Optional[bool] = None, + linked_channel_id: Optional[str] = None, + column_id: Optional[str] = None, + row_id: Optional[str] = None, + cell_date_updated: Optional[int] = None, + view_id: Optional[str] = None, + user: Optional[str] = None, + **kwargs, + ) -> None: + self.name = name + self.new_value = new_value + self.previous_value = previous_value + self.expires_on = expires_on + self.mobile_only = mobile_only + self.web_only = web_only + self.non_sso_only = non_sso_only + self.type = type + self.is_workflow = is_workflow + self.inviter = inviter if inviter is None or isinstance(inviter, User) else User(**inviter) + self.kicker = kicker if kicker is None or isinstance(kicker, User) else User(**kicker) + self.shared_to = shared_to + self.reason = reason + self.origin_team = origin_team + self.target_team = target_team + self.is_internal_integration = is_internal_integration + self.cleared_resolution = cleared_resolution + self.app_owner_id = app_owner_id + self.bot_scopes = bot_scopes + self.new_scopes = new_scopes + self.previous_scopes = previous_scopes + self.granular_bot_token = granular_bot_token + self.scopes = scopes + self.scopes_bot = scopes_bot + self.resolution = resolution + self.app_previously_resolved = app_previously_resolved + self.admin_app_id = admin_app_id + self.bot_id = bot_id + self.unknown_fields = kwargs + self.installer_user_id = installer_user_id + self.approver_id = approver_id + self.approval_type = approval_type + self.app_previously_approved = app_previously_approved + self.old_scopes = old_scopes + self.channels = channels + self.permissions = permissions + self.new_version_id = new_version_id + self.trigger = trigger + self.export_type = export_type + self.export_start_ts = export_start_ts + self.export_end_ts = export_end_ts + self.barrier_id = barrier_id + self.primary_usergroup_id = primary_usergroup_id + self.barriered_from_usergroup_ids = barriered_from_usergroup_ids + self.restricted_subjects = restricted_subjects + self.duration = duration + self.desktop_app_browser_quit = desktop_app_browser_quit + self.invite_id = invite_id + self.external_organization_id = external_organization_id + self.external_organization_name = external_organization_name + self.external_user_id = external_user_id + self.external_user_email = external_user_email + self.channel_id = channel_id + self.added_team_id = added_team_id + self.is_token_rotation_enabled_app = is_token_rotation_enabled_app + self.old_retention_policy = ( + old_retention_policy + if old_retention_policy is None or isinstance(old_retention_policy, RetentionPolicy) + else RetentionPolicy(**old_retention_policy) + ) + self.new_retention_policy = ( + new_retention_policy + if new_retention_policy is None or isinstance(new_retention_policy, RetentionPolicy) + else RetentionPolicy(**new_retention_policy) + ) + self.who_can_post = ( + who_can_post + if who_can_post is None or isinstance(who_can_post, ConversationPref) + else ConversationPref(**who_can_post) + ) + self.can_thread = ( + can_thread if can_thread is None or isinstance(can_thread, ConversationPref) else ConversationPref(**can_thread) + ) + self.is_external_limited = is_external_limited + self.exporting_team_id = exporting_team_id + self.session_search_start = session_search_start + self.deprecation_search_end = deprecation_search_end + self.is_error = is_error + self.creator = creator + self.team = team + self.app_id = app_id + self.enable_at_here = ( + enable_at_here + if enable_at_here is None or isinstance(enable_at_here, FeatureEnablement) + else FeatureEnablement(**enable_at_here) + ) + self.enable_at_channel = ( + enable_at_channel + if enable_at_channel is None or isinstance(enable_at_channel, FeatureEnablement) + else FeatureEnablement(**enable_at_channel) + ) + self.can_huddle = ( + can_huddle + if can_huddle is None or isinstance(can_huddle, FeatureEnablement) + else FeatureEnablement(**can_huddle) + ) + self.url_private = url_private + self.shared_with = ( + shared_with if shared_with is None or isinstance(shared_with, SharedWith) else SharedWith(**shared_with) + ) + self.initiated_by = initiated_by + self.source_team = source_team + self.destination_team = destination_team + self.succeeded_users = ( + succeeded_users if succeeded_users is None or isinstance(succeeded_users, list) else json.loads(succeeded_users) + ) + self.failed_users = ( + failed_users if failed_users is None or isinstance(failed_users, list) else json.loads(failed_users) + ) + self.enterprise = enterprise + self.subteam = subteam + self.action = action + self.idp_group_member_count = idp_group_member_count + self.workspace_member_count = workspace_member_count + self.added_user_count = added_user_count + self.added_user_error_count = added_user_error_count + self.reactivated_user_count = reactivated_user_count + self.removed_user_count = removed_user_count + self.removed_user_error_count = removed_user_error_count + self.total_removal_count = total_removal_count + self.is_flagged = is_flagged + self.target_user = target_user + self.idp_config_id = idp_config_id + self.config_type = config_type + self.idp_entity_id_hash = idp_entity_id_hash + self.label = label + self.previous_profile = ( + previous_profile + if previous_profile is None or isinstance(previous_profile, Profile) + else Profile(**previous_profile) + ) + self.new_profile = new_profile if new_profile is None or isinstance(new_profile, Profile) else Profile(**new_profile) + self.target_user_id = target_user_id + self.space_file_id = ( + space_file_id + if space_file_id is None or isinstance(space_file_id, SpaceFileId) + else SpaceFileId(**space_file_id) + ) + self.target_entity = target_entity + self.target_entity_id = target_entity_id + self.changed_permissions = changed_permissions + self.datastore_name = datastore_name + self.attributes = None + if attributes is not None: + self.attributes = [] + for a in attributes: + if isinstance(a, dict): + self.attributes.append(Attribute(**a)) # type: ignore[arg-type] + else: + self.attributes.append(a) + self.channel = channel + self.entity_type = entity_type + self.actor = actor + self.access_level = access_level + self.functions = functions + self.workflows = workflows + self.datastores = datastores + self.permissions_updated = permissions_updated + self.matched_rule = ( + matched_rule if matched_rule is None or isinstance(matched_rule, AAARule) else AAARule(**matched_rule) + ) + self.request = request if request is None or isinstance(request, AAARequest) else AAARequest(**request) + self.rules_checked = None + if rules_checked is not None: + self.rules_checked = [] + for a in rules_checked: # type: ignore[assignment] + if isinstance(a, dict): + self.rules_checked.append(AAARule(**a)) # type: ignore[arg-type] + else: + self.rules_checked.append(a) # type: ignore[arg-type] + self.disconnecting_team = disconnecting_team + self.is_channel_canvas = is_channel_canvas + self.linked_channel_id = linked_channel_id + self.column_id = column_id + self.row_id = row_id + self.cell_date_updated = cell_date_updated + self.view_id = view_id + self.user = user + + +class Channel: + id: Optional[str] + privacy: Optional[str] + name: Optional[str] + is_shared: Optional[bool] + is_org_shared: Optional[bool] + teams_shared_with: Optional[List[str]] + original_connected_channel_id: Optional[str] + is_salesforce_channel: Optional[bool] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + privacy: Optional[str] = None, + name: Optional[str] = None, + is_shared: Optional[bool] = None, + is_org_shared: Optional[bool] = None, + teams_shared_with: Optional[List[str]] = None, + original_connected_channel_id: Optional[str] = None, + is_salesforce_channel: Optional[bool] = None, + **kwargs, + ) -> None: + self.id = id + self.privacy = privacy + self.name = name + self.is_shared = is_shared + self.is_org_shared = is_org_shared + self.teams_shared_with = teams_shared_with + self.original_connected_channel_id = original_connected_channel_id + self.is_salesforce_channel = is_salesforce_channel + self.unknown_fields = kwargs + + +class File: + id: Optional[str] + name: Optional[str] + filetype: Optional[str] + title: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + filetype: Optional[str] = None, + title: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.filetype = filetype + self.title = title + self.unknown_fields = kwargs + + +class Usergroup: + id: Optional[str] + name: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.unknown_fields = kwargs + + +class Message: + channel: Optional[str] + team: Optional[str] + timestamp: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + channel: Optional[str] = None, + team: Optional[str] = None, + timestamp: Optional[str] = None, + **kwargs, + ) -> None: + self.channel = channel + self.team = team + self.timestamp = timestamp + self.unknown_fields = kwargs + + +class Huddle: + id: Optional[str] + date_start: Optional[int] + date_end: Optional[int] + participants: Optional[List[str]] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + date_start: Optional[int] = None, + date_end: Optional[int] = None, + participants: Optional[List[str]] = None, + **kwargs, + ) -> None: + self.id = id + self.date_start = date_start + self.date_end = date_end + self.participants = participants + self.unknown_fields = kwargs + + +class Role: + id: Optional[str] + name: Optional[str] + type: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.type = type + self.unknown_fields = kwargs + + +class Workflow: + id: Optional[str] + name: Optional[str] + domain: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + domain: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.domain = domain + self.unknown_fields = kwargs + + +class InformationBarrier: + id: Optional[str] + primary_usergroup: Optional[str] + barriered_from_usergroups: Optional[List[str]] + restricted_subjects: Optional[List[str]] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + primary_usergroup: Optional[str] = None, + barriered_from_usergroups: Optional[List[str]] = None, + restricted_subjects: Optional[List[str]] = None, + **kwargs, + ) -> None: + self.id = id + self.primary_usergroup = primary_usergroup + self.barriered_from_usergroups = barriered_from_usergroups + self.restricted_subjects = restricted_subjects + self.unknown_fields = kwargs + + +class WorkflowV2StepConfiguration: + name: Optional[str] + step_function_type: Optional[str] + step_function_app_id: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + name: Optional[str] = None, + step_function_type: Optional[str] = None, + step_function_app_id: Optional[str] = None, + **kwargs, + ) -> None: + self.name = name + self.step_function_type = step_function_type + self.step_function_app_id = step_function_app_id + self.unknown_fields = kwargs + + +class WorkflowV2: + id: Optional[str] + app_id: Optional[str] + date_updated: Optional[int] + callback_id: Optional[str] + name: Optional[str] + updated_by: Optional[str] + step_configuration: Optional[List[WorkflowV2StepConfiguration]] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + app_id: Optional[str] = None, + date_updated: Optional[int] = None, + callback_id: Optional[str] = None, + name: Optional[str] = None, + updated_by: Optional[str] = None, + step_configuration: Optional[List[Union[Dict[str, Any], WorkflowV2StepConfiguration]]] = None, + **kwargs, + ) -> None: + self.id = id + self.app_id = app_id + self.date_updated = date_updated + self.callback_id = callback_id + self.name = name + self.updated_by = updated_by + self.step_configuration = None + if step_configuration is not None: + self.step_configuration = [] + for a in step_configuration: + if isinstance(a, dict): + self.step_configuration.append(WorkflowV2StepConfiguration(**a)) + else: + self.step_configuration.append(a) + self.unknown_fields = kwargs + + +class AccountTypeRole: + id: Optional[str] + name: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + name: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.name = name + self.unknown_fields = kwargs + + +class SlackList: + id: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + **kwargs, + ) -> None: + self.id = id + self.unknown_fields = kwargs + + +class Entity: + type: Optional[str] + user: Optional[User] + workspace: Optional[Location] + enterprise: Optional[Location] + channel: Optional[Channel] + file: Optional[File] + app: Optional[App] + message: Optional[Message] + huddle: Optional[Huddle] + role: Optional[Role] + usergroup: Optional[Usergroup] + workflow: Optional[Workflow] + barrier: Optional[InformationBarrier] + workflow_v2: Optional[WorkflowV2] + account_type_role: Optional[AccountTypeRole] + list: Optional[SlackList] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + type: Optional[str] = None, + user: Optional[Union[User, Dict[str, Any]]] = None, + workspace: Optional[Union[Location, Dict[str, Any]]] = None, + enterprise: Optional[Union[Location, Dict[str, Any]]] = None, + channel: Optional[Union[Channel, Dict[str, Any]]] = None, + file: Optional[Union[File, Dict[str, Any]]] = None, + app: Optional[Union[App, Dict[str, Any]]] = None, + message: Optional[Union[Message, Dict[str, Any]]] = None, + huddle: Optional[Union[Huddle, Dict[str, Any]]] = None, + role: Optional[Union[Role, Dict[str, Any]]] = None, + usergroup: Optional[Union[Usergroup, Dict[str, Any]]] = None, + workflow: Optional[Union[Workflow, Dict[str, Any]]] = None, + barrier: Optional[Union[InformationBarrier, Dict[str, Any]]] = None, + workflow_v2: Optional[Union[WorkflowV2, Dict[str, Any]]] = None, + account_type_role: Optional[Union[AccountTypeRole, Dict[str, Any]]] = None, + list: Optional[Union[SlackList, Dict[str, Any]]] = None, + **kwargs, + ) -> None: + self.type = type + self.user = User(**user) if isinstance(user, dict) else user + self.workspace = Location(**workspace) if isinstance(workspace, dict) else workspace + self.enterprise = Location(**enterprise) if isinstance(enterprise, dict) else enterprise + self.channel = Channel(**channel) if isinstance(channel, dict) else channel + self.file = File(**file) if isinstance(file, dict) else file + self.app = App(**app) if isinstance(app, dict) else app + self.message = Message(**message) if isinstance(message, dict) else message + self.huddle = Huddle(**huddle) if isinstance(huddle, dict) else huddle + self.role = Role(**role) if isinstance(role, dict) else role + self.usergroup = Usergroup(**usergroup) if isinstance(usergroup, dict) else usergroup + self.workflow = Workflow(**workflow) if isinstance(workflow, dict) else workflow + self.barrier = InformationBarrier(**barrier) if isinstance(barrier, dict) else barrier + self.workflow_v2 = WorkflowV2(**workflow_v2) if isinstance(workflow_v2, dict) else workflow_v2 + self.account_type_role = ( + AccountTypeRole(**account_type_role) if isinstance(account_type_role, dict) else account_type_role + ) + self.list = SlackList(**list) if isinstance(list, dict) else list + self.unknown_fields = kwargs + + +class Entry: + id: Optional[str] + date_create: Optional[int] + action: Optional[str] + actor: Optional[Actor] + entity: Optional[Entity] + context: Optional[Context] + details: Optional[Details] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + id: Optional[str] = None, + date_create: Optional[int] = None, + action: Optional[str] = None, + actor: Optional[Union[Actor, Dict[str, Any]]] = None, + entity: Optional[Union[Entity, Dict[str, Any]]] = None, + context: Optional[Union[Context, Dict[str, Any]]] = None, + details: Optional[Union[Details, Dict[str, Any]]] = None, + **kwargs, + ) -> None: + self.id = id + self.date_create = date_create + self.action = action + self.actor = Actor(**actor) if isinstance(actor, dict) else actor + self.entity = Entity(**entity) if isinstance(entity, dict) else entity + self.context = Context(**context) if isinstance(context, dict) else context + self.details = Details(**details) if isinstance(details, dict) else details + self.unknown_fields = kwargs + + +class ResponseMetadata: + next_cursor: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + next_cursor: Optional[str] = None, + **kwargs, + ) -> None: + self.next_cursor = next_cursor + self.unknown_fields = kwargs + + +class LogsResponse: + entries: Optional[List[Entry]] + response_metadata: Optional[ResponseMetadata] + ok: Optional[bool] + error: Optional[str] + needed: Optional[str] + provided: Optional[str] + unknown_fields: Dict[str, Any] + + def __init__( + self, + *, + entries: Optional[List[Union[Entry, Dict[str, Any]]]] = None, + response_metadata: Optional[Union[ResponseMetadata, Dict[str, Any]]] = None, + ok: Optional[bool] = None, + error: Optional[str] = None, + needed: Optional[str] = None, + provided: Optional[str] = None, + **kwargs, + ) -> None: + self.entries = [Entry(**e) if isinstance(e, dict) else e for e in entries] # type: ignore[union-attr] + self.response_metadata = ( + ResponseMetadata(**response_metadata) if isinstance(response_metadata, dict) else response_metadata + ) + self.ok = ok + self.error = error + self.needed = needed + self.provided = provided + self.unknown_fields = kwargs diff --git a/slack_sdk/audit_logs/v1/response.py b/slack_sdk/audit_logs/v1/response.py new file mode 100644 index 000000000..a2e0705d5 --- /dev/null +++ b/slack_sdk/audit_logs/v1/response.py @@ -0,0 +1,34 @@ +import json +from typing import Dict, Any, Optional + +from slack_sdk.audit_logs.v1.logs import LogsResponse + + +# TODO: Unlike WebClient's responses, this class has not yet provided __iter__ method +class AuditLogsResponse: + url: str + status_code: int + headers: Dict[str, Any] + raw_body: Optional[str] + body: Optional[Dict[str, Any]] + typed_body: Optional[LogsResponse] + + @property # type: ignore[no-redef] + def typed_body(self) -> Optional[LogsResponse]: + if self.body is None: + return None + return LogsResponse(**self.body) + + def __init__( + self, + *, + url: str, + status_code: int, + raw_body: Optional[str], + headers: dict, + ): + self.url = url + self.status_code = status_code + self.headers = headers + self.raw_body = raw_body + self.body = json.loads(raw_body) if raw_body is not None and raw_body.startswith("{") else None diff --git a/slack_sdk/errors/__init__.py b/slack_sdk/errors/__init__.py index 7de0efb8e..51b9a04f6 100644 --- a/slack_sdk/errors/__init__.py +++ b/slack_sdk/errors/__init__.py @@ -1,3 +1,6 @@ +"""Errors that can be raised by this SDK""" + + class SlackClientError(Exception): """Base class for Client errors""" @@ -30,10 +33,26 @@ def __init__(self, message, response): super(SlackApiError, self).__init__(msg) +class SlackTokenRotationError(SlackClientError): + """Error raised when the oauth.v2.access call for token rotation fails""" + + api_error: SlackApiError + + def __init__(self, api_error: SlackApiError): + self.api_error = api_error + + class SlackClientNotConnectedError(SlackClientError): """Error raised when attempting to send messages over the websocket when the - connection is closed. """ + connection is closed.""" class SlackObjectFormationError(SlackClientError): """Error raised when a constructed object is not valid/malformed""" + + +class SlackClientConfigurationError(SlackClientError): + """Error raised because of invalid configuration on the client side: + * when attempting to send messages over the websocket when the connection is closed. + * when external system (e.g., Amazon S3) configuration / credentials are not correct + """ diff --git a/slack_sdk/http_retry/__init__.py b/slack_sdk/http_retry/__init__.py new file mode 100644 index 000000000..b7116dad9 --- /dev/null +++ b/slack_sdk/http_retry/__init__.py @@ -0,0 +1,48 @@ +from typing import List + +from .handler import RetryHandler +from .builtin_handlers import ( + ConnectionErrorRetryHandler, + RateLimitErrorRetryHandler, +) +from .interval_calculator import RetryIntervalCalculator +from .builtin_interval_calculators import ( + FixedValueRetryIntervalCalculator, + BackoffRetryIntervalCalculator, +) +from .jitter import Jitter +from .request import HttpRequest +from .response import HttpResponse +from .state import RetryState + +connect_error_retry_handler = ConnectionErrorRetryHandler() +rate_limit_error_retry_handler = RateLimitErrorRetryHandler() + + +def default_retry_handlers() -> List[RetryHandler]: + return [connect_error_retry_handler] + + +def all_builtin_retry_handlers() -> List[RetryHandler]: + return [ + connect_error_retry_handler, + rate_limit_error_retry_handler, + ] + + +__all__ = [ + "RetryHandler", + "ConnectionErrorRetryHandler", + "RateLimitErrorRetryHandler", + "RetryIntervalCalculator", + "FixedValueRetryIntervalCalculator", + "BackoffRetryIntervalCalculator", + "Jitter", + "HttpRequest", + "HttpResponse", + "RetryState", + "connect_error_retry_handler", + "rate_limit_error_retry_handler", + "default_retry_handlers", + "all_builtin_retry_handlers", +] diff --git a/slack_sdk/http_retry/async_handler.py b/slack_sdk/http_retry/async_handler.py new file mode 100644 index 000000000..ed9f6115a --- /dev/null +++ b/slack_sdk/http_retry/async_handler.py @@ -0,0 +1,89 @@ +"""asyncio compatible RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients. +""" + +import asyncio +from typing import Optional + +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.builtin_interval_calculators import ( + BackoffRetryIntervalCalculator, +) + +default_interval_calculator = BackoffRetryIntervalCalculator() + + +class AsyncRetryHandler: + """asyncio compatible RetryHandler interface. + You can pass an array of handlers to customize retry logics in supported API clients. + """ + + max_retry_count: int + interval_calculator: RetryIntervalCalculator + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + """RetryHandler interface. + + Args: + max_retry_count: The maximum times to do retries + interval_calculator: Pass an interval calculator for customizing the logic + """ + self.max_retry_count = max_retry_count + self.interval_calculator = interval_calculator + + async def can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + if state.current_attempt >= self.max_retry_count: + return False + return await self._can_retry_async( + state=state, + request=request, + response=response, + error=error, + ) + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + raise NotImplementedError() + + async def prepare_for_next_attempt_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> None: + state.next_attempt_requested = True + duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt) + await asyncio.sleep(duration) + state.increment_current_attempt() + + +__all__ = [ + "RetryState", + "HttpRequest", + "HttpResponse", + "RetryIntervalCalculator", + "BackoffRetryIntervalCalculator", + "default_interval_calculator", +] diff --git a/slack_sdk/http_retry/builtin_async_handlers.py b/slack_sdk/http_retry/builtin_async_handlers.py new file mode 100644 index 000000000..0d99d67a7 --- /dev/null +++ b/slack_sdk/http_retry/builtin_async_handlers.py @@ -0,0 +1,111 @@ +import asyncio +import random +from typing import Optional, List, Type + +from aiohttp import ServerDisconnectedError, ServerConnectionError, ClientOSError + +from slack_sdk.http_retry.async_handler import AsyncRetryHandler +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.handler import default_interval_calculator + + +class AsyncConnectionErrorRetryHandler(AsyncRetryHandler): + """RetryHandler that does retries for connectivity issues.""" + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + error_types: List[Type[Exception]] = [ + ServerConnectionError, + ServerDisconnectedError, + # ClientOSError: [Errno 104] Connection reset by peer + ClientOSError, + ], + ): + super().__init__(max_retry_count, interval_calculator) + self.error_types_to_do_retries = error_types + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + if error is None: + return False + + for error_type in self.error_types_to_do_retries: + if isinstance(error, error_type): + return True + return False + + +class AsyncRateLimitErrorRetryHandler(AsyncRetryHandler): + """RetryHandler that does retries for rate limited errors.""" + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + return response is not None and response.status_code == 429 + + async def prepare_for_next_attempt_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> None: + if response is None: + raise error # type: ignore[misc] + + state.next_attempt_requested = True + retry_after_header_name: Optional[str] = None + for k in response.headers.keys(): + if k.lower() == "retry-after": + retry_after_header_name = k + break + duration = 1 + if retry_after_header_name is None: + # This situation usually does not arise. Just in case. + duration += random.random() # type: ignore[assignment] + else: + duration = int(response.headers.get(retry_after_header_name)[0]) + random.random() # type: ignore[assignment, index] # noqa: E501 + await asyncio.sleep(duration) + state.increment_current_attempt() + + +class AsyncServerErrorRetryHandler(AsyncRetryHandler): + """RetryHandler that does retries for server errors.""" + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + super().__init__(max_retry_count, interval_calculator) + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + return response is not None and response.status_code in [500, 503] + + +def async_default_handlers() -> List[AsyncRetryHandler]: + return [AsyncConnectionErrorRetryHandler()] diff --git a/slack_sdk/http_retry/builtin_handlers.py b/slack_sdk/http_retry/builtin_handlers.py new file mode 100644 index 000000000..8755d7c89 --- /dev/null +++ b/slack_sdk/http_retry/builtin_handlers.py @@ -0,0 +1,110 @@ +import random +import time +from http.client import RemoteDisconnected +from typing import Optional, List, Type +from urllib.error import URLError + +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.handler import RetryHandler, default_interval_calculator + + +class ConnectionErrorRetryHandler(RetryHandler): + """RetryHandler that does retries for connectivity issues.""" + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + error_types: List[Type[Exception]] = [ + # To cover URLError: + URLError, + ConnectionResetError, + RemoteDisconnected, + ], + ): + super().__init__(max_retry_count, interval_calculator) + self.error_types_to_do_retries = error_types + + def _can_retry( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + if error is None: + return False + + if isinstance(error, URLError): + if response is not None: + return False # status 40x + + for error_type in self.error_types_to_do_retries: + if isinstance(error, error_type): + return True + return False + + +class RateLimitErrorRetryHandler(RetryHandler): + """RetryHandler that does retries for rate limited errors.""" + + def _can_retry( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + return response is not None and response.status_code == 429 + + def prepare_for_next_attempt( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> None: + if response is None: + raise error # type: ignore[misc] + + state.next_attempt_requested = True + retry_after_header_name: Optional[str] = None + for k in response.headers.keys(): + if k.lower() == "retry-after": + retry_after_header_name = k + break + duration = 1 + if retry_after_header_name is None: + # This situation usually does not arise. Just in case. + duration += random.random() # type: ignore[assignment] + else: + duration = int(response.headers.get(retry_after_header_name)[0]) + random.random() # type: ignore[index, assignment] # noqa: E501 + time.sleep(duration) + state.increment_current_attempt() + + +class ServerErrorRetryHandler(RetryHandler): + """RetryHandler that does retries for server errors.""" + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + super().__init__(max_retry_count, interval_calculator) + + def _can_retry( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + return response is not None and response.status_code in [500, 503] diff --git a/slack_sdk/http_retry/builtin_interval_calculators.py b/slack_sdk/http_retry/builtin_interval_calculators.py new file mode 100644 index 000000000..6354171f5 --- /dev/null +++ b/slack_sdk/http_retry/builtin_interval_calculators.py @@ -0,0 +1,44 @@ +from typing import Optional +from .jitter import Jitter, RandomJitter +from .interval_calculator import RetryIntervalCalculator + + +class FixedValueRetryIntervalCalculator(RetryIntervalCalculator): + """Retry interval calculator that uses a fixed value.""" + + fixed_interval: float + + def __init__(self, fixed_internal: float = 0.5): + """Retry interval calculator that uses a fixed value. + + Args: + fixed_internal: The fixed interval seconds + """ + self.fixed_interval = fixed_internal + + def calculate_sleep_duration(self, current_attempt: int) -> float: + return self.fixed_interval + + +class BackoffRetryIntervalCalculator(RetryIntervalCalculator): + """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter + see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ + """ + + backoff_factor: float + jitter: Jitter + + def __init__(self, backoff_factor: float = 0.5, jitter: Optional[Jitter] = None): + """Retry interval calculator that calculates in the manner of Exponential Backoff And Jitter + + Args: + backoff_factor: The factor for the backoff interval calculation + jitter: The jitter logic implementation + """ + self.backoff_factor = backoff_factor + self.jitter = jitter if jitter is not None else RandomJitter() + + def calculate_sleep_duration(self, current_attempt: int) -> float: + interval = self.backoff_factor * (2 ** (current_attempt)) + sleep_duration = self.jitter.recalculate(interval) + return sleep_duration diff --git a/slack_sdk/http_retry/handler.py b/slack_sdk/http_retry/handler.py new file mode 100644 index 000000000..7c8aa46bd --- /dev/null +++ b/slack_sdk/http_retry/handler.py @@ -0,0 +1,80 @@ +"""RetryHandler interface. +You can pass an array of handlers to customize retry logics in supported API clients. +""" + +import time +from typing import Optional + +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.builtin_interval_calculators import ( + BackoffRetryIntervalCalculator, +) + +default_interval_calculator = BackoffRetryIntervalCalculator() + + +# Note that you cannot add aiohttp to this class as the external dependency is optional +class RetryHandler: + """RetryHandler interface. + You can pass an array of handlers to customize retry logics in supported API clients. + """ + + max_retry_count: int + interval_calculator: RetryIntervalCalculator + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + """RetryHandler interface. + + Args: + max_retry_count: The maximum times to do retries + interval_calculator: Pass an interval calculator for customizing the logic + """ + self.max_retry_count = max_retry_count + self.interval_calculator = interval_calculator + + def can_retry( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + if state.current_attempt >= self.max_retry_count: + return False + return self._can_retry( + state=state, + request=request, + response=response, + error=error, + ) + + def _can_retry( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> bool: + raise NotImplementedError() + + def prepare_for_next_attempt( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse] = None, + error: Optional[Exception] = None, + ) -> None: + state.next_attempt_requested = True + duration = self.interval_calculator.calculate_sleep_duration(state.current_attempt) + time.sleep(duration) + state.increment_current_attempt() diff --git a/slack_sdk/http_retry/interval_calculator.py b/slack_sdk/http_retry/interval_calculator.py new file mode 100644 index 000000000..3911dd338 --- /dev/null +++ b/slack_sdk/http_retry/interval_calculator.py @@ -0,0 +1,12 @@ +class RetryIntervalCalculator: + """Retry interval calculator interface.""" + + def calculate_sleep_duration(self, current_attempt: int) -> float: + """Calculates an interval duration in seconds. + + Args: + current_attempt: the number of the current attempt (zero-origin; 0 means no retries are done so far) + Returns: + calculated interval duration in seconds + """ + raise NotImplementedError() diff --git a/slack_sdk/http_retry/jitter.py b/slack_sdk/http_retry/jitter.py new file mode 100644 index 000000000..852eaac60 --- /dev/null +++ b/slack_sdk/http_retry/jitter.py @@ -0,0 +1,24 @@ +import random + + +class Jitter: + """Jitter interface""" + + def recalculate(self, duration: float) -> float: + """Recalculate the given duration. + see also: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ + + Args: + duration: the duration in seconds + + Returns: + A new duration that the jitter amount is added + """ + raise NotImplementedError() + + +class RandomJitter(Jitter): + """Random jitter implementation""" + + def recalculate(self, duration: float) -> float: + return duration + random.random() diff --git a/slack_sdk/http_retry/request.py b/slack_sdk/http_retry/request.py new file mode 100644 index 000000000..420c7181a --- /dev/null +++ b/slack_sdk/http_retry/request.py @@ -0,0 +1,36 @@ +from typing import Dict, Optional, List, Union, Any +from urllib.request import Request + + +class HttpRequest: + """HTTP request representation""" + + method: str + url: str + headers: Dict[str, Union[str, List[str]]] + body_params: Optional[Dict[str, Any]] + data: Optional[bytes] + + def __init__( + self, + *, + method: str, + url: str, + headers: Dict[str, Union[str, List[str]]], + body_params: Optional[Dict[str, Any]] = None, + data: Optional[bytes] = None, + ): + self.method = method + self.url = url + self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()} + self.body_params = body_params + self.data = data + + @classmethod + def from_urllib_http_request(cls, req: Request) -> "HttpRequest": + return HttpRequest( + method=req.method, # type: ignore[arg-type] + url=req.full_url, + headers={k: v if isinstance(v, list) else [v] for k, v in req.headers.items()}, + data=req.data, # type: ignore[arg-type] + ) diff --git a/slack_sdk/http_retry/response.py b/slack_sdk/http_retry/response.py new file mode 100644 index 000000000..cb3ca6cef --- /dev/null +++ b/slack_sdk/http_retry/response.py @@ -0,0 +1,23 @@ +from typing import Dict, Optional, List, Union, Any + + +class HttpResponse: + """HTTP response representation""" + + status_code: int + headers: Dict[str, Union[List[str], str]] + body: Optional[Dict[str, Any]] + data: Optional[bytes] + + def __init__( + self, + *, + status_code: Union[int, str], + headers: Dict[str, Union[str, List[str]]], + body: Optional[Dict[str, Any]] = None, + data: Optional[bytes] = None, + ): + self.status_code = int(status_code) + self.headers = {k: v if isinstance(v, list) else [v] for k, v in headers.items()} + self.body = body + self.data = data diff --git a/slack_sdk/http_retry/state.py b/slack_sdk/http_retry/state.py new file mode 100644 index 000000000..4217eb571 --- /dev/null +++ b/slack_sdk/http_retry/state.py @@ -0,0 +1,21 @@ +from typing import Optional, Any, Dict + + +class RetryState: + next_attempt_requested: bool + current_attempt: int # zero-origin + custom_values: Optional[Dict[str, Any]] + + def __init__( + self, + *, + current_attempt: int = 0, + custom_values: Optional[Dict[str, Any]] = None, + ): + self.next_attempt_requested = False + self.current_attempt = current_attempt + self.custom_values = custom_values + + def increment_current_attempt(self) -> int: + self.current_attempt += 1 + return self.current_attempt diff --git a/slack_sdk/models/__init__.py b/slack_sdk/models/__init__.py index 06698cc42..25ecfe998 100644 --- a/slack_sdk/models/__init__.py +++ b/slack_sdk/models/__init__.py @@ -1,16 +1,18 @@ +"""Classes for constructing Slack-specific data structure""" + import logging from typing import Union, Dict, Any, Sequence, List -from .basic_objects import BaseObject # noqa -from .basic_objects import EnumValidator # noqa -from .basic_objects import JsonObject # noqa -from .basic_objects import JsonValidator # noqa +from .basic_objects import BaseObject +from .basic_objects import EnumValidator +from .basic_objects import JsonObject +from .basic_objects import JsonValidator # NOTE: used only for legacy components - don't use this for Block Kit def extract_json( item_or_items: Union[JsonObject, Sequence[JsonObject]], *format_args -) -> Union[Dict[Any, Any], List[Dict[Any, Any]]]: +) -> Union[Dict[Any, Any], List[Dict[Any, Any]], Sequence[JsonObject]]: """ Given a sequence (or single item), attempt to call the to_dict() method on each item and return a plain list. If item is not the expected type, return it @@ -24,14 +26,10 @@ def extract_json( try: return [ elem.to_dict(*format_args) if isinstance(elem, JsonObject) else elem - for elem in item_or_items + for elem in item_or_items # type: ignore[union-attr] ] except TypeError: # not iterable, so try returning it as a single item - return ( - item_or_items.to_dict(*format_args) - if isinstance(item_or_items, JsonObject) - else item_or_items - ) + return item_or_items.to_dict(*format_args) if isinstance(item_or_items, JsonObject) else item_or_items def show_unknown_key_warning(name: Union[str, object], others: dict): @@ -45,5 +43,15 @@ def show_unknown_key_warning(name: Union[str, object], others: dict): logger.debug( f"!!! {name}'s constructor args ({keys}) were ignored." f"If they should be supported by this library, report this issue to the project :bow: " - f"https://github.com/slackapi/python-slackclient/issues" + f"https://github.com/slackapi/python-slack-sdk/issues" ) + + +__all__ = [ + "BaseObject", + "EnumValidator", + "JsonObject", + "JsonValidator", + "extract_json", + "show_unknown_key_warning", +] diff --git a/slack_sdk/models/attachments/__init__.py b/slack_sdk/models/attachments/__init__.py index 5ba0c273a..85695cfb1 100644 --- a/slack_sdk/models/attachments/__init__.py +++ b/slack_sdk/models/attachments/__init__.py @@ -19,8 +19,8 @@ class Action(JsonObject): """Action in attachments - https://api.slack.com/messaging/composing/layouts#attachments - https://api.slack.com/legacy/interactive-message-field-guide#message_action_fields + https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts + https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#message_action_fields """ attributes = {"name", "text", "url"} @@ -42,7 +42,7 @@ def __init__( def name_or_url_present(self): return self.name is not None or self.url is not None - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> dict: json = super().to_dict() json["type"] = self.subtype return json @@ -66,7 +66,7 @@ def __init__( ): """Simple button for use inside attachments - https://api.slack.com/legacy/message-buttons + https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/ Args: name: Name this specific action. The name will be returned to your @@ -108,7 +108,7 @@ class ActionLinkButton(Action): def __init__(self, *, text: str, url: str): """A simple interactive button that just opens a URL - https://api.slack.com/messaging/composing/layouts#attachments + https://docs.slack.dev/messaging/formatting-message-text/#rich-layouts Args: text: text to display on the button, eg 'Click Me!" @@ -127,9 +127,7 @@ class AbstractActionSelector(Action, metaclass=ABCMeta): def data_source(self) -> str: pass - def __init__( - self, *, name: str, text: str, selected_option: Optional[Option] = None - ): + def __init__(self, *, name: str, text: str, selected_option: Optional[Option] = None): super().__init__(text=text, name=name, subtype="select") self.selected_option = selected_option @@ -152,7 +150,7 @@ class ActionUserSelector(AbstractActionSelector): def __init__(self, name: str, text: str, selected_user: Optional[Option] = None): """Automatically populate the selector with a list of users in the workspace. - https://api.slack.com/legacy/message-menus#allow_users_to_select_from_a_list_of_members + https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_team_members Args: name: Name this specific action. The name will be returned to your @@ -174,7 +172,7 @@ def __init__(self, name: str, text: str, selected_channel: Optional[Option] = No Automatically populate the selector with a list of public channels in the workspace. - https://api.slack.com/legacy/message-menus#let_users_choose_one_of_their_workspace_s_channels + https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_channels Args: name: Name this specific action. The name will be returned to your @@ -191,14 +189,12 @@ def __init__(self, name: str, text: str, selected_channel: Optional[Option] = No class ActionConversationSelector(AbstractActionSelector): data_source = "conversations" - def __init__( - self, name: str, text: str, selected_conversation: Optional[Option] = None - ): + def __init__(self, name: str, text: str, selected_conversation: Optional[Option] = None): """ Automatically populate the selector with a list of conversations they have in the workspace. - https://api.slack.com/legacy/message-menus#let_users_choose_one_of_their_conversations + https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_conversations Args: name: Name this specific action. The name will be returned to your @@ -216,7 +212,7 @@ class ActionExternalSelector(AbstractActionSelector): data_source = "external" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"min_query_length"}) def __init__( @@ -230,7 +226,7 @@ def __init__( """ Populate a message select menu from your own application dynamically. - https://api.slack.com/legacy/message-menus#populate_message_menus_dynamically + https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/#menu_dynamic Args: name: Name this specific action. The name will be returned to your @@ -270,6 +266,7 @@ class Attachment(JsonObject): "author_icon", "author_link", "author_name", + "author_subname", "color", "fallback", "fields", @@ -284,8 +281,7 @@ class Attachment(JsonObject): "ts", } - fields: List[AttachmentField] - actions: List[Action] + fields: Sequence[AttachmentField] MarkdownFields = {"fields", "pretext", "text"} @@ -303,6 +299,7 @@ def __init__( title_link: Optional[str] = None, pretext: Optional[str] = None, author_name: Optional[str] = None, + author_subname: Optional[str] = None, author_link: Optional[str] = None, author_icon: Optional[str] = None, image_url: Optional[str] = None, @@ -315,7 +312,7 @@ def __init__( A supplemental object that will display after the rest of the message. Considered legacy - recommended replacement is to use message blocks instead. - https://api.slack.com/reference/messaging/attachments#fields + https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields Args: text: The main body text of the attachment. It can be formatted as @@ -329,8 +326,7 @@ def __init__( table-like way. For best results, include no more than 2-3 field objects. color: Changes the color of the border on the left side of this attachment - from the default gray. Can either be one of "good" (green), "warning" - (yellow), "danger" (red), or any hex color code (eg. #439FE0) + from the default gray. Can be any hex color code (eg. #439FE0) markdown_in: An array of field names that should be formatted by markdown syntax - allowed values: "pretext", "text", "fields" title: Large title text near the top of the attachment. @@ -339,6 +335,7 @@ def __init__( be formatted as plain text, or with markdown by including it in the markdown_in parameter. author_name: Small text used to display the author's name. + author_subname: Small text used to display the author's sub name. author_link: A valid URL that will hyperlink the author_name text. Will only work if author_name is present. author_icon: A valid URL that displays a small 16px by 16px image to @@ -377,6 +374,7 @@ def __init__( self.title_link = title_link self.color = color self.author_name = author_name + self.author_subname = author_subname self.author_link = author_link self.author_icon = author_icon self.image_url = image_url @@ -388,42 +386,38 @@ def __init__( self.markdown_in = markdown_in or [] @JsonValidator(f"footer attribute cannot exceed {footer_max_length} characters") - def footer_length(self): + def footer_length(self) -> bool: return self.footer is None or len(self.footer) <= self.footer_max_length @JsonValidator("ts attribute cannot be present if footer attribute is absent") - def ts_without_footer(self): + def ts_without_footer(self) -> bool: return self.ts is None or self.footer is not None @EnumValidator("markdown_in", MarkdownFields) def markdown_in_valid(self): - return not self.markdown_in or all( - e in self.MarkdownFields for e in self.markdown_in - ) + return not self.markdown_in or all(e in self.MarkdownFields for e in self.markdown_in) - @JsonValidator( - "color attribute must be 'good', 'warning', 'danger', or a hex color code" - ) - def color_valid(self): + @JsonValidator("color attribute must be 'good', 'warning', 'danger', or a hex color code") + def color_valid(self) -> bool: return ( self.color is None or self.color in SeededColors - or re.match("^#(?:[0-9A-F]{2}){3}$", self.color, re.IGNORECASE) + or re.match("^#(?:[0-9A-F]{2}){3}$", self.color, re.IGNORECASE) is not None ) @JsonValidator("image_url attribute cannot be present if thumb_url is populated") - def image_url_and_thumb_url_populated(self): + def image_url_and_thumb_url_populated(self) -> bool: return self.image_url is None or self.thumb_url is None @JsonValidator("name must be present if link is present") - def author_link_without_author_name(self): + def author_link_without_author_name(self) -> bool: return self.author_link is None or self.author_name is not None @JsonValidator("icon must be present if link is present") - def author_link_without_author_icon(self): + def author_link_without_author_icon(self) -> bool: return self.author_link is None or self.author_icon is not None - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> dict: json = super().to_dict() if self.fields is not None: json["fields"] = extract_json(self.fields) @@ -433,28 +427,37 @@ def to_dict(self) -> dict: # skipcq: PYL-W0221 class BlockAttachment(Attachment): - attributes = {"color"} blocks: List[Block] - def __init__(self, *, blocks: Sequence[Block], color: Optional[str] = None): + @property + def attributes(self): + return super().attributes.union({"blocks", "color"}) + + def __init__( + self, + *, + blocks: Sequence[Block], + color: Optional[str] = None, + fallback: Optional[str] = None, + ): """ - A bridge between legacy attachments and blockkit formatting - pass a list of + A bridge between legacy attachments and Block Kit formatting - pass a list of Block objects directly to this attachment. - https://api.slack.com/reference/messaging/attachments#fields + https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields Args: blocks: a sequence of Block objects - color: Changes the color of the border on the left side of this attachment from the default gray. Can either be one of "good" (green), "warning" (yellow), "danger" (red), or any hex color code (eg. #439FE0) + fallback: fallback text """ - super().__init__(text="", color=color) + super().__init__(text="", fallback=fallback, color=color) self.blocks = list(blocks) @JsonValidator("fields attribute cannot be populated on BlockAttachment") - def fields_attribute_absent(self): + def fields_attribute_absent(self) -> bool: return not self.fields def to_dict(self) -> dict: @@ -466,7 +469,7 @@ def to_dict(self) -> dict: class InteractiveAttachment(Attachment): @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"callback_id"}) actions_max_length = 5 @@ -485,6 +488,7 @@ def __init__( title_link: Optional[str] = None, pretext: Optional[str] = None, author_name: Optional[str] = None, + author_subname: Optional[str] = None, author_link: Optional[str] = None, author_icon: Optional[str] = None, image_url: Optional[str] = None, @@ -497,8 +501,8 @@ def __init__( An Attachment, but designed to contain interactive Actions Considered legacy - recommended replacement is to use message blocks instead. - https://api.slack.com/legacy/interactive-message-field-guide#attachment_fields - https://api.slack.com/reference/messaging/attachments#fields + https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#attachment_fields + https://docs.slack.dev/legacy/legacy-messaging/legacy-secondary-message-attachments#fields Args: actions: A collection of Action objects to include in the attachment. @@ -526,6 +530,7 @@ def __init__( be formatted as plain text, or with markdown by including it in the markdown_in parameter. author_name: Small text used to display the author's name. + author_subname: Small text used to display the author's sub name. author_link: A valid URL that will hyperlink the author_name text. Will only work if author_name is present. author_icon: A valid URL that displays a small 16px by 16px image to @@ -566,6 +571,7 @@ def __init__( title_link=title_link, color=color, author_name=author_name, + author_subname=author_subname, author_link=author_link, author_icon=author_icon, image_url=image_url, @@ -579,7 +585,7 @@ def __init__( self.actions = actions or [] @JsonValidator(f"actions attribute cannot exceed {actions_max_length} elements") - def actions_length(self): + def actions_length(self) -> bool: return len(self.actions) <= self.actions_max_length def to_dict(self) -> dict: diff --git a/slack_sdk/models/basic_objects.py b/slack_sdk/models/basic_objects.py index b9cbfbfbf..4feefe3f6 100644 --- a/slack_sdk/models/basic_objects.py +++ b/slack_sdk/models/basic_objects.py @@ -6,11 +6,24 @@ class BaseObject: + """The base class for all model objects in this module""" + def __str__(self): return f"" +# Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions. +EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST = [ + {"type": "rich_text_section", "property": "elements"}, + {"type": "rich_text_list", "property": "elements"}, + {"type": "rich_text_preformatted", "property": "elements"}, + {"type": "rich_text_quote", "property": "elements"}, +] + + class JsonObject(BaseObject, metaclass=ABCMeta): + """The base class for JSON serializable class objects""" + @property @abstractmethod def attributes(self) -> Set[str]: @@ -27,38 +40,45 @@ def validate_json(self) -> None: if callable(method) and hasattr(method, "validator"): method() + def get_object_attribute(self, key: str): + return getattr(self, key, None) + def get_non_null_attributes(self) -> dict: """ Construct a dictionary out of non-null keys (from attributes property) present on this object """ - def to_dict_compatible( - value: Union[dict, list, object] - ) -> Union[dict, list, Any]: - if isinstance(value, list): # skipcq: PYL-R1705 + def to_dict_compatible(value: Union[dict, list, object, tuple]) -> Union[dict, list, Any]: + if isinstance(value, (list, tuple)): return [to_dict_compatible(v) for v in value] else: to_dict = getattr(value, "to_dict", None) - if to_dict and callable(to_dict): # skipcq: PYL-R1705 - return { - k: to_dict_compatible(v) for k, v in value.to_dict().items() # type: ignore - } + if to_dict and callable(to_dict): + return {k: to_dict_compatible(v) for k, v in value.to_dict().items()} # type: ignore[attr-defined] else: return value def is_not_empty(self, key: str) -> bool: - value = getattr(self, key, None) + value = self.get_object_attribute(key) if value is None: return False + + # Usually, Block Kit components do not allow an empty array for a property value, but there are some exceptions. + # The following code deals with these exceptions: + type_value = getattr(self, "type", None) + for empty_allowed in EMPTY_ALLOWED_TYPE_AND_PROPERTY_LIST: + if type_value == empty_allowed["type"] and key == empty_allowed["property"]: + return True + has_len = getattr(value, "__len__", None) is not None - if has_len: # skipcq: PYL-R1705 + if has_len: return len(value) > 0 else: return value is not None return { - key: to_dict_compatible(getattr(self, key, None)) + key: to_dict_compatible(value=self.get_object_attribute(key)) for key in sorted(self.attributes) if is_not_empty(self, key) } @@ -78,11 +98,16 @@ def to_dict(self, *args) -> dict: def __repr__(self): dict_value = self.get_non_null_attributes() - if dict_value: # skipcq: PYL-R1705 + if dict_value: return f"" else: return self.__str__() + def __eq__(self, other: Any) -> bool: + if not isinstance(other, JsonObject): + return False + return self.to_dict() == other.to_dict() + class JsonValidator: def __init__(self, message: str): @@ -101,13 +126,10 @@ def wrapped_f(*args, **kwargs): if not func(*args, **kwargs): raise SlackObjectFormationError(self.message) - wrapped_f.validator = True + wrapped_f.validator = True # type: ignore[attr-defined] return wrapped_f class EnumValidator(JsonValidator): def __init__(self, attribute: str, enum: Iterable[str]): - super().__init__( - f"{attribute} attribute must be one of the following values: " - f"{', '.join(enum)}" - ) + super().__init__(f"{attribute} attribute must be one of the following values: " f"{', '.join(enum)}") diff --git a/slack_sdk/models/blocks/__init__.py b/slack_sdk/models/blocks/__init__.py index df1ed6755..d2776a9dc 100644 --- a/slack_sdk/models/blocks/__init__.py +++ b/slack_sdk/models/blocks/__init__.py @@ -1,41 +1,142 @@ -from .basic_components import ButtonStyles # noqa -from .basic_components import ConfirmObject # noqa -from .basic_components import DynamicSelectElementTypes # noqa -from .basic_components import MarkdownTextObject # noqa -from .basic_components import Option # noqa -from .basic_components import OptionGroup # noqa -from .basic_components import PlainTextObject # noqa -from .basic_components import TextObject # noqa -from .block_elements import BlockElement # noqa -from .block_elements import ButtonElement # noqa -from .block_elements import ChannelMultiSelectElement # noqa -from .block_elements import ChannelSelectElement # noqa -from .block_elements import CheckboxesElement # noqa -from .block_elements import ConversationFilter # noqa -from .block_elements import ConversationMultiSelectElement # noqa -from .block_elements import ConversationSelectElement # noqa -from .block_elements import DatePickerElement # noqa -from .block_elements import ExternalDataMultiSelectElement # noqa -from .block_elements import ExternalDataSelectElement # noqa -from .block_elements import ImageElement # noqa -from .block_elements import InputInteractiveElement # noqa -from .block_elements import InteractiveElement # noqa -from .block_elements import LinkButtonElement # noqa -from .block_elements import OverflowMenuElement # noqa -from .block_elements import PlainTextInputElement # noqa -from .block_elements import RadioButtonsElement # noqa -from .block_elements import SelectElement # noqa -from .block_elements import StaticMultiSelectElement # noqa -from .block_elements import StaticSelectElement # noqa -from .block_elements import UserMultiSelectElement # noqa -from .block_elements import UserSelectElement # noqa -from .blocks import ActionsBlock # noqa -from .blocks import Block # noqa -from .blocks import CallBlock # noqa -from .blocks import ContextBlock # noqa -from .blocks import DividerBlock # noqa -from .blocks import FileBlock # noqa -from .blocks import HeaderBlock # noqa -from .blocks import ImageBlock # noqa -from .blocks import InputBlock # noqa -from .blocks import SectionBlock # noqa +"""Block Kit data model objects + +To learn more about Block Kit, please check the following resources and tools: + +* https://docs.slack.dev/block-kit/ +* https://docs.slack.dev/reference/block-kit/blocks +* https://app.slack.com/block-kit-builder +""" + +from .basic_components import ( + ButtonStyles, + ConfirmObject, + DynamicSelectElementTypes, + FeedbackButtonObject, + MarkdownTextObject, + Option, + OptionGroup, + PlainTextObject, + RawTextObject, + TextObject, +) +from .block_elements import ( + BlockElement, + ButtonElement, + ChannelMultiSelectElement, + ChannelSelectElement, + CheckboxesElement, + ConversationFilter, + ConversationMultiSelectElement, + ConversationSelectElement, + DatePickerElement, + DateTimePickerElement, + EmailInputElement, + ExternalDataMultiSelectElement, + ExternalDataSelectElement, + FeedbackButtonsElement, + IconButtonElement, + ImageElement, + InputInteractiveElement, + InteractiveElement, + LinkButtonElement, + NumberInputElement, + OverflowMenuElement, + PlainTextInputElement, + RadioButtonsElement, + RichTextElement, + RichTextElementParts, + RichTextInputElement, + RichTextListElement, + RichTextPreformattedElement, + RichTextQuoteElement, + RichTextSectionElement, + SelectElement, + StaticMultiSelectElement, + StaticSelectElement, + TimePickerElement, + UrlInputElement, + UserMultiSelectElement, + UserSelectElement, +) +from .blocks import ( + ActionsBlock, + Block, + CallBlock, + ContextActionsBlock, + ContextBlock, + DividerBlock, + FileBlock, + HeaderBlock, + ImageBlock, + InputBlock, + MarkdownBlock, + RichTextBlock, + SectionBlock, + TableBlock, + VideoBlock, +) + +__all__ = [ + "ButtonStyles", + "ConfirmObject", + "DynamicSelectElementTypes", + "FeedbackButtonObject", + "MarkdownTextObject", + "Option", + "OptionGroup", + "PlainTextObject", + "RawTextObject", + "TextObject", + "BlockElement", + "ButtonElement", + "ChannelMultiSelectElement", + "ChannelSelectElement", + "CheckboxesElement", + "ConversationFilter", + "ConversationMultiSelectElement", + "ConversationSelectElement", + "DatePickerElement", + "TimePickerElement", + "DateTimePickerElement", + "ExternalDataMultiSelectElement", + "ExternalDataSelectElement", + "FeedbackButtonsElement", + "IconButtonElement", + "ImageElement", + "InputInteractiveElement", + "InteractiveElement", + "LinkButtonElement", + "OverflowMenuElement", + "RichTextInputElement", + "PlainTextInputElement", + "EmailInputElement", + "UrlInputElement", + "NumberInputElement", + "RadioButtonsElement", + "SelectElement", + "StaticMultiSelectElement", + "StaticSelectElement", + "UserMultiSelectElement", + "UserSelectElement", + "RichTextElement", + "RichTextElementParts", + "RichTextListElement", + "RichTextPreformattedElement", + "RichTextQuoteElement", + "RichTextSectionElement", + "ActionsBlock", + "Block", + "CallBlock", + "ContextActionsBlock", + "ContextBlock", + "DividerBlock", + "FileBlock", + "HeaderBlock", + "ImageBlock", + "InputBlock", + "MarkdownBlock", + "SectionBlock", + "TableBlock", + "VideoBlock", + "RichTextBlock", +] diff --git a/slack_sdk/models/blocks/basic_components.py b/slack_sdk/models/blocks/basic_components.py index b99cb579d..b6e71683a 100644 --- a/slack_sdk/models/blocks/basic_components.py +++ b/slack_sdk/models/blocks/basic_components.py @@ -1,13 +1,10 @@ import copy import logging import warnings -from typing import List, Optional, Set, Union, Sequence +from typing import Any, Dict, List, Optional, Sequence, Set, Union from slack_sdk.models import show_unknown_key_warning -from slack_sdk.models.basic_objects import ( - JsonObject, - JsonValidator, -) +from slack_sdk.models.basic_objects import JsonObject, JsonValidator from slack_sdk.models.messages import Link ButtonStyles = {"danger", "primary"} @@ -15,10 +12,12 @@ class TextObject(JsonObject): + """The interface for text objects (types: plain_text, mrkdwn)""" + attributes = {"text", "type", "emoji"} logger = logging.getLogger(__name__) - def _subtype_warning(self): # skipcq: PYL-R0201 + def _subtype_warning(self): warnings.warn( "subtype is deprecated since slackclient 2.6.0, use type instead", DeprecationWarning, @@ -30,34 +29,34 @@ def subtype(self) -> Optional[str]: @classmethod def parse( - cls, text: Union[str, dict, "TextObject"], default_type: str = "mrkdwn" + cls, + text: Union[str, Dict[str, Any], "TextObject"], + default_type: str = "mrkdwn", ) -> Optional["TextObject"]: - if not text: # skipcq: PYL-R1705 + if not text: return None elif isinstance(text, str): - if default_type == PlainTextObject.type: # skipcq: PYL-R1705 + if default_type == PlainTextObject.type: return PlainTextObject.from_str(text) else: return MarkdownTextObject.from_str(text) elif isinstance(text, dict): d = copy.copy(text) t = d.pop("type") - if t == PlainTextObject.type: # skipcq: PYL-R1705 + if t == PlainTextObject.type: return PlainTextObject(**d) else: return MarkdownTextObject(**d) elif isinstance(text, TextObject): return text else: - cls.logger.warning( - f"Unknown type ({type(text)}) detected when parsing a TextObject" - ) + cls.logger.warning(f"Unknown type ({type(text)}) detected when parsing a TextObject") return None def __init__( self, text: str, - type: Optional[str] = None, # skipcq: PYL-W0622 + type: Optional[str] = None, subtype: Optional[str] = None, emoji: Optional[bool] = None, **kwargs, @@ -72,16 +71,24 @@ def __init__( class PlainTextObject(TextObject): + """plain_text typed text object""" + type = "plain_text" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"emoji"}) def __init__(self, *, text: str, emoji: Optional[bool] = None): """A plain text object, meaning markdown characters will not be parsed as formatting information. - https://api.slack.com/reference/block-kit/composition-objects#text + https://docs.slack.dev/reference/block-kit/composition-objects/text-object + + Args: + text (required): The text for the block. This field accepts any of the standard text formatting markup + when type is mrkdwn. + emoji: Indicates whether emojis in a text field should be escaped into the colon emoji format. + This field is only usable when type is plain_text. """ super().__init__(text=text, type=self.type) self.emoji = emoji @@ -91,22 +98,32 @@ def from_str(text: str) -> "PlainTextObject": return PlainTextObject(text=text, emoji=True) @staticmethod - def direct_from_string(text: str) -> dict: + def direct_from_string(text: str) -> Dict[str, Any]: """Transforms a string into the required object shape to act as a PlainTextObject""" return PlainTextObject.from_str(text).to_dict() class MarkdownTextObject(TextObject): + """mrkdwn typed text object""" + type = "mrkdwn" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"verbatim"}) def __init__(self, *, text: str, verbatim: Optional[bool] = None): """A Markdown text object, meaning markdown characters will be parsed as formatting information. - https://api.slack.com/reference/block-kit/composition-objects#text + https://docs.slack.dev/reference/block-kit/composition-objects/text-object + + Args: + text (required): The text for the block. This field accepts any of the standard text formatting markup + when type is mrkdwn. + verbatim: When set to false (as is default) URLs will be auto-converted into links, + conversation names will be link-ified, and certain mentions will be automatically parsed. + Using a value of true will skip any preprocessing of this nature, + although you can still include manual parsing strings. This field is only usable when type is mrkdwn. """ super().__init__(text=text, type=self.type) self.verbatim = verbatim @@ -117,7 +134,7 @@ def from_str(text: str) -> "MarkdownTextObject": return MarkdownTextObject(text=text) @staticmethod - def direct_from_string(text: str) -> dict: + def direct_from_string(text: str) -> Dict[str, Any]: """Transforms a string into the required object shape to act as a MarkdownTextObject""" return MarkdownTextObject.from_str(text).to_dict() @@ -132,7 +149,7 @@ def from_link(link: Link, title: str = "") -> "MarkdownTextObject": return MarkdownTextObject(text=f"{link}{title}") @staticmethod - def direct_from_link(link: Link, title: str = "") -> dict: + def direct_from_link(link: Link, title: str = "") -> Dict[str, Any]: """ Transform a Link object directly into the required object shape to act as a MarkdownTextObject @@ -140,27 +157,61 @@ def direct_from_link(link: Link, title: str = "") -> dict: return MarkdownTextObject.from_link(link, title).to_dict() +class RawTextObject(TextObject): + """raw_text typed text object""" + + type = "raw_text" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return {"text", "type"} + + def __init__(self, *, text: str): + """A raw text object used in table block cells. + https://docs.slack.dev/reference/block-kit/composition-objects/text-object/ + https://docs.slack.dev/reference/block-kit/blocks/table-block + + Args: + text (required): The text content for the table block cell. + """ + super().__init__(text=text, type=self.type) + + @staticmethod + def from_str(text: str) -> "RawTextObject": + """Transforms a string into a RawTextObject""" + return RawTextObject(text=text) + + @staticmethod + def direct_from_string(text: str) -> Dict[str, Any]: + """Transforms a string into the required object shape to act as a RawTextObject""" + return RawTextObject.from_str(text).to_dict() + + @JsonValidator("text attribute must have at least 1 character") + def _validate_text_min_length(self): + return len(self.text) >= 1 + + class Option(JsonObject): - """Option object used in dialogs, legacy message actions, and blocks - JSON must be retrieved with an explicit option_type - the Slack API has + """Option object used in dialogs, legacy message actions (interactivity in attachments), + and blocks. JSON must be retrieved with an explicit option_type - the Slack API has different required formats in different situations """ - attributes = {} # no attributes because to_dict has unique implementations + attributes: Set[str] = set() logger = logging.getLogger(__name__) label_max_length = 75 - value_max_length = 75 + value_max_length = 150 def __init__( self, *, value: str, label: Optional[str] = None, - text: Optional[Union[str, dict, TextObject]] = None, # Block Kit - description: Optional[str] = None, + text: Optional[Union[str, Dict[str, Any], TextObject]] = None, # Block Kit + description: Optional[Union[str, Dict[str, Any], TextObject]] = None, url: Optional[str] = None, - **others: dict, + **others: Dict[str, Any], ): """ An object that represents a single selectable item in a block element ( @@ -168,37 +219,56 @@ def __init__( (StaticDialogSelectElement) Blocks: - https://api.slack.com/reference/block-kit/composition-objects#option + https://docs.slack.dev/reference/block-kit/composition-objects/option-object Dialogs: - https://api.slack.com/dialogs#select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#select_elements Legacy interactive attachments: - https://api.slack.com/legacy/interactive-message-field-guide#option_fields + https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_fields Args: label: A short, user-facing string to label this option to users. Cannot exceed 75 characters. value: A short string that identifies this particular option to your application. It will be part of the payload when this option is selected - . Cannot exceed 75 characters. + . Cannot exceed 150 characters. description: A user-facing string that provides more details about this option. Only supported in legacy message actions, not in blocks or dialogs. """ if text: - self._text: Optional[TextObject] = TextObject.parse(text) + # For better compatibility with Block Kit ("mrkdwn" does not work for it), + # we've changed the default text object type to plain_text since version 3.10.0 + self._text: Optional[TextObject] = TextObject.parse( + text=text, # "text" here can be either a str or a TextObject + default_type=PlainTextObject.type, + ) self._label: Optional[str] = None else: - self._text: Optional[TextObject] = None - self._label: Optional[str] = label + self._text = None + self._label = label # for backward-compatibility with version 2.0-2.5, the following fields return str values self.text: Optional[str] = self._text.text if self._text else None self.label: Optional[str] = self._label self.value: str = value - self.description: Optional[str] = description + + # for backward-compatibility with version 2.0-2.5, the following fields return str values + if isinstance(description, str): + self.description = description + self._block_description = PlainTextObject.from_str(description) + elif isinstance(description, dict): + self.description = description["text"] + self._block_description = TextObject.parse(description) # type: ignore[assignment] + elif isinstance(description, TextObject): + self.description = description.text + self._block_description = description # type: ignore[assignment] + else: + self.description = None # type: ignore[assignment] + self._block_description = None # type: ignore[assignment] + # A URL to load in the user's browser when the option is clicked. # The url attribute is only available in overflow menus. # Maximum length for this field is 3000 characters. @@ -208,25 +278,19 @@ def __init__( show_unknown_key_warning(self, others) @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") - def _validate_label_length(self): + def _validate_label_length(self) -> bool: return self._label is None or len(self._label) <= self.label_max_length @JsonValidator(f"text attribute cannot exceed {label_max_length} characters") - def _validate_text_length(self): - return ( - self._text is None - or self._text.text is None - or len(self._text.text) <= self.label_max_length - ) + def _validate_text_length(self) -> bool: + return self._text is None or self._text.text is None or len(self._text.text) <= self.label_max_length @JsonValidator(f"value attribute cannot exceed {value_max_length} characters") - def _validate_value_length(self): + def _validate_value_length(self) -> bool: return len(self.value) <= self.value_max_length @classmethod - def parse_all( - cls, options: Optional[Sequence[Union[dict, "Option"]]] - ) -> Optional[List["Option"]]: + def parse_all(cls, options: Optional[Sequence[Union[Dict[str, Any], "Option"]]]) -> Optional[List["Option"]]: if options is None: return None option_objects: List[Option] = [] @@ -240,28 +304,30 @@ def parse_all( cls.logger.warning(f"Unknown option object detected and skipped ({o})") return option_objects - def to_dict(self, option_type: str = "block") -> dict: # skipcq: PYL-W0221 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: """ Different parent classes must call this with a valid value from OptionTypes - either "dialog", "action", or "block", so that JSON is returned in the correct shape. """ self.validate_json() - if option_type == "dialog": # skipcq: PYL-R1705 + if option_type == "dialog": return {"label": self.label, "value": self.value} - elif option_type == "action": - json = {"text": self.label, "value": self.value} + elif option_type == "action" or option_type == "attachment": + # "action" can be confusing but it means a legacy message action in attachments + # we don't remove the type name for backward compatibility though + json: Dict[str, Any] = {"text": self.label, "value": self.value} if self.description is not None: json["description"] = self.description return json else: # if option_type == "block"; this should be the most common case - text: TextObject = self._text or PlainTextObject.from_str(self.label) - json: dict = { + text: TextObject = self._text or PlainTextObject.from_str(self.label) # type: ignore[arg-type] + json = { "text": text.to_dict(), "value": self.value, } - if self.description: - json["description"] = self.description + if self._block_description: + json["description"] = self._block_description.to_dict() if self.url: json["url"] = self.url return json @@ -278,7 +344,7 @@ class OptionGroup(JsonObject): different required formats in different situations """ - attributes = {} # no attributes because to_dict has unique implementations + attributes: Set[str] = set() label_max_length = 75 options_max_length = 100 logger = logging.getLogger(__name__) @@ -286,31 +352,29 @@ class OptionGroup(JsonObject): def __init__( self, *, - label: Optional[Union[str, dict, TextObject]] = None, - options: Sequence[Union[dict, Option]], - **others: dict, + label: Optional[Union[str, Dict[str, Any], TextObject]] = None, + options: Sequence[Union[Dict[str, Any], Option]], + **others: Dict[str, Any], ): """ Create a group of Option objects - pass in a label (that will be part of the UI) and a list of Option objects. Blocks: - https://api.slack.com/reference/block-kit/composition-objects#option-group + https://docs.slack.dev/reference/block-kit/composition-objects/option-group-object Dialogs: - https://api.slack.com/dialogs#select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#select_elements Legacy interactive attachments: - https://api.slack.com/legacy/interactive-message-field-guide#option_groups_to_place_within_message_menu_actions + https://docs.slack.dev/legacy/legacy-messaging/legacy-interactive-message-field-guide/#option_groups Args: label: Text to display at the top of this group of options. options: A list of no more than 100 Option objects. """ # noqa prevent flake8 blowing up on the long URL # default_type=PlainTextObject.type is for backward-compatibility - self._label: Optional[TextObject] = TextObject.parse( - label, default_type=PlainTextObject.type - ) + self._label: Optional[TextObject] = TextObject.parse(label, default_type=PlainTextObject.type) # type: ignore[arg-type] # noqa: E501 self.label: Optional[str] = self._label.text if self._label else None self.options = Option.parse_all(options) # compatible with version 2.5 show_unknown_key_warning(self, others) @@ -325,7 +389,7 @@ def _validate_options_length(self): @classmethod def parse_all( - cls, option_groups: Optional[Sequence[Union[dict, "OptionGroup"]]] + cls, option_groups: Optional[Sequence[Union[Dict[str, Any], "OptionGroup"]]] ) -> Optional[List["OptionGroup"]]: if option_groups is None: return None @@ -337,15 +401,13 @@ def parse_all( elif isinstance(o, OptionGroup): option_group_objects.append(o) else: - cls.logger.warning( - f"Unknown option group object detected and skipped ({o})" - ) + cls.logger.warning(f"Unknown option group object detected and skipped ({o})") return option_group_objects - def to_dict(self, option_type: str = "block") -> dict: # skipcq: PYL-W0221 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: self.validate_json() - dict_options = [o.to_dict(option_type) for o in self.options] - if option_type == "dialog": # skipcq: PYL-R1705 + dict_options = [o.to_dict(option_type) for o in self.options] # type: ignore[union-attr] + if option_type == "dialog": return { "label": self.label, "options": dict_options, @@ -356,7 +418,7 @@ def to_dict(self, option_type: str = "block") -> dict: # skipcq: PYL-W0221 "options": dict_options, } else: # if option_type == "block"; this should be the most common case - dict_label: dict = self._label.to_dict() + dict_label: Dict[str, Any] = self._label.to_dict() # type: ignore[union-attr] return { "label": dict_label, "options": dict_options, @@ -364,7 +426,7 @@ def to_dict(self, option_type: str = "block") -> dict: # skipcq: PYL-W0221 class ConfirmObject(JsonObject): - attributes = {} # no attributes because to_dict has unique implementations + attributes: Set[str] = set() title_max_length = 100 text_max_length = 300 @@ -372,9 +434,9 @@ class ConfirmObject(JsonObject): deny_max_length = 30 @classmethod - def parse(cls, confirm: Union["ConfirmObject", dict]): + def parse(cls, confirm: Union["ConfirmObject", Dict[str, Any]]): if confirm: - if isinstance(confirm, ConfirmObject): # skipcq: PYL-R1705 + if isinstance(confirm, ConfirmObject): return confirm elif isinstance(confirm, dict): return ConfirmObject(**confirm) @@ -386,17 +448,17 @@ def parse(cls, confirm: Union["ConfirmObject", dict]): def __init__( self, *, - title: Union[str, dict, PlainTextObject], - text: Union[str, dict, TextObject], - confirm: Union[str, dict, PlainTextObject] = "Yes", - deny: Union[str, dict, PlainTextObject] = "No", - style: str = None, + title: Union[str, Dict[str, Any], PlainTextObject], + text: Union[str, Dict[str, Any], TextObject], + confirm: Union[str, Dict[str, Any], PlainTextObject] = "Yes", + deny: Union[str, Dict[str, Any], PlainTextObject] = "No", + style: Optional[str] = None, ): """ An object that defines a dialog that provides a confirmation step to any interactive element. This dialog will ask the user to confirm their action by offering a confirm and deny button. - https://api.slack.com/reference/block-kit/composition-objects#confirm + https://docs.slack.dev/reference/block-kit/composition-objects/confirmation-dialog-object/ """ self._title = TextObject.parse(title, default_type=PlainTextObject.type) self._text = TextObject.parse(text, default_type=MarkdownTextObject.type) @@ -412,38 +474,32 @@ def __init__( self.style = self._style @JsonValidator(f"title attribute cannot exceed {title_max_length} characters") - def title_length(self): + def title_length(self) -> bool: return self._title is None or len(self._title.text) <= self.title_max_length @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") - def text_length(self): + def text_length(self) -> bool: return self._text is None or len(self._text.text) <= self.text_max_length @JsonValidator(f"confirm attribute cannot exceed {confirm_max_length} characters") - def confirm_length(self): - return ( - self._confirm is None or len(self._confirm.text) <= self.confirm_max_length - ) + def confirm_length(self) -> bool: + return self._confirm is None or len(self._confirm.text) <= self.confirm_max_length @JsonValidator(f"deny attribute cannot exceed {deny_max_length} characters") - def deny_length(self): + def deny_length(self) -> bool: return self._deny is None or len(self._deny.text) <= self.deny_max_length @JsonValidator('style for confirm must be either "primary" or "danger"') - def _validate_confirm_style(self): + def _validate_confirm_style(self) -> bool: return self._style is None or self._style in ["primary", "danger"] - def to_dict(self, option_type: str = "block") -> dict: # skipcq: PYL-W0221 - if option_type == "action": # skipcq: PYL-R1705 + def to_dict(self, option_type: str = "block") -> Dict[str, Any]: + if option_type == "action": # deliberately skipping JSON validators here - can't find documentation # on actual limits here - json = { - "ok_text": self._confirm.text - if self._confirm and self._confirm.text != "Yes" - else "Okay", - "dismiss_text": self._deny.text - if self._deny and self._deny.text != "No" - else "Cancel", + json: Dict[str, Union[str, dict]] = { + "ok_text": self._confirm.text if self._confirm and self._confirm.text != "Yes" else "Okay", + "dismiss_text": self._deny.text if self._deny and self._deny.text != "No" else "Cancel", } if self._title: json["title"] = self._title.text @@ -471,9 +527,9 @@ class DispatchActionConfig(JsonObject): attributes = {"trigger_actions_on"} @classmethod - def parse(cls, config: Union["DispatchActionConfig", dict]): + def parse(cls, config: Union["DispatchActionConfig", Dict[str, Any]]): if config: - if isinstance(config, DispatchActionConfig): # skipcq: PYL-R1705 + if isinstance(config, DispatchActionConfig): return config elif isinstance(config, dict): return DispatchActionConfig(**config) @@ -483,17 +539,144 @@ def parse(cls, config: Union["DispatchActionConfig", dict]): return None def __init__( - self, *, trigger_actions_on: Optional[list] = None, + self, + *, + trigger_actions_on: Optional[List[Any]] = None, ): """ Determines when a plain-text input element will return a block_actions interaction payload. - https://api.slack.com/reference/block-kit/composition-objects#dispatch_action_config + https://docs.slack.dev/reference/block-kit/composition-objects/dispatch-action-configuration-object """ self._trigger_actions_on = trigger_actions_on or [] - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> Dict[str, Any]: self.validate_json() json = {} if self._trigger_actions_on: json["trigger_actions_on"] = self._trigger_actions_on return json + + +class FeedbackButtonObject(JsonObject): + attributes: Set[str] = set() + + text_max_length = 75 + value_max_length = 2000 + + @classmethod + def parse(cls, feedback_button: Union["FeedbackButtonObject", Dict[str, Any]]): + if feedback_button: + if isinstance(feedback_button, FeedbackButtonObject): + return feedback_button + elif isinstance(feedback_button, dict): + return FeedbackButtonObject(**feedback_button) + else: + # Not yet implemented: show some warning here + return None + return None + + def __init__( + self, + *, + text: Union[str, Dict[str, Any], PlainTextObject], + accessibility_label: Optional[str] = None, + value: str, + **others: Dict[str, Any], + ): + """ + A feedback button element object for either positive or negative feedback. + https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element#button-object-fields + + Args: + text (required): An object containing some text. Maximum length for this field is 75 characters. + accessibility_label: A label for longer descriptive text about a button element. This label will be read out by + screen readers instead of the button `text` object. + value (required): The button value. Maximum length for this field is 2000 characters. + """ + self._text: Optional[TextObject] = PlainTextObject.parse(text, default_type=PlainTextObject.type) + self._accessibility_label: Optional[str] = accessibility_label + self._value: Optional[str] = value + show_unknown_key_warning(self, others) + + @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") + def text_length(self) -> bool: + return self._text is None or len(self._text.text) <= self.text_max_length + + @JsonValidator(f"value attribute cannot exceed {value_max_length} characters") + def value_length(self) -> bool: + return self._value is None or len(self._value) <= self.value_max_length + + def to_dict(self) -> Dict[str, Any]: + self.validate_json() + json: Dict[str, Union[str, dict]] = {} + if self._text: + json["text"] = self._text.to_dict() + if self._accessibility_label: + json["accessibility_label"] = self._accessibility_label + if self._value: + json["value"] = self._value + return json + + +class WorkflowTrigger(JsonObject): + attributes = {"trigger"} + + def __init__(self, *, url: str, customizable_input_parameters: Optional[List[Dict[str, str]]] = None): + self._url = url + self._customizable_input_parameters = customizable_input_parameters + + def to_dict(self) -> Dict[str, Any]: + self.validate_json() + json = {"url": self._url} + if self._customizable_input_parameters is not None: + json.update({"customizable_input_parameters": self._customizable_input_parameters}) # type: ignore[dict-item] + return json + + +class Workflow(JsonObject): + attributes = {"trigger"} + + def __init__( + self, + *, + trigger: Union[WorkflowTrigger, dict], + ): + self._trigger = trigger + + def to_dict(self) -> Dict[str, Any]: + self.validate_json() + json = {} + if isinstance(self._trigger, WorkflowTrigger): + json["trigger"] = self._trigger.to_dict() + else: + json["trigger"] = self._trigger + return json + + +class SlackFile(JsonObject): + attributes = {"id", "url"} + + def __init__( + self, + *, + id: Optional[str] = None, + url: Optional[str] = None, + ): + """An object containing Slack file information to be used in an image block or image element. + https://docs.slack.dev/reference/block-kit/composition-objects/slack-file-object + + Args: + id: Slack ID of the file. + url: This URL can be the url_private or the permalink of the Slack file. + """ + self._id = id + self._url = url + + def to_dict(self) -> Dict[str, Any]: + self.validate_json() + json = {} + if self._id is not None: + json["id"] = self._id + if self._url is not None: + json["url"] = self._url + return json diff --git a/slack_sdk/models/blocks/block_elements.py b/slack_sdk/models/blocks/block_elements.py index d342b2e93..89f0a7994 100644 --- a/slack_sdk/models/blocks/block_elements.py +++ b/slack_sdk/models/blocks/block_elements.py @@ -3,23 +3,24 @@ import re import warnings from abc import ABCMeta -from typing import List, Optional, Set, Union, Sequence +from typing import Any, Dict, Iterator, List, Optional, Sequence, Set, Type, Union from slack_sdk.models import show_unknown_key_warning -from slack_sdk.models.basic_objects import ( - JsonObject, - JsonValidator, - EnumValidator, +from slack_sdk.models.basic_objects import EnumValidator, JsonObject, JsonValidator + +from .basic_components import ( + ButtonStyles, + ConfirmObject, + DispatchActionConfig, + FeedbackButtonObject, + MarkdownTextObject, + Option, + OptionGroup, + PlainTextObject, + SlackFile, + TextObject, + Workflow, ) -from .basic_components import ButtonStyles -from .basic_components import ConfirmObject -from .basic_components import DispatchActionConfig -from .basic_components import MarkdownTextObject -from .basic_components import Option -from .basic_components import OptionGroup -from .basic_components import PlainTextObject -from .basic_components import TextObject - # ------------------------------------------------- # Block Elements @@ -28,13 +29,13 @@ class BlockElement(JsonObject, metaclass=ABCMeta): """Block Elements are things that exists inside of your Blocks. - https://api.slack.com/reference/block-kit/block-elements + https://docs.slack.dev/reference/block-kit/block-elements/ """ attributes = {"type"} logger = logging.getLogger(__name__) - def _subtype_warning(self): # skipcq: PYL-R0201 + def _subtype_warning(self): warnings.warn( "subtype is deprecated since slackclient 2.6.0, use type instead", DeprecationWarning, @@ -47,7 +48,7 @@ def subtype(self) -> Optional[str]: def __init__( self, *, - type: Optional[str] = None, # skipcq: PYL-W0622 + type: Optional[str] = None, subtype: Optional[str] = None, **others: dict, ): @@ -57,76 +58,37 @@ def __init__( show_unknown_key_warning(self, others) @classmethod - def parse( - cls, block_element: Union[dict, "BlockElement"] - ) -> Optional[Union["BlockElement", TextObject]]: - if block_element is None: # skipcq: PYL-R1705 + def parse(cls, block_element: Union[dict, "BlockElement"]) -> Optional[Union["BlockElement", TextObject]]: + if block_element is None: return None elif isinstance(block_element, dict): if "type" in block_element: d = copy.copy(block_element) t = d.pop("type") - if t == PlainTextObject.type: # skipcq: PYL-R1705 + for subclass in cls._get_sub_block_elements(): + if t == subclass.type: + return subclass(**d) + if t == PlainTextObject.type: return PlainTextObject(**d) elif t == MarkdownTextObject.type: return MarkdownTextObject(**d) - elif t == ImageElement.type: - return ImageElement(**d) - elif t == ButtonElement.type: - return ButtonElement(**d) - elif t == StaticSelectElement.type: - return StaticSelectElement(**d) - elif t == StaticMultiSelectElement.type: - return StaticMultiSelectElement(**d) - elif t == ExternalDataSelectElement.type: - return ExternalDataSelectElement(**d) - elif t == ExternalDataMultiSelectElement.type: - return ExternalDataMultiSelectElement(**d) - elif t == UserSelectElement.type: - return UserSelectElement(**d) - elif t == UserMultiSelectElement.type: - return UserMultiSelectElement(**d) - elif t == ConversationSelectElement.type: - return ConversationSelectElement(**d) - elif t == ConversationMultiSelectElement.type: - return ConversationMultiSelectElement(**d) - elif t == ChannelSelectElement.type: - return ChannelSelectElement(**d) - elif t == ChannelMultiSelectElement.type: - return ChannelMultiSelectElement(**d) - elif t == PlainTextInputElement.type: - return PlainTextInputElement(**d) - elif t == RadioButtonsElement.type: - return RadioButtonsElement(**d) - elif t == CheckboxesElement.type: - return CheckboxesElement(**d) - elif t == OverflowMenuElement.type: - return OverflowMenuElement(**d) - elif t == DatePickerElement.type: - return DatePickerElement(**d) - else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) - return None - else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) - return None elif isinstance(block_element, (TextObject, BlockElement)): return block_element - else: - cls.logger.warning( - f"Unknown element detected and skipped ({block_element})" - ) - return None + cls.logger.warning(f"Unknown element detected and skipped ({block_element})") + return None @classmethod def parse_all( - cls, block_elements: Sequence[Union[dict, "BlockElement"]] - ) -> List["BlockElement"]: - return [cls.parse(e) for e in block_elements or []] + cls, block_elements: Sequence[Union[dict, "BlockElement", TextObject]] + ) -> List[Union["BlockElement", TextObject]]: + return [cls.parse(e) for e in block_elements or []] # type: ignore[arg-type, misc] + + @classmethod + def _get_sub_block_elements(cls: Type["BlockElement"]) -> Iterator[Type["BlockElement"]]: + for subclass in cls.__subclasses__(): + if hasattr(subclass, "type"): + yield subclass + yield from subclass._get_sub_block_elements() # ------------------------------------------------- @@ -134,47 +96,46 @@ def parse_all( # ------------------------------------------------- +# This is a base class class InteractiveElement(BlockElement): action_id_max_length = 255 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"alt_text", "action_id"}) def __init__( self, *, action_id: Optional[str] = None, - type: Optional[str] = None, # skipcq: PYL-W0622 + type: Optional[str] = None, subtype: Optional[str] = None, **others: dict, ): + """An interactive block element. + + We generally recommend using the concrete subclasses for better supports of available properties. + """ if subtype: self._subtype_warning() super().__init__(type=type or subtype) - show_unknown_key_warning(self, others) + + # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here. + # It's fine to pass any kwargs to the held dict here although the class does not do any validation. + # show_unknown_key_warning(self, others) self.action_id = action_id - @JsonValidator( - f"action_id attribute cannot exceed {action_id_max_length} characters" - ) - def _validate_action_id_length(self): - return ( - self.action_id is None or len(self.action_id) <= self.action_id_max_length - ) + @JsonValidator(f"action_id attribute cannot exceed {action_id_max_length} characters") + def _validate_action_id_length(self) -> bool: + return self.action_id is None or len(self.action_id) <= self.action_id_max_length +# This is a base class class InputInteractiveElement(InteractiveElement, metaclass=ABCMeta): placeholder_max_length = 150 - attributes = {"type", "action_id", "placeholder", "confirm"} - - def _subtype_warning(self): - warnings.warn( - "subtype is deprecated since slackclient 2.6.0, use type instead", - DeprecationWarning, - ) + attributes = {"type", "action_id", "placeholder", "confirm", "focus_on_load"} @property def subtype(self) -> Optional[str]: @@ -184,25 +145,31 @@ def __init__( self, *, action_id: Optional[str] = None, - placeholder: Union[str, TextObject] = None, - type: Optional[str] = None, # skipcq: PYL-W0622 + placeholder: Optional[Union[str, TextObject]] = None, + type: Optional[str] = None, subtype: Optional[str] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): - """InteractiveElement that is usable in input blocks""" + """InteractiveElement that is usable in input blocks + + We generally recommend using the concrete subclasses for better supports of available properties. + """ if subtype: self._subtype_warning() super().__init__(action_id=action_id, type=type or subtype) - show_unknown_key_warning(self, others) - self.placeholder = TextObject.parse(placeholder) - self.confirm = ConfirmObject.parse(confirm) + # Note that we don't intentionally have show_unknown_key_warning for the unknown key warnings here. + # It's fine to pass any kwargs to the held dict here although the class does not do any validation. + # show_unknown_key_warning(self, others) - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) - def _validate_placeholder_length(self): + self.placeholder = TextObject.parse(placeholder) # type: ignore[arg-type] + self.confirm = ConfirmObject.parse(confirm) # type: ignore[arg-type] + self.focus_on_load = focus_on_load + + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") + def _validate_placeholder_length(self) -> bool: return ( self.placeholder is None or self.placeholder.text is None @@ -222,8 +189,8 @@ class ButtonElement(InteractiveElement): value_max_length = 2000 @property - def attributes(self) -> Set[str]: - return super().attributes.union({"text", "url", "value", "style", "confirm"}) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"text", "url", "value", "style", "confirm", "accessibility_label"}) def __init__( self, @@ -234,11 +201,37 @@ def __init__( value: Optional[str] = None, style: Optional[str] = None, # primary, danger confirm: Optional[Union[dict, ConfirmObject]] = None, + accessibility_label: Optional[str] = None, **others: dict, ): """An interactive element that inserts a button. The button can be a trigger for anything from opening a simple link to starting a complex workflow. - https://api.slack.com/reference/block-kit/block-elements#button + https://docs.slack.dev/reference/block-kit/block-elements/button-element/ + + Args: + text (required): A text object that defines the button's text. + Can only be of type: plain_text. + Maximum length for the text in this field is 75 characters. + action_id (required): An identifier for this action. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + url: A URL to load in the user's browser when the button is clicked. + Maximum length for this field is 3000 characters. + If you're using url, you'll still receive an interaction payload + and will need to send an acknowledgement response. + value: The value to send along with the interaction payload. + Maximum length for this field is 2000 characters. + style: Decorates buttons with alternative visual color schemes. Use this option with restraint. + "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. + "primary" should only be used for one button within a set. + "danger" gives buttons a red outline and text, and should be used when the action is destructive. + Use "danger" even more sparingly than "primary". + If you don't include this field, the default button style will be used. + confirm: A confirm object that defines an optional confirmation dialog after the button is clicked. + accessibility_label: A label for longer descriptive text about a button element. + This label will be read out by screen readers instead of the button text object. + Maximum length for this field is 75 characters. """ super().__init__(action_id=action_id, type=self.type) show_unknown_key_warning(self, others) @@ -248,34 +241,35 @@ def __init__( self.url = url self.value = value self.style = style - self.confirm = ConfirmObject.parse(confirm) + self.confirm = ConfirmObject.parse(confirm) # type: ignore[arg-type] + self.accessibility_label = accessibility_label @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") - def _validate_text_length(self): - return ( - self.text is None - or self.text.text is None - or len(self.text.text) <= self.text_max_length - ) + def _validate_text_length(self) -> bool: + return self.text is None or self.text.text is None or len(self.text.text) <= self.text_max_length @JsonValidator(f"url attribute cannot exceed {url_max_length} characters") - def _validate_url_length(self): + def _validate_url_length(self) -> bool: return self.url is None or len(self.url) <= self.url_max_length @JsonValidator(f"value attribute cannot exceed {value_max_length} characters") - def _validate_value_length(self): + def _validate_value_length(self) -> bool: return self.value is None or len(self.value) <= self.value_max_length @EnumValidator("style", ButtonStyles) def _validate_style_valid(self): return self.style is None or self.style in ButtonStyles + @JsonValidator(f"accessibility_label attribute cannot exceed {text_max_length} characters") + def _validate_accessibility_label_length(self) -> bool: + return self.accessibility_label is None or len(self.accessibility_label) <= self.text_max_length + class LinkButtonElement(ButtonElement): def __init__( self, *, - text: str, + text: Union[str, dict, PlainTextObject], url: str, action_id: Optional[str] = None, style: Optional[str] = None, @@ -284,7 +278,26 @@ def __init__( """A simple button that simply opens a given URL. You will still receive an interaction payload and will need to send an acknowledgement response. This is a helper class that makes creating links simpler. - https://api.slack.com/reference/block-kit/block-elements#button + https://docs.slack.dev/reference/block-kit/block-elements/button-element/ + + Args: + text (required): A text object that defines the button's text. + Can only be of type: plain_text. + Maximum length for the text in this field is 75 characters. + url (required): A URL to load in the user's browser when the button is clicked. + Maximum length for this field is 3000 characters. + If you're using url, you'll still receive an interaction payload + and will need to send an acknowledgement response. + action_id (required): An identifier for this action. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + style: Decorates buttons with alternative visual color schemes. Use this option with restraint. + "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. + "primary" should only be used for one button within a set. + "danger" gives buttons a red outline and text, and should be used when the action is destructive. + Use "danger" even more sparingly than "primary". + If you don't include this field, the default button style will be used. """ super().__init__( # NOTE: value must be always absent @@ -306,27 +319,40 @@ class CheckboxesElement(InputInteractiveElement): type = "checkboxes" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"options", "initial_options"}) def __init__( self, *, action_id: Optional[str] = None, - placeholder: Optional[str] = None, options: Optional[Sequence[Union[dict, Option]]] = None, initial_options: Optional[Sequence[Union[dict, Option]]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """A checkbox group that allows a user to choose multiple items from a list of possible options. - https://api.slack.com/reference/block-kit/block-elements#checkboxes + https://docs.slack.dev/reference/block-kit/block-elements/checkboxes-element/ + + Args: + action_id (required): An identifier for the action triggered when the checkbox group is changed. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + options (required): An array of option objects. A maximum of 10 options are allowed. + initial_options: An array of option objects that exactly matches one or more of the options. + These options will be selected when the checkbox group initially loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + after clicking one of the checkboxes in this element. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -343,7 +369,7 @@ class DatePickerElement(InputInteractiveElement): type = "datepicker" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"initial_date"}) def __init__( @@ -353,28 +379,203 @@ def __init__( placeholder: Optional[Union[str, dict, TextObject]] = None, initial_date: Optional[str] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ An element which lets users easily select a date from a calendar style UI. Date picker elements can be used inside of SectionBlocks and ActionsBlocks. - https://api.slack.com/reference/block-kit/block-elements#datepicker + https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element + + Args: + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder: A plain_text only text object that defines the placeholder text shown on the datepicker. + Maximum length for the text in this field is 150 characters. + initial_date: The initial date that is selected when the element is loaded. + This should be in the format YYYY-MM-DD. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a date is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) self.initial_date = initial_date @JsonValidator("initial_date attribute must be in format 'YYYY-MM-DD'") - def _validate_initial_date_valid(self): - return self.initial_date is None or re.match( - r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date + def _validate_initial_date_valid(self) -> bool: + return ( + self.initial_date is None + or re.match(r"\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])", self.initial_date) is not None + ) + + +# ------------------------------------------------- +# TimePicker +# ------------------------------------------------- + + +class TimePickerElement(InputInteractiveElement): + type = "timepicker" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"initial_time", "timezone"}) + + def __init__( + self, + *, + action_id: Optional[str] = None, + placeholder: Optional[Union[str, dict, TextObject]] = None, + initial_time: Optional[str] = None, + confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, + timezone: Optional[str] = None, + **others: dict, + ): + """ + An element which allows selection of a time of day. + On desktop clients, this time picker will take the form of a dropdown list + with free-text entry for precise choices. + On mobile clients, the time picker will use native time picker UIs. + https://docs.slack.dev/reference/block-kit/block-elements/time-picker-element + + Args: + action_id (required): An identifier for the action triggered when a time is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder: A plain_text only text object that defines the placeholder text shown on the timepicker. + Maximum length for the text in this field is 150 characters. + initial_time: The initial time that is selected when the element is loaded. + This should be in the format HH:mm, where HH is the 24-hour format of an hour (00 to 23) + and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a time is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. + timezone: The timezone to consider for this input value. + """ + super().__init__( + type=self.type, + action_id=action_id, + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) + show_unknown_key_warning(self, others) + + self.initial_time = initial_time + self.timezone = timezone + + @JsonValidator("initial_time attribute must be in format 'HH:mm'") + def _validate_initial_time_valid(self) -> bool: + return self.initial_time is None or re.match(r"([0-1][0-9]|2[0-3]):([0-5][0-9])", self.initial_time) is not None + + +# ------------------------------------------------- +# DateTimePicker +# ------------------------------------------------- + + +class DateTimePickerElement(InputInteractiveElement): + type = "datetimepicker" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"initial_date_time"}) + + def __init__( + self, + *, + action_id: Optional[str] = None, + initial_date_time: Optional[int] = None, + confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, + **others: dict, + ): + """ + An element that allows the selection of a time of day formatted as a UNIX timestamp. + On desktop clients, this time picker will take the form of a dropdown list and the + date picker will take the form of a dropdown calendar. Both options will have free-text + entry for precise choices. On mobile clients, the time picker and date + picker will use native UIs. + https://docs.slack.dev/reference/block-kit/block-elements/date-picker-element/ + + Args: + action_id (required): An identifier for the action triggered when a time is selected. You can use this + when you receive an interaction payload to identify the source of the action. Should be unique among + all other action_ids in the containing block. Maximum length for this field is 255 characters. + initial_date_time: The initial date and time that is selected when the element is loaded, represented as + a UNIX timestamp in seconds. This should be in the format of 10 digits, for example 1628633820 + represents the date and time August 10th, 2021 at 03:17pm PST. + and mm is minutes with leading zeros (00 to 59), for example 22:25 for 10:25pm. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a time is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. + """ + super().__init__( + type=self.type, + action_id=action_id, + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, + ) + show_unknown_key_warning(self, others) + + self.initial_date_time = initial_date_time + + @JsonValidator("initial_date_time attribute must be between 0 and 99999999 seconds") + def _validate_initial_date_time_valid(self) -> bool: + return self.initial_date_time is None or (0 <= self.initial_date_time <= 9999999999) + + +# ------------------------------------------------- +# Feedback Buttons Element +# ------------------------------------------------- + + +class FeedbackButtonsElement(InteractiveElement): + type = "feedback_buttons" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"positive_button", "negative_button"}) + + def __init__( + self, + *, + action_id: Optional[str] = None, + positive_button: Union[dict, FeedbackButtonObject], + negative_button: Union[dict, FeedbackButtonObject], + **others: dict, + ): + """Buttons to indicate positive or negative feedback. + https://docs.slack.dev/reference/block-kit/block-elements/feedback-buttons-element + + Args: + action_id (required): An identifier for this action. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + positive_button (required): A button to indicate positive feedback. + negative_button (required): A button to indicate negative feedback. + """ + super().__init__(action_id=action_id, type=self.type) + show_unknown_key_warning(self, others) + + self.positive_button = FeedbackButtonObject.parse(positive_button) + self.negative_button = FeedbackButtonObject.parse(negative_button) # ------------------------------------------------- @@ -388,36 +589,95 @@ class ImageElement(BlockElement): alt_text_max_length = 2000 @property - def attributes(self) -> Set[str]: - return super().attributes.union({"alt_text", "image_url"}) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"alt_text", "image_url", "slack_file"}) def __init__( self, *, - image_url: Optional[str] = None, alt_text: Optional[str] = None, + image_url: Optional[str] = None, + slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None, **others: dict, ): """An element to insert an image - this element can be used in section and context blocks only. If you want a block with only an image in it, you're looking for the image block. - https://api.slack.com/reference/block-kit/block-elements#image + https://docs.slack.dev/reference/block-kit/block-elements/image-element + + Args: + alt_text (required): A plain-text summary of the image. This should not contain any markup. + image_url: The URL of the image to be displayed. + slack_file: A Slack image file object that defines the source of the image. """ super().__init__(type=self.type) show_unknown_key_warning(self, others) self.image_url = image_url self.alt_text = alt_text + self.slack_file = slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file) - @JsonValidator( - f"image_url attribute cannot exceed {image_url_max_length} characters" - ) - def _validate_image_url_length(self): - return len(self.image_url) <= self.image_url_max_length + @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters") + def _validate_image_url_length(self) -> bool: + return self.image_url is None or len(self.image_url) <= self.image_url_max_length @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters") - def _validate_alt_text_length(self): - return len(self.alt_text) <= self.alt_text_max_length + def _validate_alt_text_length(self) -> bool: + return len(self.alt_text) <= self.alt_text_max_length # type: ignore[arg-type] + + +# ------------------------------------------------- +# Icon Button Element +# ------------------------------------------------- + + +class IconButtonElement(InteractiveElement): + type = "icon_button" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"icon", "text", "accessibility_label", "value", "visible_to_user_ids", "confirm"}) + + def __init__( + self, + *, + action_id: Optional[str] = None, + icon: str, + text: Union[str, dict, TextObject], + accessibility_label: Optional[str] = None, + value: Optional[str] = None, + visible_to_user_ids: Optional[List[str]] = None, + confirm: Optional[Union[dict, ConfirmObject]] = None, + **others: dict, + ): + """An icon button to perform actions. + https://docs.slack.dev/reference/block-kit/block-elements/icon-button-element + + Args: + action_id: An identifier for this action. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + icon (required): The icon to show (e.g., 'trash'). + text (required): Defines an object containing some text. + accessibility_label: A label for longer descriptive text about a button element. + This label will be read out by screen readers instead of the button text object. + Maximum length for this field is 75 characters. + value: The button value. + Maximum length for this field is 2000 characters. + visible_to_user_ids: User IDs for which the icon appears. + Maximum length for this field is 10 user IDs. + confirm: A confirm object that defines an optional confirmation dialog after the button is clicked. + """ + super().__init__(action_id=action_id, type=self.type) + show_unknown_key_warning(self, others) + + self.icon = icon + self.text = TextObject.parse(text, PlainTextObject.type) + self.accessibility_label = accessibility_label + self.value = value + self.visible_to_user_ids = visible_to_user_ids + self.confirm = ConfirmObject.parse(confirm) if confirm else None # ------------------------------------------------- @@ -431,7 +691,7 @@ class StaticSelectElement(InputInteractiveElement): option_groups_max_length = 100 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"options", "option_groups", "initial_option"}) def __init__( @@ -443,16 +703,38 @@ def __init__( option_groups: Optional[Sequence[Union[dict, OptionGroup]]] = None, initial_option: Optional[Union[dict, Option]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """This is the simplest form of select menu, with a static list of options passed in when defining the element. - ps://api.slack.com/reference/block-kit/block-elements#static_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + options (either options or option_groups is required): An array of option objects. + Maximum number of options is 100. + If option_groups is specified, this field should not be. + option_groups (either options or option_groups is required): An array of option group objects. + Maximum number of option groups is 100. + If options is specified, this field should not be. + initial_option: A single option that exactly matches one of the options or option_groups. + This option will be selected when the menu initially loads. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a menu item is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -461,24 +743,19 @@ def __init__( self.initial_option = initial_option @JsonValidator(f"options attribute cannot exceed {options_max_length} elements") - def _validate_options_length(self): + def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) - def _validate_option_groups_length(self): - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") + def _validate_option_groups_length(self) -> bool: + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") - def _validate_options_and_option_groups_both_specified(self): + def _validate_options_and_option_groups_both_specified(self) -> bool: return not (self.options is not None and self.option_groups is not None) @JsonValidator("options or option_groups must be specified") - def _validate_neither_options_or_option_groups_is_specified(self): + def _validate_neither_options_or_option_groups_is_specified(self) -> bool: return self.options is not None or self.option_groups is not None @@ -488,10 +765,8 @@ class StaticMultiSelectElement(InputInteractiveElement): option_groups_max_length = 100 @property - def attributes(self) -> Set[str]: - return super().attributes.union( - {"options", "option_groups", "initial_options", "max_selected_items"} - ) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"options", "option_groups", "initial_options", "max_selected_items"}) def __init__( self, @@ -503,17 +778,41 @@ def __init__( initial_options: Optional[Sequence[Option]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, max_selected_items: Optional[int] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This is the simplest form of select menu, with a static list of options passed in when defining the element. - https://api.slack.com/reference/block-kit/block-elements#static_multi_select + https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#static_multi_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + options (either options or option_groups is required): An array of option objects. + Maximum number of options is 100. + If option_groups is specified, this field should not be. + option_groups (either options or option_groups is required): An array of option group objects. + Maximum number of option groups is 100. + If options is specified, this field should not be. + initial_options: An array of option objects that exactly match one or more of the options + within options or option_groups. These options will be selected when the menu initially loads. + confirm: A confirm object that defines an optional confirmation dialog + that appears before the multi-select choices are submitted. + max_selected_items: Specifies the maximum number of items that can be selected in the menu. + Minimum number is 1. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -523,24 +822,19 @@ def __init__( self.max_selected_items = max_selected_items @JsonValidator(f"options attribute cannot exceed {options_max_length} elements") - def _validate_options_length(self): + def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) - def _validate_option_groups_length(self): - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") + def _validate_option_groups_length(self) -> bool: + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") - def _validate_options_and_option_groups_both_specified(self): + def _validate_options_and_option_groups_both_specified(self) -> bool: return self.options is None or self.option_groups is None @JsonValidator("options or option_groups must be specified") - def _validate_neither_options_or_option_groups_is_specified(self): + def _validate_neither_options_or_option_groups_is_specified(self) -> bool: return self.options is not None or self.option_groups is not None @@ -551,7 +845,7 @@ class SelectElement(InputInteractiveElement): option_groups_max_length = 100 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"options", "option_groups", "initial_option"}) def __init__( @@ -563,16 +857,38 @@ def __init__( option_groups: Optional[Sequence[OptionGroup]] = None, initial_option: Optional[Option] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """This is the simplest form of select menu, with a static list of options passed in when defining the element. - https://api.slack.com/reference/block-kit/block-elements#static_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#static_select + + Args: + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + options (either options or option_groups is required): An array of option objects. + Maximum number of options is 100. + If option_groups is specified, this field should not be. + option_groups (either options or option_groups is required): An array of option group objects. + Maximum number of option groups is 100. + If options is specified, this field should not be. + initial_option: A single option that exactly matches one of the options or option_groups. + This option will be selected when the menu initially loads. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a menu item is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -581,24 +897,19 @@ def __init__( self.initial_option = initial_option @JsonValidator(f"options attribute cannot exceed {options_max_length} elements") - def _validate_options_length(self): + def _validate_options_length(self) -> bool: return self.options is None or len(self.options) <= self.options_max_length - @JsonValidator( - f"option_groups attribute cannot exceed {option_groups_max_length} elements" - ) - def _validate_option_groups_length(self): - return ( - self.option_groups is None - or len(self.option_groups) <= self.option_groups_max_length - ) + @JsonValidator(f"option_groups attribute cannot exceed {option_groups_max_length} elements") + def _validate_option_groups_length(self) -> bool: + return self.option_groups is None or len(self.option_groups) <= self.option_groups_max_length @JsonValidator("options and option_groups cannot both be specified") - def _validate_options_and_option_groups_both_specified(self): + def _validate_options_and_option_groups_both_specified(self) -> bool: return not (self.options is not None and self.option_groups is not None) @JsonValidator("options or option_groups must be specified") - def _validate_neither_options_or_option_groups_is_specified(self): + def _validate_neither_options_or_option_groups_is_specified(self) -> bool: return self.options is not None or self.option_groups is not None @@ -611,29 +922,51 @@ class ExternalDataSelectElement(InputInteractiveElement): type = "external_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"min_query_length", "initial_option"}) def __init__( self, *, action_id: Optional[str] = None, - placeholder: Union[str, TextObject] = None, + placeholder: Optional[Union[str, TextObject]] = None, initial_option: Union[Optional[Option], Optional[OptionGroup]] = None, min_query_length: Optional[int] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will load its options from an external data source, allowing for a dynamic list of options. - https://api.slack.com/reference/block-kit/block-elements#external_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#external_select + + Args: + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + initial_option: A single option that exactly matches one of the options + within the options or option_groups loaded from the external data source. + This option will be selected when the menu initially loads. + min_query_length: When the typeahead field is used, a request will be sent on every character change. + If you prefer fewer requests or more fully ideated queries, + use the min_query_length attribute to tell Slack + the fewest number of typed characters required before dispatch. + The default value is 3. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a menu item is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -645,10 +978,8 @@ class ExternalDataMultiSelectElement(InputInteractiveElement): type = "multi_external_select" @property - def attributes(self) -> Set[str]: - return super().attributes.union( - {"min_query_length", "initial_options", "max_selected_items"} - ) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"min_query_length", "initial_options", "max_selected_items"}) def __init__( self, @@ -659,18 +990,41 @@ def __init__( initial_options: Optional[Sequence[Union[dict, Option]]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, max_selected_items: Optional[int] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will load its options from an external data source, allowing for a dynamic list of options. - https://api.slack.com/reference/block-kit/block-elements#external-select + https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + min_query_length: When the typeahead field is used, a request will be sent on every character change. + If you prefer fewer requests or more fully ideated queries, + use the min_query_length attribute to tell Slack + the fewest number of typed characters required before dispatch. + The default value is 3 + initial_options: An array of option objects that exactly match one or more of the options + within options or option_groups. These options will be selected when the menu initially loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + before the multi-select choices are submitted. + max_selected_items: Specifies the maximum number of items that can be selected in the menu. + Minimum number is 1. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -688,7 +1042,7 @@ class UserSelectElement(InputInteractiveElement): type = "users_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"initial_user"}) def __init__( @@ -698,18 +1052,33 @@ def __init__( action_id: Optional[str] = None, initial_user: Optional[str] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will populate its options with a list of Slack users visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#users_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element#users_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_user: The user ID of any valid user to be pre-selected when the menu loads. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a menu item is selected. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -720,7 +1089,7 @@ class UserMultiSelectElement(InputInteractiveElement): type = "multi_users_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"initial_users", "max_selected_items"}) def __init__( @@ -731,18 +1100,35 @@ def __init__( initial_users: Optional[Sequence[str]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, max_selected_items: Optional[int] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will populate its options with a list of Slack users visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#users_multi_select + https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#users_multi_select + + Args: + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + initial_users: An array of user IDs of any valid users to be pre-selected when the menu loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + before the multi-select choices are submitted. + max_selected_items: Specifies the maximum number of items that can be selected in the menu. + Minimum number is 1. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -756,7 +1142,7 @@ def __init__( class ConversationFilter(JsonObject): - attributes = {"include", "exclude_bot_users"} + attributes = {"include", "exclude_bot_users", "exclude_external_shared_channels"} logger = logging.getLogger(__name__) def __init__( @@ -764,13 +1150,28 @@ def __init__( *, include: Optional[Sequence[str]] = None, exclude_bot_users: Optional[bool] = None, + exclude_external_shared_channels: Optional[bool] = None, ): + """Provides a way to filter the list of options in a conversations select menu + or conversations multi-select menu. + https://docs.slack.dev/reference/block-kit/composition-objects/conversation-filter-object + + Args: + include: Indicates which type of conversations should be included in the list. + When this field is provided, any conversations that do not match will be excluded. + You should provide an array of strings from the following options: + "im", "mpim", "private", and "public". The array cannot be empty. + exclude_bot_users: Indicates whether to exclude bot users from conversation lists. Defaults to false. + exclude_external_shared_channels: Indicates whether to exclude external shared channels + from conversation lists. Defaults to false. + """ self.include = include self.exclude_bot_users = exclude_bot_users + self.exclude_external_shared_channels = exclude_external_shared_channels @classmethod - def parse(cls, filter: Union[dict, "ConversationFilter"]): # skipcq: PYL-W0622 - if filter is None: # skipcq: PYL-R1705 + def parse(cls, filter: Union[dict, "ConversationFilter"]): + if filter is None: return None elif isinstance(filter, ConversationFilter): return filter @@ -778,9 +1179,7 @@ def parse(cls, filter: Union[dict, "ConversationFilter"]): # skipcq: PYL-W0622 d = copy.copy(filter) return ConversationFilter(**d) else: - cls.logger.warning( - f"Unknown conversation filter object detected and skipped ({filter})" - ) + cls.logger.warning(f"Unknown conversation filter object detected and skipped ({filter})") return None @@ -788,7 +1187,7 @@ class ConversationSelectElement(InputInteractiveElement): type = "conversations_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union( { "initial_conversation", @@ -807,19 +1206,42 @@ def __init__( confirm: Optional[Union[dict, ConfirmObject]] = None, response_url_enabled: Optional[bool] = None, default_to_current_conversation: Optional[bool] = None, - filter: Optional[ConversationFilter] = None, # skipcq: PYL-W0622 + filter: Optional[ConversationFilter] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will populate its options with a list of public and private channels, DMs, and MPIMs visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#conversation_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#conversations_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_conversation: The ID of any valid conversation to be pre-selected when the menu loads. + If default_to_current_conversation is also supplied, initial_conversation will take precedence. + confirm: A confirm object that defines an optional confirmation dialog + that appears after a menu item is selected. + response_url_enabled: This field only works with menus in input blocks in modals. + When set to true, the view_submission payload from the menu's parent view will contain a response_url. + This response_url can be used for message responses. The target conversation for the message + will be determined by the value of this select menu. + default_to_current_conversation: Pre-populates the select menu with the conversation + that the user was viewing when they opened the modal, if available. Default is false. + filter: A filter object that reduces the list of available conversations using the specified criteria. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -833,7 +1255,7 @@ class ConversationMultiSelectElement(InputInteractiveElement): type = "multi_conversations_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union( { "initial_conversations", @@ -852,26 +1274,48 @@ def __init__( confirm: Optional[Union[dict, ConfirmObject]] = None, max_selected_items: Optional[int] = None, default_to_current_conversation: Optional[bool] = None, - filter: Optional[Union[dict, ConversationFilter]] = None, # skipcq: PYL-W0622 + filter: Optional[Union[dict, ConversationFilter]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This multi-select menu will populate its options with a list of public and private channels, DMs, and MPIMs visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#conversation_multi_select + https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element/#conversation_multi_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_conversations: An array of one or more IDs of any valid conversations to be pre-selected + when the menu loads. If default_to_current_conversation is also supplied, + initial_conversations will be ignored. + confirm: A confirm object that defines an optional confirmation dialog that appears + before the multi-select choices are submitted. + max_selected_items: Specifies the maximum number of items that can be selected in the menu. + Minimum number is 1. + default_to_current_conversation: Pre-populates the select menu with the conversation that + the user was viewing when they opened the modal, if available. Default is false. + filter: A filter object that reduces the list of available conversations using the specified criteria. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) self.initial_conversations = initial_conversations self.max_selected_items = max_selected_items self.default_to_current_conversation = default_to_current_conversation - self.filter = ConversationFilter.parse(filter) + self.filter = ConversationFilter.parse(filter) # type: ignore[arg-type] # ------------------------------------------------- @@ -883,7 +1327,7 @@ class ChannelSelectElement(InputInteractiveElement): type = "channels_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"initial_channel", "response_url_enabled"}) def __init__( @@ -894,18 +1338,37 @@ def __init__( initial_channel: Optional[str] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, response_url_enabled: Optional[bool] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This select menu will populate its options with a list of public channels visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#channel_select + https://docs.slack.dev/reference/block-kit/block-elements/select-menu-element/#channels_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_channel: The ID of any valid public channel to be pre-selected when the menu loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + after a menu item is selected. + response_url_enabled: This field only works with menus in input blocks in modals. + When set to true, the view_submission payload from the menu's parent view will contain a response_url. + This response_url can be used for message responses. + The target channel for the message will be determined by the value of this select menu + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -917,7 +1380,7 @@ class ChannelMultiSelectElement(InputInteractiveElement): type = "multi_channels_select" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"initial_channels", "max_selected_items"}) def __init__( @@ -928,18 +1391,36 @@ def __init__( initial_channels: Optional[Sequence[str]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, max_selected_items: Optional[int] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ This multi-select menu will populate its options with a list of public channels visible to the current user in the active workspace. - https://api.slack.com/reference/block-kit/block-elements#channel_multi_select + https://docs.slack.dev/reference/block-kit/block-elements/multi-select-menu-element#channel_multi_select + + Args: + placeholder (required): A plain_text only text object that defines the placeholder text shown on the menu. + Maximum length for the text in this field is 150 characters. + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_channels: An array of one or more IDs of any valid public channel + to be pre-selected when the menu loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + before the multi-select choices are submitted. + max_selected_items: Specifies the maximum number of items that can be selected in the menu. + Minimum number is 1. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -948,7 +1429,47 @@ def __init__( # ------------------------------------------------- -# Input Elements +# Rich Text Input Element +# ------------------------------------------------- + + +class RichTextInputElement(InputInteractiveElement): + type = "rich_text_input" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "initial_value", + "dispatch_action_config", + } + ) + + def __init__( + self, + *, + action_id: Optional[str] = None, + placeholder: Optional[Union[str, dict, TextObject]] = None, + # To avoid circular imports, the RichTextBlock type here is intentionally a string + initial_value: Optional[Union[Dict[str, Any], "RichTextBlock"]] = None, # type: ignore[name-defined] # noqa: F821 + dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None, + focus_on_load: Optional[bool] = None, + **others: dict, + ): + super().__init__( + type=self.type, + action_id=action_id, + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + focus_on_load=focus_on_load, + ) + show_unknown_key_warning(self, others) + + self.initial_value = initial_value + self.dispatch_action_config = dispatch_action_config + + +# ------------------------------------------------- +# Plain Text Input Element # ------------------------------------------------- @@ -956,7 +1477,7 @@ class PlainTextInputElement(InputInteractiveElement): type = "plain_text_input" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union( { "initial_value", @@ -972,12 +1493,12 @@ def __init__( *, action_id: Optional[str] = None, placeholder: Optional[Union[str, dict, TextObject]] = None, - confirm: Optional[Union[dict, ConfirmObject]] = None, initial_value: Optional[str] = None, multiline: Optional[bool] = None, min_length: Optional[int] = None, max_length: Optional[int] = None, dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """ @@ -985,13 +1506,32 @@ def __init__( where a user can enter freeform data. It can appear as a single-line field or a larger textarea using the multiline flag. Plain-text input elements can be used inside of SectionBlocks and ActionsBlocks. - https://api.slack.com/reference/block-kit/block-elements#input + https://docs.slack.dev/reference/block-kit/block-elements/plain-text-input-element + + Args: + action_id (required): An identifier for the input value when the parent modal is submitted. + You can use this when you receive a view_submission payload to identify the value of the input element. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + placeholder: A plain_text only text object that defines the placeholder text shown + in the plain-text input. Maximum length for the text in this field is 150 characters. + initial_value: The initial value in the plain-text input when it is loaded. + multiline: Indicates whether the input will be a single line (false) or a larger textarea (true). + Defaults to false. + min_length: The minimum length of input that the user must provide. If the user provides less, + they will receive an error. Maximum value is 3000. + max_length: The maximum length of input that the user can provide. If the user provides more, + they will receive an error. + dispatch_action_config: A dispatch configuration object that determines when + during text input the element returns a block_actions payload. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -1002,6 +1542,235 @@ def __init__( self.dispatch_action_config = dispatch_action_config +# ------------------------------------------------- +# Email Input Element +# ------------------------------------------------- + + +class EmailInputElement(InputInteractiveElement): + type = "email_text_input" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "initial_value", + "dispatch_action_config", + } + ) + + def __init__( + self, + *, + action_id: Optional[str] = None, + initial_value: Optional[str] = None, + dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None, + focus_on_load: Optional[bool] = None, + placeholder: Optional[Union[str, dict, TextObject]] = None, + **others: dict, + ): + """ + https://docs.slack.dev/reference/block-kit/block-elements/email-input-element + + Args: + action_id (required): An identifier for the input value when the parent modal is submitted. + You can use this when you receive a view_submission payload to identify the value of the input element. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_value: The initial value in the email input when it is loaded. + dispatch_action_config: dispatch configuration object that determines when during + text input the element returns a block_actions payload. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. + placeholder: A plain_text only text object that defines the placeholder text shown in the + email input. Maximum length for the text in this field is 150 characters. + """ + super().__init__( + type=self.type, + action_id=action_id, + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + focus_on_load=focus_on_load, + ) + show_unknown_key_warning(self, others) + + self.initial_value = initial_value + self.dispatch_action_config = dispatch_action_config + + +# ------------------------------------------------- +# Url Input Element +# ------------------------------------------------- + + +class UrlInputElement(InputInteractiveElement): + type = "url_text_input" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "initial_value", + "dispatch_action_config", + } + ) + + def __init__( + self, + *, + action_id: Optional[str] = None, + initial_value: Optional[str] = None, + dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None, + focus_on_load: Optional[bool] = None, + placeholder: Optional[Union[str, dict, TextObject]] = None, + **others: dict, + ): + """ + A URL input element, similar to the Plain-text input element, + creates a single line field where a user can enter URL-encoded data. + https://docs.slack.dev/reference/block-kit/block-elements/url-input-element + + Args: + action_id (required): An identifier for the input value when the parent modal is submitted. + You can use this when you receive a view_submission payload to identify the value of the input element. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + initial_value: The initial value in the URL input when it is loaded. + dispatch_action_config: A dispatch configuration object that determines when during text input + the element returns a block_actions payload. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. + placeholder: A plain_text only text object that defines the placeholder text shown in the URL input. + Maximum length for the text in this field is 150 characters. + """ + super().__init__( + type=self.type, + action_id=action_id, + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + focus_on_load=focus_on_load, + ) + show_unknown_key_warning(self, others) + + self.initial_value = initial_value + self.dispatch_action_config = dispatch_action_config + + +# ------------------------------------------------- +# Number Input Element +# ------------------------------------------------- + + +class NumberInputElement(InputInteractiveElement): + type = "number_input" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "initial_value", + "is_decimal_allowed", + "min_value", + "max_value", + "dispatch_action_config", + } + ) + + def __init__( + self, + *, + action_id: Optional[str] = None, + is_decimal_allowed: Optional[bool] = False, + initial_value: Optional[Union[int, float, str]] = None, + min_value: Optional[Union[int, float, str]] = None, + max_value: Optional[Union[int, float, str]] = None, + dispatch_action_config: Optional[Union[dict, DispatchActionConfig]] = None, + focus_on_load: Optional[bool] = None, + placeholder: Optional[Union[str, dict, TextObject]] = None, + **others: dict, + ): + """ + https://docs.slack.dev/reference/block-kit/block-elements/number-input-element/ + + Args: + action_id (required): An identifier for the input value when the parent modal is submitted. + You can use this when you receive a view_submission payload to identify the value of the input element. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + is_decimal_allowed (required): Decimal numbers are allowed if is_decimal_allowed= true, set the value to + false otherwise. + initial_value: The initial value in the number input when it is loaded. + min_value: The minimum value, cannot be greater than max_value. + max_value: The maximum value, cannot be less than min_value. + dispatch_action_config: A dispatch configuration object that determines when + during text input the element returns a block_actions payload. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. + placeholder: A plain_text only text object that defines the placeholder text shown + in the plain-text input. Maximum length for the text in this field is 150 characters. + """ + super().__init__( + type=self.type, + action_id=action_id, + placeholder=TextObject.parse(placeholder, PlainTextObject.type), # type: ignore[arg-type] + focus_on_load=focus_on_load, + ) + show_unknown_key_warning(self, others) + + self.initial_value = str(initial_value) if initial_value is not None else None + self.is_decimal_allowed = is_decimal_allowed + self.min_value = str(min_value) if min_value is not None else None + self.max_value = str(max_value) if max_value is not None else None + self.dispatch_action_config = dispatch_action_config + + +# ------------------------------------------------- +# File Input Element +# ------------------------------------------------- + + +class FileInputElement(InputInteractiveElement): + type = "file_input" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "filetypes", + "max_files", + } + ) + + def __init__( + self, + *, + action_id: Optional[str] = None, + filetypes: Optional[List[str]] = None, + max_files: Optional[int] = None, + **others: dict, + ): + """ + https://docs.slack.dev/reference/block-kit/block-elements/file-input-element + + Args: + action_id (required): An identifier for the input value when the parent modal is submitted. + You can use this when you receive a view_submission payload to identify the value of the input element. + Should be unique among all other action_ids in the containing block. Maximum length is 255 characters. + filetypes: An array of valid file extensions that will be accepted for this element. + All file extensions will be accepted if filetypes is not specified. + This validation is provided for convenience only, + and you should perform your own file type validation based on what you expect to receive. + max_files: Maximum number of files that can be uploaded for this file_input element. + Minimum of 1, maximum of 10. Defaults to 10 if not specified. + """ + super().__init__( + type=self.type, + action_id=action_id, + ) + show_unknown_key_warning(self, others) + + self.filetypes = filetypes + self.max_files = max_files + + # ------------------------------------------------- # Radio Buttons Select # ------------------------------------------------- @@ -1011,27 +1780,40 @@ class RadioButtonsElement(InputInteractiveElement): type = "radio_buttons" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"options", "initial_option"}) def __init__( self, *, action_id: Optional[str] = None, - placeholder: Optional[Union[str, dict, TextObject]] = None, options: Optional[Sequence[Union[dict, Option]]] = None, initial_option: Optional[Union[dict, Option]] = None, confirm: Optional[Union[dict, ConfirmObject]] = None, + focus_on_load: Optional[bool] = None, **others: dict, ): """A radio button group that allows a user to choose one item from a list of possible options. - https://api.slack.com/reference/block-kit/block-elements#radio + https://docs.slack.dev/reference/block-kit/block-elements/radio-button-group-element + + Args: + action_id (required): An identifier for the action triggered when the radio button group is changed. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + options (required): An array of option objects. A maximum of 10 options are allowed. + initial_option: An option object that exactly matches one of the options. + This option will be selected when the radio button group initially loads. + confirm: A confirm object that defines an optional confirmation dialog that appears + after clicking one of the radio buttons in this element. + focus_on_load: Indicates whether the element will be set to auto focus within the view object. + Only one element can be set to true. Defaults to false. """ super().__init__( type=self.type, action_id=action_id, - placeholder=TextObject.parse(placeholder, PlainTextObject.type), - confirm=ConfirmObject.parse(confirm), + confirm=ConfirmObject.parse(confirm), # type: ignore[arg-type] + focus_on_load=focus_on_load, ) show_unknown_key_warning(self, others) @@ -1046,18 +1828,18 @@ def __init__( class OverflowMenuElement(InteractiveElement): type = "overflow" - options_min_length = 2 + options_min_length = 1 options_max_length = 5 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"confirm", "options"}) def __init__( self, *, action_id: Optional[str] = None, - options: Sequence[Union[Option]], + options: Sequence[Option], confirm: Optional[Union[dict, ConfirmObject]] = None, **others: dict, ): @@ -1072,17 +1854,396 @@ def __init__( buttons. You can also specify simple URL links as overflow menu options, instead of actions. - https://api.slack.com/reference/block-kit/block-elements#overflow + https://docs.slack.dev/reference/block-kit/block-elements/overflow-menu-element + + Args: + action_id (required): An identifier for the action triggered when a menu option is selected. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + options (required): An array of option objects to display in the menu. + Maximum number of options is 5, minimum is 1. + confirm: A confirm object that defines an optional confirmation dialog that appears + after a menu item is selected. """ super().__init__(action_id=action_id, type=self.type) show_unknown_key_warning(self, others) self.options = options - self.confirm = ConfirmObject.parse(confirm) + self.confirm = ConfirmObject.parse(confirm) # type: ignore[arg-type] - @JsonValidator( - f"options attribute must have between {options_min_length} " - f"and {options_max_length} items" - ) - def _validate_options_length(self): + @JsonValidator(f"options attribute must have between {options_min_length} " f"and {options_max_length} items") + def _validate_options_length(self) -> bool: return self.options_min_length <= len(self.options) <= self.options_max_length + + +# ------------------------------------------------- +# Workflow Button +# ------------------------------------------------- + + +class WorkflowButtonElement(InteractiveElement): + type = "workflow_button" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"text", "workflow", "style", "accessibility_label"}) + + def __init__( + self, + *, + text: Union[str, dict, TextObject], + action_id: Optional[str] = None, + workflow: Optional[Union[dict, Workflow]] = None, + style: Optional[str] = None, # primary, danger + accessibility_label: Optional[str] = None, + **others: dict, + ): + """Allows users to run a link trigger with customizable inputs + Interactive component - but interactions with workflow button elements will not send block_actions events, + since these are used to start new workflow runs. + https://docs.slack.dev/reference/block-kit/block-elements/workflow-button-element + + Args: + text (required): A text object that defines the button's text. + Can only be of type: plain_text. text may truncate with ~30 characters. + Maximum length for the text in this field is 75 characters. + action_id (required): An identifier for this action. + You can use this when you receive an interaction payload to identify the source of the action. + Should be unique among all other action_ids in the containing block. + Maximum length for this field is 255 characters. + workflow: A workflow object that contains details about the workflow + that will run when the button is clicked. + style: Decorates buttons with alternative visual color schemes. Use this option with restraint. + "primary" gives buttons a green outline and text, ideal for affirmation or confirmation actions. + "primary" should only be used for one button within a set. + "danger" gives buttons a red outline and text, and should be used when the action is destructive. + Use "danger" even more sparingly than "primary". + If you don't include this field, the default button style will be used. + accessibility_label: A label for longer descriptive text about a button element. + This label will be read out by screen readers instead of the button text object. + Maximum length for this field is 75 characters. + """ + super().__init__(action_id=action_id, type=self.type) + show_unknown_key_warning(self, others) + + # NOTE: default_type=PlainTextObject.type here is only for backward-compatibility with version 2.5.0 + self.text = TextObject.parse(text, default_type=PlainTextObject.type) + self.workflow = workflow + self.style = style + self.accessibility_label = accessibility_label + + +# ------------------------------------------------- +# Rich text elements +# ------------------------------------------------- + + +class RichTextElement(BlockElement): + pass + + +class RichTextListElement(RichTextElement): + type = "rich_text_list" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements", "style", "indent", "offset", "border"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, RichTextElement]], + style: Optional[str] = None, # bullet, ordered + indent: Optional[int] = None, + offset: Optional[int] = None, + border: Optional[int] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.elements = BlockElement.parse_all(elements) + self.style = style + self.indent = indent + self.offset = offset + self.border = border + + +class RichTextPreformattedElement(RichTextElement): + type = "rich_text_preformatted" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements", "border"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, RichTextElement]], + border: Optional[int] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.elements = BlockElement.parse_all(elements) + self.border = border + + +class RichTextQuoteElement(RichTextElement): + type = "rich_text_quote" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, RichTextElement]], + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.elements = BlockElement.parse_all(elements) + + +class RichTextSectionElement(RichTextElement): + type = "rich_text_section" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, RichTextElement]], + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.elements = BlockElement.parse_all(elements) + + +class RichTextElementParts: + class TextStyle: + def __init__( + self, + *, + bold: Optional[bool] = None, + italic: Optional[bool] = None, + strike: Optional[bool] = None, + code: Optional[bool] = None, + underline: Optional[bool] = None, + ): + self.bold = bold + self.italic = italic + self.strike = strike + self.code = code + self.underline = underline + + def to_dict(self, *args) -> dict: + result = { + "bold": self.bold, + "italic": self.italic, + "strike": self.strike, + "code": self.code, + "underline": self.underline, + } + return {k: v for k, v in result.items() if v is not None} + + class Text(RichTextElement): + type = "text" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"text", "style"}) + + def __init__( + self, + *, + text: str, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.text = text + self.style = style + + class Channel(RichTextElement): + type = "channel" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"channel_id", "style"}) + + def __init__( + self, + *, + channel_id: str, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.channel_id = channel_id + self.style = style + + class User(RichTextElement): + type = "user" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"user_id", "style"}) + + def __init__( + self, + *, + user_id: str, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.user_id = user_id + self.style = style + + class Emoji(RichTextElement): + type = "emoji" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"name", "skin_tone", "unicode", "style"}) + + def __init__( + self, + *, + name: str, + skin_tone: Optional[int] = None, + unicode: Optional[str] = None, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.name = name + self.skin_tone = skin_tone + self.unicode = unicode + self.style = style + + class Link(RichTextElement): + type = "link" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"url", "text", "style"}) + + def __init__( + self, + *, + url: str, + text: Optional[str] = None, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.url = url + self.text = text + self.style = style + + class Team(RichTextElement): + type = "team" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"team_id", "style"}) + + def __init__( + self, + *, + team_id: str, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.team_id = team_id + self.style = style + + class UserGroup(RichTextElement): + type = "usergroup" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"usergroup_id", "style"}) + + def __init__( + self, + *, + usergroup_id: str, + style: Optional[Union[dict, "RichTextElementParts.TextStyle"]] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.usergroup_id = usergroup_id + self.style = style + + class Date(RichTextElement): + type = "date" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"timestamp", "format", "url", "fallback"}) + + def __init__( + self, + *, + timestamp: int, + format: str, + url: Optional[str] = None, + fallback: Optional[str] = None, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.timestamp = timestamp + self.format = format + self.url = url + self.fallback = fallback + + class Broadcast(RichTextElement): + type = "broadcast" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"range"}) + + def __init__( + self, + *, + range: str, # channel, here, .. + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.range = range + + class Color(RichTextElement): + type = "color" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"value"}) + + def __init__( + self, + *, + value: str, + **others: dict, + ): + super().__init__(type=self.type) + show_unknown_key_warning(self, others) + self.value = value diff --git a/slack_sdk/models/blocks/blocks.py b/slack_sdk/models/blocks/blocks.py index 69b45c54e..cac463c99 100644 --- a/slack_sdk/models/blocks/blocks.py +++ b/slack_sdk/models/blocks/blocks.py @@ -1,20 +1,22 @@ import copy import logging import warnings -from typing import Dict, Sequence, Optional, Set, Union, Any, List +from typing import Any, Dict, List, Optional, Sequence, Set, Union from slack_sdk.models import show_unknown_key_warning -from slack_sdk.models.basic_objects import ( - JsonObject, - JsonValidator, +from slack_sdk.models.basic_objects import JsonObject, JsonValidator + +from ...errors import SlackObjectFormationError +from .basic_components import MarkdownTextObject, PlainTextObject, SlackFile, TextObject +from .block_elements import ( + BlockElement, + FeedbackButtonsElement, + IconButtonElement, + ImageElement, + InputInteractiveElement, + InteractiveElement, + RichTextElement, ) -from .basic_components import MarkdownTextObject -from .basic_components import PlainTextObject -from .basic_components import TextObject -from .block_elements import BlockElement -from .block_elements import InputInteractiveElement -from .block_elements import InteractiveElement - # ------------------------------------------------- # Base Classes @@ -24,14 +26,14 @@ class Block(JsonObject): """Blocks are a series of components that can be combined to create visually rich and compellingly interactive messages. - https://api.slack.com/reference/block-kit/blocks + https://docs.slack.dev/reference/block-kit/blocks """ attributes = {"block_id", "type"} block_id_max_length = 255 logger = logging.getLogger(__name__) - def _subtype_warning(self): # skipcq: PYL-R0201 + def _subtype_warning(self): warnings.warn( "subtype is deprecated since slackclient 2.6.0, use type instead", DeprecationWarning, @@ -44,7 +46,7 @@ def subtype(self) -> Optional[str]: def __init__( self, *, - type: Optional[str] = None, # skipcq: PYL-W0622 + type: Optional[str] = None, subtype: Optional[str] = None, # deprecated block_id: Optional[str] = None, ): @@ -60,14 +62,14 @@ def _validate_block_id_length(self): @classmethod def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]: - if block is None: # skipcq: PYL-R1705 + if block is None: return None elif isinstance(block, Block): return block else: if "type" in block: - type = block["type"] # skipcq: PYL-W0622 - if type == SectionBlock.type: # skipcq: PYL-R1705 + type = block["type"] + if type == SectionBlock.type: return SectionBlock(**block) elif type == DividerBlock.type: return DividerBlock(**block) @@ -77,6 +79,8 @@ def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]: return ActionsBlock(**block) elif type == ContextBlock.type: return ContextBlock(**block) + elif type == ContextActionsBlock.type: + return ContextActionsBlock(**block) elif type == InputBlock.type: return InputBlock(**block) elif type == FileBlock.type: @@ -85,6 +89,14 @@ def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]: return CallBlock(**block) elif type == HeaderBlock.type: return HeaderBlock(**block) + elif type == MarkdownBlock.type: + return MarkdownBlock(**block) + elif type == VideoBlock.type: + return VideoBlock(**block) + elif type == RichTextBlock.type: + return RichTextBlock(**block) + elif type == TableBlock.type: + return TableBlock(**block) else: cls.logger.warning(f"Unknown block detected and skipped ({block})") return None @@ -93,10 +105,8 @@ def parse(cls, block: Union[dict, "Block"]) -> Optional["Block"]: return None @classmethod - def parse_all( - cls, blocks: Optional[Sequence[Union[dict, "Block"]]] - ) -> List["Block"]: - return [cls.parse(b) for b in blocks or []] + def parse_all(cls, blocks: Optional[Sequence[Union[dict, "Block"]]]) -> List["Block"]: + return [cls.parse(b) for b in blocks or []] # type: ignore[misc] # ------------------------------------------------- @@ -110,42 +120,64 @@ class SectionBlock(Block): text_max_length = 3000 @property - def attributes(self) -> Set[str]: - return super().attributes.union({"text", "fields", "accessory"}) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"text", "fields", "accessory", "expand"}) def __init__( self, *, block_id: Optional[str] = None, - text: Union[str, dict, TextObject] = None, - fields: Sequence[Union[str, dict, TextObject]] = None, + text: Optional[Union[str, dict, TextObject]] = None, + fields: Optional[Sequence[Union[str, dict, TextObject]]] = None, accessory: Optional[Union[dict, BlockElement]] = None, + expand: Optional[bool] = None, **others: dict, ): """A section is one of the most flexible blocks available. - https://api.slack.com/reference/block-kit/blocks#section + https://docs.slack.dev/reference/block-kit/blocks/section-block + + Args: + block_id (required): A string acting as a unique identifier for a block. + If not specified, one will be generated. + You can use this block_id when you receive an interaction payload to identify the source of the action. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + text (preferred): The text for the block, in the form of a text object. + Maximum length for the text in this field is 3000 characters. + This field is not required if a valid array of fields objects is provided instead. + fields (required if no text is provided): Required if no text is provided. + An array of text objects. Any text objects included with fields will be rendered + in a compact format that allows for 2 columns of side-by-side text. + Maximum number of items is 10. Maximum length for the text in each item is 2000 characters. + accessory: One of the available element objects. + expand: Whether or not this section block's text should always expand when rendered. + If false or not provided, it may be rendered with a 'see more' option to expand and show the full text. + For AI Assistant apps, this allows the app to post long messages without users needing + to click 'see more' to expand the message. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) - self.text = TextObject.parse(text) + self.text = TextObject.parse(text) # type: ignore[arg-type] field_objects = [] for f in fields or []: if isinstance(f, str): field_objects.append(MarkdownTextObject.from_str(f)) elif isinstance(f, TextObject): - field_objects.append(f) + field_objects.append(f) # type: ignore[arg-type] elif isinstance(f, dict) and "type" in f: d = copy.copy(f) t = d.pop("type") if t == MarkdownTextObject.type: field_objects.append(MarkdownTextObject(**d)) else: - field_objects.append(PlainTextObject(**d)) + field_objects.append(PlainTextObject(**d)) # type: ignore[arg-type] else: self.logger.warning(f"Unsupported filed detected and skipped {f}") self.fields = field_objects - self.accessory = BlockElement.parse(accessory) + self.accessory = BlockElement.parse(accessory) # type: ignore[arg-type] + self.expand = expand @JsonValidator("text or fields attribute must be specified") def _validate_text_or_fields_populated(self): @@ -164,10 +196,20 @@ class DividerBlock(Block): type = "divider" def __init__( - self, *, block_id: Optional[str] = None, **others: dict, + self, + *, + block_id: Optional[str] = None, + **others: dict, ): """A content divider, like an
, to split up different blocks inside of a message. - https://api.slack.com/reference/block-kit/blocks#divider + https://docs.slack.dev/reference/block-kit/blocks/divider-block + + Args: + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + You can use this block_id when you receive an interaction payload to identify the source of the action. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) @@ -177,8 +219,8 @@ class ImageBlock(Block): type = "image" @property - def attributes(self) -> Set[str]: - return super().attributes.union({"alt_text", "image_url", "title"}) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"alt_text", "image_url", "title", "slack_file"}) image_url_max_length = 3000 alt_text_max_length = 2000 @@ -187,27 +229,55 @@ def attributes(self) -> Set[str]: def __init__( self, *, - image_url: str, alt_text: str, - title: Optional[Union[str, dict, TextObject]] = None, + image_url: Optional[str] = None, + slack_file: Optional[Union[Dict[str, Any], SlackFile]] = None, + title: Optional[Union[str, dict, PlainTextObject]] = None, block_id: Optional[str] = None, **others: dict, ): """A simple image block, designed to make those cat photos really pop. - https://api.slack.com/reference/block-kit/blocks#image + https://docs.slack.dev/reference/block-kit/blocks/image-block + + Args: + alt_text (required): A plain-text summary of the image. This should not contain any markup. + Maximum length for this field is 2000 characters. + image_url: The URL of the image to be displayed. + Maximum length for this field is 3000 characters. + slack_file: A Slack image file object that defines the source of the image. + title: An optional title for the image in the form of a text object that can only be of type: plain_text. + Maximum length for the text in this field is 2000 characters. + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) self.image_url = image_url self.alt_text = alt_text - self.title = TextObject.parse(title) - - @JsonValidator( - f"image_url attribute cannot exceed {image_url_max_length} characters" - ) + parsed_title = None + if title is not None: + if isinstance(title, str): + parsed_title = PlainTextObject(text=title) + elif isinstance(title, dict): + if title.get("type") != PlainTextObject.type: + raise SlackObjectFormationError(f"Unsupported type for title in an image block: {title.get('type')}") + parsed_title = PlainTextObject(text=title.get("text"), emoji=title.get("emoji")) # type: ignore[arg-type] + elif isinstance(title, PlainTextObject): + parsed_title = title + else: + raise SlackObjectFormationError(f"Unsupported type for title in an image block: {type(title)}") + if slack_file is not None: + self.slack_file = ( + slack_file if slack_file is None or isinstance(slack_file, SlackFile) else SlackFile(**slack_file) + ) + self.title = parsed_title + + @JsonValidator(f"image_url attribute cannot exceed {image_url_max_length} characters") def _validate_image_url_length(self): - return len(self.image_url) <= self.image_url_max_length + return self.image_url is None or len(self.image_url) <= self.image_url_max_length @JsonValidator(f"alt_text attribute cannot exceed {alt_text_max_length} characters") def _validate_alt_text_length(self): @@ -215,19 +285,15 @@ def _validate_alt_text_length(self): @JsonValidator(f"title attribute cannot exceed {title_max_length} characters") def _validate_title_length(self): - return ( - self.title is None - or self.title.text is None - or len(self.title.text) <= self.title_max_length - ) + return self.title is None or self.title.text is None or len(self.title.text) <= self.title_max_length class ActionsBlock(Block): type = "actions" - elements_max_length = 5 + elements_max_length = 25 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"elements"}) def __init__( @@ -238,12 +304,22 @@ def __init__( **others: dict, ): """A block that is used to hold interactive elements. - https://api.slack.com/reference/block-kit/blocks#actions + https://docs.slack.dev/reference/block-kit/blocks/actions-block + + Args: + elements (required): An array of interactive element objects - buttons, select menus, overflow menus, + or date pickers. There is a maximum of 25 elements in each action block. + block_id: A string acting as a unique identifier for a block. + If not specified, a block_id will be generated. + You can use this block_id when you receive an interaction payload to identify the source of the action. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) - self.elements = elements + self.elements = BlockElement.parse_all(elements) @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements") def _validate_elements_length(self): @@ -255,18 +331,25 @@ class ContextBlock(Block): elements_max_length = 10 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"elements"}) def __init__( self, *, - elements: Sequence[Union[dict, ImageBlock, TextObject]], + elements: Sequence[Union[dict, ImageElement, TextObject]], block_id: Optional[str] = None, **others: dict, ): """Displays message context, which can include both images and text. - https://api.slack.com/reference/block-kit/blocks#context + https://docs.slack.dev/reference/block-kit/blocks/context-block + + Args: + elements (required): An array of image elements and text objects. Maximum number of items is 10. + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) @@ -278,16 +361,53 @@ def _validate_elements_length(self): return self.elements is None or len(self.elements) <= self.elements_max_length +class ContextActionsBlock(Block): + type = "context_actions" + elements_max_length = 5 + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, FeedbackButtonsElement, IconButtonElement]], + block_id: Optional[str] = None, + **others: dict, + ): + """Displays actions as contextual info, which can include both feedback buttons and icon buttons. + https://docs.slack.dev/reference/block-kit/blocks/context-actions-block + + Args: + elements (required): An array of feedback_buttons or icon_button block elements. Maximum number of items is 5. + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + """ + super().__init__(type=self.type, block_id=block_id) + show_unknown_key_warning(self, others) + + self.elements = BlockElement.parse_all(elements) + + @JsonValidator("elements attribute must be specified") + def _validate_elements(self): + return self.elements is None or len(self.elements) > 0 + + @JsonValidator(f"elements attribute cannot exceed {elements_max_length} elements") + def _validate_elements_length(self): + return self.elements is None or len(self.elements) <= self.elements_max_length + + class InputBlock(Block): type = "input" label_max_length = 2000 hint_max_length = 2000 @property - def attributes(self) -> Set[str]: - return super().attributes.union( - {"label", "hint", "element", "optional", "dispatch_action"} - ) + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"label", "hint", "element", "optional", "dispatch_action"}) def __init__( self, @@ -302,33 +422,41 @@ def __init__( ): """A block that collects information from users - it can hold a plain-text input element, a select menu element, a multi-select menu element, or a datepicker. - Important Note: Input blocks are only available in modals. - https://api.slack.com/reference/block-kit/blocks#input + https://docs.slack.dev/reference/block-kit/blocks/input-block + + Args: + label (required): A label that appears above an input element in the form of a text object + that must have type of plain_text. Maximum length for the text in this field is 2000 characters. + element (required): An plain-text input element, a checkbox element, a radio button element, + a select menu element, a multi-select menu element, or a datepicker. + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message or view and each iteration of a message or view. + If a message or view is updated, use a new block_id. + hint: An optional hint that appears below an input element in a lighter grey. + It must be a text object with a type of plain_text. + Maximum length for the text in this field is 2000 characters. + dispatch_action: A boolean that indicates whether or not the use of elements in this block + should dispatch a block_actions payload. Defaults to false. + optional: A boolean that indicates whether the input element may be empty when a user submits the modal. + Defaults to false. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) self.label = TextObject.parse(label, default_type=PlainTextObject.type) - self.element = BlockElement.parse(element) - self.hint = TextObject.parse(hint, default_type=PlainTextObject.type) + self.element = BlockElement.parse(element) # type: ignore[arg-type] + self.hint = TextObject.parse(hint, default_type=PlainTextObject.type) # type: ignore[arg-type] self.dispatch_action = dispatch_action self.optional = optional @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") def _validate_label_length(self): - return ( - self.label is None - or self.label.text is None - or len(self.label.text) <= self.label_max_length - ) + return self.label is None or self.label.text is None or len(self.label.text) <= self.label_max_length @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters") def _validate_hint_length(self): - return ( - self.hint is None - or self.hint.text is None - or len(self.hint.text) <= self.label_max_length - ) + return self.hint is None or self.hint.text is None or len(self.hint.text) <= self.label_max_length @JsonValidator( ( @@ -337,16 +465,14 @@ def _validate_hint_length(self): ) ) def _validate_element_type(self): - return self.element is None or isinstance( - self.element, (str, InputInteractiveElement) - ) + return self.element is None or isinstance(self.element, (str, InputInteractiveElement)) class FileBlock(Block): type = "file" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"external_id", "source"}) def __init__( @@ -358,7 +484,15 @@ def __init__( **others: dict, ): """Displays a remote file. - https://api.slack.com/reference/block-kit/blocks#file + https://docs.slack.dev/reference/block-kit/blocks/file-block + + Args: + external_id (required): The external unique ID for this file. + source (required): At the moment, source will always be remote for a remote file. + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) @@ -371,7 +505,7 @@ class CallBlock(Block): type = "call" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"call_id", "api_decoration_available", "call"}) def __init__( @@ -384,7 +518,7 @@ def __init__( **others: dict, ): """Displays a call information - https://api.slack.com/reference/block-kit/blocks#call + https://docs.slack.dev/reference/block-kit/blocks#call """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) @@ -399,23 +533,31 @@ class HeaderBlock(Block): text_max_length = 150 @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"text"}) def __init__( self, *, block_id: Optional[str] = None, - text: Union[str, dict, TextObject] = None, + text: Optional[Union[str, dict, TextObject]] = None, **others: dict, ): """A header is a plain-text block that displays in a larger, bold font. - https://api.slack.com/reference/block-kit/blocks#header + https://docs.slack.dev/reference/block-kit/blocks/header-block + + Args: + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + text (required): The text for the block, in the form of a plain_text text object. + Maximum length for the text in this field is 150 characters. """ super().__init__(type=self.type, block_id=block_id) show_unknown_key_warning(self, others) - self.text = TextObject.parse(text, default_type=PlainTextObject.type) + self.text = TextObject.parse(text, default_type=PlainTextObject.type) # type: ignore[arg-type] @JsonValidator("text attribute must be specified") def _validate_text(self): @@ -424,3 +566,214 @@ def _validate_text(self): @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") def _validate_alt_text_length(self): return self.text is None or len(self.text.text) <= self.text_max_length + + +class MarkdownBlock(Block): + type = "markdown" + text_max_length = 12000 + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"text"}) + + def __init__( + self, + *, + text: str, + block_id: Optional[str] = None, + **others: dict, + ): + """Displays formatted markdown. + https://docs.slack.dev/reference/block-kit/blocks/markdown-block/ + + Args: + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + text (required): The standard markdown-formatted text. Limit 12,000 characters max. + """ + super().__init__(type=self.type, block_id=block_id) + show_unknown_key_warning(self, others) + + self.text = text + + @JsonValidator("text attribute must be specified") + def _validate_text(self): + return self.text != "" + + @JsonValidator(f"text attribute cannot exceed {text_max_length} characters") + def _validate_alt_text_length(self): + return len(self.text) <= self.text_max_length + + +class VideoBlock(Block): + type = "video" + title_max_length = 200 + author_name_max_length = 50 + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union( + { + "alt_text", + "video_url", + "thumbnail_url", + "title", + "title_url", + "description", + "provider_icon_url", + "provider_name", + "author_name", + } + ) + + def __init__( + self, + *, + block_id: Optional[str] = None, + alt_text: Optional[str] = None, + video_url: Optional[str] = None, + thumbnail_url: Optional[str] = None, + title: Optional[Union[str, dict, PlainTextObject]] = None, + title_url: Optional[str] = None, + description: Optional[Union[str, dict, PlainTextObject]] = None, + provider_icon_url: Optional[str] = None, + provider_name: Optional[str] = None, + author_name: Optional[str] = None, + **others: dict, + ): + """A video block is designed to embed videos in all app surfaces + (e.g. link unfurls, messages, modals, App Home) β€” + anywhere you can put blocks! To use the video block within your app, + you must have the links.embed:write scope. + https://docs.slack.dev/reference/block-kit/blocks/video-block + + Args: + block_id: A string acting as a unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + alt_text (required): A tooltip for the video. Required for accessibility + video_url (required): The URL to be embedded. Must match any existing unfurl domains within the app + and point to a HTTPS URL. + thumbnail_url (required): The thumbnail image URL + title (required): Video title in plain text format. Must be less than 200 characters. + title_url: Hyperlink for the title text. Must correspond to the non-embeddable URL for the video. + Must go to an HTTPS URL. + description: Description for video in plain text format. + provider_icon_url: Icon for the video provider - ex. Youtube icon + provider_name: The originating application or domain of the video ex. Youtube + author_name: Author name to be displayed. Must be less than 50 characters. + """ + super().__init__(type=self.type, block_id=block_id) + show_unknown_key_warning(self, others) + + self.alt_text = alt_text + self.video_url = video_url + self.thumbnail_url = thumbnail_url + self.title = TextObject.parse(title, default_type=PlainTextObject.type) # type: ignore[arg-type] + self.title_url = title_url + self.description = TextObject.parse(description, default_type=PlainTextObject.type) # type: ignore[arg-type] + self.provider_icon_url = provider_icon_url + self.provider_name = provider_name + self.author_name = author_name + + @JsonValidator("alt_text attribute must be specified") + def _validate_alt_text(self): + return self.alt_text is not None + + @JsonValidator("video_url attribute must be specified") + def _validate_video_url(self): + return self.video_url is not None + + @JsonValidator("thumbnail_url attribute must be specified") + def _validate_thumbnail_url(self): + return self.thumbnail_url is not None + + @JsonValidator("title attribute must be specified") + def _validate_title(self): + return self.title is not None + + @JsonValidator(f"title attribute cannot exceed {title_max_length} characters") + def _validate_title_length(self): + return self.title is None or len(self.title.text) < self.title_max_length + + @JsonValidator(f"author_name attribute cannot exceed {author_name_max_length} characters") + def _validate_author_name_length(self): + return self.author_name is None or len(self.author_name) < self.author_name_max_length + + +class RichTextBlock(Block): + type = "rich_text" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"elements"}) + + def __init__( + self, + *, + elements: Sequence[Union[dict, RichTextElement]], + block_id: Optional[str] = None, + **others: dict, + ): + """A block that is used to hold interactive elements. + https://docs.slack.dev/reference/block-kit/blocks/rich-text-block + + Args: + elements (required): An array of rich text objects - + rich_text_section, rich_text_list, rich_text_quote, rich_text_preformatted + block_id: A unique identifier for a block. If not specified, one will be generated. + Maximum length for this field is 255 characters. + block_id should be unique for each message or view and each iteration of a message or view. + If a message or view is updated, use a new block_id. + """ + super().__init__(type=self.type, block_id=block_id) + show_unknown_key_warning(self, others) + + self.elements = BlockElement.parse_all(elements) + + +class TableBlock(Block): + type = "table" + + @property + def attributes(self) -> Set[str]: # type: ignore[override] + return super().attributes.union({"rows", "column_settings"}) + + def __init__( + self, + *, + rows: Sequence[Sequence[Dict[str, Any]]], + column_settings: Optional[Sequence[Optional[Dict[str, Any]]]] = None, + block_id: Optional[str] = None, + **others: dict, + ): + """Displays structured information in a table. + https://docs.slack.dev/reference/block-kit/blocks/table-block + + Args: + rows (required): An array consisting of table rows. Maximum 100 rows. + Each row object is an array with a max of 20 table cells. + Table cells can have a type of raw_text or rich_text. + column_settings: An array describing column behavior. If there are fewer items in the column_settings array + than there are columns in the table, then the items in the the column_settings array will describe + the same number of columns in the table as there are in the array itself. + Any additional columns will have the default behavior. Maximum 20 items. + See below for column settings schema. + block_id: A unique identifier for a block. If not specified, a block_id will be generated. + You can use this block_id when you receive an interaction payload to identify the source of the action. + Maximum length for this field is 255 characters. + block_id should be unique for each message and each iteration of a message. + If a message is updated, use a new block_id. + """ + super().__init__(type=self.type, block_id=block_id) + show_unknown_key_warning(self, others) + + self.rows = rows + self.column_settings = column_settings + + @JsonValidator("rows attribute must be specified") + def _validate_rows(self): + return self.rows is not None and len(self.rows) > 0 diff --git a/slack_sdk/models/dialoags.py b/slack_sdk/models/dialoags.py new file mode 100644 index 000000000..1adf7b504 --- /dev/null +++ b/slack_sdk/models/dialoags.py @@ -0,0 +1,29 @@ +from slack_sdk.models.dialogs import AbstractDialogSelector +from slack_sdk.models.dialogs import DialogChannelSelector +from slack_sdk.models.dialogs import DialogConversationSelector +from slack_sdk.models.dialogs import DialogExternalSelector +from slack_sdk.models.dialogs import DialogStaticSelector +from slack_sdk.models.dialogs import DialogTextArea +from slack_sdk.models.dialogs import DialogTextComponent +from slack_sdk.models.dialogs import DialogTextField +from slack_sdk.models.dialogs import DialogUserSelector +from slack_sdk.models.dialogs import TextElementSubtypes +from slack_sdk.models.dialogs import DialogBuilder + +from slack import deprecation + +deprecation.show_message(__name__, "slack_sdk.models.dialogs") + +__all__ = [ + "AbstractDialogSelector", + "DialogChannelSelector", + "DialogConversationSelector", + "DialogExternalSelector", + "DialogStaticSelector", + "DialogTextArea", + "DialogTextComponent", + "DialogTextField", + "DialogUserSelector", + "TextElementSubtypes", + "DialogBuilder", +] diff --git a/slack_sdk/models/dialoags/__init__.py b/slack_sdk/models/dialogs/__init__.py similarity index 88% rename from slack_sdk/models/dialoags/__init__.py rename to slack_sdk/models/dialogs/__init__.py index 88027e9d3..cc67ed37e 100644 --- a/slack_sdk/models/dialoags/__init__.py +++ b/slack_sdk/models/dialogs/__init__.py @@ -63,52 +63,47 @@ def __init__( self.subtype = subtype @JsonValidator(f"name attribute cannot exceed {name_max_length} characters") - def name_length(self): + def name_length(self) -> bool: return len(self.name) < self.name_max_length @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") - def label_length(self): + def label_length(self) -> bool: return len(self.label) < self.label_max_length - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) - def placeholder_length(self): - return ( - self.placeholder is None - or len(self.placeholder) < self.placeholder_max_length - ) + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") + def placeholder_length(self) -> bool: + return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length @JsonValidator(f"hint attribute cannot exceed {hint_max_length} characters") - def hint_length(self): + def hint_length(self) -> bool: return self.hint is None or len(self.hint) < self.hint_max_length @JsonValidator("value attribute exceeded bounds") - def value_length(self): + def value_length(self) -> bool: return self.value is None or len(self.value) < self.max_value_length @JsonValidator("min_length attribute must be greater than or equal to 0") - def min_length_above_zero(self): + def min_length_above_zero(self) -> bool: return self.min_length is None or self.min_length >= 0 @JsonValidator("min_length attribute exceed bounds") - def min_length_length(self): + def min_length_length(self) -> bool: return self.min_length is None or self.min_length <= self.max_value_length @JsonValidator("min_length attribute must be less than max value attribute") - def min_length_below_max_length(self): + def min_length_below_max_length(self) -> bool: return self.min_length is None or self.min_length < self.max_length @JsonValidator("max_length attribute must be greater than or equal to 0") - def max_length_above_zero(self): + def max_length_above_zero(self) -> bool: return self.max_length is None or self.max_length > 0 @JsonValidator("max_length attribute exceeded bounds") - def max_length_length(self): + def max_length_length(self) -> bool: return self.max_length is None or self.max_length <= self.max_value_length @EnumValidator("subtype", TextElementSubtypes) - def subtype_valid(self): + def subtype_valid(self) -> bool: return self.subtype is None or self.subtype in TextElementSubtypes @@ -116,7 +111,7 @@ class DialogTextField(DialogTextComponent): """ Text elements are single-line plain text fields. - https://api.slack.com/dialogs#text_elements + https://docs.slack.dev/legacy/legacy-dialogs/#text_elements """ type = "text" @@ -130,7 +125,7 @@ class DialogTextArea(DialogTextComponent): answer from users. The element UI provides a remaining character count to the max_length you have set or the default, 3000. - https://api.slack.com/dialogs#textarea_elements + https://docs.slack.dev/legacy/legacy-dialogs/#textarea_elements """ type = "textarea" @@ -157,8 +152,8 @@ def __init__( name: str, label: str, optional: bool = False, - value: Union[Option, str] = None, - placeholder: str = None, + value: Optional[Union[Option, str]] = None, + placeholder: Optional[str] = None, ): self.name = name self.label = label @@ -168,27 +163,22 @@ def __init__( self.type = "select" @JsonValidator(f"name attribute cannot exceed {name_max_length} characters") - def name_length(self): + def name_length(self) -> bool: return len(self.name) < self.name_max_length @JsonValidator(f"label attribute cannot exceed {label_max_length} characters") - def label_length(self): + def label_length(self) -> bool: return len(self.label) < self.label_max_length - @JsonValidator( - f"placeholder attribute cannot exceed {placeholder_max_length} characters" - ) - def placeholder_length(self): - return ( - self.placeholder is None - or len(self.placeholder) < self.placeholder_max_length - ) + @JsonValidator(f"placeholder attribute cannot exceed {placeholder_max_length} characters") + def placeholder_length(self) -> bool: + return self.placeholder is None or len(self.placeholder) < self.placeholder_max_length @EnumValidator("data_source", DataSourceTypes) - def data_source_valid(self): + def data_source_valid(self) -> bool: return self.data_source in self.DataSourceTypes - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> dict: json = super().to_dict() if self.data_source == "external": if isinstance(self.value, Option): @@ -209,7 +199,7 @@ class DialogStaticSelector(AbstractDialogSelector): single item from a list. True to web roots, this selection is displayed as a dropdown menu. - https://api.slack.com/dialogs#select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#select_elements """ data_source = "static" @@ -223,8 +213,8 @@ def __init__( label: str, options: Union[Sequence[Option], Sequence[OptionGroup]], optional: bool = False, - value: Union[Option, str] = None, - placeholder: str = None, + value: Optional[Union[Option, str]] = None, + placeholder: Optional[str] = None, ): """ Use the select element for multiple choice selections allowing users to pick @@ -234,7 +224,7 @@ def __init__( A select element may contain up to 100 selections, provided as a list of Option or OptionGroup objects - https://api.slack.com/dialogs#attributes_select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements Args: name: Name of form element. Required. No more than 300 characters. @@ -257,7 +247,7 @@ def __init__( self.options = options @JsonValidator(f"options attribute cannot exceed {options_max_length} items") - def options_length(self): + def options_length(self) -> bool: return len(self.options) < self.options_max_length def to_dict(self) -> dict: @@ -272,14 +262,14 @@ def to_dict(self) -> dict: class DialogUserSelector(AbstractDialogSelector): data_source = "users" - def __init__( # skipcq: PYL-W0235 + def __init__( self, *, name: str, label: str, optional: bool = False, - value: str = None, - placeholder: str = None, + value: Optional[str] = None, + placeholder: Optional[str] = None, ): """ Now you can easily populate a select menu with a list of users. For example, @@ -287,7 +277,7 @@ def __init__( # skipcq: PYL-W0235 assignee. Slack pre-populates the user list in client-side, so your app doesn't need access to a related OAuth scope. - https://api.slack.com/dialogs#dynamic_select_elements_users + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users Args: name: Name of form element. Required. No more than 300 characters. @@ -310,20 +300,20 @@ def __init__( # skipcq: PYL-W0235 class DialogChannelSelector(AbstractDialogSelector): data_source = "channels" - def __init__( # skipcq: PYL-W0235 + def __init__( self, *, name: str, label: str, optional: bool = False, - value: str = None, - placeholder: str = None, + value: Optional[str] = None, + placeholder: Optional[str] = None, ): """ You can also provide a select menu with a list of channels. Specify your data_source as channels to limit only to public channels - https://api.slack.com/dialogs#dynamic_select_elements_channels_conversations + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations Args: name: Name of form element. Required. No more than 300 characters. @@ -346,21 +336,21 @@ def __init__( # skipcq: PYL-W0235 class DialogConversationSelector(AbstractDialogSelector): data_source = "conversations" - def __init__( # skipcq: PYL-W0235 + def __init__( self, *, name: str, label: str, optional: bool = False, - value: str = None, - placeholder: str = None, + value: Optional[str] = None, + placeholder: Optional[str] = None, ): """ You can also provide a select menu with a list of conversations - including private channels, direct messages, MPIMs, and whatever else we consider a conversation-like thing. - https://api.slack.com/dialogs#dynamic_select_elements_channels_conversations + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations Args: name: Name of form element. Required. No more than 300 characters. @@ -384,7 +374,7 @@ class DialogExternalSelector(AbstractDialogSelector): data_source = "external" @property - def attributes(self) -> Set[str]: + def attributes(self) -> Set[str]: # type: ignore[override] return super().attributes.union({"min_query_length"}) def __init__( @@ -395,7 +385,7 @@ def __init__( value: Optional[Option] = None, min_query_length: Optional[int] = None, optional: Optional[bool] = False, - placeholder: str = None, + placeholder: Optional[str] = None, ): """ Use the select element for multiple choice selections allowing users to pick @@ -405,7 +395,7 @@ def __init__( A list of options can be loaded from an external URL and used in your dialog menus. - https://api.slack.com/dialogs#dynamic_select_elements_external + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external Args: name: Name of form element. Required. No more than 300 characters. @@ -424,14 +414,14 @@ def __init__( name=name, label=label, value=value, - optional=optional, + optional=optional, # type: ignore[arg-type] placeholder=placeholder, ) self.min_query_length = min_query_length class DialogBuilder(JsonObject): - attributes = {} # no attributes because to_dict has unique implementation + attributes: Set[str] = set() _callback_id: Optional[str] _elements: List[Union[DialogTextComponent, AbstractDialogSelector]] @@ -532,7 +522,7 @@ def text_field( """ Text elements are single-line plain text fields. - https://api.slack.com/dialogs#attributes_text_elements + https://docs.slack.dev/legacy/legacy-dialogs/#attributes_text_elements Args: name: Name of form element. Required. No more than 300 characters. @@ -587,7 +577,7 @@ def text_area( character count to the max_length you have set or the default, 3000. - https://api.slack.com/dialogs#attributes_textarea_elements + https://docs.slack.dev/legacy/legacy-dialogs/#attributes_textarea_elements Args: name: Name of form element. Required. No more than 300 characters. @@ -640,7 +630,7 @@ def static_selector( A select element may contain up to 100 selections, provided as a list of Option or OptionGroup objects - https://api.slack.com/dialogs#attributes_select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#attributes_select_elements Args: name: Name of form element. Required. No more than 300 characters. @@ -683,7 +673,7 @@ def external_selector( A list of options can be loaded from an external URL and used in your dialog menus. - https://api.slack.com/dialogs#dynamic_select_elements_external + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_external Args: name: Name of form element. Required. No more than 300 characters. @@ -726,7 +716,7 @@ def user_selector( assignee. Slack pre-populates the user list in client-side, so your app doesn't need access to a related OAuth scope. - https://api.slack.com/dialogs#dynamic_select_elements_users + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_users Args: name: Name of form element. Required. No more than 300 characters. @@ -761,7 +751,7 @@ def channel_selector( You can also provide a select menu with a list of channels. Specify your data_source as channels to limit only to public channels - https://api.slack.com/dialogs#dynamic_select_elements_channels_conversations + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations Args: name: Name of form element. Required. No more than 300 characters. @@ -797,7 +787,7 @@ def conversation_selector( private channels, direct messages, MPIMs, and whatever else we consider a conversation-like thing. - https://api.slack.com/dialogs#dynamic_select_elements_channels_conversations + https://docs.slack.dev/legacy/legacy-dialogs/#dynamic_select_elements_channels_conversations Args: name: Name of form element. Required. No more than 300 characters. @@ -820,37 +810,34 @@ def conversation_selector( return self @JsonValidator("title attribute is required") - def title_present(self): + def title_present(self) -> bool: return self._title is not None @JsonValidator(f"title attribute cannot exceed {title_max_length} characters") - def title_length(self): + def title_length(self) -> bool: return self._title is not None and len(self._title) <= self.title_max_length @JsonValidator("callback_id attribute is required") - def callback_id_present(self): + def callback_id_present(self) -> bool: return self._callback_id is not None @JsonValidator(f"dialogs must contain between 1 and {elements_max_length} elements") - def elements_length(self): + def elements_length(self) -> bool: return 0 < len(self._elements) <= self.elements_max_length @JsonValidator(f"submit_label cannot exceed {submit_label_max_length} characters") - def submit_label_length(self): - return ( - self._submit_label is None - or len(self._submit_label) <= self.submit_label_max_length - ) + def submit_label_length(self) -> bool: + return self._submit_label is None or len(self._submit_label) <= self.submit_label_max_length @JsonValidator("submit_label can only be one word") - def submit_label_valid(self): + def submit_label_valid(self) -> bool: return self._submit_label is None or " " not in self._submit_label @JsonValidator(f"state cannot exceed {state_max_length} characters") - def state_length(self): + def state_length(self) -> bool: return not self._state or len(self._state) <= self.state_max_length - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> dict: self.validate_json() json = { "title": self._title, @@ -871,7 +858,7 @@ class ActionStaticSelector(AbstractActionSelector): single item from a list. True to web roots, this selection is displayed as a dropdown menu. - https://api.slack.com/dialogs#select_elements + https://docs.slack.dev/legacy/legacy-dialogs/#select_elements """ data_source = "static" @@ -890,7 +877,7 @@ def __init__( Help users make clear, concise decisions by providing a menu of options within messages. - https://api.slack.com/docs/message-menus + https://docs.slack.dev/legacy/legacy-messaging/legacy-adding-menus-to-messages/ Args: name: Name this specific action. The name will be returned to your @@ -906,7 +893,7 @@ def __init__( self.options = options @JsonValidator(f"options attribute cannot exceed {options_max_length} items") - def options_length(self): + def options_length(self) -> bool: return len(self.options) < self.options_max_length def to_dict(self) -> dict: @@ -916,3 +903,19 @@ def to_dict(self) -> dict: else: json["options"] = extract_json(self.options, "action") return json + + +__all__ = [ + "TextElementSubtypes", + "AbstractDialogSelector", + "DialogChannelSelector", + "DialogConversationSelector", + "DialogExternalSelector", + "DialogStaticSelector", + "DialogTextArea", + "DialogTextComponent", + "DialogTextField", + "DialogUserSelector", + "TextElementSubtypes", + "DialogBuilder", +] diff --git a/slack_sdk/models/messages/__init__.py b/slack_sdk/models/messages/__init__.py index 610624e1c..47d42ddc6 100644 --- a/slack_sdk/models/messages/__init__.py +++ b/slack_sdk/models/messages/__init__.py @@ -7,7 +7,7 @@ class Link(BaseObject): def __init__(self, *, url: str, text: str): """Base class used to generate links in Slack's not-quite Markdown, not quite HTML syntax - https://api.slack.com/reference/surfaces/formatting#linking_to_urls + https://docs.slack.dev/messaging/formatting-message-text/#linking_to_urls """ self.url = url self.text = text @@ -30,7 +30,7 @@ def __init__( link: Optional[str] = None, ): """Text containing a date or time should display that date in the local timezone of the person seeing the text. - https://api.slack.com/reference/surfaces/formatting#date-formatting + https://docs.slack.dev/messaging/formatting-message-text/#date-formatting """ if isinstance(date, datetime): epoch = int(date.timestamp()) @@ -55,7 +55,7 @@ class ObjectLink(Link): def __init__(self, *, object_id: str, text: str = ""): """Convenience class to create links to specific object types - https://api.slack.com/reference/surfaces/formatting#linking-channels + https://docs.slack.dev/messaging/formatting-message-text/#linking-channels """ prefix = self.prefix_mapping.get(object_id[0].upper(), "@") super().__init__(url=f"{prefix}{object_id}", text=text) @@ -64,7 +64,7 @@ def __init__(self, *, object_id: str, text: str = ""): class ChannelLink(Link): def __init__(self): """Represents an @channel link, which notifies everyone present in this channel. - https://api.slack.com/reference/surfaces/formatting + https://docs.slack.dev/messaging/formatting-message-text/ """ super().__init__(url="!channel", text="channel") @@ -72,7 +72,7 @@ def __init__(self): class HereLink(Link): def __init__(self): """Represents an @here link, which notifies all online users of this channel. - https://api.slack.com/reference/surfaces/formatting + https://docs.slack.dev/messaging/formatting-message-text/ """ super().__init__(url="!here", text="here") @@ -80,6 +80,6 @@ def __init__(self): class EveryoneLink(Link): def __init__(self): """Represents an @everyone link, which notifies all users of this workspace. - https://api.slack.com/reference/surfaces/formatting + https://docs.slack.dev/messaging/formatting-message-text/ """ super().__init__(url="!everyone", text="everyone") diff --git a/slack_sdk/models/messages/message.py b/slack_sdk/models/messages/message.py index 01cefc84d..d4744aae7 100644 --- a/slack_sdk/models/messages/message.py +++ b/slack_sdk/models/messages/message.py @@ -1,4 +1,6 @@ import logging +import os +import warnings from typing import Optional, Sequence from slack_sdk.models import extract_json @@ -11,6 +13,11 @@ LOGGER = logging.getLogger(__name__) +skip_warn = os.environ.get("SLACKCLIENT_SKIP_DEPRECATION") # for unit tests etc. +if not skip_warn: + message = "This class is no longer actively maintained. " "Please use a dict object for building message data instead." + warnings.warn(message) + class Message(JsonObject): attributes = {"text"} @@ -28,7 +35,7 @@ def __init__( """ Create a message. - https://api.slack.com/messaging/composing#message-structure + https://docs.slack.dev/messaging/#message-structure Args: text: Plain or Slack Markdown-like text to display in the message. @@ -46,28 +53,24 @@ def __init__( self.blocks = blocks or [] self.markdown = markdown - @JsonValidator( - f"attachments attribute cannot exceed {attachments_max_length} items" - ) + @JsonValidator(f"attachments attribute cannot exceed {attachments_max_length} items") def attachments_length(self): - return ( - self.attachments is None - or len(self.attachments) <= self.attachments_max_length - ) + return self.attachments is None or len(self.attachments) <= self.attachments_max_length - def to_dict(self) -> dict: # skipcq: PYL-W0221 + def to_dict(self) -> dict: json = super().to_dict() if len(self.text) > 40000: - LOGGER.error( - "Messages over 40,000 characters are automatically truncated by Slack" - ) - if self.text and self.blocks: - # Slack doesn't render the text property if there are blocks, so: - LOGGER.info( - "text attribute is treated as fallback text if blocks are attached to " - "a message - insert text as a new SectionBlock if you want it to be " - "displayed " - ) + LOGGER.error("Messages over 40,000 characters are automatically truncated by Slack") + # The following limitation used to be true in the past. + # As of Feb 2021, having both is recommended + # ----------------- + # if self.text and self.blocks: + # # Slack doesn't render the text property if there are blocks, so: + # LOGGER.info(q + # "text attribute is treated as fallback text if blocks are attached to " + # "a message - insert text as a new SectionBlock if you want it to be " + # "displayed " + # ) json["attachments"] = extract_json(self.attachments) json["blocks"] = extract_json(self.blocks) json["mrkdwn"] = self.markdown diff --git a/slack_sdk/models/metadata/__init__.py b/slack_sdk/models/metadata/__init__.py new file mode 100644 index 000000000..7e4918401 --- /dev/null +++ b/slack_sdk/models/metadata/__init__.py @@ -0,0 +1,1255 @@ +from typing import Dict, Any, Union, Optional, List +from slack_sdk.models.basic_objects import JsonObject, EnumValidator + + +class Metadata(JsonObject): + """Message metadata + + https://docs.slack.dev/messaging/message-metadata/ + """ + + attributes = { + "event_type", + "event_payload", + } + + def __init__( + self, + event_type: str, + event_payload: Dict[str, Any], + **kwargs, + ): + self.event_type = event_type + self.event_payload = event_payload + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +# +# Work object entity metadata +# https://docs.slack.dev/messaging/work-objects/ +# + + +"""Entity types""" +EntityType = { + "slack#/entities/task", + "slack#/entities/file", + "slack#/entities/item", + "slack#/entities/incident", + "slack#/entities/content_item", +} + + +"""Custom field types""" +CustomFieldType = { + "integer", + "string", + "array", + "boolean", + "slack#/types/date", + "slack#/types/timestamp", + "slack#/types/image", + "slack#/types/channel_id", + "slack#/types/user", + "slack#/types/entity_ref", + "slack#/types/link", + "slack#/types/email", +} + + +class ExternalRef(JsonObject): + """Reference (and optional type) used to identify an entity within the developer's system""" + + attributes = { + "id", + "type", + } + + def __init__( + self, + id: str, + type: Optional[str] = None, + **kwargs, + ): + self.id = id + self.type = type + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class FileEntitySlackFile(JsonObject): + """Slack file reference for file entities""" + + attributes = { + "id", + "type", + } + + def __init__( + self, + id: str, + type: Optional[str] = None, + **kwargs, + ): + self.id = id + self.type = type + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityIconSlackFile(JsonObject): + """Slack file reference for entity icon""" + + attributes = { + "id", + "url", + } + + def __init__( + self, + id: Optional[str] = None, + url: Optional[str] = None, + **kwargs, + ): + self.id = id + self.url = url + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityIconField(JsonObject): + """Icon field for entity attributes""" + + attributes = { + "alt_text", + "url", + "slack_file", + } + + def __init__( + self, + alt_text: str, + url: Optional[str] = None, + slack_file: Optional[Union[Dict[str, Any], EntityIconSlackFile]] = None, + **kwargs, + ): + self.alt_text = alt_text + self.url = url + self.slack_file = slack_file + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityEditSelectConfig(JsonObject): + """Select configuration for entity edit support""" + + attributes = { + "current_value", + "current_values", + "static_options", + "fetch_options_dynamically", + "min_query_length", + } + + def __init__( + self, + current_value: Optional[str] = None, + current_values: Optional[List[str]] = None, + static_options: Optional[List[Dict[str, Any]]] = None, # Option[] + fetch_options_dynamically: Optional[bool] = None, + min_query_length: Optional[int] = None, + **kwargs, + ): + self.current_value = current_value + self.current_values = current_values + self.static_options = static_options + self.fetch_options_dynamically = fetch_options_dynamically + self.min_query_length = min_query_length + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityEditNumberConfig(JsonObject): + """Number configuration for entity edit support""" + + attributes = { + "is_decimal_allowed", + "min_value", + "max_value", + } + + def __init__( + self, + is_decimal_allowed: Optional[bool] = None, + min_value: Optional[Union[int, float]] = None, + max_value: Optional[Union[int, float]] = None, + **kwargs, + ): + self.is_decimal_allowed = is_decimal_allowed + self.min_value = min_value + self.max_value = max_value + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityEditTextConfig(JsonObject): + """Text configuration for entity edit support""" + + attributes = { + "min_length", + "max_length", + } + + def __init__( + self, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + **kwargs, + ): + self.min_length = min_length + self.max_length = max_length + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityEditSupport(JsonObject): + """Edit support configuration for entity fields""" + + attributes = { + "enabled", + "placeholder", + "hint", + "optional", + "select", + "number", + "text", + } + + def __init__( + self, + enabled: bool, + placeholder: Optional[Dict[str, Any]] = None, # PlainTextElement + hint: Optional[Dict[str, Any]] = None, # PlainTextElement + optional: Optional[bool] = None, + select: Optional[Union[Dict[str, Any], EntityEditSelectConfig]] = None, + number: Optional[Union[Dict[str, Any], EntityEditNumberConfig]] = None, + text: Optional[Union[Dict[str, Any], EntityEditTextConfig]] = None, + **kwargs, + ): + self.enabled = enabled + self.placeholder = placeholder + self.hint = hint + self.optional = optional + self.select = select + self.number = number + self.text = text + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityFullSizePreviewError(JsonObject): + """Error information for full-size preview""" + + attributes = { + "code", + "message", + } + + def __init__( + self, + code: str, + message: Optional[str] = None, + **kwargs, + ): + self.code = code + self.message = message + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityFullSizePreview(JsonObject): + """Full-size preview configuration for entity""" + + attributes = { + "is_supported", + "preview_url", + "mime_type", + "error", + } + + def __init__( + self, + is_supported: bool, + preview_url: Optional[str] = None, + mime_type: Optional[str] = None, + error: Optional[Union[Dict[str, Any], EntityFullSizePreviewError]] = None, + **kwargs, + ): + self.is_supported = is_supported + self.preview_url = preview_url + self.mime_type = mime_type + self.error = error + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityUserIDField(JsonObject): + """User ID field for entity""" + + attributes = { + "user_id", + } + + def __init__( + self, + user_id: str, + **kwargs, + ): + self.user_id = user_id + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityUserField(JsonObject): + """User field for entity""" + + attributes = { + "text", + "url", + "email", + "icon", + } + + def __init__( + self, + text: str, + url: Optional[str] = None, + email: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + **kwargs, + ): + self.text = text + self.url = url + self.email = email + self.icon = icon + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityRefField(JsonObject): + """Entity reference field""" + + attributes = { + "entity_url", + "external_ref", + "title", + "display_type", + "icon", + } + + def __init__( + self, + entity_url: str, + external_ref: Union[Dict[str, Any], ExternalRef], + title: str, + display_type: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + **kwargs, + ): + self.entity_url = entity_url + self.external_ref = external_ref + self.title = title + self.display_type = display_type + self.icon = icon + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityTypedField(JsonObject): + """Typed field for entity with various display options""" + + attributes = { + "type", + "label", + "value", + "link", + "icon", + "long", + "format", + "image_url", + "slack_file", + "alt_text", + "edit", + "tag_color", + "user", + "entity_ref", + } + + def __init__( + self, + type: str, + label: Optional[str] = None, + value: Optional[Union[str, int]] = None, + link: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + long: Optional[bool] = None, + format: Optional[str] = None, + image_url: Optional[str] = None, + slack_file: Optional[Dict[str, Any]] = None, + alt_text: Optional[str] = None, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + tag_color: Optional[str] = None, + user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None, + entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None, + **kwargs, + ): + self.type = type + self.label = label + self.value = value + self.link = link + self.icon = icon + self.long = long + self.format = format + self.image_url = image_url + self.slack_file = slack_file + self.alt_text = alt_text + self.edit = edit + self.tag_color = tag_color + self.user = user + self.entity_ref = entity_ref + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityStringField(JsonObject): + """String field for entity""" + + attributes = { + "value", + "label", + "format", + "link", + "icon", + "long", + "type", + "tag_color", + "edit", + } + + def __init__( + self, + value: str, + label: Optional[str] = None, + format: Optional[str] = None, + link: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + long: Optional[bool] = None, + type: Optional[str] = None, + tag_color: Optional[str] = None, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + **kwargs, + ): + self.value = value + self.label = label + self.format = format + self.link = link + self.icon = icon + self.long = long + self.type = type + self.tag_color = tag_color + self.edit = edit + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityTimestampField(JsonObject): + """Timestamp field for entity""" + + attributes = { + "value", + "label", + "type", + "edit", + } + + def __init__( + self, + value: int, + label: Optional[str] = None, + type: Optional[str] = None, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + **kwargs, + ): + self.value = value + self.label = label + self.type = type + self.edit = edit + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityImageField(JsonObject): + """Image field for entity""" + + attributes = { + "alt_text", + "label", + "image_url", + "slack_file", + "title", + "type", + } + + def __init__( + self, + alt_text: str, + label: Optional[str] = None, + image_url: Optional[str] = None, + slack_file: Optional[Dict[str, Any]] = None, + title: Optional[str] = None, + type: Optional[str] = None, + **kwargs, + ): + self.alt_text = alt_text + self.label = label + self.image_url = image_url + self.slack_file = slack_file + self.title = title + self.type = type + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityBooleanCheckboxField(JsonObject): + """Boolean checkbox properties""" + + attributes = {"type", "text", "description"} + + def __init__( + self, + type: str, + text: str, + description: Optional[str], + **kwargs, + ): + self.type = type + self.text = text + self.description = description + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityBooleanTextField(JsonObject): + """Boolean text properties""" + + attributes = {"type", "true_text", "false_text", "true_description", "false_description"} + + def __init__( + self, + type: str, + true_text: str, + false_text: str, + true_description: Optional[str], + false_description: Optional[str], + **kwargs, + ): + self.type = type + self.true_text = (true_text,) + self.false_text = (false_text,) + self.true_description = (true_description,) + self.false_description = (false_description,) + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityArrayItemField(JsonObject): + """Array item field for entity (similar to EntityTypedField but with optional type)""" + + attributes = { + "type", + "label", + "value", + "link", + "icon", + "long", + "format", + "image_url", + "slack_file", + "alt_text", + "edit", + "tag_color", + "user", + "entity_ref", + } + + def __init__( + self, + type: Optional[str] = None, + label: Optional[str] = None, + value: Optional[Union[str, int]] = None, + link: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + long: Optional[bool] = None, + format: Optional[str] = None, + image_url: Optional[str] = None, + slack_file: Optional[Dict[str, Any]] = None, + alt_text: Optional[str] = None, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + tag_color: Optional[str] = None, + user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None, + entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None, + **kwargs, + ): + self.type = type + self.label = label + self.value = value + self.link = link + self.icon = icon + self.long = long + self.format = format + self.image_url = image_url + self.slack_file = slack_file + self.alt_text = alt_text + self.edit = edit + self.tag_color = tag_color + self.user = user + self.entity_ref = entity_ref + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityCustomField(JsonObject): + """Custom field for entity with flexible types""" + + attributes = { + "label", + "key", + "type", + "value", + "link", + "icon", + "long", + "format", + "image_url", + "slack_file", + "alt_text", + "tag_color", + "edit", + "item_type", + "user", + "entity_ref", + "boolean", + } + + def __init__( + self, + label: str, + key: str, + type: str, + value: Optional[Union[str, int, List[Union[Dict[str, Any], EntityArrayItemField]]]] = None, + link: Optional[str] = None, + icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + long: Optional[bool] = None, + format: Optional[str] = None, + image_url: Optional[str] = None, + slack_file: Optional[Dict[str, Any]] = None, + alt_text: Optional[str] = None, + tag_color: Optional[str] = None, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + item_type: Optional[str] = None, + user: Optional[Union[Dict[str, Any], EntityUserIDField, EntityUserField]] = None, + entity_ref: Optional[Union[Dict[str, Any], EntityRefField]] = None, + boolean: Optional[Union[Dict[str, Any], EntityBooleanCheckboxField, EntityBooleanTextField]] = None, + **kwargs, + ): + self.label = label + self.key = key + self.type = type + self.value = value + self.link = link + self.icon = icon + self.long = long + self.format = format + self.image_url = image_url + self.slack_file = slack_file + self.alt_text = alt_text + self.tag_color = tag_color + self.edit = edit + self.item_type = item_type + self.user = user + self.entity_ref = entity_ref + self.boolean = boolean + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + @EnumValidator("type", CustomFieldType) + def type_valid(self): + return self.type is None or self.type in CustomFieldType + + +class FileEntityFields(JsonObject): + """Fields specific to file entities""" + + attributes = { + "preview", + "created_by", + "date_created", + "date_updated", + "last_modified_by", + "file_size", + "mime_type", + "full_size_preview", + } + + def __init__( + self, + preview: Optional[Union[Dict[str, Any], EntityImageField]] = None, + created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + last_modified_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + file_size: Optional[Union[Dict[str, Any], EntityStringField]] = None, + mime_type: Optional[Union[Dict[str, Any], EntityStringField]] = None, + full_size_preview: Optional[Union[Dict[str, Any], EntityFullSizePreview]] = None, + **kwargs, + ): + self.preview = preview + self.created_by = created_by + self.date_created = date_created + self.date_updated = date_updated + self.last_modified_by = last_modified_by + self.file_size = file_size + self.mime_type = mime_type + self.full_size_preview = full_size_preview + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class TaskEntityFields(JsonObject): + """Fields specific to task entities""" + + attributes = { + "description", + "created_by", + "date_created", + "date_updated", + "assignee", + "status", + "due_date", + "priority", + } + + def __init__( + self, + description: Optional[Union[Dict[str, Any], EntityStringField]] = None, + created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + assignee: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + status: Optional[Union[Dict[str, Any], EntityStringField]] = None, + due_date: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + priority: Optional[Union[Dict[str, Any], EntityStringField]] = None, + **kwargs, + ): + self.description = description + self.created_by = created_by + self.date_created = date_created + self.date_updated = date_updated + self.assignee = assignee + self.status = status + self.due_date = due_date + self.priority = priority + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class IncidentEntityFields(JsonObject): + """Fields specific to incident entities""" + + attributes = { + "status", + "priority", + "urgency", + "created_by", + "assigned_to", + "date_created", + "date_updated", + "description", + "service", + } + + def __init__( + self, + status: Optional[Union[Dict[str, Any], EntityStringField]] = None, + priority: Optional[Union[Dict[str, Any], EntityStringField]] = None, + urgency: Optional[Union[Dict[str, Any], EntityStringField]] = None, + created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + assigned_to: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + description: Optional[Union[Dict[str, Any], EntityStringField]] = None, + service: Optional[Union[Dict[str, Any], EntityStringField]] = None, + **kwargs, + ): + self.status = status + self.priority = priority + self.urgency = urgency + self.created_by = created_by + self.assigned_to = assigned_to + self.date_created = date_created + self.date_updated = date_updated + self.description = description + self.service = service + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class ContentItemEntityFields(JsonObject): + """Fields specific to content item entities""" + + attributes = { + "preview", + "description", + "created_by", + "date_created", + "date_updated", + "last_modified_by", + } + + def __init__( + self, + preview: Optional[Union[Dict[str, Any], EntityImageField]] = None, + description: Optional[Union[Dict[str, Any], EntityStringField]] = None, + created_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + date_created: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + date_updated: Optional[Union[Dict[str, Any], EntityTimestampField]] = None, + last_modified_by: Optional[Union[Dict[str, Any], EntityTypedField]] = None, + **kwargs, + ): + self.preview = preview + self.description = description + self.created_by = created_by + self.date_created = date_created + self.date_updated = date_updated + self.last_modified_by = last_modified_by + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityActionProcessingState(JsonObject): + """Processing state configuration for entity action button""" + + attributes = { + "enabled", + "interstitial_text", + } + + def __init__( + self, + enabled: bool, + interstitial_text: Optional[str] = None, + **kwargs, + ): + self.enabled = enabled + self.interstitial_text = interstitial_text + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityActionButton(JsonObject): + """Action button for entity""" + + attributes = { + "text", + "action_id", + "value", + "style", + "url", + "accessibility_label", + "processing_state", + } + + def __init__( + self, + text: str, + action_id: str, + value: Optional[str] = None, + style: Optional[str] = None, + url: Optional[str] = None, + accessibility_label: Optional[str] = None, + processing_state: Optional[Union[Dict[str, Any], EntityActionProcessingState]] = None, + **kwargs, + ): + self.text = text + self.action_id = action_id + self.value = value + self.style = style + self.url = url + self.accessibility_label = accessibility_label + self.processing_state = processing_state + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityTitle(JsonObject): + """Title for entity attributes""" + + attributes = { + "text", + "edit", + } + + def __init__( + self, + text: str, + edit: Optional[Union[Dict[str, Any], EntityEditSupport]] = None, + **kwargs, + ): + self.text = text + self.edit = edit + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityAttributes(JsonObject): + """Attributes for an entity""" + + attributes = { + "title", + "display_type", + "display_id", + "product_icon", + "product_name", + "locale", + "full_size_preview", + "metadata_last_modified", + } + + def __init__( + self, + title: Union[Dict[str, Any], EntityTitle], + display_type: Optional[str] = None, + display_id: Optional[str] = None, + product_icon: Optional[Union[Dict[str, Any], EntityIconField]] = None, + product_name: Optional[str] = None, + locale: Optional[str] = None, + full_size_preview: Optional[Union[Dict[str, Any], EntityFullSizePreview]] = None, + metadata_last_modified: Optional[int] = None, + **kwargs, + ): + self.title = title + self.display_type = display_type + self.display_id = display_id + self.product_icon = product_icon + self.product_name = product_name + self.locale = locale + self.full_size_preview = full_size_preview + self.metadata_last_modified = metadata_last_modified + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityActions(JsonObject): + """Actions configuration for entity""" + + attributes = { + "primary_actions", + "overflow_actions", + } + + def __init__( + self, + primary_actions: Optional[List[Union[Dict[str, Any], EntityActionButton]]] = None, + overflow_actions: Optional[List[Union[Dict[str, Any], EntityActionButton]]] = None, + **kwargs, + ): + self.primary_actions = primary_actions + self.overflow_actions = overflow_actions + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityPayload(JsonObject): + """Payload schema for an entity""" + + attributes = { + "attributes", + "fields", + "custom_fields", + "slack_file", + "display_order", + "actions", + } + + def __init__( + self, + attributes: Union[Dict[str, Any], EntityAttributes], + fields: Optional[ + Union[Dict[str, Any], ContentItemEntityFields, FileEntityFields, IncidentEntityFields, TaskEntityFields] + ] = None, + custom_fields: Optional[List[Union[Dict[str, Any], EntityCustomField]]] = None, + slack_file: Optional[Union[Dict[str, Any], FileEntitySlackFile]] = None, + display_order: Optional[List[str]] = None, + actions: Optional[Union[Dict[str, Any], EntityActions]] = None, + **kwargs, + ): + # Store entity attributes data with a different internal name to avoid + # shadowing the class-level 'attributes' set used for JSON serialization + self._entity_attributes = attributes + self.fields = fields + self.custom_fields = custom_fields + self.slack_file = slack_file + self.display_order = display_order + self.actions = actions + self.additional_attributes = kwargs + + @property + def entity_attributes(self) -> Union[Dict[str, Any], EntityAttributes]: + """Get the entity attributes data. + + Note: Use this property to access the attributes data. The class-level + 'attributes' is reserved for the JSON serialization schema. + """ + return self._entity_attributes + + @entity_attributes.setter + def entity_attributes(self, value: Union[Dict[str, Any], EntityAttributes]): + """Set the entity attributes data.""" + self._entity_attributes = value + + def get_object_attribute(self, key: str): + if key == "attributes": + return self._entity_attributes + else: + return getattr(self, key, None) + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + +class EntityMetadata(JsonObject): + """Work object entity metadata + + https://docs.slack.dev/messaging/work-objects/ + """ + + attributes = { + "entity_type", + "entity_payload", + "external_ref", + "url", + "app_unfurl_url", + } + + def __init__( + self, + entity_type: str, + entity_payload: Union[Dict[str, Any], EntityPayload], + external_ref: Union[Dict[str, Any], ExternalRef], + url: str, + app_unfurl_url: Optional[str] = None, + **kwargs, + ): + self.entity_type = entity_type + self.entity_payload = entity_payload + self.external_ref = external_ref + self.url = url + self.app_unfurl_url = app_unfurl_url + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() + + @EnumValidator("entity_type", EntityType) + def entity_type_valid(self): + return self.entity_type is None or self.entity_type in EntityType + + +class EventAndEntityMetadata(JsonObject): + """Message metadata with entities + + https://docs.slack.dev/messaging/message-metadata/ + https://docs.slack.dev/messaging/work-objects/ + """ + + attributes = {"event_type", "event_payload", "entities"} + + def __init__( + self, + event_type: Optional[str] = None, + event_payload: Optional[Dict[str, Any]] = None, + entities: Optional[List[Union[Dict[str, Any], EntityMetadata]]] = None, + **kwargs, + ): + self.event_type = event_type + self.event_payload = event_payload + self.entities = entities + self.additional_attributes = kwargs + + def __str__(self): + return str(self.get_non_null_attributes()) + + def __repr__(self): + return self.__str__() diff --git a/slack_sdk/models/views/__init__.py b/slack_sdk/models/views/__init__.py index 8a389475a..915f6eade 100644 --- a/slack_sdk/models/views/__init__.py +++ b/slack_sdk/models/views/__init__.py @@ -9,7 +9,7 @@ class View(JsonObject): """View object for modals and Home tabs. - https://api.slack.com/reference/surfaces/views + https://docs.slack.dev/reference/views/ """ types = ["modal", "home", "workflow_step"] @@ -38,8 +38,8 @@ class View(JsonObject): def __init__( self, # "modal", "home", and "workflow_step" - type: str, # skipcq: PYL-W0622 - id: Optional[str] = None, # skipcq: PYL-W0622 + type: str, + id: Optional[str] = None, callback_id: Optional[str] = None, external_id: Optional[str] = None, team_id: Optional[str] = None, @@ -47,13 +47,13 @@ def __init__( app_id: Optional[str] = None, root_view_id: Optional[str] = None, previous_view_id: Optional[str] = None, - title: Union[str, dict, PlainTextObject] = None, + title: Optional[Union[str, dict, PlainTextObject]] = None, submit: Optional[Union[str, dict, PlainTextObject]] = None, close: Optional[Union[str, dict, PlainTextObject]] = None, blocks: Optional[Sequence[Union[dict, Block]]] = None, private_metadata: Optional[str] = None, state: Optional[Union[dict, "ViewState"]] = None, - hash: Optional[str] = None, # skipcq: PYL-W0622 + hash: Optional[str] = None, clear_on_close: Optional[bool] = None, notify_on_close: Optional[bool] = None, **kwargs, @@ -67,12 +67,14 @@ def __init__( self.app_id = app_id self.root_view_id = root_view_id self.previous_view_id = previous_view_id - self.title = TextObject.parse(title, default_type=PlainTextObject.type) - self.submit = TextObject.parse(submit, default_type=PlainTextObject.type) - self.close = TextObject.parse(close, default_type=PlainTextObject.type) + self.title = TextObject.parse(title, default_type=PlainTextObject.type) # type: ignore[arg-type] + self.submit = TextObject.parse(submit, default_type=PlainTextObject.type) # type: ignore[arg-type] + self.close = TextObject.parse(close, default_type=PlainTextObject.type) # type: ignore[arg-type] self.blocks = Block.parse_all(blocks) self.private_metadata = private_metadata self.state = state + if self.state is not None and isinstance(self.state, dict): + self.state = ViewState(**self.state) self.hash = hash self.clear_on_close = clear_on_close self.notify_on_close = notify_on_close @@ -99,9 +101,7 @@ def _validate_blocks_length(self): @JsonValidator("home view cannot have submit and close") def _validate_home_tab_structure(self): - return self.type != "home" or ( - self.type == "home" and self.close is None and self.submit is None - ) + return self.type != "home" or (self.type == "home" and self.close is None and self.submit is None) @JsonValidator(f"close cannot exceed {close_max_length} characters") def _validate_close_length(self): @@ -109,25 +109,15 @@ def _validate_close_length(self): @JsonValidator(f"submit cannot exceed {submit_max_length} characters") def _validate_submit_length(self): - return self.submit is None or len(self.submit.text) <= int( - self.submit_max_length - ) + return self.submit is None or len(self.submit.text) <= int(self.submit_max_length) - @JsonValidator( - f"private_metadata cannot exceed {private_metadata_max_length} characters" - ) + @JsonValidator(f"private_metadata cannot exceed {private_metadata_max_length} characters") def _validate_private_metadata_max_length(self): - return ( - self.private_metadata is None - or len(self.private_metadata) <= self.private_metadata_max_length - ) + return self.private_metadata is None or len(self.private_metadata) <= self.private_metadata_max_length @JsonValidator(f"callback_id cannot exceed {callback_id_max_length} characters") def _validate_callback_id_max_length(self): - return ( - self.callback_id is None - or len(self.callback_id) <= self.callback_id_max_length - ) + return self.callback_id is None or len(self.callback_id) <= self.callback_id_max_length def __str__(self): return str(self.get_non_null_attributes()) @@ -144,47 +134,45 @@ class ViewState(JsonObject): def _show_warning_about_unknown(cls, value): c = value.__class__ name = ".".join([c.__module__, c.__name__]) - cls.logger.warning( - f"Unknown type for view.state.values detected ({name}) and ViewState skipped to add it" - ) + cls.logger.warning(f"Unknown type for view.state.values detected ({name}) and ViewState skipped to add it") def __init__( - self, *, values: Dict[str, Dict[str, Union[dict, "ViewStateValue"]]], + self, + *, + values: Dict[str, Dict[str, Union[dict, "ViewStateValue"]]], ): value_objects: Dict[str, Dict[str, ViewStateValue]] = {} new_state_values = copy.copy(values) - for block_id, actions in new_state_values.items(): - if actions is None: # skipcq: PYL-R1724 - continue - elif isinstance(actions, dict): - new_actions = copy.copy(actions) - for action_id, v in actions.items(): - if isinstance(v, dict): - d = copy.copy(v) - value_object = ViewStateValue(**d) - elif isinstance(v, ViewStateValue): - value_object = v - else: - self._show_warning_about_unknown(v) - continue - new_actions[action_id] = value_object - value_objects[block_id] = new_actions - else: - self._show_warning_about_unknown(v) + if isinstance(new_state_values, dict): # just in case + for block_id, actions in new_state_values.items(): + if actions is None: + continue + elif isinstance(actions, dict): + new_actions: Dict[str, Union[ViewStateValue, dict]] = copy.copy(actions) + for action_id, v in actions.items(): + if isinstance(v, dict): + d = copy.copy(v) + value_object = ViewStateValue(**d) + elif isinstance(v, ViewStateValue): + value_object = v + else: + self._show_warning_about_unknown(v) + continue + new_actions[action_id] = value_object + value_objects[block_id] = new_actions # type: ignore[assignment] + else: + self._show_warning_about_unknown(v) self.values = value_objects - def to_dict(self, *args) -> Dict[str, Dict[str, Dict[str, dict]]]: # type: ignore + def to_dict(self, *args) -> Dict[str, Dict[str, Dict[str, dict]]]: self.validate_json() - if self.values: # skipcq: PYL-R1705 + if self.values is not None: dict_values: Dict[str, Dict[str, dict]] = {} for block_id, actions in self.values.items(): if actions: - dict_value: Dict[str, dict] = { - action_id: value.to_dict() # type: ignore - for action_id, value in actions.items() # type: ignore - } + dict_value: Dict[str, dict] = {action_id: value.to_dict() for action_id, value in actions.items()} dict_values[block_id] = dict_value - return {"values": dict_values} # type: ignore + return {"values": dict_values} else: return {} @@ -194,6 +182,7 @@ class ViewStateValue(JsonObject): "type", "value", "selected_date", + "selected_time", "selected_conversation", "selected_channel", "selected_user", @@ -207,13 +196,14 @@ class ViewStateValue(JsonObject): def __init__( self, *, - type: Optional[str] = None, # skipcq: PYL-W0622 + type: Optional[str] = None, value: Optional[str] = None, selected_date: Optional[str] = None, + selected_time: Optional[str] = None, selected_conversation: Optional[str] = None, selected_channel: Optional[str] = None, selected_user: Optional[str] = None, - selected_option: Optional[str] = None, + selected_option: Optional[Union[dict, Option]] = None, selected_conversations: Optional[Sequence[str]] = None, selected_channels: Optional[Sequence[str]] = None, selected_users: Optional[Sequence[str]] = None, @@ -222,6 +212,7 @@ def __init__( self.type = type self.value = value self.selected_date = selected_date + self.selected_time = selected_time self.selected_conversation = selected_conversation self.selected_channel = selected_channel self.selected_user = selected_user @@ -229,8 +220,13 @@ def __init__( self.selected_conversations = selected_conversations self.selected_channels = selected_channels self.selected_users = selected_users - if selected_options: - if isinstance(selected_options, dict): - self.selected_options = [Option(**d) for d in selected_options] - else: - self.selected_options = selected_options + + if isinstance(selected_options, list): + self.selected_options = [] + for option in selected_options: + if isinstance(option, Option): + self.selected_options.append(option) + elif isinstance(option, dict): + self.selected_options.append(Option(**option)) + else: + self.selected_options = selected_options # type: ignore[assignment] diff --git a/slack_sdk/oauth/__init__.py b/slack_sdk/oauth/__init__.py index f480716e1..a27b606b0 100644 --- a/slack_sdk/oauth/__init__.py +++ b/slack_sdk/oauth/__init__.py @@ -1,5 +1,20 @@ -from .authorize_url_generator import AuthorizeUrlGenerator # noqa -from .installation_store import InstallationStore # noqa -from .redirect_uri_page_renderer import RedirectUriPageRenderer # noqa -from .state_store import OAuthStateStore # noqa -from .state_utils import OAuthStateUtils # noqa +"""Modules for implementing the Slack OAuth flow + +https://docs.slack.dev/tools/python-slack-sdk/oauth +""" + +from .authorize_url_generator import AuthorizeUrlGenerator +from .authorize_url_generator import OpenIDConnectAuthorizeUrlGenerator +from .installation_store import InstallationStore +from .redirect_uri_page_renderer import RedirectUriPageRenderer +from .state_store import OAuthStateStore +from .state_utils import OAuthStateUtils + +__all__ = [ + "AuthorizeUrlGenerator", + "OpenIDConnectAuthorizeUrlGenerator", + "InstallationStore", + "RedirectUriPageRenderer", + "OAuthStateStore", + "OAuthStateUtils", +] diff --git a/slack_sdk/oauth/authorize_url_generator/__init__.py b/slack_sdk/oauth/authorize_url_generator/__init__.py index 8410205f9..f2617bec6 100644 --- a/slack_sdk/oauth/authorize_url_generator/__init__.py +++ b/slack_sdk/oauth/authorize_url_generator/__init__.py @@ -17,7 +17,7 @@ def __init__( self.user_scopes = user_scopes self.authorization_url = authorization_url - def generate(self, state: str): + def generate(self, state: str, team: Optional[str] = None) -> str: scopes = ",".join(self.scopes) if self.scopes else "" user_scopes = ",".join(self.user_scopes) if self.user_scopes else "" url = ( @@ -29,4 +29,39 @@ def generate(self, state: str): ) if self.redirect_uri is not None: url += f"&redirect_uri={self.redirect_uri}" + if team is not None: + url += f"&team={team}" + return url + + +class OpenIDConnectAuthorizeUrlGenerator: + """Refer to https://openid.net/specs/openid-connect-core-1_0.html""" + + def __init__( + self, + *, + client_id: str, + redirect_uri: str, + scopes: Optional[Sequence[str]] = None, + authorization_url: str = "https://slack.com/openid/connect/authorize", + ): + self.client_id = client_id + self.redirect_uri = redirect_uri + self.scopes = scopes + self.authorization_url = authorization_url + + def generate(self, state: str, nonce: Optional[str] = None, team: Optional[str] = None) -> str: + scopes = ",".join(self.scopes) if self.scopes else "" + url = ( + f"{self.authorization_url}?" + "response_type=code&" + f"state={state}&" + f"client_id={self.client_id}&" + f"scope={scopes}&" + f"redirect_uri={self.redirect_uri}" + ) + if team is not None: + url += f"&team={team}" + if nonce is not None: + url += f"&nonce={nonce}" return url diff --git a/slack_sdk/oauth/installation_store/__init__.py b/slack_sdk/oauth/installation_store/__init__.py index fab59de44..b93ebca5e 100644 --- a/slack_sdk/oauth/installation_store/__init__.py +++ b/slack_sdk/oauth/installation_store/__init__.py @@ -1,3 +1,10 @@ -from .file import FileInstallationStore # noqa -from .installation_store import InstallationStore # noqa -from .models import Bot, Installation # noqa +from .file import FileInstallationStore +from .installation_store import InstallationStore +from .models import Bot, Installation + +__all__ = [ + "FileInstallationStore", + "InstallationStore", + "Bot", + "Installation", +] diff --git a/slack_sdk/oauth/installation_store/amazon_s3/__init__.py b/slack_sdk/oauth/installation_store/amazon_s3/__init__.py index 58a6a6ae4..c5c420f12 100644 --- a/slack_sdk/oauth/installation_store/amazon_s3/__init__.py +++ b/slack_sdk/oauth/installation_store/amazon_s3/__init__.py @@ -3,8 +3,9 @@ from logging import Logger from typing import Optional -from botocore.client import BaseClient +from botocore.client import BaseClient # type: ignore[import-untyped] +from slack_sdk.errors import SlackClientConfigurationError from slack_sdk.oauth.installation_store.async_installation_store import ( AsyncInstallationStore, ) @@ -38,84 +39,103 @@ def logger(self) -> Logger: async def async_save(self, installation: Installation): return self.save(installation) + async def async_save_bot(self, bot: Bot): + return self.save_bot(bot) + def save(self, installation: Installation): none = "none" e_id = installation.enterprise_id or none t_id = installation.team_id or none workspace_path = f"{self.client_id}/{e_id}-{t_id}" + self.save_bot(installation.to_bot()) + if self.historical_data_enabled: history_version: str = str(installation.installed_at) - entity: str = json.dumps(installation.to_bot().__dict__) + + # per workspace + entity: str = json.dumps(installation.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/bot-latest", + Key=f"{workspace_path}/installer-latest", ) self.logger.debug(f"S3 put_object response: {response}") response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/bot-{history_version}", + Key=f"{workspace_path}/installer-{history_version}", ) self.logger.debug(f"S3 put_object response: {response}") - # per workspace - entity: str = json.dumps(installation.__dict__) + # per workspace per user + u_id = installation.user_id or none + entity = json.dumps(installation.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-latest", + Key=f"{workspace_path}/installer-{u_id}-latest", ) self.logger.debug(f"S3 put_object response: {response}") response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-{history_version}", + Key=f"{workspace_path}/installer-{u_id}-{history_version}", ) self.logger.debug(f"S3 put_object response: {response}") - # per workspace per user - u_id = installation.user_id or none - entity: str = json.dumps(installation.__dict__) + else: + # per workspace + entity = json.dumps(installation.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-{u_id}-latest", + Key=f"{workspace_path}/installer-latest", ) self.logger.debug(f"S3 put_object response: {response}") + + # per workspace per user + u_id = installation.user_id or none + entity = json.dumps(installation.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-{u_id}-{history_version}", + Key=f"{workspace_path}/installer-{u_id}-latest", ) self.logger.debug(f"S3 put_object response: {response}") - else: - entity: str = json.dumps(installation.to_bot().__dict__) + def save_bot(self, bot: Bot): + if bot.bot_token is None: + self.logger.debug("Skipped saving a new row because of the absense of bot token in it") + return + + none = "none" + e_id = bot.enterprise_id or none + t_id = bot.team_id or none + workspace_path = f"{self.client_id}/{e_id}-{t_id}" + + if self.historical_data_enabled: + history_version: str = str(bot.installed_at) + entity: str = json.dumps(bot.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, Key=f"{workspace_path}/bot-latest", ) self.logger.debug(f"S3 put_object response: {response}") - - # per workspace - entity: str = json.dumps(installation.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-latest", + Key=f"{workspace_path}/bot-{history_version}", ) self.logger.debug(f"S3 put_object response: {response}") - # per workspace per user - u_id = installation.user_id or none - entity: str = json.dumps(installation.__dict__) + else: + entity = json.dumps(bot.__dict__) response = self.s3_client.put_object( Bucket=self.bucket_name, Body=entity, - Key=f"{workspace_path}/installer-{u_id}-latest", + Key=f"{workspace_path}/bot-latest", ) self.logger.debug(f"S3 put_object response: {response}") @@ -147,13 +167,14 @@ def find_bot( workspace_path = f"{self.client_id}/{e_id}-{t_id}" try: fetch_response = self.s3_client.get_object( - Bucket=self.bucket_name, Key=f"{workspace_path}/bot-latest", + Bucket=self.bucket_name, + Key=f"{workspace_path}/bot-latest", ) self.logger.debug(f"S3 get_object response: {fetch_response}") body = fetch_response["Body"].read().decode("utf-8") data = json.loads(body) return Bot(**data) - except Exception as e: # skipcq: PYL-W0703 + except Exception as e: message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" self.logger.warning(message) return None @@ -188,19 +209,143 @@ def find_installation( t_id = none workspace_path = f"{self.client_id}/{e_id}-{t_id}" try: - key = ( - f"{workspace_path}/installer-{user_id}-latest" - if user_id - else f"{workspace_path}/installer-latest" - ) + key = f"{workspace_path}/installer-{user_id}-latest" if user_id else f"{workspace_path}/installer-latest" fetch_response = self.s3_client.get_object( - Bucket=self.bucket_name, Key=key, + Bucket=self.bucket_name, + Key=key, ) self.logger.debug(f"S3 get_object response: {fetch_response}") body = fetch_response["Body"].read().decode("utf-8") data = json.loads(body) - return Installation(**data) - except Exception as e: # skipcq: PYL-W0703 + installation = Installation(**data) + + 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 = self.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.bot_token != latest_bot_installation.bot_token: + # NOTE: this logic is based on the assumption that every single installation has bot scopes + # If you need to installation patterns without bot scopes in the same S3 bucket, + # please fork this code and implement your own logic. + 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 + + except Exception as e: message = f"Failed to find an installation data for enterprise: {e_id}, team: {t_id}: {e}" self.logger.warning(message) return None + + async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + return self.delete_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + none = "none" + e_id = enterprise_id or none + t_id = team_id or none + workspace_path = f"{self.client_id}/{e_id}-{t_id}" + objects = self.s3_client.list_objects( + Bucket=self.bucket_name, + Prefix=f"{workspace_path}/bot-", + ) + for content in objects.get("Contents", []): + key = content.get("Key") + if key is not None: + self.logger.info(f"Going to delete bot installation ({key})") + try: + self.s3_client.delete_object( + Bucket=self.bucket_name, + Key=content.get("Key"), + ) + except Exception as e: + message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" + raise SlackClientConfigurationError(message) + + async def async_delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + return self.delete_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + ) + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + none = "none" + e_id = enterprise_id or none + t_id = team_id or none + workspace_path = f"{self.client_id}/{e_id}-{t_id}" + objects = self.s3_client.list_objects( + Bucket=self.bucket_name, + Prefix=f"{workspace_path}/installer-{user_id or ''}", + ) + deleted_keys = [] + for content in objects.get("Contents", []): + key = content.get("Key") + if key is not None: + self.logger.info(f"Going to delete installation ({key})") + try: + self.s3_client.delete_object( + Bucket=self.bucket_name, + Key=key, + ) + deleted_keys.append(key) + except Exception as e: + message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" + raise SlackClientConfigurationError(message) + + try: + no_user_id_key = key.replace(f"-{user_id}", "") + if not no_user_id_key.endswith("installer-latest"): + self.s3_client.delete_object( + Bucket=self.bucket_name, + Key=no_user_id_key, + ) + deleted_keys.append(no_user_id_key) + except Exception as e: + message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" + raise SlackClientConfigurationError(message) + + # Check the remaining installation data + objects = self.s3_client.list_objects( + Bucket=self.bucket_name, + Prefix=f"{workspace_path}/installer-", + MaxKeys=10, # the small number would be enough for this purpose + ) + keys = [c.get("Key") for c in objects.get("Contents", []) if c.get("Key") not in deleted_keys] + # If only installer-latest remains, we should delete the one as well + if len(keys) == 1 and keys[0].endswith("installer-latest"): + content = objects.get("Contents", [])[0] + try: + self.s3_client.delete_object( + Bucket=self.bucket_name, + Key=content.get("Key"), + ) + except Exception as e: + message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" + raise SlackClientConfigurationError(message) diff --git a/slack_sdk/oauth/installation_store/async_cacheable_installation_store.py b/slack_sdk/oauth/installation_store/async_cacheable_installation_store.py index 87fba9312..935d24fe4 100644 --- a/slack_sdk/oauth/installation_store/async_cacheable_installation_store.py +++ b/slack_sdk/oauth/installation_store/async_cacheable_installation_store.py @@ -15,7 +15,8 @@ class AsyncCacheableInstallationStore(AsyncInstallationStore): def __init__(self, installation_store: AsyncInstallationStore): """A simple memory cache wrapper for any installation stores. - :param installation_store: the installation store to wrap + Args: + installation_store: The installation store to wrap """ self.underlying = installation_store self.cached_bots = {} @@ -26,8 +27,22 @@ 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, *, @@ -37,7 +52,7 @@ async def async_find_bot( ) -> Optional[Bot]: if is_enterprise_install or team_id is None: team_id = "" - key = f"{enterprise_id}-{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( @@ -59,7 +74,7 @@ async def async_find_installation( ) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = "" - key = f"{enterprise_id}-{team_id}-{user_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( @@ -71,3 +86,51 @@ async def async_find_installation( if installation: self.cached_installations[key] = installation return installation + + async def async_delete_bot( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ) -> None: + await self.underlying.async_delete_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + key = f"{enterprise_id or ''}-{team_id or ''}" + self.cached_bots.pop(key) + + async def async_delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + await self.underlying.async_delete_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + ) + key_prefix = f"{enterprise_id or ''}-{team_id or ''}" + for key in list(self.cached_installations.keys()): + if key.startswith(key_prefix): + self.cached_installations.pop(key) + + async def async_delete_all( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ): + await self.underlying.async_delete_all( + enterprise_id=enterprise_id, + team_id=team_id, + ) + key_prefix = f"{enterprise_id or ''}-{team_id or ''}" + for key in list(self.cached_bots.keys()): + if key.startswith(key_prefix): + self.cached_bots.pop(key) + for key in list(self.cached_installations.keys()): + if key.startswith(key_prefix): + self.cached_installations.pop(key) diff --git a/slack_sdk/oauth/installation_store/async_installation_store.py b/slack_sdk/oauth/installation_store/async_installation_store.py index a19af86a2..f8b76b860 100644 --- a/slack_sdk/oauth/installation_store/async_installation_store.py +++ b/slack_sdk/oauth/installation_store/async_installation_store.py @@ -6,11 +6,37 @@ class AsyncInstallationStore: + """The installation store interface for asyncio-based apps. + + The minimum required methods are: + + * async_save(installation) + * async_find_installation(enterprise_id, team_id, user_id, is_enterprise_install) + + If you would like to properly handle app uninstallations and token revocations, + the following methods should be implemented. + + * async_delete_installation(enterprise_id, team_id, user_id) + * async_delete_all(enterprise_id, team_id) + + If your app needs only bot scope installations, the simpler way to implement would be: + + * async_save(installation) + * async_find_bot(enterprise_id, team_id, is_enterprise_install) + * async_delete_bot(enterprise_id, team_id) + * async_delete_all(enterprise_id, team_id) + """ + @property def logger(self) -> Logger: raise NotImplementedError() async def async_save(self, installation: Installation): + """Saves an installation data""" + raise NotImplementedError() + + async def async_save_bot(self, bot: Bot): + """Saves a bot installation data""" raise NotImplementedError() async def async_find_bot( @@ -20,6 +46,7 @@ async def async_find_bot( team_id: Optional[str], is_enterprise_install: Optional[bool] = False, ) -> Optional[Bot]: + """Finds a bot scope installation per workspace / org""" raise NotImplementedError() async def async_find_installation( @@ -30,4 +57,36 @@ async def async_find_installation( 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() + + async def async_delete_bot( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ) -> None: + """Deletes a bot scope installation per workspace / org""" + raise NotImplementedError() + + async def async_delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + """Deletes an installation that matches the given IDs""" + raise NotImplementedError() + + async def async_delete_all( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ): + """Deletes all installation data for the given workspace / org""" + await self.async_delete_bot(enterprise_id=enterprise_id, team_id=team_id) + await self.async_delete_installation(enterprise_id=enterprise_id, team_id=team_id) diff --git a/slack_sdk/oauth/installation_store/cacheable_installation_store.py b/slack_sdk/oauth/installation_store/cacheable_installation_store.py index 22525d653..2455779dd 100644 --- a/slack_sdk/oauth/installation_store/cacheable_installation_store.py +++ b/slack_sdk/oauth/installation_store/cacheable_installation_store.py @@ -13,7 +13,8 @@ class CacheableInstallationStore(InstallationStore): def __init__(self, installation_store: InstallationStore): """A simple memory cache wrapper for any installation stores. - :param installation_store: the installation store to wrap + Args: + installation_store: The installation store to wrap """ self.underlying = installation_store self.cached_bots = {} @@ -24,8 +25,23 @@ def logger(self) -> Logger: return self.underlying.logger def 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 self.underlying.save(installation) + def 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 self.underlying.save_bot(bot) + def find_bot( self, *, @@ -35,7 +51,7 @@ def find_bot( ) -> Optional[Bot]: if is_enterprise_install or team_id is None: team_id = "" - key = f"{enterprise_id}-{team_id}" + key = f"{enterprise_id or ''}-{team_id or ''}" if key in self.cached_bots: return self.cached_bots[key] bot = self.underlying.find_bot( @@ -57,7 +73,7 @@ def find_installation( ) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = "" - key = f"{enterprise_id}-{team_id}={user_id}" + key = f"{enterprise_id or ''}-{team_id or ''}-{user_id or ''}" if key in self.cached_installations: return self.cached_installations[key] installation = self.underlying.find_installation( @@ -69,3 +85,52 @@ def find_installation( if installation: self.cached_installations[key] = installation return installation + + def delete_bot( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ) -> None: + self.underlying.delete_bot( + enterprise_id=enterprise_id, + team_id=team_id, + ) + key = f"{enterprise_id or ''}-{team_id or ''}" + if key in self.cached_bots: + self.cached_bots.pop(key) + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + self.underlying.delete_installation( + enterprise_id=enterprise_id, + team_id=team_id, + user_id=user_id, + ) + key_prefix = f"{enterprise_id or ''}-{team_id or ''}" + for key in list(self.cached_installations.keys()): + if key.startswith(key_prefix): + self.cached_installations.pop(key) + + def delete_all( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ): + self.underlying.delete_all( + enterprise_id=enterprise_id, + team_id=team_id, + ) + key_prefix = f"{enterprise_id or ''}-{team_id or ''}" + for key in list(self.cached_bots.keys()): + if key.startswith(key_prefix): + self.cached_bots.pop(key) + for key in list(self.cached_installations.keys()): + if key.startswith(key_prefix): + self.cached_installations.pop(key) diff --git a/slack_sdk/oauth/installation_store/file/__init__.py b/slack_sdk/oauth/installation_store/file/__init__.py index f51f46ada..e178048b4 100644 --- a/slack_sdk/oauth/installation_store/file/__init__.py +++ b/slack_sdk/oauth/installation_store/file/__init__.py @@ -1,5 +1,7 @@ +import glob import json import logging +import os from logging import Logger from pathlib import Path from typing import Optional, Union @@ -37,6 +39,9 @@ def logger(self) -> Logger: async def async_save(self, installation: Installation): return self.save(installation) + async def async_save_bot(self, bot: Bot): + return self.save_bot(bot) + def save(self, installation: Installation): none = "none" e_id = installation.enterprise_id or none @@ -44,15 +49,11 @@ def save(self, installation: Installation): team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}" self._mkdir(team_installation_dir) + self.save_bot(installation.to_bot()) + if self.historical_data_enabled: history_version: str = str(installation.installed_at) - entity: str = json.dumps(installation.to_bot().__dict__) - with open(f"{team_installation_dir}/bot-latest", "w") as f: - f.write(entity) - with open(f"{team_installation_dir}/bot-{history_version}", "w") as f: - f.write(entity) - # per workspace entity: str = json.dumps(installation.__dict__) with open(f"{team_installation_dir}/installer-latest", "w") as f: @@ -62,23 +63,41 @@ def save(self, installation: Installation): # per workspace per user u_id = installation.user_id or none - entity: str = json.dumps(installation.__dict__) + entity = json.dumps(installation.__dict__) with open(f"{team_installation_dir}/installer-{u_id}-latest", "w") as f: f.write(entity) - with open( - f"{team_installation_dir}/installer-{u_id}-{history_version}", "w" - ) as f: + with open(f"{team_installation_dir}/installer-{u_id}-{history_version}", "w") as f: f.write(entity) else: - with open(f"{team_installation_dir}/bot-latest", "w") as f: - entity: str = json.dumps(installation.to_bot().__dict__) - f.write(entity) - u_id = installation.user_id or none installer_filepath = f"{team_installation_dir}/installer-{u_id}-latest" with open(installer_filepath, "w") as f: - entity: str = json.dumps(installation.__dict__) + entity = json.dumps(installation.__dict__) + f.write(entity) + + def save_bot(self, bot: Bot): + if bot.bot_token is None: + self.logger.debug("Skipped saving a new row because of the absense of bot token in it") + return + + none = "none" + e_id = bot.enterprise_id or none + t_id = bot.team_id or none + team_installation_dir = f"{self.base_dir}/{e_id}-{t_id}" + self._mkdir(team_installation_dir) + + if self.historical_data_enabled: + history_version: str = str(bot.installed_at) + + entity: str = json.dumps(bot.__dict__) + with open(f"{team_installation_dir}/bot-latest", "w") as f: + f.write(entity) + with open(f"{team_installation_dir}/bot-{history_version}", "w") as f: + f.write(entity) + else: + with open(f"{team_installation_dir}/bot-latest", "w") as f: + entity = json.dumps(bot.__dict__) f.write(entity) async def async_find_bot( @@ -112,8 +131,8 @@ def find_bot( data = json.loads(f.read()) return Bot(**data) except FileNotFoundError as e: - message = f"Failed to find bot installation data for enterprise: {e_id}, team: {t_id}: {e}" - self.logger.warning(message) + message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" + self.logger.debug(message) return None async def async_find_installation( @@ -146,19 +165,86 @@ def find_installation( t_id = none installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-latest" if user_id is not None: - installation_filepath = ( - f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest" - ) + installation_filepath = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-latest" try: + installation: Optional[Installation] = None with open(installation_filepath) as f: data = json.loads(f.read()) - return Installation(**data) + installation = Installation(**data) + + 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 = self.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.bot_token != latest_bot_installation.bot_token: + # NOTE: this logic is based on the assumption that every single installation has bot scopes + # If you need to installation patterns without bot scopes in the same S3 bucket, + # please fork this code and implement your own logic. + 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 + except FileNotFoundError as e: - message = f"Failed to find an installation data for enterprise: {e_id}, team: {t_id}: {e}" - self.logger.warning(message) + message = f"Installation data missing for enterprise: {e_id}, team: {t_id}: {e}" + self.logger.debug(message) return None + async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + return self.delete_bot(enterprise_id=enterprise_id, team_id=team_id) + + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + none = "none" + e_id = enterprise_id or none + t_id = team_id or none + filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/bot-*" + self._delete_by_glob(e_id, t_id, filepath_glob) + + async def async_delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + return self.delete_installation(enterprise_id=enterprise_id, team_id=team_id, user_id=user_id) + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + none = "none" + e_id = enterprise_id or none + t_id = team_id or none + if user_id is not None: + filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-{user_id}-*" + else: + filepath_glob = f"{self.base_dir}/{e_id}-{t_id}/installer-*" + self._delete_by_glob(e_id, t_id, filepath_glob) + + def _delete_by_glob(self, e_id: str, t_id: str, filepath_glob: str): + for filepath in glob.glob(filepath_glob): + try: + os.remove(filepath) + except FileNotFoundError as e: + message = f"Failed to delete installation data for enterprise: {e_id}, team: {t_id}: {e}" + self.logger.warning(message) + @staticmethod def _mkdir(path: Union[str, Path]): if isinstance(path, str): diff --git a/slack_sdk/oauth/installation_store/installation_store.py b/slack_sdk/oauth/installation_store/installation_store.py index ffa9b260a..8143d2fb7 100644 --- a/slack_sdk/oauth/installation_store/installation_store.py +++ b/slack_sdk/oauth/installation_store/installation_store.py @@ -1,3 +1,8 @@ +"""Slack installation data store + +Refer to https://docs.slack.dev/tools/python-slack-sdk/oauth for details. +""" + from logging import Logger from typing import Optional @@ -6,11 +11,37 @@ class InstallationStore: + """The installation store interface. + + The minimum required methods are: + + * save(installation) + * find_installation(enterprise_id, team_id, user_id, is_enterprise_install) + + If you would like to properly handle app uninstallations and token revocations, + the following methods should be implemented. + + * delete_installation(enterprise_id, team_id, user_id) + * delete_all(enterprise_id, team_id) + + If your app needs only bot scope installations, the simpler way to implement would be: + + * save(installation) + * find_bot(enterprise_id, team_id, is_enterprise_install) + * delete_bot(enterprise_id, team_id) + * delete_all(enterprise_id, team_id) + """ + @property def logger(self) -> Logger: raise NotImplementedError() def save(self, installation: Installation): + """Saves an installation data""" + raise NotImplementedError() + + def save_bot(self, bot: Bot): + """Saves a bot installation data""" raise NotImplementedError() def find_bot( @@ -20,6 +51,7 @@ def find_bot( team_id: Optional[str], is_enterprise_install: Optional[bool] = False, ) -> Optional[Bot]: + """Finds a bot scope installation per workspace / org""" raise NotImplementedError() def find_installation( @@ -30,4 +62,36 @@ def find_installation( 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() + + def delete_bot( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ) -> None: + """Deletes a bot scope installation per workspace / org""" + raise NotImplementedError() + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + """Deletes an installation that matches the given IDs""" + raise NotImplementedError() + + def delete_all( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ): + """Deletes all installation data for the given workspace / org""" + self.delete_bot(enterprise_id=enterprise_id, team_id=team_id) + self.delete_installation(enterprise_id=enterprise_id, team_id=team_id) diff --git a/slack_sdk/oauth/installation_store/internals.py b/slack_sdk/oauth/installation_store/internals.py new file mode 100644 index 000000000..52eeeb98b --- /dev/null +++ b/slack_sdk/oauth/installation_store/internals.py @@ -0,0 +1,40 @@ +from datetime import datetime +from typing import Type, TypeVar, Union + + +def _from_iso_format_to_datetime(iso_datetime_str: str) -> datetime: + if "+" not in iso_datetime_str: + iso_datetime_str += "+00:00" + return datetime.fromisoformat(iso_datetime_str) + + +def _from_iso_format_to_unix_timestamp(iso_datetime_str: str) -> float: + return _from_iso_format_to_datetime(iso_datetime_str).timestamp() + + +TimestampType = TypeVar("TimestampType", float, int) + + +def _timestamp_to_type(ts: Union[TimestampType, datetime, str], target_type: Type[TimestampType]) -> TimestampType: + result: TimestampType + + if isinstance(ts, target_type): + # unnecessary type casting makes pytype happy + result = target_type(ts) + + # although a type of the timestamp is just checked, + # pytype doesn't consider the following line valid: + # result = ts + # see https://github.com/google/pytype/issues/1012 + + elif isinstance(ts, datetime): + result = target_type(ts.timestamp()) + elif isinstance(ts, str): + try: + result = target_type(ts) + except ValueError: + result = target_type(_from_iso_format_to_unix_timestamp(ts)) + else: + raise ValueError(f"Unsupported data format for timestamp {ts}") + + return result diff --git a/slack_sdk/oauth/installation_store/models/__init__.py b/slack_sdk/oauth/installation_store/models/__init__.py index ef1b7b864..d65b1474c 100644 --- a/slack_sdk/oauth/installation_store/models/__init__.py +++ b/slack_sdk/oauth/installation_store/models/__init__.py @@ -1,2 +1,7 @@ -from .bot import Bot # noqa -from .installation import Installation # noqa +from .bot import Bot +from .installation import Installation + +__all__ = [ + "Bot", + "Installation", +] diff --git a/slack_sdk/oauth/installation_store/models/bot.py b/slack_sdk/oauth/installation_store/models/bot.py index 7a54e036e..3f2f6de81 100644 --- a/slack_sdk/oauth/installation_store/models/bot.py +++ b/slack_sdk/oauth/installation_store/models/bot.py @@ -1,6 +1,9 @@ -from datetime import datetime +from datetime import datetime, timezone +from time import time from typing import Optional, Union, Dict, Any, Sequence +from slack_sdk.oauth.installation_store.internals import _timestamp_to_type + class Bot: app_id: Optional[str] @@ -12,9 +15,15 @@ class Bot: bot_id: str bot_user_id: str bot_scopes: Sequence[str] + # only when token rotation is enabled + bot_refresh_token: Optional[str] + # only when token rotation is enabled + bot_token_expires_at: Optional[int] is_enterprise_install: bool installed_at: float + custom_values: Dict[str, Any] + def __init__( self, *, @@ -29,9 +38,20 @@ def __init__( bot_id: str, bot_user_id: str, bot_scopes: Union[str, Sequence[str]] = "", + # only when token rotation is enabled + bot_refresh_token: Optional[str] = None, + # only when token rotation is enabled + bot_token_expires_in: Optional[int] = None, + # only for duplicating this object + # only when token rotation is enabled + bot_token_expires_at: Optional[Union[int, datetime, str]] = None, is_enterprise_install: Optional[bool] = False, # timestamps - installed_at: float, + # The expected value type is float but the internals handle other types too + # for str values, we support only ISO datetime format. + installed_at: Union[float, datetime, str], + # custom values + custom_values: Optional[Dict[str, Any]] = None, ): self.app_id = app_id self.enterprise_id = enterprise_id @@ -46,10 +66,28 @@ def __init__( 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: + 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.is_enterprise_install = is_enterprise_install or False - self.installed_at = installed_at - def to_dict(self) -> Dict[str, Any]: + 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, @@ -60,6 +98,20 @@ def to_dict(self) -> Dict[str, Any]: "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.utcfromtimestamp(self.installed_at), + "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()} diff --git a/slack_sdk/oauth/installation_store/models/installation.py b/slack_sdk/oauth/installation_store/models/installation.py index da5cb8b7f..18ca8e0b1 100644 --- a/slack_sdk/oauth/installation_store/models/installation.py +++ b/slack_sdk/oauth/installation_store/models/installation.py @@ -1,7 +1,8 @@ -from datetime import datetime +from datetime import datetime, timezone from time import time from typing import Optional, Union, Dict, Any, Sequence +from slack_sdk.oauth.installation_store.internals import _timestamp_to_type from slack_sdk.oauth.installation_store.models.bot import Bot @@ -16,9 +17,16 @@ class Installation: bot_id: Optional[str] bot_user_id: Optional[str] bot_scopes: Optional[Sequence[str]] + bot_refresh_token: Optional[str] # only when token rotation is enabled + # only when token rotation is enabled + # Unix time (seconds): only when token rotation is enabled + bot_token_expires_at: Optional[int] user_id: str user_token: Optional[str] user_scopes: Optional[Sequence[str]] + user_refresh_token: Optional[str] # only when token rotation is enabled + # Unix time (seconds): only when token rotation is enabled + user_token_expires_at: Optional[int] incoming_webhook_url: Optional[str] incoming_webhook_channel: Optional[str] incoming_webhook_channel_id: Optional[str] @@ -27,6 +35,8 @@ class Installation: token_type: Optional[str] installed_at: float + custom_values: Dict[str, Any] + def __init__( self, *, @@ -42,10 +52,22 @@ def __init__( bot_id: Optional[str] = None, bot_user_id: Optional[str] = None, bot_scopes: Union[str, Sequence[str]] = "", + bot_refresh_token: Optional[str] = None, # only when token rotation is enabled + # only when token rotation is enabled + bot_token_expires_in: Optional[int] = None, + # only for duplicating this object + # only when token rotation is enabled + bot_token_expires_at: Optional[Union[int, datetime, str]] = None, # installer user_id: str, user_token: Optional[str] = None, user_scopes: Union[str, Sequence[str]] = "", + user_refresh_token: Optional[str] = None, # only when token rotation is enabled + # only when token rotation is enabled + user_token_expires_in: Optional[int] = None, + # only for duplicating this object + # only when token rotation is enabled + user_token_expires_at: Optional[Union[int, datetime, str]] = None, # incoming webhook incoming_webhook_url: Optional[str] = None, incoming_webhook_channel: Optional[str] = None, @@ -55,7 +77,11 @@ def __init__( is_enterprise_install: Optional[bool] = False, token_type: Optional[str] = None, # timestamps - installed_at: Optional[float] = None, + # The expected value type is float but the internals handle other types too + # for str values, we supports only ISO datetime format. + installed_at: Optional[Union[float, datetime, str]] = None, + # custom values + custom_values: Optional[Dict[str, Any]] = None, ): self.app_id = app_id self.enterprise_id = enterprise_id @@ -70,6 +96,14 @@ def __init__( 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: + 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 @@ -77,6 +111,14 @@ def __init__( 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: + 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 @@ -86,7 +128,12 @@ def __init__( self.is_enterprise_install = is_enterprise_install or False self.token_type = token_type - self.installed_at = time() if installed_at is None else installed_at + if installed_at is None: + self.installed_at = datetime.now().timestamp() + else: + self.installed_at = _timestamp_to_type(installed_at, float) + + self.custom_values = custom_values if custom_values is not None else {} def to_bot(self) -> Bot: return Bot( @@ -95,15 +142,24 @@ def to_bot(self) -> Bot: 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_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, ) - def to_dict(self) -> Dict[str, Any]: + 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, @@ -115,14 +171,34 @@ def to_dict(self) -> Dict[str, Any]: "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 + ), "user_id": self.user_id, "user_token": self.user_token, "user_scopes": ",".join(self.user_scopes) if self.user_scopes else None, + "user_refresh_token": self.user_refresh_token, + "user_token_expires_at": ( + datetime.fromtimestamp(self.user_token_expires_at, tz=timezone.utc) + if self.user_token_expires_at is not None + else None + ), "incoming_webhook_url": self.incoming_webhook_url, "incoming_webhook_channel": self.incoming_webhook_channel, "incoming_webhook_channel_id": self.incoming_webhook_channel_id, "incoming_webhook_configuration_url": self.incoming_webhook_configuration_url, "is_enterprise_install": self.is_enterprise_install, "token_type": self.token_type, - "installed_at": datetime.utcfromtimestamp(self.installed_at), + "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()} diff --git a/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py b/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py index d4d9a2cc1..f629deead 100644 --- a/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py +++ b/slack_sdk/oauth/installation_store/sqlalchemy/__init__.py @@ -16,10 +16,13 @@ ) from sqlalchemy.engine import Engine from sqlalchemy.sql.sqltypes import Boolean - +from sqlalchemy.ext.asyncio import AsyncEngine from slack_sdk.oauth.installation_store.installation_store import InstallationStore from slack_sdk.oauth.installation_store.models.bot import Bot from slack_sdk.oauth.installation_store.models.installation import Installation +from slack_sdk.oauth.installation_store.async_installation_store import ( + AsyncInstallationStore, +) class SQLAlchemyInstallationStore(InstallationStore): @@ -37,26 +40,30 @@ def build_installations_table(cls, metadata: MetaData, table_name: str) -> Table table_name, metadata, Column("id", Integer, primary_key=True, autoincrement=True), - Column("client_id", String, nullable=False), - Column("app_id", String, nullable=False), - Column("enterprise_id", String), - Column("enterprise_name", String), - Column("enterprise_url", String), - Column("team_id", String), - Column("team_name", String), - Column("bot_token", String), - Column("bot_id", String), - Column("bot_user_id", String), - Column("bot_scopes", String), - Column("user_id", String, nullable=False), - Column("user_token", String), - Column("user_scopes", String), - Column("incoming_webhook_url", String), - Column("incoming_webhook_channel", String), - Column("incoming_webhook_channel_id", String), - Column("incoming_webhook_configuration_url", String), + Column("client_id", String(32), nullable=False), + Column("app_id", String(32), nullable=False), + Column("enterprise_id", String(32)), + Column("enterprise_name", String(200)), + Column("enterprise_url", String(200)), + Column("team_id", String(32)), + Column("team_name", String(200)), + Column("bot_token", String(200)), + Column("bot_id", String(32)), + Column("bot_user_id", String(32)), + Column("bot_scopes", String(1000)), + Column("bot_refresh_token", String(200)), # added in v3.8.0 + Column("bot_token_expires_at", DateTime), # added in v3.8.0 + Column("user_id", String(32), nullable=False), + Column("user_token", String(200)), + Column("user_scopes", String(1000)), + Column("user_refresh_token", String(200)), # added in v3.8.0 + Column("user_token_expires_at", DateTime), # added in v3.8.0 + Column("incoming_webhook_url", String(200)), + Column("incoming_webhook_channel", String(200)), + Column("incoming_webhook_channel_id", String(200)), + Column("incoming_webhook_configuration_url", String(200)), Column("is_enterprise_install", Boolean, default=False, nullable=False), - Column("token_type", String), + Column("token_type", String(32)), Column( "installed_at", DateTime, @@ -79,16 +86,18 @@ def build_bots_table(cls, metadata: MetaData, table_name: str) -> Table: table_name, metadata, Column("id", Integer, primary_key=True, autoincrement=True), - Column("client_id", String, nullable=False), - Column("app_id", String, nullable=False), - Column("enterprise_id", String), - Column("enterprise_name", String), - Column("team_id", String), - Column("team_name", String), - Column("bot_token", String), - Column("bot_id", String), - Column("bot_user_id", String), - Column("bot_scopes", String), + Column("client_id", String(32), nullable=False), + Column("app_id", String(32), nullable=False), + Column("enterprise_id", String(32)), + Column("enterprise_name", String(200)), + Column("team_id", String(32)), + Column("team_name", String(200)), + Column("bot_token", String(200)), + Column("bot_id", String(32)), + Column("bot_user_id", String(32)), + Column("bot_scopes", String(1000)), + Column("bot_refresh_token", String(200)), # added in v3.8.0 + Column("bot_token_expires_at", DateTime), # added in v3.8.0 Column("is_enterprise_install", Boolean, default=False, nullable=False), Column( "installed_at", @@ -114,12 +123,8 @@ def __init__( logger: Logger = logging.getLogger(__name__), ): 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.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._logger = logger self.engine = engine @@ -135,10 +140,59 @@ def save(self, installation: Installation): with self.engine.begin() as conn: i = installation.to_dict() i["client_id"] = self.client_id - conn.execute(self.installations.insert(), i) - b = installation.to_bot().to_dict() + + i_column = self.installations.c + installations_rows = conn.execute( + sqlalchemy.select(i_column.id) + .where( + and_( + i_column.client_id == self.client_id, + i_column.enterprise_id == installation.enterprise_id, + i_column.team_id == installation.team_id, + i_column.installed_at == i.get("installed_at"), + ) + ) + .limit(1) + ) + installations_row_id: Optional[str] = None + for row in installations_rows.mappings(): + installations_row_id = row["id"] + if installations_row_id is None: + conn.execute(self.installations.insert(), i) + else: + update_statement = self.installations.update().where(i_column.id == installations_row_id).values(**i) + conn.execute(update_statement, i) + + # bots + self.save_bot(installation.to_bot()) + + def save_bot(self, bot: Bot): + with self.engine.begin() as conn: + # bots + b = bot.to_dict() b["client_id"] = self.client_id - conn.execute(self.bots.insert(), b) + + b_column = self.bots.c + bots_rows = conn.execute( + sqlalchemy.select(b_column.id) + .where( + and_( + b_column.client_id == self.client_id, + b_column.enterprise_id == bot.enterprise_id, + b_column.team_id == bot.team_id, + b_column.installed_at == b.get("installed_at"), + ) + ) + .limit(1) + ) + bots_row_id: Optional[str] = None + for row in bots_rows.mappings(): + bots_row_id = row["id"] + if bots_row_id is None: + conn.execute(self.bots.insert(), b) + else: + update_statement = self.bots.update().where(b_column.id == bots_row_id).values(**b) + conn.execute(update_statement, b) def find_bot( self, @@ -153,27 +207,22 @@ def find_bot( c = self.bots.c query = ( self.bots.select() - .where(and_(c.enterprise_id == enterprise_id, c.team_id == team_id)) + .where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + c.bot_token.is_not(None), # the latest one that has a bot token + ) + ) .order_by(desc(c.installed_at)) .limit(1) ) with self.engine.connect() as conn: result: object = conn.execute(query) - for row in result: - return Bot( - app_id=row["app_id"], - enterprise_id=row["enterprise_id"], - enterprise_name=row["enterprise_name"], - team_id=row["team_id"], - team_name=row["team_name"], - bot_token=row["bot_token"], - bot_id=row["bot_id"], - bot_user_id=row["bot_user_id"], - bot_scopes=row["bot_scopes"], - is_enterprise_install=row["is_enterprise_install"], - installed_at=row["installed_at"], - ) + for row in result.mappings(): # type: ignore[attr-defined] + return self.build_bot_entity(row) return None def find_installation( @@ -188,47 +237,375 @@ def find_installation( team_id = None c = self.installations.c - where_clause = and_(c.enterprise_id == enterprise_id, c.team_id == team_id) + 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 + with self.engine.connect() as conn: + result: object = conn.execute(query) + for row in result.mappings(): # type: ignore[attr-defined] + installation = self.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 = self.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 + + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + table = self.bots + c = table.c + with self.engine.begin() as conn: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + ) + ) + conn.execute(deletion) + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + table = self.installations + c = table.c + with self.engine.begin() as conn: + if user_id is not None: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + c.user_id == user_id, + ) + ) + conn.execute(deletion) + else: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + ) + ) + conn.execute(deletion) + + @classmethod + def build_installation_entity(cls, row) -> Installation: + return Installation( + app_id=row["app_id"], + enterprise_id=row["enterprise_id"], + enterprise_name=row["enterprise_name"], + enterprise_url=row["enterprise_url"], + team_id=row["team_id"], + team_name=row["team_name"], + bot_token=row["bot_token"], + bot_id=row["bot_id"], + bot_user_id=row["bot_user_id"], + bot_scopes=row["bot_scopes"], + bot_refresh_token=row["bot_refresh_token"], + bot_token_expires_at=row["bot_token_expires_at"], + user_id=row["user_id"], + user_token=row["user_token"], + user_scopes=row["user_scopes"], + user_refresh_token=row["user_refresh_token"], + user_token_expires_at=row["user_token_expires_at"], + # Only the incoming webhook issued in the latest installation is set in this logic + incoming_webhook_url=row["incoming_webhook_url"], + incoming_webhook_channel=row["incoming_webhook_channel"], + incoming_webhook_channel_id=row["incoming_webhook_channel_id"], + incoming_webhook_configuration_url=row["incoming_webhook_configuration_url"], + is_enterprise_install=row["is_enterprise_install"], + token_type=row["token_type"], + installed_at=row["installed_at"], + ) + + @classmethod + def build_bot_entity(cls, row) -> Bot: + return Bot( + app_id=row["app_id"], + enterprise_id=row["enterprise_id"], + enterprise_name=row["enterprise_name"], + team_id=row["team_id"], + team_name=row["team_name"], + bot_token=row["bot_token"], + bot_id=row["bot_id"], + bot_user_id=row["bot_user_id"], + bot_scopes=row["bot_scopes"], + bot_refresh_token=row["bot_refresh_token"], + bot_token_expires_at=row["bot_token_expires_at"], + is_enterprise_install=row["is_enterprise_install"], + installed_at=row["installed_at"], + ) + + +class AsyncSQLAlchemyInstallationStore(AsyncInstallationStore): + default_bots_table_name: str = "slack_bots" + default_installations_table_name: str = "slack_installations" + + client_id: str + engine: AsyncEngine + metadata: MetaData + installations: Table + + def __init__( + self, + client_id: str, + engine: AsyncEngine, + bots_table_name: str = default_bots_table_name, + installations_table_name: str = default_installations_table_name, + logger: Logger = logging.getLogger(__name__), + ): + 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._logger = logger + self.engine = engine + + @classmethod + def build_installations_table(cls, metadata: MetaData, table_name: str) -> Table: + return SQLAlchemyInstallationStore.build_installations_table(metadata, table_name) + + @classmethod + def build_bots_table(cls, metadata: MetaData, table_name: str) -> Table: + return SQLAlchemyInstallationStore.build_bots_table(metadata, table_name) + + async def create_tables(self): + async with self.engine.begin() as conn: + await conn.run_sync(self.metadata.create_all) + + @property + def logger(self) -> Logger: + return self._logger + + async def async_save(self, installation: Installation): + async with self.engine.begin() as conn: + i = installation.to_dict() + i["client_id"] = self.client_id + + i_column = self.installations.c + installations_rows = await conn.execute( + sqlalchemy.select(i_column.id) + .where( + and_( + i_column.client_id == self.client_id, + i_column.enterprise_id == installation.enterprise_id, + i_column.team_id == installation.team_id, + i_column.installed_at == i.get("installed_at"), + ) + ) + .limit(1) + ) + installations_row_id: Optional[str] = None + for row in installations_rows.mappings(): + installations_row_id = row["id"] + if installations_row_id is None: + await conn.execute(self.installations.insert(), i) + else: + update_statement = self.installations.update().where(i_column.id == installations_row_id).values(**i) + await conn.execute(update_statement, i) + + # bots + await self.async_save_bot(installation.to_bot()) + + async def async_save_bot(self, bot: Bot): + async with self.engine.begin() as conn: + # bots + b = bot.to_dict() + b["client_id"] = self.client_id + + b_column = self.bots.c + bots_rows = await conn.execute( + sqlalchemy.select(b_column.id) + .where( + and_( + b_column.client_id == self.client_id, + b_column.enterprise_id == bot.enterprise_id, + b_column.team_id == bot.team_id, + b_column.installed_at == b.get("installed_at"), + ) + ) + .limit(1) + ) + bots_row_id: Optional[str] = None + for row in bots_rows.mappings(): + bots_row_id = row["id"] + if bots_row_id is None: + await conn.execute(self.bots.insert(), b) + else: + update_statement = self.bots.update().where(b_column.id == bots_row_id).values(**b) + await conn.execute(update_statement, b) + + 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 = None + + c = self.bots.c query = ( - self.installations.select() - .where(where_clause) + self.bots.select() + .where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + c.bot_token.is_not(None), # the latest one that has a bot token + ) + ) .order_by(desc(c.installed_at)) .limit(1) ) - with self.engine.connect() as conn: - result: object = conn.execute(query) - for row in result: - return Installation( - app_id=row["app_id"], - enterprise_id=row["enterprise_id"], - enterprise_name=row["enterprise_name"], - enterprise_url=row["enterprise_url"], - team_id=row["team_id"], - team_name=row["team_name"], - bot_token=row["bot_token"], - bot_id=row["bot_id"], - bot_user_id=row["bot_user_id"], - bot_scopes=row["bot_scopes"], - user_id=row["user_id"], - user_token=row["user_token"], - user_scopes=row["user_scopes"], - # Only the incoming webhook issued in the latest installation is set in this logic - incoming_webhook_url=row["incoming_webhook_url"], - incoming_webhook_channel=row["incoming_webhook_channel"], - incoming_webhook_channel_id=row["incoming_webhook_channel_id"], - incoming_webhook_configuration_url=row[ - "incoming_webhook_configuration_url" - ], - is_enterprise_install=row["is_enterprise_install"], - token_type=row["token_type"], - installed_at=row["installed_at"], - ) + async with self.engine.connect() as conn: + result: object = await conn.execute(query) + for row in result.mappings(): # type: ignore[attr-defined] + return SQLAlchemyInstallationStore.build_bot_entity(row) return None + + 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 + + async def async_delete_bot( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + ) -> None: + table = self.bots + c = table.c + async with self.engine.begin() as conn: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + ) + ) + await conn.execute(deletion) + + async def async_delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + table = self.installations + c = table.c + async with self.engine.begin() as conn: + if user_id is not None: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + c.user_id == user_id, + ) + ) + await conn.execute(deletion) + else: + deletion = table.delete().where( + and_( + c.client_id == self.client_id, + c.enterprise_id == enterprise_id, + c.team_id == team_id, + ) + ) + await conn.execute(deletion) diff --git a/slack_sdk/oauth/installation_store/sqlite3/__init__.py b/slack_sdk/oauth/installation_store/sqlite3/__init__.py index db2669c4b..12acd05c7 100644 --- a/slack_sdk/oauth/installation_store/sqlite3/__init__.py +++ b/slack_sdk/oauth/installation_store/sqlite3/__init__.py @@ -36,10 +36,8 @@ def init(self): with sqlite3.connect(database=self.database) as conn: cur = conn.execute("select count(1) from slack_installations;") row_num = cur.fetchone()[0] - self.logger.debug( - f"{row_num} installations are stored in {self.database}" - ) - except Exception: # skipcq: PYL-W0703 + self.logger.debug(f"{row_num} installations are stored in {self.database}") + except Exception: self.create_tables() self.init_called = True @@ -61,13 +59,17 @@ def create_tables(self): enterprise_url text, team_id text not null default '', team_name text, - bot_token text not null, - bot_id text not null, - bot_user_id text not null, + bot_token text, + bot_id text, + bot_user_id text, bot_scopes text, + bot_refresh_token text, -- since v3.8 + bot_token_expires_at datetime, -- since v3.8 user_id text not null, user_token text, user_scopes text, + user_refresh_token text, -- since v3.8 + user_token_expires_at datetime, -- since v3.8 incoming_webhook_url text, incoming_webhook_channel text, incoming_webhook_channel_id text, @@ -103,6 +105,8 @@ def create_tables(self): bot_id text not null, bot_user_id text not null, bot_scopes text, + bot_refresh_token text, -- since v3.8 + bot_token_expires_at datetime, -- since v3.8 is_enterprise_install boolean not null default 0, installed_at datetime not null default current_timestamp ); @@ -124,25 +128,54 @@ def create_tables(self): async def async_save(self, installation: Installation): return self.save(installation) + async def async_save_bot(self, bot: Bot): + return self.save_bot(bot) + def save(self, installation: Installation): with self.connect() as conn: conn.execute( """ - insert into slack_bots ( + insert into slack_installations ( client_id, app_id, enterprise_id, enterprise_name, + enterprise_url, team_id, team_name, bot_token, bot_id, bot_user_id, bot_scopes, - is_enterprise_install + bot_refresh_token, -- since v3.8 + bot_token_expires_at, -- since v3.8 + user_id, + user_token, + user_scopes, + user_refresh_token, -- since v3.8 + user_token_expires_at, -- since v3.8 + incoming_webhook_url, + incoming_webhook_channel, + incoming_webhook_channel_id, + incoming_webhook_configuration_url, + is_enterprise_install, + token_type ) values ( + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, + ?, ?, ?, ?, @@ -161,38 +194,57 @@ def save(self, installation: Installation): installation.app_id, installation.enterprise_id or "", installation.enterprise_name, + installation.enterprise_url, installation.team_id or "", installation.team_name, installation.bot_token, installation.bot_id, installation.bot_user_id, - ",".join(installation.bot_scopes), - installation.is_enterprise_install, + ",".join(installation.bot_scopes), # type: ignore[arg-type] + installation.bot_refresh_token, + installation.bot_token_expires_at, + installation.user_id, + installation.user_token, + ",".join(installation.user_scopes) if installation.user_scopes else None, + installation.user_refresh_token, + installation.user_token_expires_at, + installation.incoming_webhook_url, + installation.incoming_webhook_channel, + installation.incoming_webhook_channel_id, + installation.incoming_webhook_configuration_url, + 1 if installation.is_enterprise_install else 0, + installation.token_type, ], ) + self.logger.debug( + f"New rows in slack_bots and slack_installations have been created (database: {self.database})" + ) + conn.commit() + + self.save_bot(installation.to_bot()) + + def save_bot(self, bot: Bot): + if bot.bot_token is None: + self.logger.debug("Skipped saving a new row because of the absense of bot token in it") + return + + with self.connect() as conn: conn.execute( """ - insert into slack_installations ( + insert into slack_bots ( client_id, app_id, enterprise_id, enterprise_name, - enterprise_url, team_id, team_name, bot_token, bot_id, bot_user_id, bot_scopes, - user_id, - user_token, - user_scopes, - incoming_webhook_url, - incoming_webhook_channel, - incoming_webhook_channel_id, - incoming_webhook_configuration_url, - is_enterprise_install, - token_type + bot_refresh_token, -- since v3.8 + bot_token_expires_at, -- since v3.8 + is_enterprise_install ) values ( @@ -208,44 +260,25 @@ def save(self, installation: Installation): ?, ?, ?, - ?, - ?, - ?, - ?, - ?, - ?, - ?, ? ); """, [ self.client_id, - installation.app_id, - installation.enterprise_id or "", - installation.enterprise_name, - installation.enterprise_url, - installation.team_id or "", - installation.team_name, - installation.bot_token, - installation.bot_id, - installation.bot_user_id, - ",".join(installation.bot_scopes), - installation.user_id, - installation.user_token, - ",".join(installation.user_scopes) - if installation.user_scopes - else None, - installation.incoming_webhook_url, - installation.incoming_webhook_channel, - installation.incoming_webhook_channel_id, - installation.incoming_webhook_configuration_url, - 1 if installation.is_enterprise_install else 0, - installation.token_type, + bot.app_id, + bot.enterprise_id or "", + bot.enterprise_name, + bot.team_id or "", + bot.team_name, + bot.bot_token, + bot.bot_id, + bot.bot_user_id, + ",".join(bot.bot_scopes), + bot.bot_refresh_token, + bot.bot_token_expires_at, + bot.is_enterprise_install, ], ) - self.logger.debug( - f"New rows in slack_bots and slack_installations have been created (database: {self.database})" - ) conn.commit() async def async_find_bot( @@ -285,6 +318,8 @@ def find_bot( bot_id, bot_user_id, bot_scopes, + bot_refresh_token, -- since v3.8 + bot_token_expires_at, -- since v3.8 is_enterprise_install, installed_at from @@ -302,9 +337,7 @@ def find_bot( ) row = cur.fetchone() result = "found" if row and len(row) > 0 else "not found" - self.logger.debug( - f"find_bot's query result: {result} (database: {self.database})" - ) + self.logger.debug(f"find_bot's query result: {result} (database: {self.database})") if row and len(row) > 0: bot = Bot( app_id=row[0], @@ -316,15 +349,20 @@ def find_bot( bot_id=row[6], bot_user_id=row[7], bot_scopes=row[8], - is_enterprise_install=row[9], - installed_at=row[10], + bot_refresh_token=row[9], + bot_token_expires_at=row[10], + is_enterprise_install=row[11], + installed_at=row[12], ) return bot return None - except Exception as e: # skipcq: PYL-W0703 + except Exception as e: message = f"Failed to find bot installation data for enterprise: {enterprise_id}, team: {team_id}: {e}" - self.logger.warning(message) + if self.logger.level <= logging.DEBUG: + self.logger.exception(message) + else: + self.logger.warning(message) return None async def async_find_installation( @@ -367,9 +405,13 @@ def find_installation( bot_id, bot_user_id, bot_scopes, + bot_refresh_token, -- since v3.8 + bot_token_expires_at, -- since v3.8 user_id, user_token, user_scopes, + user_refresh_token, -- since v3.8 + user_token_expires_at, -- since v3.8 incoming_webhook_url, incoming_webhook_channel, incoming_webhook_channel_id, @@ -423,9 +465,7 @@ def find_installation( return None result = "found" if row and len(row) > 0 else "not found" - self.logger.debug( - f"find_installation's query result: {result} (database: {self.database})" - ) + self.logger.debug(f"find_installation's query result: {result} (database: {self.database})") if row and len(row) > 0: installation = Installation( app_id=row[0], @@ -438,21 +478,138 @@ def find_installation( bot_id=row[7], bot_user_id=row[8], bot_scopes=row[9], - user_id=row[10], - user_token=row[11], - user_scopes=row[12], - incoming_webhook_url=row[13], - incoming_webhook_channel=row[14], - incoming_webhook_channel_id=row[15], - incoming_webhook_configuration_url=row[16], - is_enterprise_install=row[17], - token_type=row[18], - installed_at=row[19], + bot_refresh_token=row[10], + bot_token_expires_at=row[11], + user_id=row[12], + user_token=row[13], + user_scopes=row[14], + user_refresh_token=row[15], + user_token_expires_at=row[16], + incoming_webhook_url=row[17], + incoming_webhook_channel=row[18], + incoming_webhook_channel_id=row[19], + incoming_webhook_configuration_url=row[20], + is_enterprise_install=row[21], + token_type=row[22], + installed_at=row[23], ) + + if user_id is not None: + # Retrieve the latest bot token, just in case + # See also: https://github.com/slackapi/bolt-python/issues/664 + cur = conn.execute( + """ + select + bot_token, + bot_id, + bot_user_id, + bot_scopes, + bot_refresh_token, + bot_token_expires_at + from + slack_installations + where + client_id = ? + and + enterprise_id = ? + and + team_id = ? + and + bot_token is not null + order by installed_at desc + limit 1 + """, + [self.client_id, enterprise_id or "", team_id], + ) + row = cur.fetchone() + installation.bot_token = row[0] + installation.bot_id = row[1] + installation.bot_user_id = row[2] + installation.bot_scopes = row[3] + installation.bot_refresh_token = row[4] + installation.bot_token_expires_at = row[5] + return installation return None - except Exception as e: # skipcq: PYL-W0703 + except Exception as e: message = f"Failed to find an installation data for enterprise: {enterprise_id}, team: {team_id}: {e}" - self.logger.warning(message) + if self.logger.level <= logging.DEBUG: + self.logger.exception(message) + else: + self.logger.warning(message) return None + + def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: + try: + with self.connect() as conn: + conn.execute( + """ + delete + from + slack_bots + where + client_id = ? + and + enterprise_id = ? + and + team_id = ? + """, + [self.client_id, enterprise_id or "", team_id or ""], + ) + conn.commit() + except Exception as e: + message = f"Failed to delete bot installation data for enterprise: {enterprise_id}, team: {team_id}: {e}" + if self.logger.level <= logging.DEBUG: + self.logger.exception(message) + else: + self.logger.warning(message) + + def delete_installation( + self, + *, + enterprise_id: Optional[str], + team_id: Optional[str], + user_id: Optional[str] = None, + ) -> None: + try: + with self.connect() as conn: + if user_id is None: + conn.execute( + """ + delete + from + slack_installations + where + client_id = ? + and + enterprise_id = ? + and + team_id = ? + """, + [self.client_id, enterprise_id or "", team_id], + ) + else: + conn.execute( + """ + delete + from + slack_installations + where + client_id = ? + and + enterprise_id = ? + and + team_id = ? + and + user_id = ? + """, + [self.client_id, enterprise_id or "", team_id, user_id], + ) + conn.commit() + except Exception as e: + message = f"Failed to delete installation data for enterprise: {enterprise_id}, team: {team_id}: {e}" + if self.logger.level <= logging.DEBUG: + self.logger.exception(message) + else: + self.logger.warning(message) diff --git a/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py b/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py index 8b2763f49..bc630953f 100644 --- a/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py +++ b/slack_sdk/oauth/redirect_uri_page_renderer/__init__.py @@ -1,3 +1,4 @@ +import html from typing import Optional @@ -24,20 +25,18 @@ def render_success_page( ) -> str: url = self.success_url if url is None: - if ( - is_enterprise_install is True - and enterprise_url is not None - and app_id is not None - ): + if is_enterprise_install is True and enterprise_url is not None and app_id is not None: url = f"{enterprise_url}manage/organization/apps/profile/{app_id}/workspaces/add" elif team_id is None or app_id is None: url = "slack://open" else: url = f"slack://app?team={team_id}&id={app_id}" + browser_url = f"https://app.slack.com/client/{team_id}" + return f""" - + \n\n\n\t\n\t
\n\t\t
\n\t\t\t

\n\t\t\t\t\n\t\t\t\tServer Error\n\t\t\t

\n\t\t\t
\n\t\t\t\t

It seems like there’s a problem connecting to our servers, and we’re investigating the issue.

\n\t\t\t\t

Please check our Status page for updates.

\n\t\t\t
\n\t\t
\n\t
\n\t\n\n' + state = {"ratelimited_count": 0, "fatal_error_count": 0, "server_error_count": 0} + def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): return True - return "Authorization" in self.headers and str( - self.headers["Authorization"] - ).startswith("Bearer xoxb-") + return "Authorization" in self.headers and str(self.headers["Authorization"]).startswith("Bearer xoxb-") def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -50,18 +50,78 @@ def set_common_headers(self): "error": "test_data_not_found", } + token_refresh = { + "ok": True, + "app_id": "A111", + "authed_user": { + "id": "W111", + "scope": "search:read", + "access_token": "xoxe.xoxp-1-xxx", + "token_type": "user", + "refresh_token": "xoxe-1-xxx", + "expires_in": 43200, + }, + "scope": "app_mentions:read,chat:write,commands", + "token_type": "bot", + "access_token": "xoxe.xoxb-1-yyy", + "bot_user_id": "UB111", + "refresh_token": "xoxe-1-yyy", + "expires_in": 43201, + "team": {"id": "T111", "name": "Testing Workspace"}, + "enterprise": {"id": "E111", "name": "Sandbox Org"}, + "is_enterprise_install": False, + } + def _handle(self): try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) + if self.path in {"/oauth.access", "/oauth.v2.access"}: self.send_response(200) self.set_common_headers() if self.headers["authorization"] == "Basic MTExLjIyMjpzZWNyZXQ=": self.wfile.write("""{"ok":true}""".encode("utf-8")) return + elif self.headers["authorization"] == "Basic MTExLjIyMjp0b2tlbl9yb3RhdGlvbl9zZWNyZXQ=": + self.wfile.write(json.dumps(self.token_refresh).encode("utf-8")) + return else: - self.wfile.write( - """{"ok":false, "error":"invalid"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false, "error":"invalid"}""".encode("utf-8")) + return + + header = self.headers["Authorization"] + if header is not None and ("xoxb-" in header or "xoxp-" in header): + pattern = "" + xoxb = str(header).split("xoxb-", 1) + if len(xoxb) > 1: + pattern = xoxb[1] + else: + xoxp = str(header).split("xoxp-", 1) + pattern = xoxp[1] + + if "remote_disconnected" in pattern: + # http.client.RemoteDisconnected + self.finish() + return + + if pattern == "ratelimited" or (pattern == "ratelimited_only_once" and self.state["ratelimited_count"] == 0): + self.state["ratelimited_count"] += 1 + self.send_response(429) + self.send_header("retry-after", 1) + self.send_header("content-type", "application/json;charset=utf-8") + self.send_header("connection", "close") + self.end_headers() + self.wfile.write("""{"ok":false,"error":"ratelimited"}""".encode("utf-8")) + self.wfile.close() + return + + if pattern == "fatal_error" or (pattern == "fatal_error_only_once" and self.state["fatal_error_count"] == 0): + self.state["fatal_error_count"] += 1 + self.send_response(200) + self.set_common_headers() + self.wfile.write("""{"ok":false,"error":"fatal_error"}""".encode("utf-8")) + self.wfile.close() return if self.is_valid_token() and self.is_valid_user_agent(): @@ -77,16 +137,12 @@ def _handle(self): if post_body.startswith("{"): request_body = json.loads(post_body) else: - request_body = { - k: v[0] for k, v in parse_qs(post_body).items() - } + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} except UnicodeDecodeError: pass else: if parsed_path and parsed_path.query: - request_body = { - k: v[0] for k, v in parse_qs(parsed_path.query).items() - } + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} header = self.headers["authorization"] pattern = str(header).split("xoxb-", 1)[1] @@ -95,19 +151,11 @@ def _handle(self): self.set_common_headers() self.wfile.write("""{"ok":false}""".encode("utf-8")) return - if pattern == "rate_limited": - self.send_response(429) - self.send_header("Retry-After", 30) - self.set_common_headers() - self.wfile.write( - """{"ok":false,"error":"rate_limited"}""".encode("utf-8") - ) - self.wfile.close() - return if pattern == "timeout": - time.sleep(2) + time.sleep(3) self.send_response(200) + self.set_common_headers() self.wfile.write("""{"ok":true}""".encode("utf-8")) self.wfile.close() return @@ -129,6 +177,23 @@ def _handle(self): self.wfile.write(self.error_html_response_body.encode("utf-8")) self.wfile.close() return + if pattern == "server_error_only_once": + if self.state["server_error_count"] == 0: + self.state["server_error_count"] += 1 + self.send_response(500) + # no charset here is intentional for testing + self.send_header("content-type", "text/html") + self.send_header("connection", "close") + self.end_headers() + self.wfile.write(self.error_html_response_body.encode("utf-8")) + self.wfile.close() + return + else: + self.send_response(200) + self.set_common_headers() + self.wfile.write("""{"ok":true}""".encode("utf-8")) + self.wfile.close() + return if pattern.startswith("user-agent"): elements = pattern.split(" ") @@ -143,11 +208,7 @@ def _handle(self): else: self.send_response(400) self.set_common_headers() - self.wfile.write( - """{"ok":false, "error":"invalid_user_agent"}""".encode( - "utf-8" - ) - ) + self.wfile.write("""{"ok":false, "error":"invalid_user_agent"}""".encode("utf-8")) self.wfile.close() return @@ -167,17 +228,11 @@ def _handle(self): if request_body: for k, v in request_body.items(): if k in ids: - if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match( - v - ): - raise Exception( - f"The parameter {k} is not a comma-separated string value: {v}" - ) + if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match(v): + raise Exception(f"The parameter {k} is not a comma-separated string value: {v}") body = {"ok": True, "method": parsed_path.path.replace("/", "")} else: - with open( - f"tests/slack_sdk_fixture/web_response_{pattern}.json" - ) as file: + with open(f"tests/slack_sdk_fixture/web_response_{pattern}.json") as file: body = json.load(file) if self.path == "/api.test" and request_body: @@ -207,38 +262,33 @@ def do_POST(self): class MockServerThread(threading.Thread): def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler + self, queue: Union[Queue, asyncio.Queue], test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler ): threading.Thread.__init__(self) self.handler = handler self.test = test + self.queue = queue def run(self): self.server = HTTPServer(("localhost", 8888), self.handler) + self.server.queue = self.queue self.test.server_url = "http://localhost:8888" self.test.host, self.test.port = self.server.socket.getsockname() self.test.server_started.set() # threading.Event() self.test = None try: - self.server.serve_forever() + self.server.serve_forever(0.05) finally: self.server.server_close() def stop(self): + with self.server.queue.mutex: + del self.server.queue self.server.shutdown() self.join() - -def setup_mock_web_api_server(test: TestCase): - test.server_started = threading.Event() - test.thread = MockServerThread(test) - test.thread.start() - - test.server_started.wait() - - -def cleanup_mock_web_api_server(test: TestCase): - test.thread.stop() - - test.thread = None + def stop_unsafe(self): + del self.server.queue + self.server.shutdown() + self.join() diff --git a/tests/slack_sdk/web/mock_web_api_http_retry_handler.py b/tests/slack_sdk/web/mock_web_api_http_retry_handler.py new file mode 100644 index 000000000..d22eaa38b --- /dev/null +++ b/tests/slack_sdk/web/mock_web_api_http_retry_handler.py @@ -0,0 +1,67 @@ +import logging +import time +from http import HTTPStatus +from http.server import SimpleHTTPRequestHandler + + +class MockHandler(SimpleHTTPRequestHandler): + protocol_version = "HTTP/1.1" + default_request_version = "HTTP/1.1" + logger = logging.getLogger(__name__) + state = {"request_count": 0} + + def set_common_headers(self): + self.send_header("content-type", "application/json;charset=utf-8") + self.send_header("connection", "close") + self.end_headers() + + success_response = {"ok": True} + + def _handle(self): + self.state["request_count"] += 1 + try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) + header = self.headers["authorization"] + pattern = str(header).split("xoxb-", 1)[1] + + if self.state["request_count"] % 2 == 1: + if "remote_disconnected" in pattern: + # http.client.RemoteDisconnected + self.finish() + return + + if pattern.isnumeric(): + self.send_response(int(pattern)) + self.set_common_headers() + self.wfile.write("""{"ok":false}""".encode("utf-8")) + return + if pattern == "ratelimited": + self.send_response(429) + self.send_header("retry-after", 1) + self.set_common_headers() + self.wfile.write("""{"ok":false,"error":"ratelimited"}""".encode("utf-8")) + self.wfile.close() + return + + if pattern == "timeout": + time.sleep(2) + self.send_response(200) + self.wfile.write("""{"ok":true}""".encode("utf-8")) + self.wfile.close() + return + + self.send_response(HTTPStatus.OK) + self.set_common_headers() + self.wfile.write("""{"ok":true}""".encode("utf-8")) + self.wfile.close() + + except Exception as e: + self.logger.error(str(e), exc_info=True) + raise + + def do_GET(self): + self._handle() + + def do_POST(self): + self._handle() diff --git a/tests/slack_sdk/web/test_chat_stream.py b/tests/slack_sdk/web/test_chat_stream.py new file mode 100644 index 000000000..75c13c8c2 --- /dev/null +++ b/tests/slack_sdk/web/test_chat_stream.py @@ -0,0 +1,188 @@ +import json +import unittest +from urllib.parse import parse_qs, urlparse + +from slack_sdk import WebClient +from slack_sdk.errors import SlackRequestError +from slack_sdk.models.blocks.basic_components import FeedbackButtonObject +from slack_sdk.models.blocks.block_elements import FeedbackButtonsElement, IconButtonElement +from slack_sdk.models.blocks.blocks import ContextActionsBlock +from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server +from tests.slack_sdk.web.mock_web_api_handler import MockHandler + + +class ChatStreamMockHandler(MockHandler): + """Extended mock handler that captures request bodies for chat stream methods""" + + def _handle(self): + try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) + + # Standard auth and validation from parent + if self.is_valid_token() and self.is_valid_user_agent(): + token = self.headers["authorization"].split(" ")[1] + parsed_path = urlparse(self.path) + len_header = self.headers.get("Content-Length") or 0 + content_len = int(len_header) + post_body = self.rfile.read(content_len) + request_body = None + if post_body: + try: + post_body = post_body.decode("utf-8") + if post_body.startswith("{"): + request_body = json.loads(post_body) + else: + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} + except UnicodeDecodeError: + pass + else: + if parsed_path and parsed_path.query: + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} + + # Store request body for chat stream endpoints + if self.path in ["/chat.startStream", "/chat.appendStream", "/chat.stopStream"] and request_body: + if not hasattr(self.server, "chat_stream_requests"): + self.server.chat_stream_requests = {} + self.server.chat_stream_requests[self.path] = { + "token": token, + **request_body, + } + + # Load response file + pattern = str(token).split("xoxb-", 1)[1] + with open(f"tests/slack_sdk_fixture/web_response_{pattern}.json") as file: + body = json.load(file) + + else: + body = self.invalid_auth + + if not body: + body = self.not_found + + self.send_response(200) + self.set_common_headers() + self.wfile.write(json.dumps(body).encode("utf-8")) + self.wfile.close() + + except Exception as e: + self.logger.error(str(e), exc_info=True) + raise + + +class TestChatStream(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, ChatStreamMockHandler) + self.client = WebClient( + token="xoxb-chat_stream_test", + base_url="http://localhost:8888", + ) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_streams_a_short_message(self): + streamer = self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + recipient_team_id="T0123456789", + recipient_user_id="U0123456789", + ) + streamer.append(markdown_text="nice!") + streamer.stop() + + self.assertEqual(self.received_requests.get("/chat.startStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.appendStream", 0), 0) + self.assertEqual(self.received_requests.get("/chat.stopStream", 0), 1) + + if hasattr(self.thread.server, "chat_stream_requests"): + start_request = self.thread.server.chat_stream_requests.get("/chat.startStream", {}) + self.assertEqual(start_request.get("channel"), "C0123456789") + self.assertEqual(start_request.get("thread_ts"), "123.000") + self.assertEqual(start_request.get("recipient_team_id"), "T0123456789") + self.assertEqual(start_request.get("recipient_user_id"), "U0123456789") + + stop_request = self.thread.server.chat_stream_requests.get("/chat.stopStream", {}) + self.assertEqual(stop_request.get("channel"), "C0123456789") + self.assertEqual(stop_request.get("ts"), "123.123") + self.assertEqual(stop_request.get("markdown_text"), "nice!") + + def test_streams_a_long_message(self): + streamer = self.client.chat_stream( + buffer_size=5, + channel="C0123456789", + recipient_team_id="T0123456789", + recipient_user_id="U0123456789", + thread_ts="123.000", + ) + streamer.append(markdown_text="**this messag") + streamer.append(markdown_text="e is", token="xoxb-chat_stream_test_token1") + streamer.append(markdown_text=" bold!") + streamer.append(markdown_text="*") + streamer.stop( + blocks=[ + ContextActionsBlock( + elements=[ + FeedbackButtonsElement( + positive_button=FeedbackButtonObject(text="good", value="+1"), + negative_button=FeedbackButtonObject(text="bad", value="-1"), + ), + IconButtonElement( + icon="trash", + text="delete", + ), + ], + ) + ], + markdown_text="*", + token="xoxb-chat_stream_test_token2", + ) + + self.assertEqual(self.received_requests.get("/chat.startStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.appendStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.stopStream", 0), 1) + + if hasattr(self.thread.server, "chat_stream_requests"): + start_request = self.thread.server.chat_stream_requests.get("/chat.startStream", {}) + self.assertEqual(start_request.get("channel"), "C0123456789") + self.assertEqual(start_request.get("thread_ts"), "123.000") + self.assertEqual(start_request.get("markdown_text"), "**this messag") + self.assertEqual(start_request.get("recipient_team_id"), "T0123456789") + self.assertEqual(start_request.get("recipient_user_id"), "U0123456789") + + append_request = self.thread.server.chat_stream_requests.get("/chat.appendStream", {}) + self.assertEqual(append_request.get("channel"), "C0123456789") + self.assertEqual(append_request.get("markdown_text"), "e is bold!") + self.assertEqual(append_request.get("token"), "xoxb-chat_stream_test_token1") + self.assertEqual(append_request.get("ts"), "123.123") + + stop_request = self.thread.server.chat_stream_requests.get("/chat.stopStream", {}) + self.assertEqual( + json.dumps(stop_request.get("blocks")), + '[{"elements": [{"negative_button": {"text": {"emoji": true, "text": "bad", "type": "plain_text"}, "value": "-1"}, "positive_button": {"text": {"emoji": true, "text": "good", "type": "plain_text"}, "value": "+1"}, "type": "feedback_buttons"}, {"icon": "trash", "text": {"emoji": true, "text": "delete", "type": "plain_text"}, "type": "icon_button"}], "type": "context_actions"}]', + ) + self.assertEqual(stop_request.get("channel"), "C0123456789") + self.assertEqual(stop_request.get("markdown_text"), "**") + self.assertEqual(stop_request.get("token"), "xoxb-chat_stream_test_token2") + self.assertEqual(stop_request.get("ts"), "123.123") + + def test_streams_errors_when_appending_to_an_unstarted_stream(self): + streamer = self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + token="xoxb-chat_stream_test_missing_ts", + ) + with self.assertRaisesRegex(SlackRequestError, r"^Failed to stop stream: stream not started$"): + streamer.stop() + + def test_streams_errors_when_appending_to_a_completed_stream(self): + streamer = self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + ) + streamer.append(markdown_text="nice!") + streamer.stop() + with self.assertRaisesRegex(SlackRequestError, r"^Cannot append to stream: stream state is completed$"): + streamer.append(markdown_text="more...") + with self.assertRaisesRegex(SlackRequestError, r"^Cannot stop stream: stream state is completed$"): + streamer.stop() diff --git a/tests/slack_sdk/web/test_internal_utils.py b/tests/slack_sdk/web/test_internal_utils.py new file mode 100644 index 000000000..ac7704b30 --- /dev/null +++ b/tests/slack_sdk/web/test_internal_utils.py @@ -0,0 +1,136 @@ +import json +import unittest +from io import BytesIO +from pathlib import Path +from typing import Dict, Sequence, Union + +import pytest + +from slack_sdk.models.attachments import Attachment +from slack_sdk.models.blocks import Block, DividerBlock +from slack_sdk.web.internal_utils import ( + _build_unexpected_body_error_message, + _parse_web_class_objects, + _to_v2_file_upload_item, + _next_cursor_is_present, + _get_url, +) + + +class TestInternalUtils(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + error_html_response_body = '\n\n\n\t\n\tServer Error | Slack\n\t\n\t\n\n\n\t\n\t
\n\t\t
\n\t\t\t

\n\t\t\t\t\n\t\t\t\tServer Error\n\t\t\t

\n\t\t\t
\n\t\t\t\t

It seems like there’s a problem connecting to our servers, and we’re investigating the issue.

\n\t\t\t\t

Please check our Status page for updates.

\n\t\t\t
\n\t\t
\n\t
\n\t\n\n' + + def test_build_unexpected_body_error_message(self): + message = _build_unexpected_body_error_message(self.error_html_response_body) + assert message.startswith( + """Received a response in a non-JSON format: """ + ) + + def test_can_parse_sequence_of_blocks(self): + for blocks in [ + [Block(block_id="42"), Block(block_id="24")], # list + (Block(block_id="42"), Block(block_id="24")), # tuple + ]: + kwargs = {"blocks": blocks} + _parse_web_class_objects(kwargs) + assert kwargs["blocks"] + for block in kwargs["blocks"]: + assert isinstance(block, Dict) + + def test_can_parse_sequence_of_attachments(self): + for attachments in [ + [Attachment(text="foo"), Attachment(text="bar")], # list + ( + Attachment(text="foo"), + Attachment(text="bar"), + ), # tuple + ]: + kwargs = {"attachments": attachments} + _parse_web_class_objects(kwargs) + assert kwargs["attachments"] + for attachment in kwargs["attachments"]: + assert isinstance(attachment, Dict) + + def test_can_parse_str_blocks(self): + input = json.dumps([Block(block_id="42").to_dict(), Block(block_id="24").to_dict()]) + kwargs = {"blocks": input} + _parse_web_class_objects(kwargs) + assert isinstance(kwargs["blocks"], str) + assert input == kwargs["blocks"] + + def test_can_parse_str_attachments(self): + input = json.dumps([Attachment(text="foo").to_dict(), Attachment(text="bar").to_dict()]) + kwargs = {"attachments": input} + _parse_web_class_objects(kwargs) + assert isinstance(kwargs["attachments"], str) + assert input == kwargs["attachments"] + + def test_can_parse_user_auth_blocks(self): + kwargs = { + "channel": "C12345", + "ts": "1111.2222", + "unfurls": {}, + "user_auth_blocks": [DividerBlock(), DividerBlock()], + } + _parse_web_class_objects(kwargs) + assert isinstance(kwargs["user_auth_blocks"][0], dict) + + def test_files_upload_v2_issue_1356(self): + content_item = _to_v2_file_upload_item({"content": "test"}) + assert content_item.get("filename") == "Uploaded file" + + filepath_item = _to_v2_file_upload_item({"file": "tests/slack_sdk/web/test_internal_utils.py"}) + assert filepath_item.get("filename") == "test_internal_utils.py" + filepath_item = _to_v2_file_upload_item({"file": "tests/slack_sdk/web/test_internal_utils.py", "filename": "foo.py"}) + assert filepath_item.get("filename") == "foo.py" + + file_bytes = "This is a test!".encode("utf-8") + file_bytes_item = _to_v2_file_upload_item({"file": file_bytes}) + assert file_bytes_item.get("filename") == "Uploaded file" + file_bytes_item = _to_v2_file_upload_item({"file": file_bytes, "filename": "foo.txt"}) + assert file_bytes_item.get("filename") == "foo.txt" + + file_io = BytesIO(file_bytes) + file_io_item = _to_v2_file_upload_item({"file": file_io}) + assert file_io_item.get("filename") == "Uploaded file" + file_io_item = _to_v2_file_upload_item({"file": file_io, "filename": "foo.txt"}) + assert file_io_item.get("filename") == "foo.txt" + + def test_to_v2_file_upload_item_can_accept_file_as_path(self): + filepath = "tests/slack_sdk/web/test_internal_utils.py" + upload_item_str = _to_v2_file_upload_item({"file": filepath}) + upload_item_path = _to_v2_file_upload_item({"file": Path(filepath)}) + assert upload_item_path == upload_item_str + assert upload_item_str.get("filename") == "test_internal_utils.py" + + def test_next_cursor_is_present(self): + assert _next_cursor_is_present({"next_cursor": "next-page"}) is True + assert _next_cursor_is_present({"next_cursor": ""}) is False + assert _next_cursor_is_present({"next_cursor": None}) is False + assert _next_cursor_is_present({"response_metadata": {"next_cursor": "next-page"}}) is True + assert _next_cursor_is_present({"response_metadata": {"next_cursor": ""}}) is False + assert _next_cursor_is_present({"response_metadata": {"next_cursor": None}}) is False + assert _next_cursor_is_present({"something_else": {"next_cursor": "next-page"}}) is False + + def test_get_url_prevent_double_slash(self): + # Test case: Prevent double slash when both base_url and api_method include slashes + api_url = _get_url("https://slack.com/api/", "/chat.postMessage") + self.assertEqual( + api_url, + "https://slack.com/api/chat.postMessage", + "Should correctly handle and remove double slashes between base_url and api_method", + ) + + # Test case: Handle api_method without leading slash + api_url = _get_url("https://slack.com/api/", "chat.postMessage") + self.assertEqual( + api_url, + "https://slack.com/api/chat.postMessage", + "Should correctly handle api_method without a leading slash", + ) diff --git a/tests/slack_sdk/web/test_legacy_web_client_url_format.py b/tests/slack_sdk/web/test_legacy_web_client_url_format.py new file mode 100644 index 000000000..65c8c35b2 --- /dev/null +++ b/tests/slack_sdk/web/test_legacy_web_client_url_format.py @@ -0,0 +1,53 @@ +from unittest import TestCase + +from slack_sdk.web.legacy_client import LegacyWebClient +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server, assert_received_request_count + + +class TestLegacyWebClientUrlFormat(TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + self.client = LegacyWebClient(token="xoxb-api_test", base_url="http://localhost:8888") + self.client_base_url_slash = LegacyWebClient(token="xoxb-api_test", base_url="http://localhost:8888/") + self.client_api = LegacyWebClient(token="xoxb-api_test", base_url="http://localhost:8888/api") + self.client_api_slash = LegacyWebClient(token="xoxb-api_test", base_url="http://localhost:8888/api/") + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_base_url_without_slash_api_method_without_slash(self): + self.client.api_call("chat.postMessage") + assert_received_request_count(self, "/chat.postMessage", 1) + + def test_base_url_without_slash_api_method_with_slash(self): + self.client.api_call("/chat.postMessage") + assert_received_request_count(self, "/chat.postMessage", 1) + + def test_base_url_with_slash_api_method_without_slash(self): + self.client_base_url_slash.api_call("chat.postMessage") + assert_received_request_count(self, "/chat.postMessage", 1) + + def test_base_url_with_slash_api_method_with_slash(self): + self.client_base_url_slash.api_call("/chat.postMessage") + assert_received_request_count(self, "/chat.postMessage", 1) + + def test_base_url_without_slash_api_method_with_slash_and_trailing_slash(self): + self.client.api_call("/chat.postMessage/") + assert_received_request_count(self, "/chat.postMessage/", 1) + + def test_base_url_with_api(self): + self.client_api.api_call("chat.postMessage") + assert_received_request_count(self, "/api/chat.postMessage", 1) + + def test_base_url_with_api_method_without_slash_method_with_slash(self): + self.client_api.api_call("/chat.postMessage") + assert_received_request_count(self, "/api/chat.postMessage", 1) + + def test_base_url_with_api_slash(self): + self.client_api_slash.api_call("chat.postMessage") + assert_received_request_count(self, "/api/chat.postMessage", 1) + + def test_base_url_with_api_slash_and_method_with_slash(self): + self.client_api_slash.api_call("/chat.postMessage") + assert_received_request_count(self, "/api/chat.postMessage", 1) diff --git a/tests/slack_sdk/web/test_slack_response.py b/tests/slack_sdk/web/test_slack_response.py index 4eca11fbb..bb34d7c2d 100644 --- a/tests/slack_sdk/web/test_slack_response.py +++ b/tests/slack_sdk/web/test_slack_response.py @@ -26,3 +26,34 @@ def test_issue_559(self): self.assertTrue("ok" in response.data) self.assertTrue("args" in response.data) self.assertFalse("error" in response.data) + + # https://github.com/slackapi/python-slack-sdk/issues/1100 + def test_issue_1100(self): + response = SlackResponse( + client=WebClient(token="xoxb-dummy"), + http_verb="POST", + api_url="http://localhost:3000/api.test", + req_args={}, + data=None, + headers={}, + status_code=200, + ) + with self.assertRaises(ValueError): + response["foo"] + + foo = response.get("foo") + self.assertIsNone(foo) + + # https://github.com/slackapi/python-slack-sdk/issues/1102 + def test_issue_1102(self): + response = SlackResponse( + client=WebClient(token="xoxb-dummy"), + http_verb="POST", + api_url="http://localhost:3000/api.test", + req_args={}, + data={"ok": True, "args": {"hello": "world"}}, + headers={}, + status_code=200, + ) + self.assertTrue("ok" in response) + self.assertTrue("foo" not in response) diff --git a/tests/slack_sdk/web/test_web_client.py b/tests/slack_sdk/web/test_web_client.py index 1dff7877c..cea47a38c 100644 --- a/tests/slack_sdk/web/test_web_client.py +++ b/tests/slack_sdk/web/test_web_client.py @@ -1,20 +1,22 @@ import re import socket import unittest +import time import slack_sdk.errors as err from slack_sdk import WebClient -from tests.slack_sdk.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from slack_sdk.models.blocks import DividerBlock +from slack_sdk.models.metadata import Metadata +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server class TestWebClient(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server(self, MockHandler) self.client = WebClient( - token="xoxb-api_test", base_url="http://localhost:8888", + token="xoxb-api_test", + base_url="http://localhost:8888", ) def tearDown(self): @@ -84,19 +86,18 @@ def test_slack_api_error_is_raised_on_unsuccessful_responses(self): self.client.api_test() def test_slack_api_rate_limiting_exception_returns_retry_after(self): - self.client.token = "xoxb-rate_limited" + self.client.token = "xoxb-ratelimited" try: self.client.api_test() except err.SlackApiError as slack_api_error: self.assertFalse(slack_api_error.response["ok"]) self.assertEqual(429, slack_api_error.response.status_code) - self.assertEqual(30, int(slack_api_error.response.headers["Retry-After"])) + self.assertEqual(1, int(slack_api_error.response.headers["retry-after"])) + self.assertEqual(1, int(slack_api_error.response.headers["Retry-After"])) def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" - resp = self.client.users_setPhoto( - image="tests/slack_sdk_fixture/slack_logo.png" - ) + resp = self.client.users_setPhoto(image="tests/slack_sdk_fixture/slack_logo.png") self.assertEqual(200, resp.status_code) def test_issue_560_bool_in_params_sync(self): @@ -107,25 +108,17 @@ def test_issue_560_bool_in_params_sync(self): def test_issue_690_oauth_v2_access(self): self.client.token = "" - resp = self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_v2_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_v2_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_690_oauth_access(self): self.client.token = "" - resp = self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_705_no_param_request_pagination(self): self.client.token = "xoxb-users_list_pagination" @@ -155,9 +148,7 @@ def test_html_response_body_issue_718(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( - str(e).startswith( - "Failed to parse the response body: Expecting value: line 1 column 1 (char 0)" - ), + str(e).startswith("The request to the Slack API failed. (url: http://"), e, ) @@ -175,3 +166,72 @@ def test_default_team_id(self): client = WebClient(base_url="http://localhost:8888", team_id="T_DEFAULT") resp = client.users_list(token="xoxb-users_list_pagination") self.assertIsNone(resp["error"]) + + def test_message_metadata(self): + client = self.client + new_message = client.chat_postMessage( + channel="#random", + text="message with metadata", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 5000, + "tags": ["foo", "bar", "baz"], + }, + ), + ) + self.assertIsNone(new_message.get("error")) + + history = client.conversations_history( + channel=new_message.get("channel"), + limit=1, + include_all_metadata=True, + ) + self.assertIsNone(history.get("error")) + + modification = client.chat_update( + channel=new_message.get("channel"), + ts=new_message.get("ts"), + text="message with metadata (modified)", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 6000, + }, + ), + ) + self.assertIsNone(modification.get("error")) + + scheduled = client.chat_scheduleMessage( + channel=new_message.get("channel"), + post_at=int(time.time()) + 30, + text="message with metadata (scheduled)", + metadata=Metadata( + event_type="procurement-task", + event_payload={ + "id": "11111", + "amount": 10, + }, + ), + ) + self.assertIsNone(scheduled.get("error")) + + def test_user_auth_blocks(self): + client = self.client + new_message = client.chat_unfurl( + channel="C12345", + ts="1111.2222", + unfurls={}, + user_auth_blocks=[DividerBlock(), DividerBlock()], + ) + self.assertIsNone(new_message.get("error")) + + def test_base_url_appends_trailing_slash_issue_15141(self): + client = self.client + self.assertEqual(client.base_url, "http://localhost:8888/") + + def test_base_url_preserves_trailing_slash_issue_15141(self): + client = WebClient(base_url="http://localhost:8888/") + self.assertEqual(client.base_url, "http://localhost:8888/") diff --git a/tests/slack_sdk/web/test_web_client_http_retry.py b/tests/slack_sdk/web/test_web_client_http_retry.py new file mode 100644 index 000000000..85d1c0875 --- /dev/null +++ b/tests/slack_sdk/web/test_web_client_http_retry.py @@ -0,0 +1,80 @@ +import unittest + +from slack_sdk.errors import SlackApiError +from slack_sdk.http_retry import RateLimitErrorRetryHandler +from slack_sdk.web import WebClient +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server +from ..fatal_error_retry_handler import FatalErrorRetryHandler +from ..my_retry_handler import MyRetryHandler + + +class TestWebClient_HttpRetry(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_remote_disconnected(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-remote_disconnected", + team_id="T111", + retry_handlers=[retry_handler], + ) + try: + client.auth_test() + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + def test_ratelimited_no_retry(self): + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-ratelimited", + team_id="T111", + ) + try: + client.auth_test() + self.fail("An exception is expected") + except SlackApiError as e: + # Just running retries; no assertions for call count so far + self.assertEqual(429, e.response.status_code) + + def test_ratelimited(self): + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-ratelimited_only_once", + team_id="T111", + ) + client.retry_handlers.append(RateLimitErrorRetryHandler()) + # The auto-retry should work here + client.auth_test() + + def test_fatal_error_no_retry(self): + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-fatal_error", + team_id="T111", + ) + try: + client.auth_test() + self.fail("An exception is expected") + except SlackApiError as e: + # Just running retries; no assertions for call count so far + self.assertEqual(200, e.response.status_code) + self.assertEqual("fatal_error", e.response["error"]) + + def test_fatal_error(self): + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-fatal_error_only_once", + team_id="T111", + ) + client.retry_handlers.append(FatalErrorRetryHandler()) + # The auto-retry should work here + client.auth_test() diff --git a/tests/slack_sdk/web/test_web_client_http_retry_connection.py b/tests/slack_sdk/web/test_web_client_http_retry_connection.py new file mode 100644 index 000000000..b77a30b7e --- /dev/null +++ b/tests/slack_sdk/web/test_web_client_http_retry_connection.py @@ -0,0 +1,21 @@ +import unittest + +from slack_sdk.web import WebClient +from tests.slack_sdk.web.mock_web_api_http_retry_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server + + +class TestWebClient_HttpRetry(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler, port=8889) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_remote_disconnected(self): + client = WebClient( + base_url="http://localhost:8889", + token="xoxb-remote_disconnected", + team_id="T111", + ) + client.auth_test() diff --git a/tests/slack_sdk/web/test_web_client_http_retry_server_error.py b/tests/slack_sdk/web/test_web_client_http_retry_server_error.py new file mode 100644 index 000000000..b0d607683 --- /dev/null +++ b/tests/slack_sdk/web/test_web_client_http_retry_server_error.py @@ -0,0 +1,71 @@ +import unittest + +import slack_sdk.errors as err +from slack_sdk.http_retry import RetryHandler, RetryIntervalCalculator +from slack_sdk.http_retry.builtin_handlers import ServerErrorRetryHandler +from slack_sdk.http_retry.handler import default_interval_calculator +from slack_sdk.web import WebClient +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server + + +class MyServerErrorRetryHandler(RetryHandler): + """RetryHandler that does retries for server-side errors.""" + + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + super().__init__(max_retry_count, interval_calculator) + self.call_count = 0 + + def _can_retry( + self, + *, + state, + request, + response, + error, + ) -> bool: + self.call_count += 1 + return response is not None and response.status_code >= 500 + + +class TestWebClient_HttpRetry_ServerError(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_html_response_body_issue_829(self): + retry_handlers = [MyServerErrorRetryHandler(max_retry_count=2)] + client = WebClient( + base_url="http://localhost:8888", + retry_handlers=retry_handlers, + ) + try: + client.users_list(token="xoxb-error_html_response") + self.fail("SlackApiError expected here") + except err.SlackApiError as e: + self.assertTrue( + str(e).startswith("The request to the Slack API failed. (url: http://"), + e, + ) + self.assertIsInstance(e.response.status_code, int) + self.assertFalse(e.response["ok"]) + self.assertTrue( + e.response["error"].startswith("Received a response in a non-JSON format: ")) def test_proxy_issue_714(self): - client = WebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = WebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(urllib.error.URLError): client.send_dict({"text": "hello!"}) @@ -177,3 +172,44 @@ def test_user_agent_customization_issue_769(self): ) resp = client.send_dict({"text": "hi!"}) self.assertEqual(resp.body, "ok") + + def test_issue_919_response_url_flag_options(self): + client = WebhookClient("http://localhost:8888") + resp = client.send( + text="hello!", + response_type="ephemeral", + replace_original=True, + blocks=[ + SectionBlock(text="Some text"), + ImageBlock(image_url="image.jpg", alt_text="an image"), + ], + ) + self.assertEqual("ok", resp.body) + + resp = client.send( + text="hello!", + response_type="ephemeral", + delete_original=True, + blocks=[ + SectionBlock(text="Some text"), + ImageBlock(image_url="image.jpg", alt_text="an image"), + ], + ) + self.assertEqual("ok", resp.body) + + def test_if_it_uses_custom_logger_issue_921(self): + logger = CustomLogger("test-logger") + client = WebhookClient(url="http://localhost:8888", logger=logger) + client.send_dict({"text": "hi!"}) + self.assertTrue(logger.called) + + +class CustomLogger(Logger): + called: bool + + def __init__(self, name, level="DEBUG"): + Logger.__init__(self, name, level) + self.called = False + + def debug(self, msg, *args, **kwargs): + self.called = True diff --git a/tests/slack_sdk/webhook/test_webhook_http_retry.py b/tests/slack_sdk/webhook/test_webhook_http_retry.py new file mode 100644 index 000000000..c35441500 --- /dev/null +++ b/tests/slack_sdk/webhook/test_webhook_http_retry.py @@ -0,0 +1,36 @@ +import unittest + +from slack_sdk.http_retry import RateLimitErrorRetryHandler +from slack_sdk.webhook import WebhookClient +from tests.slack_sdk.webhook.mock_web_api_server import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server +from ..my_retry_handler import MyRetryHandler + + +class TestWebhook_HttpRetries(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_send(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = WebhookClient( + "http://localhost:8888/remote_disconnected", + retry_handlers=[retry_handler], + ) + try: + client.send(text="hello!") + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + def test_ratelimited(self): + client = WebhookClient("http://localhost:8888/ratelimited") + client.retry_handlers.append(RateLimitErrorRetryHandler()) + response = client.send(text="hello!") + # Just running retries; no assertions for call count so far + self.assertEqual(429, response.status_code) diff --git a/tests/slack_sdk_async/audit_logs/__init__.py b/tests/slack_sdk_async/audit_logs/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/slack_sdk_async/audit_logs/test_async_client.py b/tests/slack_sdk_async/audit_logs/test_async_client.py new file mode 100644 index 000000000..92f9fa149 --- /dev/null +++ b/tests/slack_sdk_async/audit_logs/test_async_client.py @@ -0,0 +1,44 @@ +import unittest + +from slack_sdk.audit_logs.async_client import AsyncAuditLogsClient +from slack_sdk.audit_logs import AuditLogsResponse +from tests.helpers import async_test +from tests.slack_sdk.audit_logs.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestAsyncAuditLogsClient(unittest.TestCase): + def setUp(self): + self.client = AsyncAuditLogsClient(token="xoxp-", base_url="http://localhost:8888/") + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_logs(self): + resp: AuditLogsResponse = await self.client.logs(limit=1, action="user_login") + self.assertEqual(200, resp.status_code) + self.assertIsNotNone(resp.body.get("entries")) + + self.assertEqual(resp.typed_body.entries[0].id, "xxx-yyy-zzz-111") + + @async_test + async def test_logs_pagination(self): + resp: AuditLogsResponse = await self.client.logs(limit=1, action="user_login", cursor="XXXXXXXXXXX") + self.assertEqual(200, resp.status_code) + self.assertIsNotNone(resp.body.get("entries")) + + self.assertEqual(resp.typed_body.entries[0].id, "xxx-yyy-zzz-111") + + @async_test + async def test_actions(self): + resp: AuditLogsResponse = await self.client.actions() + self.assertEqual(200, resp.status_code) + self.assertIsNotNone(resp.body.get("actions")) + + @async_test + async def test_schemas(self): + resp: AuditLogsResponse = await self.client.schemas() + self.assertEqual(200, resp.status_code) + self.assertIsNotNone(resp.body.get("schemas")) diff --git a/tests/slack_sdk_async/audit_logs/test_async_client_http_retry.py b/tests/slack_sdk_async/audit_logs/test_async_client_http_retry.py new file mode 100644 index 000000000..b25200072 --- /dev/null +++ b/tests/slack_sdk_async/audit_logs/test_async_client_http_retry.py @@ -0,0 +1,44 @@ +import unittest + +from slack_sdk.audit_logs.async_client import AsyncAuditLogsClient +from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler +from tests.helpers import async_test +from tests.slack_sdk.audit_logs.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from ..my_retry_handler import MyRetryHandler + + +class TestAsyncAuditLogsClient_HttpRetries(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_http_retries(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = AsyncAuditLogsClient( + token="xoxp-remote_disconnected", + base_url="http://localhost:8888/", + retry_handlers=[retry_handler], + ) + try: + await client.actions() + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + @async_test + async def test_ratelimited(self): + client = AsyncAuditLogsClient( + token="xoxp-ratelimited", + base_url="http://localhost:8888/", + retry_handlers=[AsyncRateLimitErrorRetryHandler()], + ) + + response = await client.actions() + # Just running retries; no assertions for call count so far + self.assertEqual(429, response.status_code) diff --git a/tests/slack_sdk_async/fatal_error_retry_handler.py b/tests/slack_sdk_async/fatal_error_retry_handler.py new file mode 100644 index 000000000..b7b5ac038 --- /dev/null +++ b/tests/slack_sdk_async/fatal_error_retry_handler.py @@ -0,0 +1,30 @@ +from typing import Optional +from aiohttp import ServerDisconnectedError, ClientOSError + +from slack_sdk.http_retry.async_handler import AsyncRetryHandler +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.handler import default_interval_calculator + + +class FatalErrorRetryHandler(AsyncRetryHandler): + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + super().__init__(max_retry_count, interval_calculator) + self.call_count = 0 + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse], + error: Optional[Exception], + ) -> bool: + self.call_count += 1 + return response is not None and response.status_code == 200 and response.body.get("error") == "fatal_error" diff --git a/tests/slack_sdk_async/http_retry/__init__.py b/tests/slack_sdk_async/http_retry/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/slack_sdk_async/http_retry/test_builtins.py b/tests/slack_sdk_async/http_retry/test_builtins.py new file mode 100644 index 000000000..45c086e61 --- /dev/null +++ b/tests/slack_sdk_async/http_retry/test_builtins.py @@ -0,0 +1,13 @@ +import unittest + +from slack_sdk.http_retry.builtin_async_handlers import async_default_handlers + + +class TestBuiltins(unittest.TestCase): + def test_default_ones(self): + list = async_default_handlers() + self.assertEqual(1, len(list)) + list.clear() + self.assertEqual(0, len(list)) + list = async_default_handlers() + self.assertEqual(1, len(list)) diff --git a/tests/slack_sdk_async/my_retry_handler.py b/tests/slack_sdk_async/my_retry_handler.py new file mode 100644 index 000000000..6ee3766cc --- /dev/null +++ b/tests/slack_sdk_async/my_retry_handler.py @@ -0,0 +1,35 @@ +from typing import Optional +from aiohttp import ServerDisconnectedError, ClientOSError + +from slack_sdk.http_retry.async_handler import AsyncRetryHandler +from slack_sdk.http_retry.interval_calculator import RetryIntervalCalculator +from slack_sdk.http_retry.state import RetryState +from slack_sdk.http_retry.request import HttpRequest +from slack_sdk.http_retry.response import HttpResponse +from slack_sdk.http_retry.handler import default_interval_calculator + + +class MyRetryHandler(AsyncRetryHandler): + def __init__( + self, + max_retry_count: int = 1, + interval_calculator: RetryIntervalCalculator = default_interval_calculator, + ): + super().__init__(max_retry_count, interval_calculator) + self.call_count = 0 + + async def _can_retry_async( + self, + *, + state: RetryState, + request: HttpRequest, + response: Optional[HttpResponse], + error: Optional[Exception], + ) -> bool: + self.call_count += 1 + if error is None: + return False + for error_type in [ServerDisconnectedError, ClientOSError]: + if isinstance(error, error_type): + return True + return False diff --git a/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py b/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py index 12cc84602..c1f43f4e4 100644 --- a/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py +++ b/tests/slack_sdk_async/oauth/installation_store/test_simple_cache.py @@ -12,9 +12,7 @@ class TestCacheable(unittest.TestCase): @async_test async def test_save_and_find(self): - sqlite3_store = SQLite3InstallationStore( - database="logs/cacheable.db", client_id="111.222" - ) + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") sqlite3_store.init() store = AsyncCacheableInstallationStore(sqlite3_store) @@ -39,3 +37,52 @@ async def test_save_and_find(self): self.assertIsNone(bot) bot = await store.async_find_bot(enterprise_id="E111", team_id="T111") self.assertIsNotNone(bot) + + @async_test + async def test_save_and_find_token_rotation(self): + sqlite3_store = SQLite3InstallationStore(database="logs/cacheable.db", client_id="111.222") + sqlite3_store.init() + store = AsyncCacheableInstallationStore(sqlite3_store) + + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxb-initial", + bot_scopes=["chat:write"], + bot_user_id="U222", + bot_refresh_token="xoxe-1-initial", + bot_token_expires_in=43200, + ) + await store.async_save(installation) + + bot = await store.async_find_bot(enterprise_id="E111", team_id="T111") + self.assertIsNotNone(bot) + self.assertEqual(bot.bot_refresh_token, "xoxe-1-initial") + + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxb-refreshed", + bot_scopes=["chat:write"], + bot_user_id="U222", + bot_refresh_token="xoxe-1-refreshed", + bot_token_expires_in=43200, + ) + await store.async_save(installation) + + bot = await store.async_find_bot(enterprise_id="E111", team_id="T111") + self.assertIsNotNone(bot) + self.assertEqual(bot.bot_refresh_token, "xoxe-1-refreshed") + + os.remove("logs/cacheable.db") + + bot = await sqlite3_store.async_find_bot(enterprise_id="E111", team_id="T111") + self.assertIsNone(bot) + bot = await store.async_find_bot(enterprise_id="E111", team_id="T111") + self.assertIsNotNone(bot) diff --git a/tests/slack_sdk_async/oauth/token_rotation/__init__.py b/tests/slack_sdk_async/oauth/token_rotation/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py b/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py new file mode 100644 index 000000000..4c16bb3b5 --- /dev/null +++ b/tests/slack_sdk_async/oauth/token_rotation/test_token_rotator.py @@ -0,0 +1,117 @@ +import unittest + +from slack_sdk.errors import SlackTokenRotationError +from slack_sdk.oauth.installation_store import Installation +from slack_sdk.oauth.token_rotation.async_rotator import AsyncTokenRotator +from slack_sdk.web.async_client import AsyncWebClient +from tests.helpers import async_test +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestTokenRotator(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.token_rotator = AsyncTokenRotator( + client=AsyncWebClient(base_url="http://localhost:8888", token=None), + client_id="111.222", + client_secret="token_rotation_secret", + ) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_refresh(self): + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxe.xoxp-1-initial", + bot_scopes=["chat:write"], + bot_user_id="U222", + bot_refresh_token="xoxe-1-initial", + bot_token_expires_in=43200, + ) + refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=60 * 24 * 365 + ) + self.assertIsNotNone(refreshed) + + should_not_be_refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=1 + ) + self.assertIsNone(should_not_be_refreshed) + + @async_test + async def test_refresh_with_custom_values(self): + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxe.xoxp-1-initial", + bot_scopes=["chat:write"], + bot_user_id="U222", + bot_refresh_token="xoxe-1-initial", + bot_token_expires_in=43200, + custom_values={"foo": "bar"}, + ) + refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=60 * 24 * 365 + ) + self.assertIsNotNone(refreshed) + self.assertIsNotNone(refreshed.custom_values) + + should_not_be_refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=1 + ) + self.assertIsNone(should_not_be_refreshed) + + @async_test + async def test_token_rotation_disabled(self): + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxe.xoxp-1-initial", + bot_scopes=["chat:write"], + bot_user_id="U222", + ) + should_not_be_refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=60 * 24 * 365 + ) + self.assertIsNone(should_not_be_refreshed) + + should_not_be_refreshed = await self.token_rotator.perform_token_rotation( + installation=installation, minutes_before_expiration=1 + ) + self.assertIsNone(should_not_be_refreshed) + + @async_test + async def test_refresh_error(self): + token_rotator = AsyncTokenRotator( + client=AsyncWebClient(base_url="http://localhost:8888", token=None), + client_id="111.222", + client_secret="invalid_value", + ) + + installation = Installation( + app_id="A111", + enterprise_id="E111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxe.xoxp-1-initial", + bot_scopes=["chat:write"], + bot_user_id="U222", + bot_refresh_token="xoxe-1-initial", + bot_token_expires_in=43200, + ) + with self.assertRaises(SlackTokenRotationError): + await token_rotator.perform_token_rotation(installation=installation, minutes_before_expiration=60 * 24 * 365) diff --git a/tests/slack_sdk_async/scim/__init__.py b/tests/slack_sdk_async/scim/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/slack_sdk_async/scim/test_async_client.py b/tests/slack_sdk_async/scim/test_async_client.py new file mode 100644 index 000000000..c4faa6a73 --- /dev/null +++ b/tests/slack_sdk_async/scim/test_async_client.py @@ -0,0 +1,76 @@ +import time +import unittest + +from slack_sdk.scim import User, Group +from slack_sdk.scim.v1.async_client import AsyncSCIMClient +from slack_sdk.scim.v1.group import GroupMember +from slack_sdk.scim.v1.user import UserName, UserEmail +from tests.helpers import async_test +from tests.slack_sdk.scim.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestSCIMClient(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_users(self): + client = AsyncSCIMClient(base_url="http://localhost:8888/", token="xoxp-valid") + await client.search_users(start_index=0, count=1) + await client.read_user("U111") + + now = str(time.time())[:10] + user = User( + user_name=f"user_{now}", + name=UserName(given_name="Kaz", family_name="Sera"), + emails=[UserEmail(value=f"seratch+{now}@example.com")], + schemas=["urn:scim:schemas:core:1.0"], + ) + await client.create_user(user) + # The mock server does not work for PATH requests + try: + await client.patch_user("U111", partial_user=User(user_name="foo")) + except: + pass + user.id = "U111" + user.user_name = "updated" + try: + await client.update_user(user) + except: + pass + try: + await client.delete_user("U111") + except: + pass + + @async_test + async def test_groups(self): + client = AsyncSCIMClient(base_url="http://localhost:8888/", token="xoxp-valid") + await client.search_groups(start_index=0, count=1) + await client.read_group("S111") + + now = str(time.time())[:10] + group = Group( + display_name=f"TestGroup_{now}", + members=[GroupMember(value="U111")], + ) + await client.create_group(group) + # The mock server does not work for PATH requests + try: + await client.patch_group("S111", partial_group=Group(display_name=f"TestGroup_{now}_2")) + except: + pass + group.id = "S111" + group.display_name = "updated" + try: + await client.update_group(group) + except: + pass + try: + await client.delete_group("S111") + except: + pass diff --git a/tests/slack_sdk_async/scim/test_async_client_http_retry.py b/tests/slack_sdk_async/scim/test_async_client_http_retry.py new file mode 100644 index 000000000..92fe595dd --- /dev/null +++ b/tests/slack_sdk_async/scim/test_async_client_http_retry.py @@ -0,0 +1,45 @@ +import unittest + +from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler +from slack_sdk.scim.v1.async_client import AsyncSCIMClient +from tests.helpers import async_test +from tests.slack_sdk.scim.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from ..my_retry_handler import MyRetryHandler + + +class TestSCIMClient_HttpRetries(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_retries(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = AsyncSCIMClient( + base_url="http://localhost:8888/", + token="xoxp-remote_disconnected", + retry_handlers=[retry_handler], + ) + + try: + await client.search_users(start_index=0, count=1) + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + @async_test + async def test_ratelimited(self): + client = AsyncSCIMClient( + base_url="http://localhost:8888/", + token="xoxp-ratelimited", + retry_handlers=[AsyncRateLimitErrorRetryHandler()], + ) + + response = await client.search_users(start_index=0, count=1) + # Just running retries; no assertions for call count so far + self.assertEqual(429, response.status_code) diff --git a/tests/slack_sdk_async/socket_mode/__init__.py b/tests/slack_sdk_async/socket_mode/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/slack_sdk_async/socket_mode/test_aiohttp.py b/tests/slack_sdk_async/socket_mode/test_aiohttp.py new file mode 100644 index 000000000..eda1fecdd --- /dev/null +++ b/tests/slack_sdk_async/socket_mode/test_aiohttp.py @@ -0,0 +1,99 @@ +import asyncio +import unittest + +from slack_sdk.socket_mode.aiohttp import SocketModeClient +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk.socket_mode.mock_web_api_handler import MockHandler +from tests.slack_sdk_async.helpers import async_test +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestAiohttp(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.web_client = AsyncWebClient( + token="xoxb-api_test", + base_url="http://localhost:8888", + ) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_init_close(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + ) + try: + self.assertIsNotNone(client) + finally: + await client.close() + + @async_test + async def test_init_with_loop(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + loop=asyncio.get_event_loop(), + ) + try: + self.assertIsNotNone(client) + finally: + await client.close() + + @async_test + async def test_issue_new_wss_url(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + ) + try: + url = await client.issue_new_wss_url() + self.assertTrue(url.startswith("ws://")) + finally: + await client.close() + + # TODO: valid test to connect + # @async_test + # async def test_connect_to_new_endpoint(self): + # client = SocketModeClient( + # app_token="xapp-A111-222-xyz", + # web_client=self.web_client, + # auto_reconnect_enabled=False, + # ) + # try: + # await client.connect_to_new_endpoint() + # except Exception as e: + # pass + # finally: + # await client.close() + + @async_test + async def test_enqueue_message(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + trace_enabled=True, + on_message_listeners=[lambda msg: None], + ) + client.message_listeners.append(listener) + try: + await client.enqueue_message("hello") + await client.process_message() + + await client.enqueue_message( + """{"type":"hello","num_connections":1,"debug_info":{"host":"applink-111-222","build_number":10,"approximate_connection_time":18060},"connection_info":{"app_id":"A111"}}""" + ) + await client.process_message() + finally: + await client.disconnect() + await client.close() + + +async def listener(self, message, raw_message): + pass diff --git a/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py b/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py new file mode 100644 index 000000000..91e28d7ca --- /dev/null +++ b/tests/slack_sdk_async/socket_mode/test_interactions_aiohttp.py @@ -0,0 +1,203 @@ +import asyncio +import logging +import time +import unittest +from random import randint + +import pytest +from aiohttp import WSMessage + +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient + +from slack_sdk.socket_mode.aiohttp import SocketModeClient +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk.socket_mode.mock_socket_mode_server import ( + request_socket_mode_server_disconnect, + start_socket_mode_server, + socket_mode_envelopes, + socket_mode_hello_message, + stop_socket_mode_server, +) +from tests.slack_sdk.socket_mode.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from tests.slack_sdk_async.helpers import async_test + + +class TestInteractionsAiohttp(unittest.TestCase): + logger = logging.getLogger(__name__) + + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.web_client = AsyncWebClient( + token="xoxb-api_test", + base_url="http://localhost:8888", + ) + start_socket_mode_server(self, 3001) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + stop_socket_mode_server(self) + + @async_test + async def test_interactions(self): + received_messages = [] + received_socket_mode_requests = [] + + async def message_handler(message: WSMessage): + self.logger.info(f"Raw Message: {message}") + await asyncio.sleep(randint(50, 200) / 1000) + received_messages.append(message.data) + + async def socket_mode_listener( + self: AsyncBaseSocketModeClient, + request: SocketModeRequest, + ): + self.logger.info(f"Socket Mode Request: {request.payload}") + await asyncio.sleep(randint(50, 200) / 1000) + received_socket_mode_requests.append(request.payload) + + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + on_message_listeners=[message_handler], + auto_reconnect_enabled=False, + trace_enabled=True, + ) + client.socket_mode_request_listeners.append(socket_mode_listener) + + try: + client.wss_uri = "ws://0.0.0.0:3001/link" + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + + for _ in range(10): + await client.send_message("foo") + await client.send_message("bar") + await client.send_message("baz") + + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 + expected.sort() + expected.sort() + + count = 0 + while count < 10 and ( + len(received_messages) < len(expected) or len(received_socket_mode_requests) < len(socket_mode_envelopes) + ): + await asyncio.sleep(0.2) + count += 0.2 + + received_messages.sort() + self.assertEqual(received_messages, expected) + + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) + finally: + await client.close() + + @async_test + async def test_interactions_with_disconnection(self): + self.disconnected = False + received_messages = [] + received_socket_mode_requests = [] + + async def message_handler(message: WSMessage): + session_id = client.build_session_id(client.current_session) + if "wait_for_disconnect" in message.data: + return + self.logger.info(f"Raw Message: {message}") + await asyncio.sleep(randint(50, 200) / 1000) + self.disconnected = "disconnect" in message.data + received_messages.append(message.data + "_" + session_id) + + async def socket_mode_listener( + self: AsyncBaseSocketModeClient, + request: SocketModeRequest, + ): + self.logger.info(f"Socket Mode Request: {request.payload}") + await asyncio.sleep(randint(50, 200) / 1000) + received_socket_mode_requests.append(request.payload) + + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + on_message_listeners=[message_handler], + auto_reconnect_enabled=True, + trace_enabled=True, + ) + client.socket_mode_request_listeners.append(socket_mode_listener) + + try: + client.wss_uri = "ws://0.0.0.0:3001/link" + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + + request_socket_mode_server_disconnect(3001, 1) + + # Because we want to check the expected messages of new session, + # we need to ensure we send messaged after disconnected. + count = 0 + while not self.disconnected and count < 10: + try: + await client.send_message("wait_for_disconnect") + except Exception as e: + self.logger.exception(e) + finally: + await asyncio.sleep(1) + count += 1 + await asyncio.sleep(10) + expected_session_id = client.build_session_id(client.current_session) + + for _ in range(10): + await client.send_message("foo") + await client.send_message("bar") + await client.send_message("baz") + + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 + expected.sort() + + count = 0 + while count < 10 and ( + len([msg for msg in received_messages if expected_session_id in msg]) < len(expected) + or len(received_socket_mode_requests) < len(socket_mode_envelopes) + ): + await asyncio.sleep(0.2) + count += 0.2 + + received_messages.sort() + + # Only check messages of current alive session. Ignore the disconnected session. + received_messages = [msg for msg in received_messages if expected_session_id in msg] + expected = [msg + "_" + expected_session_id for msg in expected] + + self.assertEqual(received_messages, expected) + + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) + finally: + await client.close() + + @async_test + async def test_send_message_while_disconnection(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + trace_enabled=True, + ) + + try: + client.wss_uri = "ws://0.0.0.0:3001/link" + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + await client.send_message("foo") + + await client.disconnect() + await asyncio.sleep(1) # wait for the message receiver + with pytest.raises(ConnectionError): + await client.send_message("foo") + + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + await client.send_message("foo") + finally: + await client.close() diff --git a/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py b/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py new file mode 100644 index 000000000..5b408dbcf --- /dev/null +++ b/tests/slack_sdk_async/socket_mode/test_interactions_websockets.py @@ -0,0 +1,121 @@ +import asyncio +import logging +import time +import unittest +from random import randint +from typing import Optional + +import pytest +from websockets.exceptions import WebSocketException + +from slack_sdk.socket_mode.request import SocketModeRequest + +from slack_sdk.socket_mode.async_client import AsyncBaseSocketModeClient +from slack_sdk.socket_mode.websockets import SocketModeClient +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk.socket_mode.mock_socket_mode_server import ( + start_socket_mode_server, + socket_mode_envelopes, + socket_mode_hello_message, +) +from tests.slack_sdk.socket_mode.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from tests.slack_sdk_async.helpers import async_test + + +class TestInteractionsWebsockets(unittest.TestCase): + logger = logging.getLogger(__name__) + + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.web_client = AsyncWebClient( + token="xoxb-api_test", + base_url="http://localhost:8888", + ) + start_socket_mode_server(self, 3001) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_interactions(self): + received_messages = [] + received_socket_mode_requests = [] + + async def message_handler( + receiver: AsyncBaseSocketModeClient, + message: dict, + raw_message: Optional[str], + ): + self.logger.info(f"Raw Message: {raw_message}") + await asyncio.sleep(randint(50, 200) / 1000) + received_messages.append(raw_message) + + async def socket_mode_listener( + receiver: AsyncBaseSocketModeClient, + request: SocketModeRequest, + ): + self.logger.info(f"Socket Mode Request: {request}") + await asyncio.sleep(randint(50, 200) / 1000) + received_socket_mode_requests.append(request) + + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + ) + client.message_listeners.append(message_handler) + client.socket_mode_request_listeners.append(socket_mode_listener) + + try: + client.wss_uri = "ws://0.0.0.0:3001/link" + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + + for _ in range(10): + await client.send_message("foo") + await client.send_message("bar") + await client.send_message("baz") + + expected = socket_mode_envelopes + [socket_mode_hello_message] + ["foo", "bar", "baz"] * 10 + expected.sort() + + count = 0 + while count < 10 and ( + len(received_messages) < len(expected) or len(received_socket_mode_requests) < len(socket_mode_envelopes) + ): + await asyncio.sleep(0.2) + count += 0.2 + + received_messages.sort() + self.assertEqual(received_messages, expected) + + self.assertEqual(len(socket_mode_envelopes), len(received_socket_mode_requests)) + finally: + await client.close() + + @async_test + async def test_send_message_while_disconnection(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + auto_reconnect_enabled=False, + trace_enabled=True, + ) + + try: + client.wss_uri = "ws://0.0.0.0:3001/link" + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + await client.send_message("foo") + + await client.disconnect() + await asyncio.sleep(1) # wait for the message receiver + with pytest.raises(WebSocketException): + await client.send_message("foo") + + await client.connect() + await asyncio.sleep(1) # wait for the message receiver + await client.send_message("foo") + finally: + await client.close() diff --git a/tests/slack_sdk_async/socket_mode/test_websockets.py b/tests/slack_sdk_async/socket_mode/test_websockets.py new file mode 100644 index 000000000..322bd8c73 --- /dev/null +++ b/tests/slack_sdk_async/socket_mode/test_websockets.py @@ -0,0 +1,75 @@ +import unittest + +from slack_sdk.socket_mode.websockets import SocketModeClient +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk.socket_mode.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from tests.slack_sdk_async.helpers import async_test + + +class TestAiohttp(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.web_client = AsyncWebClient( + token="xoxb-api_test", + base_url="http://localhost:8888", + ) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_init_close(self): + client = SocketModeClient(app_token="xapp-A111-222-xyz") + try: + self.assertIsNotNone(client) + finally: + await client.close() + + @async_test + async def test_issue_new_wss_url(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + ) + try: + url = await client.issue_new_wss_url() + self.assertTrue(url.startswith("ws://")) + finally: + await client.close() + + @async_test + async def test_connect_to_new_endpoint(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + ) + try: + await client.connect_to_new_endpoint() + except Exception as e: + # TODO: valida test to connect + pass + finally: + await client.close() + + @async_test + async def test_enqueue_message(self): + client = SocketModeClient( + app_token="xapp-A111-222-xyz", + web_client=self.web_client, + ) + client.message_listeners.append(listener) + try: + await client.enqueue_message("hello") + await client.process_message() + + await client.enqueue_message( + """{"type":"hello","num_connections":1,"debug_info":{"host":"applink-111-222","build_number":10,"approximate_connection_time":18060},"connection_info":{"app_id":"A111"}}""" + ) + await client.process_message() + finally: + await client.close() + + +async def listener(message, raw_message): + pass diff --git a/tests/slack_sdk_async/web/test_async_chat_stream.py b/tests/slack_sdk_async/web/test_async_chat_stream.py new file mode 100644 index 000000000..212fee1e2 --- /dev/null +++ b/tests/slack_sdk_async/web/test_async_chat_stream.py @@ -0,0 +1,193 @@ +import json +import unittest +from urllib.parse import parse_qs, urlparse + +from slack_sdk.errors import SlackRequestError +from slack_sdk.models.blocks.basic_components import FeedbackButtonObject +from slack_sdk.models.blocks.block_elements import FeedbackButtonsElement, IconButtonElement +from slack_sdk.models.blocks.blocks import ContextActionsBlock +from slack_sdk.web.async_client import AsyncWebClient +from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.slack_sdk_async.helpers import async_test + + +class ChatStreamMockHandler(MockHandler): + """Extended mock handler that captures request bodies for chat stream methods""" + + def _handle(self): + try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) + + # Standard auth and validation from parent + if self.is_valid_token() and self.is_valid_user_agent(): + token = self.headers["authorization"].split(" ")[1] + parsed_path = urlparse(self.path) + len_header = self.headers.get("Content-Length") or 0 + content_len = int(len_header) + post_body = self.rfile.read(content_len) + request_body = None + if post_body: + try: + post_body = post_body.decode("utf-8") + if post_body.startswith("{"): + request_body = json.loads(post_body) + else: + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} + except UnicodeDecodeError: + pass + else: + if parsed_path and parsed_path.query: + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} + + # Store request body for chat stream endpoints + if self.path in ["/chat.startStream", "/chat.appendStream", "/chat.stopStream"] and request_body: + if not hasattr(self.server, "chat_stream_requests"): + self.server.chat_stream_requests = {} + self.server.chat_stream_requests[self.path] = { + "token": token, + **request_body, + } + + # Load response file + pattern = str(token).split("xoxb-", 1)[1] + with open(f"tests/slack_sdk_fixture/web_response_{pattern}.json") as file: + body = json.load(file) + + else: + body = self.invalid_auth + + if not body: + body = self.not_found + + self.send_response(200) + self.set_common_headers() + self.wfile.write(json.dumps(body).encode("utf-8")) + self.wfile.close() + + except Exception as e: + self.logger.error(str(e), exc_info=True) + raise + + +class TestAsyncChatStream(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, ChatStreamMockHandler) + self.client = AsyncWebClient( + token="xoxb-chat_stream_test", + base_url="http://localhost:8888", + ) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + @async_test + async def test_streams_a_short_message(self): + streamer = await self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + recipient_team_id="T0123456789", + recipient_user_id="U0123456789", + ) + await streamer.append(markdown_text="nice!") + await streamer.stop() + + self.assertEqual(self.received_requests.get("/chat.startStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.appendStream", 0), 0) + self.assertEqual(self.received_requests.get("/chat.stopStream", 0), 1) + + if hasattr(self.thread.server, "chat_stream_requests"): + start_request = self.thread.server.chat_stream_requests.get("/chat.startStream", {}) + self.assertEqual(start_request.get("channel"), "C0123456789") + self.assertEqual(start_request.get("thread_ts"), "123.000") + self.assertEqual(start_request.get("recipient_team_id"), "T0123456789") + self.assertEqual(start_request.get("recipient_user_id"), "U0123456789") + + stop_request = self.thread.server.chat_stream_requests.get("/chat.stopStream", {}) + self.assertEqual(stop_request.get("channel"), "C0123456789") + self.assertEqual(stop_request.get("ts"), "123.123") + self.assertEqual(stop_request.get("markdown_text"), "nice!") + + @async_test + async def test_streams_a_long_message(self): + streamer = await self.client.chat_stream( + buffer_size=5, + channel="C0123456789", + recipient_team_id="T0123456789", + recipient_user_id="U0123456789", + thread_ts="123.000", + ) + await streamer.append(markdown_text="**this messag") + await streamer.append(markdown_text="e is", token="xoxb-chat_stream_test_token1") + await streamer.append(markdown_text=" bold!") + await streamer.append(markdown_text="*") + await streamer.stop( + blocks=[ + ContextActionsBlock( + elements=[ + FeedbackButtonsElement( + positive_button=FeedbackButtonObject(text="good", value="+1"), + negative_button=FeedbackButtonObject(text="bad", value="-1"), + ), + IconButtonElement( + icon="trash", + text="delete", + ), + ], + ) + ], + markdown_text="*", + token="xoxb-chat_stream_test_token2", + ) + + self.assertEqual(self.received_requests.get("/chat.startStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.appendStream", 0), 1) + self.assertEqual(self.received_requests.get("/chat.stopStream", 0), 1) + + if hasattr(self.thread.server, "chat_stream_requests"): + start_request = self.thread.server.chat_stream_requests.get("/chat.startStream", {}) + self.assertEqual(start_request.get("channel"), "C0123456789") + self.assertEqual(start_request.get("thread_ts"), "123.000") + self.assertEqual(start_request.get("markdown_text"), "**this messag") + self.assertEqual(start_request.get("recipient_team_id"), "T0123456789") + self.assertEqual(start_request.get("recipient_user_id"), "U0123456789") + + append_request = self.thread.server.chat_stream_requests.get("/chat.appendStream", {}) + self.assertEqual(append_request.get("channel"), "C0123456789") + self.assertEqual(append_request.get("markdown_text"), "e is bold!") + self.assertEqual(append_request.get("token"), "xoxb-chat_stream_test_token1") + self.assertEqual(append_request.get("ts"), "123.123") + + stop_request = self.thread.server.chat_stream_requests.get("/chat.stopStream", {}) + self.assertEqual( + json.dumps(stop_request.get("blocks")), + '[{"elements": [{"negative_button": {"text": {"emoji": true, "text": "bad", "type": "plain_text"}, "value": "-1"}, "positive_button": {"text": {"emoji": true, "text": "good", "type": "plain_text"}, "value": "+1"}, "type": "feedback_buttons"}, {"icon": "trash", "text": {"emoji": true, "text": "delete", "type": "plain_text"}, "type": "icon_button"}], "type": "context_actions"}]', + ) + self.assertEqual(stop_request.get("channel"), "C0123456789") + self.assertEqual(stop_request.get("markdown_text"), "**") + self.assertEqual(stop_request.get("token"), "xoxb-chat_stream_test_token2") + self.assertEqual(stop_request.get("ts"), "123.123") + + @async_test + async def test_streams_errors_when_appending_to_an_unstarted_stream(self): + streamer = await self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + token="xoxb-chat_stream_test_missing_ts", + ) + with self.assertRaisesRegex(SlackRequestError, r"^Failed to stop stream: stream not started$"): + await streamer.stop() + + @async_test + async def test_streams_errors_when_appending_to_a_completed_stream(self): + streamer = await self.client.chat_stream( + channel="C0123456789", + thread_ts="123.000", + ) + await streamer.append(markdown_text="nice!") + await streamer.stop() + with self.assertRaisesRegex(SlackRequestError, r"^Cannot append to stream: stream state is completed$"): + await streamer.append(markdown_text="more...") + with self.assertRaisesRegex(SlackRequestError, r"^Cannot stop stream: stream state is completed$"): + await streamer.stop() diff --git a/tests/slack_sdk_async/web/test_async_slack_response.py b/tests/slack_sdk_async/web/test_async_slack_response.py new file mode 100644 index 000000000..f2820375b --- /dev/null +++ b/tests/slack_sdk_async/web/test_async_slack_response.py @@ -0,0 +1,43 @@ +import unittest + +from slack_sdk.web.async_slack_response import AsyncSlackResponse +from slack_sdk.web.async_client import AsyncWebClient + + +class TestAsyncSlackResponse(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + # https://github.com/slackapi/python-slack-sdk/issues/1100 + def test_issue_1100(self): + response = AsyncSlackResponse( + client=AsyncWebClient(token="xoxb-dummy"), + http_verb="POST", + api_url="http://localhost:3000/api.test", + req_args={}, + data=None, + headers={}, + status_code=200, + ) + with self.assertRaises(ValueError): + response["foo"] + + foo = response.get("foo") + self.assertIsNone(foo) + + # https://github.com/slackapi/python-slack-sdk/issues/1102 + def test_issue_1102(self): + response = AsyncSlackResponse( + client=AsyncWebClient(token="xoxb-dummy"), + http_verb="POST", + api_url="http://localhost:3000/api.test", + req_args={}, + data={"ok": True, "args": {"hello": "world"}}, + headers={}, + status_code=200, + ) + self.assertTrue("ok" in response) + self.assertTrue("foo" not in response) diff --git a/tests/slack_sdk_async/web/test_async_web_client.py b/tests/slack_sdk_async/web/test_async_web_client.py index 1fabbdb11..e48ad0941 100644 --- a/tests/slack_sdk_async/web/test_async_web_client.py +++ b/tests/slack_sdk_async/web/test_async_web_client.py @@ -1,26 +1,24 @@ import re import unittest -import aiohttp - import slack_sdk.errors as err +from slack_sdk.models.blocks import DividerBlock from slack_sdk.web.async_client import AsyncWebClient from tests.slack_sdk_async.helpers import async_test -from tests.slack_sdk.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestAsyncWebClient(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server_async(self, MockHandler) self.client = AsyncWebClient( - token="xoxp-1234", base_url="http://localhost:8888", + token="xoxp-1234", + base_url="http://localhost:8888", ) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) pattern_for_package_identifier = re.compile("slackclient/(\\S+)") @@ -64,20 +62,19 @@ async def test_slack_api_error_is_raised_on_unsuccessful_responses(self): @async_test async def test_slack_api_rate_limiting_exception_returns_retry_after(self): - self.client.token = "xoxb-rate_limited" + self.client.token = "xoxb-ratelimited" try: await self.client.api_test() except err.SlackApiError as slack_api_error: self.assertFalse(slack_api_error.response["ok"]) self.assertEqual(429, slack_api_error.response.status_code) - self.assertEqual(30, int(slack_api_error.response.headers["Retry-After"])) + self.assertEqual(1, int(slack_api_error.response.headers["retry-after"])) + self.assertEqual(1, int(slack_api_error.response.headers["Retry-After"])) @async_test async def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" - resp = await self.client.users_setPhoto( - image="tests/slack_sdk_fixture/slack_logo.png" - ) + resp = await self.client.users_setPhoto(image="tests/slack_sdk_fixture/slack_logo.png") self.assertEqual(200, resp.status_code) @async_test @@ -91,25 +88,25 @@ async def test_issue_560_bool_in_params_sync(self): async def test_issue_690_oauth_v2_access_async(self): self.client.token = "" resp = await self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee", + client_id="111.222", + client_secret="secret", + code="codeeeeeeeeee", ) self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee", + client_id="999.999", + client_secret="secret", + code="codeeeeeeeeee", ) @async_test async def test_issue_690_oauth_access_async(self): self.client.token = "" - resp = await self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_token_param_async(self): @@ -122,8 +119,13 @@ async def test_token_param_async(self): @async_test async def test_timeout_issue_712_async(self): + client = AsyncWebClient( + token="xoxp-1234", + base_url="http://localhost:8888", + timeout=1, + ) with self.assertRaises(Exception): - await self.client.users_list(token="xoxb-timeout") + await client.users_list(token="xoxb-timeout") @async_test async def test_html_response_body_issue_718_async(self): @@ -132,7 +134,7 @@ async def test_html_response_body_issue_718_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" + "The request to the Slack API failed. (url: http://localhost:8888/users.list, status: 404)\n" "The server responded with: {}", str(e), ) @@ -153,3 +155,15 @@ async def test_default_team_id(self): client = AsyncWebClient(base_url="http://localhost:8888", team_id="T_DEFAULT") resp = await client.users_list(token="xoxb-users_list_pagination") self.assertIsNone(resp["error"]) + + @async_test + async def test_user_auth_blocks(self): + self.client.token = "xoxb-api_test" + client = self.client + new_message = await client.chat_unfurl( + channel="C12345", + ts="1111.2222", + unfurls={}, + user_auth_blocks=[DividerBlock(), DividerBlock()], + ) + self.assertIsNone(new_message.get("error")) diff --git a/tests/slack_sdk_async/web/test_async_web_client_http_retry.py b/tests/slack_sdk_async/web/test_async_web_client_http_retry.py new file mode 100644 index 000000000..dac633aeb --- /dev/null +++ b/tests/slack_sdk_async/web/test_async_web_client_http_retry.py @@ -0,0 +1,111 @@ +import unittest + +import slack_sdk.errors as err +from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler, AsyncServerErrorRetryHandler +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk_async.helpers import async_test +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from ..fatal_error_retry_handler import FatalErrorRetryHandler +from ..my_retry_handler import MyRetryHandler + + +class TestAsyncWebClient_HttpRetries(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_remote_disconnected(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-remote_disconnected", + team_id="T111", + retry_handlers=[retry_handler], + ) + try: + await client.auth_test() + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + @async_test + async def test_ratelimited_no_retry(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-ratelimited", + team_id="T111", + ) + try: + await client.auth_test() + self.fail("An exception is expected") + except err.SlackApiError as e: + # Just running retries; no assertions for call count so far + self.assertEqual(429, e.response.status_code) + + @async_test + async def test_ratelimited(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-ratelimited_only_once", + team_id="T111", + ) + client.retry_handlers.append(AsyncRateLimitErrorRetryHandler()) + # The auto-retry should work here + await client.auth_test() + + @async_test + async def test_fatal_error_no_retry(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-fatal_error", + team_id="T111", + ) + try: + await client.auth_test() + self.fail("An exception is expected") + except err.SlackApiError as e: + self.assertEqual("fatal_error", e.response["error"]) + + @async_test + async def test_fatal_error(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-fatal_error_only_once", + team_id="T111", + ) + client.retry_handlers.append(FatalErrorRetryHandler()) + # The auto-retry should work here + await client.auth_test() + + @async_test + async def test_retries(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = AsyncWebClient( + token="xoxp-remote_disconnected", + base_url="http://localhost:8888", + retry_handlers=[retry_handler], + ) + try: + await client.auth_test() + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + @async_test + async def test_server_error(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-server_error_only_once", + team_id="T111", + ) + client.retry_handlers.append(AsyncServerErrorRetryHandler()) + # The auto-retry should work here + await client.chat_postMessage(channel="C123", text="Hi there!") diff --git a/tests/slack_sdk_async/web/test_async_web_client_logger.py b/tests/slack_sdk_async/web/test_async_web_client_logger.py new file mode 100644 index 000000000..1a267cb72 --- /dev/null +++ b/tests/slack_sdk_async/web/test_async_web_client_logger.py @@ -0,0 +1,49 @@ +import logging +import unittest + +from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.web import async_base_client +from tests.helpers import create_copy +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestAsyncWebClientLogger(unittest.TestCase): + test_logger: logging.Logger + + def setUp(self): + self.test_logger = logging.getLogger("test-logger") + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + def test_logger_property_returns_default_logger(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + self.assertEqual(client.logger.name, async_base_client.__name__) + + def test_logger_property_returns_custom_logger(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-api_test", + logger=self.test_logger, + ) + self.assertEqual(client.logger, self.test_logger) + + def test_logger_property_has_no_setter(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-api_test", + ) + with self.assertRaises(AttributeError): + client.logger = self.test_logger + + def test_ensure_async_web_client_with_logger_is_copyable(self): + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-api_test", + logger=self.test_logger, + ) + client_copy = create_copy(client) + self.assertEqual(client.logger, self.test_logger) + self.assertEqual(client_copy.logger, self.test_logger) diff --git a/tests/slack_sdk_async/web/test_web_client_coverage.py b/tests/slack_sdk_async/web/test_web_client_coverage.py index 62f106392..0a3c1687b 100644 --- a/tests/slack_sdk_async/web/test_web_client_coverage.py +++ b/tests/slack_sdk_async/web/test_web_client_coverage.py @@ -1,21 +1,21 @@ import os import unittest -import slack_sdk +import slack_sdk.errors as e from slack_sdk.models.blocks import DividerBlock from slack_sdk.models.views import View +from slack_sdk.web import WebClient from slack_sdk.web.async_client import AsyncWebClient +from slack_sdk.web.legacy_client import LegacyWebClient +from tests.mock_web_api_server import cleanup_mock_web_api_server_async, setup_mock_web_api_server_async +from tests.slack_sdk.web.mock_web_api_handler import MockHandler from tests.slack_sdk_async.helpers import async_test -from tests.slack_sdk.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) class TestWebClientCoverage(unittest.TestCase): - # 226 endpoints as of Oct 29, 2020 - # Can be fetched by running `var methodNames = [].slice.call(document.getElementsByClassName('bold')).map(e => e.text);console.log(methodNames.toString());console.log(methodNames.length);` on https://api.slack.com/methods - all_api_methods = "admin.analytics.getFile,admin.apps.approve,admin.apps.clearResolution,admin.apps.restrict,admin.apps.approved.list,admin.apps.requests.list,admin.apps.restricted.list,admin.conversations.archive,admin.conversations.convertToPrivate,admin.conversations.create,admin.conversations.delete,admin.conversations.disconnectShared,admin.conversations.getConversationPrefs,admin.conversations.getTeams,admin.conversations.invite,admin.conversations.rename,admin.conversations.search,admin.conversations.setConversationPrefs,admin.conversations.setTeams,admin.conversations.unarchive,admin.conversations.ekm.listOriginalConnectedChannelInfo,admin.conversations.restrictAccess.addGroup,admin.conversations.restrictAccess.listGroups,admin.conversations.restrictAccess.removeGroup,admin.emoji.add,admin.emoji.addAlias,admin.emoji.list,admin.emoji.remove,admin.emoji.rename,admin.inviteRequests.approve,admin.inviteRequests.deny,admin.inviteRequests.list,admin.inviteRequests.approved.list,admin.inviteRequests.denied.list,admin.teams.admins.list,admin.teams.create,admin.teams.list,admin.teams.owners.list,admin.teams.settings.info,admin.teams.settings.setDefaultChannels,admin.teams.settings.setDescription,admin.teams.settings.setDiscoverability,admin.teams.settings.setIcon,admin.teams.settings.setName,admin.usergroups.addChannels,admin.usergroups.addTeams,admin.usergroups.listChannels,admin.usergroups.removeChannels,admin.users.assign,admin.users.invite,admin.users.list,admin.users.remove,admin.users.setAdmin,admin.users.setExpiration,admin.users.setOwner,admin.users.setRegular,admin.users.session.invalidate,admin.users.session.list,admin.users.session.reset,api.test,apps.event.authorizations.list,apps.permissions.info,apps.permissions.request,apps.permissions.resources.list,apps.permissions.scopes.list,apps.permissions.users.list,apps.permissions.users.request,apps.uninstall,auth.revoke,auth.test,bots.info,calls.add,calls.end,calls.info,calls.update,calls.participants.add,calls.participants.remove,chat.delete,chat.deleteScheduledMessage,chat.getPermalink,chat.meMessage,chat.postEphemeral,chat.postMessage,chat.scheduleMessage,chat.unfurl,chat.update,chat.scheduledMessages.list,conversations.archive,conversations.close,conversations.create,conversations.history,conversations.info,conversations.invite,conversations.join,conversations.kick,conversations.leave,conversations.list,conversations.mark,conversations.members,conversations.open,conversations.rename,conversations.replies,conversations.setPurpose,conversations.setTopic,conversations.unarchive,dialog.open,dnd.endDnd,dnd.endSnooze,dnd.info,dnd.setSnooze,dnd.teamInfo,emoji.list,files.comments.delete,files.delete,files.info,files.list,files.revokePublicURL,files.sharedPublicURL,files.upload,files.remote.add,files.remote.info,files.remote.list,files.remote.remove,files.remote.share,files.remote.update,migration.exchange,oauth.access,oauth.token,oauth.v2.access,pins.add,pins.list,pins.remove,reactions.add,reactions.get,reactions.list,reactions.remove,reminders.add,reminders.complete,reminders.delete,reminders.info,reminders.list,rtm.connect,rtm.start,search.all,search.files,search.messages,stars.add,stars.list,stars.remove,team.accessLogs,team.billableInfo,team.info,team.integrationLogs,team.profile.get,usergroups.create,usergroups.disable,usergroups.enable,usergroups.list,usergroups.update,usergroups.users.list,usergroups.users.update,users.conversations,users.deletePhoto,users.getPresence,users.identity,users.info,users.list,users.lookupByEmail,users.setActive,users.setPhoto,users.setPresence,users.profile.get,users.profile.set,views.open,views.publish,views.push,views.update,workflows.stepCompleted,workflows.stepFailed,workflows.updateStep,admin.conversations.whitelist.add,admin.conversations.whitelist.listGroupsLinkedToChannel,admin.conversations.whitelist.remove,channels.archive,channels.create,channels.history,channels.info,channels.invite,channels.join,channels.kick,channels.leave,channels.list,channels.mark,channels.rename,channels.replies,channels.setPurpose,channels.setTopic,channels.unarchive,groups.archive,groups.create,groups.createChild,groups.history,groups.info,groups.invite,groups.kick,groups.leave,groups.list,groups.mark,groups.open,groups.rename,groups.replies,groups.setPurpose,groups.setTopic,groups.unarchive,im.close,im.history,im.list,im.mark,im.open,im.replies,mpim.close,mpim.history,mpim.list,mpim.mark,mpim.open,mpim.replies".split( + # 295 endpoints as of September 17, 2025 + # Can be fetched by running `var methodNames = [].slice.call(document.getElementsByClassName('apiReferenceFilterableList__listItemLink')).map(e => e.href.replace("https://api.slack.com/methods/", ""));console.log(methodNames.toString());console.log(methodNames.length);` on https://api.slack.com/methods + all_api_methods = "admin.analytics.getFile,admin.apps.activities.list,admin.apps.approve,admin.apps.clearResolution,admin.apps.restrict,admin.apps.uninstall,admin.apps.approved.list,admin.apps.config.lookup,admin.apps.config.set,admin.apps.requests.cancel,admin.apps.requests.list,admin.apps.restricted.list,admin.audit.anomaly.allow.getItem,admin.audit.anomaly.allow.updateItem,admin.auth.policy.assignEntities,admin.auth.policy.getEntities,admin.auth.policy.removeEntities,admin.barriers.create,admin.barriers.delete,admin.barriers.list,admin.barriers.update,admin.conversations.archive,admin.conversations.bulkArchive,admin.conversations.bulkDelete,admin.conversations.bulkMove,admin.conversations.convertToPrivate,admin.conversations.convertToPublic,admin.conversations.create,admin.conversations.createForObjects,admin.conversations.delete,admin.conversations.disconnectShared,admin.conversations.getConversationPrefs,admin.conversations.getCustomRetention,admin.conversations.getTeams,admin.conversations.invite,admin.conversations.linkObjects,admin.conversations.lookup,admin.conversations.removeCustomRetention,admin.conversations.rename,admin.conversations.search,admin.conversations.setConversationPrefs,admin.conversations.setCustomRetention,admin.conversations.setTeams,admin.conversations.unarchive,admin.conversations.unlinkObjects,admin.conversations.ekm.listOriginalConnectedChannelInfo,admin.conversations.restrictAccess.addGroup,admin.conversations.restrictAccess.listGroups,admin.conversations.restrictAccess.removeGroup,admin.emoji.add,admin.emoji.addAlias,admin.emoji.list,admin.emoji.remove,admin.emoji.rename,admin.functions.list,admin.functions.permissions.lookup,admin.functions.permissions.set,admin.inviteRequests.approve,admin.inviteRequests.deny,admin.inviteRequests.list,admin.inviteRequests.approved.list,admin.inviteRequests.denied.list,admin.roles.addAssignments,admin.roles.listAssignments,admin.roles.removeAssignments,admin.teams.admins.list,admin.teams.create,admin.teams.list,admin.teams.owners.list,admin.teams.settings.info,admin.teams.settings.setDefaultChannels,admin.teams.settings.setDescription,admin.teams.settings.setDiscoverability,admin.teams.settings.setIcon,admin.teams.settings.setName,admin.usergroups.addChannels,admin.usergroups.addTeams,admin.usergroups.listChannels,admin.usergroups.removeChannels,admin.users.assign,admin.users.invite,admin.users.list,admin.users.remove,admin.users.setAdmin,admin.users.setExpiration,admin.users.setOwner,admin.users.setRegular,admin.users.session.clearSettings,admin.users.session.getSettings,admin.users.session.invalidate,admin.users.session.list,admin.users.session.reset,admin.users.session.resetBulk,admin.users.session.setSettings,admin.users.unsupportedVersions.export,admin.workflows.collaborators.add,admin.workflows.collaborators.remove,admin.workflows.permissions.lookup,admin.workflows.search,admin.workflows.unpublish,admin.workflows.triggers.types.permissions.lookup,admin.workflows.triggers.types.permissions.set,api.test,apps.activities.list,apps.auth.external.delete,apps.auth.external.get,apps.connections.open,apps.uninstall,apps.datastore.bulkDelete,apps.datastore.bulkGet,apps.datastore.bulkPut,apps.datastore.count,apps.datastore.delete,apps.datastore.get,apps.datastore.put,apps.datastore.query,apps.datastore.update,apps.event.authorizations.list,apps.manifest.create,apps.manifest.delete,apps.manifest.export,apps.manifest.update,apps.manifest.validate,assistant.search.context,assistant.threads.setStatus,assistant.threads.setSuggestedPrompts,assistant.threads.setTitle,auth.revoke,auth.test,auth.teams.list,bookmarks.add,bookmarks.edit,bookmarks.list,bookmarks.remove,bots.info,calls.add,calls.end,calls.info,calls.update,calls.participants.add,calls.participants.remove,canvases.access.delete,canvases.access.set,canvases.create,canvases.delete,canvases.edit,canvases.sections.lookup,channels.mark,chat.appendStream,chat.delete,chat.deleteScheduledMessage,chat.getPermalink,chat.meMessage,chat.postEphemeral,chat.postMessage,chat.scheduleMessage,chat.scheduledMessages.list,chat.startStream,chat.stopStream,chat.unfurl,chat.update,conversations.acceptSharedInvite,conversations.approveSharedInvite,conversations.archive,conversations.close,conversations.create,conversations.declineSharedInvite,conversations.history,conversations.info,conversations.invite,conversations.inviteShared,conversations.join,conversations.kick,conversations.leave,conversations.list,conversations.listConnectInvites,conversations.mark,conversations.members,conversations.open,conversations.rename,conversations.replies,conversations.setPurpose,conversations.setTopic,conversations.unarchive,conversations.canvases.create,conversations.externalInvitePermissions.set,conversations.requestSharedInvite.approve,conversations.requestSharedInvite.deny,conversations.requestSharedInvite.list,dialog.open,dnd.endDnd,dnd.endSnooze,dnd.info,dnd.setSnooze,dnd.teamInfo,emoji.list,files.completeUploadExternal,files.delete,files.getUploadURLExternal,files.info,files.list,files.revokePublicURL,files.sharedPublicURL,files.upload,files.comments.delete,files.remote.add,files.remote.info,files.remote.list,files.remote.remove,files.remote.share,files.remote.update,functions.completeError,functions.completeSuccess,functions.distributions.permissions.add,functions.distributions.permissions.list,functions.distributions.permissions.remove,functions.distributions.permissions.set,functions.workflows.steps.list,functions.workflows.steps.responses.export,groups.mark,migration.exchange,oauth.access,oauth.v2.access,oauth.v2.exchange,openid.connect.token,openid.connect.userInfo,pins.add,pins.list,pins.remove,reactions.add,reactions.get,reactions.list,reactions.remove,reminders.add,reminders.complete,reminders.delete,reminders.info,reminders.list,rtm.connect,rtm.start,search.all,search.files,search.messages,slackLists.access.delete,slackLists.access.set,slackLists.create,slackLists.download.get,slackLists.download.start,slackLists.items.create,slackLists.items.delete,slackLists.items.delete,slackLists.items.deleteMultiple,slackLists.items.info,slackLists.items.list,slackLists.items.update,slackLists.update,stars.add,stars.list,stars.remove,team.accessLogs,team.billableInfo,team.info,team.integrationLogs,team.billing.info,team.externalTeams.disconnect,team.externalTeams.list,team.preferences.list,team.profile.get,tooling.tokens.rotate,usergroups.create,usergroups.disable,usergroups.enable,usergroups.list,usergroups.update,usergroups.users.list,usergroups.users.update,users.conversations,users.deletePhoto,users.getPresence,users.identity,users.info,users.list,users.lookupByEmail,users.setActive,users.setPhoto,users.setPresence,users.discoverableContacts.lookup,users.profile.get,users.profile.set,views.open,views.publish,views.push,views.update,workflows.featured.add,workflows.featured.list,workflows.featured.remove,workflows.featured.set,workflows.stepCompleted,workflows.stepFailed,workflows.updateStep,workflows.triggers.permissions.add,workflows.triggers.permissions.list,workflows.triggers.permissions.remove,workflows.triggers.permissions.set,im.list,im.mark,mpim.list,mpim.mark".split( "," ) @@ -23,291 +23,461 @@ class TestWebClientCoverage(unittest.TestCase): os.environ.setdefault("SLACKCLIENT_SKIP_DEPRECATION", "1") def setUp(self): - setup_mock_web_api_server(self) - self.client = slack_sdk.web.WebClient( - token="xoxb-coverage", base_url="http://localhost:8888" - ) - self.async_client = AsyncWebClient( - token="xoxb-coverage", base_url="http://localhost:8888" - ) + setup_mock_web_api_server_async(self, MockHandler) + self.client = WebClient(token="xoxb-coverage", base_url="http://localhost:8888") + self.legacy_client = LegacyWebClient(token="xoxb-coverage", base_url="http://localhost:8888") + self.async_client = AsyncWebClient(token="xoxb-coverage", base_url="http://localhost:8888") + + self.api_methods_to_call = [] for api_method in self.all_api_methods: if api_method.startswith("apps.permissions.") or api_method in [ + "apps.connections.open", # app-level token "oauth.access", "oauth.v2.access", + "oauth.v2.exchange", "oauth.token", + "openid.connect.token", + "openid.connect.userInfo", "users.setActive", - "admin.conversations.whitelist.add", # deprecated - "admin.conversations.whitelist.listGroupsLinkedToChannel", # deprecated - "admin.conversations.whitelist.remove", # deprecated + # automation platform token required ones + "apps.activities.list", + "apps.auth.external.delete", + "apps.auth.external.get", + "apps.datastore.delete", + "apps.datastore.get", + "apps.datastore.put", + "apps.datastore.query", + "apps.datastore.update", + "apps.datastore.bulkDelete", + "apps.datastore.bulkGet", + "apps.datastore.bulkPut", + "apps.datastore.count", + "functions.workflows.steps.list", + "functions.workflows.steps.responses.export", + "functions.distributions.permissions.add", + "functions.distributions.permissions.list", + "functions.distributions.permissions.remove", + "functions.distributions.permissions.set", + "workflows.triggers.permissions.add", + "workflows.triggers.permissions.list", + "workflows.triggers.permissions.remove", + "workflows.triggers.permissions.set", + "admin.workflows.triggers.types.permissions.lookup", + "admin.workflows.triggers.types.permissions.set", + # TODO: admin.audit.anomaly.allow.* / The endpoints requires a "session" token + "admin.audit.anomaly.allow.getItem", + "admin.audit.anomaly.allow.updateItem", + "assistant.search.context", # TODO: add this method in follow up PR + "conversations.requestSharedInvite.list", # TODO: add this method in follow up PR ]: continue self.api_methods_to_call.append(api_method) def tearDown(self): - cleanup_mock_web_api_server(self) - - @async_test - async def test_coverage(self): - for api_method in self.all_api_methods: - if self.api_methods_to_call.count(api_method) == 0: - continue - method_name = api_method.replace(".", "_") - method = getattr(self.client, method_name, None) - async_method = getattr(self.async_client, method_name, None) + cleanup_mock_web_api_server_async(self) - # Run the api calls with required arguments - if callable(method): - if method_name == "admin_analytics_getFile": - self.api_methods_to_call.remove( - method(date="2020-09-01", type="member")["method"] - ) - await async_method(date="2020-09-01", type="member") - elif method_name == "admin_apps_approve": - self.api_methods_to_call.remove( - method(app_id="AID123", request_id="RID123")["method"] - ) - await async_method(app_id="AID123", request_id="RID123") - elif method_name == "admin_apps_clearResolution": - self.api_methods_to_call.remove(method(app_id="AID123")["method"]) - await async_method(app_id="AID123") - elif method_name == "admin_inviteRequests_approve": - self.api_methods_to_call.remove( - method(invite_request_id="ID123")["method"] - ) - await async_method(invite_request_id="ID123") - elif method_name == "admin_inviteRequests_deny": - self.api_methods_to_call.remove( - method(invite_request_id="ID123")["method"] - ) - await async_method(invite_request_id="ID123") - elif method_name == "admin_teams_admins_list": - self.api_methods_to_call.remove(method(team_id="T123")["method"]) - await async_method(team_id="T123") - elif method_name == "admin_teams_create": - self.api_methods_to_call.remove( - method(team_domain="awesome-team", team_name="Awesome Team")[ - "method" - ] - ) - await async_method( - team_domain="awesome-team", team_name="Awesome Team" - ) - elif method_name == "admin_teams_owners_list": - self.api_methods_to_call.remove(method(team_id="T123")["method"]) - await async_method(team_id="T123") - elif method_name == "admin_teams_settings_info": - self.api_methods_to_call.remove(method(team_id="T123")["method"]) - await async_method(team_id="T123") - elif method_name == "admin_teams_settings_setDefaultChannels": - self.api_methods_to_call.remove( - method(team_id="T123", channel_ids=["C123", "C234"])["method"] - ) - method(team_id="T123", channel_ids="C123,C234") - await async_method(team_id="T123", channel_ids="C123,C234") - elif method_name == "admin_teams_settings_setDescription": - self.api_methods_to_call.remove( - method( - team_id="T123", description="Workspace for an awesome team" - )["method"] - ) - await async_method( - team_id="T123", description="Workspace for an awesome team" - ) - elif method_name == "admin_teams_settings_setDiscoverability": - self.api_methods_to_call.remove( - method(team_id="T123", discoverability="invite_only")["method"] - ) - await async_method(team_id="T123", discoverability="invite_only") - elif method_name == "admin_teams_settings_setIcon": - self.api_methods_to_call.remove( - method( - team_id="T123", - image_url="https://www.example.com/images/dummy.png", - )["method"] - ) - await async_method( + async def run_method(self, method_name, method, async_method): + # Run the api calls with required arguments + if callable(method): + if method_name == "admin_analytics_getFile": + self.api_methods_to_call.remove(method(date="2020-09-01", type="member")["method"]) + await async_method(date="2020-09-01", type="member") + elif method_name == "admin_apps_approve": + self.api_methods_to_call.remove(method(app_id="AID123", request_id="RID123")["method"]) + await async_method(app_id="AID123", request_id="RID123") + elif method_name == "admin_apps_restrict": + self.api_methods_to_call.remove(method(app_id="AID123", request_id="RID123")["method"]) + await async_method(app_id="AID123", request_id="RID123") + elif method_name == "admin_apps_uninstall": + self.api_methods_to_call.remove( + method(app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"])["method"] + ) + await async_method(app_id="AID123", enterprise_id="E111", team_ids=["T1", "T2"]) + elif method_name == "apps_manifest_create": + self.api_methods_to_call.remove(method(manifest="{}")["method"]) + await async_method(manifest="{}") + elif method_name == "apps_manifest_delete": + self.api_methods_to_call.remove(method(app_id="AID123")["method"]) + await async_method(app_id="AID123") + elif method_name == "apps_manifest_export": + self.api_methods_to_call.remove(method(app_id="AID123")["method"]) + await async_method(app_id="AID123") + elif method_name == "apps_manifest_update": + self.api_methods_to_call.remove(method(app_id="AID123", manifest="{}")["method"]) + await async_method(app_id="AID123", manifest="{}") + elif method_name == "apps_manifest_validate": + self.api_methods_to_call.remove(method(manifest="{}")["method"]) + await async_method(manifest="{}") + elif method_name == "admin_apps_requests_cancel": + self.api_methods_to_call.remove(method(request_id="XXX", enterprise_id="E111", team_id="T123")["method"]) + await async_method(request_id="XXX", enterprise_id="E111", team_id="T123") + elif method_name == "admin_apps_clearResolution": + self.api_methods_to_call.remove(method(app_id="AID123")["method"]) + await async_method(app_id="AID123") + elif method_name == "admin_apps_activities_list": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "admin_apps_config_lookup": + self.api_methods_to_call.remove(method(app_ids=["A111"])["method"]) + await async_method(app_ids=["A111"]) + elif method_name == "admin_apps_config_set": + self.api_methods_to_call.remove(method(app_id="A111")["method"]) + await async_method(app_id="A111") + elif method_name == "admin_auth_policy_getEntities": + self.api_methods_to_call.remove(method(policy_name="policyname")["method"]) + await async_method(policy_name="policyname") + elif method_name == "admin_auth_policy_assignEntities": + self.api_methods_to_call.remove( + method( + entity_ids=["1", "2"], + entity_type="type", + policy_name="policyname", + )["method"] + ) + await async_method(entity_ids=["1", "2"], entity_type="type", policy_name="policyname") + elif method_name == "admin_auth_policy_removeEntities": + self.api_methods_to_call.remove( + method( + entity_ids=["1", "2"], + entity_type="type", + policy_name="policyname", + )["method"] + ) + await async_method(entity_ids=["1", "2"], entity_type="type", policy_name="policyname") + elif method_name == "admin_conversations_createForObjects": + self.api_methods_to_call.remove( + method( + object_id="0019000000DmehKAAR", + salesforce_org_id="00DGC00000024hsuWY", + )["method"] + ) + await async_method(object_id="0019000000DmehKAAR", salesforce_org_id="00DGC00000024hsuWY") + elif method_name == "admin_conversations_linkObjects": + self.api_methods_to_call.remove( + method( + channel="C1234567890", + record_id="0019000000DmehKAAR", + salesforce_org_id="00DGC00000024hsuWY", + )["method"] + ) + await async_method( + channel="C1234567890", record_id="0019000000DmehKAAR", salesforce_org_id="00DGC00000024hsuWY" + ) + elif method_name == "admin_conversations_unlinkObjects": + self.api_methods_to_call.remove( + method( + channel="C1234567890", + new_name="new-channel-name", + )["method"] + ) + await async_method(channel="C1234567890", new_name="new-channel-name") + elif method_name == "admin_barriers_create": + self.api_methods_to_call.remove( + method( + barriered_from_usergroup_ids=["AAA"], + primary_usergroup_id="AAA", + restricted_subjects=["AAA"], + )["method"] + ) + await async_method( + barriered_from_usergroup_ids=["AAA"], + primary_usergroup_id="AAA", + restricted_subjects=["AAA"], + ) + elif method_name == "admin_barriers_update": + self.api_methods_to_call.remove( + method( + barrier_id="AAA", + barriered_from_usergroup_ids=["AAA"], + primary_usergroup_id="AAA", + restricted_subjects=["AAA"], + )["method"] + ) + await async_method( + barrier_id="AAA", + barriered_from_usergroup_ids=["AAA"], + primary_usergroup_id="AAA", + restricted_subjects=["AAA"], + ) + elif method_name == "admin_barriers_delete": + self.api_methods_to_call.remove(method(barrier_id="AAA")["method"]) + await async_method(barrier_id="AAA") + elif method_name == "admin_emoji_add": + self.api_methods_to_call.remove(method(name="eyes", url="https://www.example.com/")["method"]) + await async_method(name="eyes", url="https://www.example.com/") + elif method_name == "admin_emoji_addAlias": + self.api_methods_to_call.remove(method(name="watching", alias_for="eyes")["method"]) + await async_method(name="watching", alias_for="eyes") + elif method_name == "admin_emoji_remove": + self.api_methods_to_call.remove(method(name="eyes")["method"]) + await async_method(name="eyes") + elif method_name == "admin_emoji_rename": + self.api_methods_to_call.remove(method(name="eyes", new_name="eyez")["method"]) + await async_method(name="eyes", new_name="eyez") + elif method_name == "admin_functions_list": + self.api_methods_to_call.remove(method(app_ids=["A111"])["method"]) + await async_method(app_ids=["A111"]) + elif method_name == "admin_functions_permissions_lookup": + self.api_methods_to_call.remove(method(function_ids=["A111"])["method"]) + await async_method(function_ids=["A111"]) + elif method_name == "admin_functions_permissions_set": + self.api_methods_to_call.remove(method(function_id="F", visibility="everyone")["method"]) + await async_method(function_id="F", visibility="everyone") + elif method_name == "admin_inviteRequests_approve": + self.api_methods_to_call.remove(method(invite_request_id="ID123")["method"]) + await async_method(invite_request_id="ID123") + elif method_name == "admin_inviteRequests_deny": + self.api_methods_to_call.remove(method(invite_request_id="ID123")["method"]) + await async_method(invite_request_id="ID123") + elif method_name == "admin_roles_addAssignments": + self.api_methods_to_call.remove(method(entity_ids=["X"], user_ids=["U"], role_id="R")["method"]) + await async_method(entity_ids=["X"], user_ids=["U"], role_id="R") + elif method_name == "admin_roles_listAssignments": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "admin_roles_removeAssignments": + self.api_methods_to_call.remove(method(entity_ids=["X"], user_ids=["U"], role_id="R")["method"]) + await async_method(entity_ids=["X"], user_ids=["U"], role_id="R") + elif method_name == "admin_teams_admins_list": + self.api_methods_to_call.remove(method(team_id="T123")["method"]) + await async_method(team_id="T123") + elif method_name == "admin_teams_create": + self.api_methods_to_call.remove(method(team_domain="awesome-team", team_name="Awesome Team")["method"]) + await async_method(team_domain="awesome-team", team_name="Awesome Team") + elif method_name == "admin_teams_owners_list": + self.api_methods_to_call.remove(method(team_id="T123")["method"]) + await async_method(team_id="T123") + elif method_name == "admin_teams_settings_info": + self.api_methods_to_call.remove(method(team_id="T123")["method"]) + await async_method(team_id="T123") + elif method_name == "admin_teams_settings_setDefaultChannels": + self.api_methods_to_call.remove(method(team_id="T123", channel_ids=["C123", "C234"])["method"]) + # checking tuple compatibility as sample + method(team_id="T123", channel_ids=("C123", "C234")) + method(team_id="T123", channel_ids="C123,C234") + await async_method(team_id="T123", channel_ids="C123,C234") + elif method_name == "admin_teams_settings_setDescription": + self.api_methods_to_call.remove( + method(team_id="T123", description="Workspace for an awesome team")["method"] + ) + await async_method(team_id="T123", description="Workspace for an awesome team") + elif method_name == "admin_teams_settings_setDiscoverability": + self.api_methods_to_call.remove(method(team_id="T123", discoverability="invite_only")["method"]) + await async_method(team_id="T123", discoverability="invite_only") + elif method_name == "admin_teams_settings_setIcon": + self.api_methods_to_call.remove( + method( team_id="T123", image_url="https://www.example.com/images/dummy.png", - ) - elif method_name == "admin_teams_settings_setName": - self.api_methods_to_call.remove( - method(team_id="T123", name="Awesome Engineering Team")[ - "method" - ] - ) - await async_method(team_id="T123", name="Awesome Engineering Team") - elif method_name == "admin_usergroups_addChannels": - self.api_methods_to_call.remove( - method( - team_id="T123", - usergroup_id="S123", - channel_ids=["C1A2B3C4D", "C26Z25Y24"], - )["method"] - ) + )["method"] + ) + await async_method( + team_id="T123", + image_url="https://www.example.com/images/dummy.png", + ) + elif method_name == "admin_teams_settings_setName": + self.api_methods_to_call.remove(method(team_id="T123", name="Awesome Engineering Team")["method"]) + await async_method(team_id="T123", name="Awesome Engineering Team") + elif method_name == "admin_usergroups_addChannels": + self.api_methods_to_call.remove( method( - team_id="T123", - usergroup_id="S123", - channel_ids="C1A2B3C4D,C26Z25Y24", - ) - await async_method( team_id="T123", usergroup_id="S123", channel_ids=["C1A2B3C4D", "C26Z25Y24"], - ) - elif method_name == "admin_usergroups_addTeams": - self.api_methods_to_call.remove( - method( - team_id="T123", - usergroup_id="S123", - team_ids=["T111", "T222"], - )["method"] - ) - method( - team_id="T123", usergroup_id="S123", team_ids="T111,T222", - ) - await async_method( - team_id="T123", usergroup_id="S123", team_ids="T111,T222", - ) - elif method_name == "admin_usergroups_listChannels": - self.api_methods_to_call.remove( - method(usergroup_id="S123")["method"] - ) - method( - usergroup_id="S123", include_num_members=True, team_id="T123" - ) - method(usergroup_id="S123", include_num_members="1", team_id="T123") - method(usergroup_id="S123", include_num_members=1, team_id="T123") - method( - usergroup_id="S123", include_num_members=False, team_id="T123" - ) - method(usergroup_id="S123", include_num_members="0", team_id="T123") - method(usergroup_id="S123", include_num_members=0, team_id="T123") - await async_method( - usergroup_id="S123", include_num_members=0, team_id="T123" - ) - elif method_name == "admin_usergroups_removeChannels": - self.api_methods_to_call.remove( - method( - team_id="T123", - usergroup_id="S123", - channel_ids=["C1A2B3C4D", "C26Z25Y24"], - )["method"] - ) + )["method"] + ) + method( + team_id="T123", + usergroup_id="S123", + channel_ids="C1A2B3C4D,C26Z25Y24", + ) + await async_method( + team_id="T123", + usergroup_id="S123", + channel_ids=["C1A2B3C4D", "C26Z25Y24"], + ) + elif method_name == "admin_usergroups_addTeams": + self.api_methods_to_call.remove( method( team_id="T123", usergroup_id="S123", - channel_ids="C1A2B3C4D,C26Z25Y24", - ) - await async_method( + team_ids=["T111", "T222"], + )["method"] + ) + method( + team_id="T123", + usergroup_id="S123", + team_ids="T111,T222", + ) + await async_method( + team_id="T123", + usergroup_id="S123", + team_ids="T111,T222", + ) + elif method_name == "admin_usergroups_listChannels": + self.api_methods_to_call.remove(method(usergroup_id="S123")["method"]) + method(usergroup_id="S123", include_num_members=True, team_id="T123") + method(usergroup_id="S123", include_num_members="1", team_id="T123") + method(usergroup_id="S123", include_num_members=1, team_id="T123") + method(usergroup_id="S123", include_num_members=False, team_id="T123") + method(usergroup_id="S123", include_num_members="0", team_id="T123") + method(usergroup_id="S123", include_num_members=0, team_id="T123") + await async_method(usergroup_id="S123", include_num_members=0, team_id="T123") + elif method_name == "admin_usergroups_removeChannels": + self.api_methods_to_call.remove( + method( team_id="T123", usergroup_id="S123", - channel_ids="C1A2B3C4D,C26Z25Y24", - ) - elif method_name == "admin_users_assign": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) - await async_method(team_id="T123", user_id="W123") - elif method_name == "admin_users_invite": - self.api_methods_to_call.remove( - method( - team_id="T123", - email="test@example.com", - channel_ids=["C1A2B3C4D", "C26Z25Y24"], - )["method"] - ) + channel_ids=["C1A2B3C4D", "C26Z25Y24"], + )["method"] + ) + method( + team_id="T123", + usergroup_id="S123", + channel_ids="C1A2B3C4D,C26Z25Y24", + ) + await async_method( + team_id="T123", + usergroup_id="S123", + channel_ids="C1A2B3C4D,C26Z25Y24", + ) + elif method_name == "admin_users_assign": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) + await async_method(team_id="T123", user_id="W123") + elif method_name == "admin_users_invite": + self.api_methods_to_call.remove( method( team_id="T123", email="test@example.com", - channel_ids="C1A2B3C4D,C26Z25Y24", - ) - await async_method( - team_id="T123", - email="test@example.com", - channel_ids="C1A2B3C4D,C26Z25Y24", - ) - elif method_name == "admin_users_list": - self.api_methods_to_call.remove(method(team_id="T123")["method"]) - await async_method(team_id="T123") - elif method_name == "admin_users_remove": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) - await async_method(team_id="T123", user_id="W123") - elif method_name == "admin_users_setAdmin": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) - await async_method(team_id="T123", user_id="W123") - elif method_name == "admin_users_setExpiration": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123", expiration_ts=123)[ - "method" - ] - ) - await async_method( - team_id="T123", user_id="W123", expiration_ts=123 - ) - elif method_name == "admin_users_setOwner": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) - await async_method(team_id="T123", user_id="W123") - elif method_name == "admin_users_setRegular": - self.api_methods_to_call.remove( - method(team_id="T123", user_id="W123")["method"] - ) - await async_method(team_id="T123", user_id="W123") - elif method_name == "admin_users_session_invalidate": - self.api_methods_to_call.remove( - method(session_id="XXX", team_id="T111")["method"] - ) - await async_method(session_id="XXX", team_id="T111") - elif method_name == "admin_users_session_reset": - self.api_methods_to_call.remove(method(user_id="W123")["method"]) - await async_method(user_id="W123") - elif method_name == "apps_event_authorizations_list": - self.api_methods_to_call.remove( - method(event_context="xxx")["method"] - ) - await async_method(event_context="xxx") - elif method_name == "apps_uninstall": - self.api_methods_to_call.remove( - method(client_id="111.222", client_secret="xxx")["method"] - ) - await async_method(client_id="111.222", client_secret="xxx") - elif method_name == "calls_add": - self.api_methods_to_call.remove( - method( - external_unique_id="unique-id", - join_url="https://www.example.com", - )["method"] - ) - await async_method( + channel_ids=["C1A2B3C4D", "C26Z25Y24"], + )["method"] + ) + method( + team_id="T123", + email="test@example.com", + channel_ids="C1A2B3C4D,C26Z25Y24", + ) + await async_method( + team_id="T123", + email="test@example.com", + channel_ids="C1A2B3C4D,C26Z25Y24", + ) + elif method_name == "admin_users_list": + self.api_methods_to_call.remove(method(team_id="T123")["method"]) + await async_method(team_id="T123") + elif method_name == "admin_users_remove": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) + await async_method(team_id="T123", user_id="W123") + elif method_name == "admin_users_setAdmin": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) + await async_method(team_id="T123", user_id="W123") + elif method_name == "admin_users_setExpiration": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123", expiration_ts=123)["method"]) + await async_method(team_id="T123", user_id="W123", expiration_ts=123) + elif method_name == "admin_users_setOwner": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) + await async_method(team_id="T123", user_id="W123") + elif method_name == "admin_users_setRegular": + self.api_methods_to_call.remove(method(team_id="T123", user_id="W123")["method"]) + await async_method(team_id="T123", user_id="W123") + elif method_name == "admin_users_session_invalidate": + self.api_methods_to_call.remove(method(session_id="XXX", team_id="T111")["method"]) + await async_method(session_id="XXX", team_id="T111") + elif method_name == "admin_users_session_reset": + self.api_methods_to_call.remove(method(user_id="W123")["method"]) + await async_method(user_id="W123") + elif method_name == "admin_users_session_resetBulk": + self.api_methods_to_call.remove(method(user_ids=["W123"])["method"]) + method(user_ids="W123,W234") + await async_method(user_ids=["W123"]) + await async_method(user_ids="W123,W234") + elif method_name == "admin_users_session_getSettings": + self.api_methods_to_call.remove(method(user_ids=["W111"])["method"]) + await async_method(user_ids=["W111"]) + elif method_name == "admin_users_session_setSettings": + self.api_methods_to_call.remove(method(user_ids=["W111"])["method"]) + await async_method(user_ids=["W111"]) + elif method_name == "admin_users_session_clearSettings": + self.api_methods_to_call.remove(method(user_ids=["W111"])["method"]) + await async_method(user_ids=["W111"]) + elif method_name == "admin_workflows_search": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "admin_workflows_permissions_lookup": + self.api_methods_to_call.remove(method(workflow_ids=["W"])["method"]) + await async_method(workflow_ids=["W"]) + elif method_name == "admin_workflows_collaborators_add": + self.api_methods_to_call.remove(method(workflow_ids=["W"], collaborator_ids=["W111"])["method"]) + await async_method(workflow_ids=["W"], collaborator_ids=["W111"]) + elif method_name == "admin_workflows_collaborators_remove": + self.api_methods_to_call.remove(method(workflow_ids=["W"], collaborator_ids=["W111"])["method"]) + await async_method(workflow_ids=["W"], collaborator_ids=["W111"]) + elif method_name == "admin_workflows_unpublish": + self.api_methods_to_call.remove(method(workflow_ids=["W"])["method"]) + await async_method(workflow_ids=["W"]) + elif method_name == "apps_event_authorizations_list": + self.api_methods_to_call.remove(method(event_context="xxx")["method"]) + await async_method(event_context="xxx") + elif method_name == "apps_uninstall": + self.api_methods_to_call.remove(method(client_id="111.222", client_secret="xxx")["method"]) + await async_method(client_id="111.222", client_secret="xxx") + elif method_name == "assistant_threads_setStatus": + self.api_methods_to_call.remove( + method(channel_id="D111", thread_ts="111.222", status="is typing...")["method"] + ) + method( + channel_id="D111", + thread_ts="111.222", + status="is typing...", + loading_states=["Thinking...", "Writing..."], + ) + await async_method(channel_id="D111", thread_ts="111.222", status="is typing...") + await async_method( + channel_id="D111", + thread_ts="111.222", + status="is typing...", + loading_states=["Thinking...", "Writing..."], + ) + elif method_name == "assistant_threads_setTitle": + self.api_methods_to_call.remove(method(channel_id="D111", thread_ts="111.222", title="New chat")["method"]) + await async_method(channel_id="D111", thread_ts="111.222", title="New chat") + elif method_name == "assistant_threads_setSuggestedPrompts": + self.api_methods_to_call.remove( + method(channel_id="D111", thread_ts="111.222", prompts=[{"title": "X", "message": "Y"}])["method"] + ) + await async_method(channel_id="D111", thread_ts="111.222", prompts=[{"title": "X", "message": "Y"}]) + elif method_name == "bookmarks_add": + self.api_methods_to_call.remove(method(channel_id="C1234", title="bedtime story", type="article")["method"]) + await async_method(channel_id="C1234", title="bedtime story", type="article") + elif method_name == "bookmarks_edit": + self.api_methods_to_call.remove(method(bookmark_id="B1234", channel_id="C1234")["method"]) + await async_method(bookmark_id="B1234", channel_id="C1234") + elif method_name == "bookmarks_list": + self.api_methods_to_call.remove(method(channel_id="C1234")["method"]) + await async_method(channel_id="C1234") + elif method_name == "bookmarks_remove": + self.api_methods_to_call.remove(method(bookmark_id="B1234", channel_id="C1234")["method"]) + await async_method(bookmark_id="B1234", channel_id="C1234") + elif method_name == "calls_add": + self.api_methods_to_call.remove( + method( external_unique_id="unique-id", join_url="https://www.example.com", - ) - elif method_name == "calls_end": - self.api_methods_to_call.remove(method(id="R111")["method"]) - await async_method(id="R111") - elif method_name == "calls_info": - self.api_methods_to_call.remove(method(id="R111")["method"]) - await async_method(id="R111") - elif method_name == "calls_participants_add": - self.api_methods_to_call.remove( - method( - id="R111", - users=[ - {"slack_id": "U1H77"}, - { - "external_id": "54321678", - "display_name": "External User", - "avatar_url": "https://example.com/users/avatar1234.jpg", - }, - ], - )["method"] - ) - await async_method( + )["method"] + ) + await async_method( + external_unique_id="unique-id", + join_url="https://www.example.com", + ) + elif method_name == "calls_end": + self.api_methods_to_call.remove(method(id="R111")["method"]) + await async_method(id="R111") + elif method_name == "calls_info": + self.api_methods_to_call.remove(method(id="R111")["method"]) + await async_method(id="R111") + elif method_name == "calls_participants_add": + self.api_methods_to_call.remove( + method( id="R111", users=[ {"slack_id": "U1H77"}, @@ -317,22 +487,22 @@ async def test_coverage(self): "avatar_url": "https://example.com/users/avatar1234.jpg", }, ], - ) - elif method_name == "calls_participants_remove": - self.api_methods_to_call.remove( - method( - id="R111", - users=[ - {"slack_id": "U1H77"}, - { - "external_id": "54321678", - "display_name": "External User", - "avatar_url": "https://example.com/users/avatar1234.jpg", - }, - ], - )["method"] - ) - await async_method( + )["method"] + ) + await async_method( + id="R111", + users=[ + {"slack_id": "U1H77"}, + { + "external_id": "54321678", + "display_name": "External User", + "avatar_url": "https://example.com/users/avatar1234.jpg", + }, + ], + ) + elif method_name == "calls_participants_remove": + self.api_methods_to_call.remove( + method( id="R111", users=[ {"slack_id": "U1H77"}, @@ -342,585 +512,654 @@ async def test_coverage(self): "avatar_url": "https://example.com/users/avatar1234.jpg", }, ], - ) - elif method_name == "calls_update": - self.api_methods_to_call.remove(method(id="R111")["method"]) - await async_method(id="R111") - elif method_name == "chat_delete": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "chat_deleteScheduledMessage": - self.api_methods_to_call.remove( - method(channel="C123", scheduled_message_id="123")["method"] - ) - await async_method(channel="C123", scheduled_message_id="123") - elif method_name == "chat_getPermalink": - self.api_methods_to_call.remove( - method(channel="C123", message_ts="123.123")["method"] - ) - await async_method(channel="C123", message_ts="123.123") - elif method_name == "chat_meMessage": - self.api_methods_to_call.remove( - method(channel="C123", text=":wave: Hi there!")["method"] - ) - await async_method(channel="C123", text=":wave: Hi there!") - elif method_name == "chat_postEphemeral": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) - await async_method(channel="C123", user="U123") - elif method_name == "chat_postMessage": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "chat_scheduleMessage": - self.api_methods_to_call.remove( - method(channel="C123", post_at=123, text="Hi")["method"] - ) - await async_method(channel="C123", post_at=123, text="Hi") - elif method_name == "chat_unfurl": - self.api_methods_to_call.remove( - method( - channel="C123", - ts="123.123", - unfurls={ - "https://example.com/": { - "text": "Every day is the test." - } - }, - )["method"] - ) - await async_method( + )["method"] + ) + await async_method( + id="R111", + users=[ + {"slack_id": "U1H77"}, + { + "external_id": "54321678", + "display_name": "External User", + "avatar_url": "https://example.com/users/avatar1234.jpg", + }, + ], + ) + elif method_name == "calls_update": + self.api_methods_to_call.remove(method(id="R111")["method"]) + await async_method(id="R111") + elif method_name == "canvases_create": + self.api_methods_to_call.remove(method(document_content={})["method"]) + await async_method(document_content={}) + elif method_name == "conversations_canvases_create": + self.api_methods_to_call.remove(method(channel_id="C123", document_content={})["method"]) + await async_method(channel_id="C123", document_content={}) + elif method_name == "conversations_externalInvitePermissions_set": + self.api_methods_to_call.remove(method(action="upgrade", channel="C123", target_team="T123")["method"]) + await async_method(action="upgrade", channel="C123", target_team="T123") + elif method_name == "canvases_access_set": + self.api_methods_to_call.remove(method(canvas_id="F111", access_level="write")["method"]) + await async_method(canvas_id="F111", access_level="write") + elif method_name == "canvases_access_delete": + self.api_methods_to_call.remove(method(canvas_id="F111")["method"]) + await async_method(canvas_id="F111") + elif method_name == "canvases_delete": + self.api_methods_to_call.remove(method(canvas_id="F111")["method"]) + await async_method(canvas_id="F111") + elif method_name == "canvases_edit": + self.api_methods_to_call.remove(method(canvas_id="F111", changes=[])["method"]) + await async_method(canvas_id="F111", changes=[]) + elif method_name == "canvases_sections_lookup": + self.api_methods_to_call.remove(method(canvas_id="F123", criteria={})["method"]) + await async_method(canvas_id="F123", criteria={}) + elif method_name == "chat_appendStream": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123", markdown_text="**bold**")["method"]) + await async_method(channel="C123", ts="123.123", markdown_text="**bold**") + elif method_name == "chat_delete": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "chat_deleteScheduledMessage": + self.api_methods_to_call.remove(method(channel="C123", scheduled_message_id="123")["method"]) + await async_method(channel="C123", scheduled_message_id="123") + elif method_name == "chat_getPermalink": + self.api_methods_to_call.remove(method(channel="C123", message_ts="123.123")["method"]) + await async_method(channel="C123", message_ts="123.123") + elif method_name == "chat_meMessage": + self.api_methods_to_call.remove(method(channel="C123", text=":wave: Hi there!")["method"]) + await async_method(channel="C123", text=":wave: Hi there!") + elif method_name == "chat_postEphemeral": + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) + await async_method(channel="C123", user="U123") + elif method_name == "chat_postMessage": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "chat_scheduleMessage": + self.api_methods_to_call.remove(method(channel="C123", post_at=123, text="Hi")["method"]) + await async_method(channel="C123", post_at=123, text="Hi") + elif method_name == "chat_scheduledMessages_list": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "chat_startStream": + self.api_methods_to_call.remove(method(channel="C123", thread_ts="123.123")["method"]) + await async_method(channel="C123", thread_ts="123.123") + method(channel="C123", thread_ts="123.123", recipient_team_id="T123", recipient_user_id="U123") + await async_method(channel="C123", thread_ts="123.123", recipient_team_id="T123", recipient_user_id="U123") + elif method_name == "chat_stopStream": + self.api_methods_to_call.remove( + method(channel="C123", ts="123.123", blocks=[{"type": "markdown", "text": "**twelve**"}])["method"] + ) + await async_method(channel="C123", ts="123.123", blocks=[{"type": "markdown", "text": "**twelve**"}]) + elif method_name == "chat_unfurl": + self.api_methods_to_call.remove( + method( channel="C123", ts="123.123", - unfurls={ - "https://example.com/": {"text": "Every day is the test."} - }, - ) - elif method_name == "chat_update": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "conversations_archive": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_close": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_create": - self.api_methods_to_call.remove( - method(name="announcements")["method"] - ) - await async_method(name="announcements") - elif method_name == "conversations_history": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_info": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_invite": - self.api_methods_to_call.remove( - method(channel="C123", users=["U2345678901", "U3456789012"])[ - "method" - ] - ) - method(channel="C123", users="U2345678901,U3456789012") - await async_method( - channel="C123", users=["U2345678901", "U3456789012"] - ) - elif method_name == "conversations_join": - self.api_methods_to_call.remove(method(channel="C123")["method"]) + unfurls={"https://example.com/": {"text": "Every day is the test."}}, + )["method"] + ) + await async_method( + channel="C123", + ts="123.123", + unfurls={"https://example.com/": {"text": "Every day is the test."}}, + ) + method( + source="composer", + unfurl_id="Uxxxxxxx-909b5454-75f8-4ac4-b325-1b40e230bbd8", + unfurls={"https://example.com/": {"text": "Every day is the test."}}, + ) + await async_method( + source="composer", + unfurl_id="Uxxxxxxx-909b5454-75f8-4ac4-b325-1b40e230bbd8", + unfurls={"https://example.com/": {"text": "Every day is the test."}}, + ) + elif method_name == "chat_update": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "conversations_acceptSharedInvite": + self.api_methods_to_call.remove(method(channel_name="test-channel-name", channel_id="C123")["method"]) + method(channel_name="test-channel-name", invite_id="123") + # either invite_id or channel_id supplied or exception + self.assertRaises(e.SlackRequestError, method, channel_name="test-channel-name") + await async_method(channel_name="test-channel-name", channel_id="C123") + await async_method(channel_name="test-channel-name", invite_id="123") + with self.assertRaises(e.SlackRequestError): + await async_method(channel_name="test-channel-name") + elif method_name == "conversations_approveSharedInvite": + self.api_methods_to_call.remove(method(invite_id="123")["method"]) + await async_method(invite_id="123") + elif method_name == "conversations_archive": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_close": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_open": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_create": + self.api_methods_to_call.remove(method(name="announcements")["method"]) + await async_method(name="announcements") + elif method_name == "conversations_declineSharedInvite": + self.api_methods_to_call.remove(method(invite_id="123")["method"]) + await async_method(invite_id="123") + elif method_name == "conversations_history": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_info": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_invite": + self.api_methods_to_call.remove(method(channel="C123", users=["U2345678901", "U3456789012"])["method"]) + method(channel="C123", users="U2345678901,U3456789012") + await async_method(channel="C123", users=["U2345678901", "U3456789012"]) + elif method_name == "conversations_inviteShared": + self.api_methods_to_call.remove(method(channel="C123", emails="test@example.com")["method"]) + method(channel="C123", emails=["test2@example.com", "test3@example.com"]) + method(channel="C123", user_ids="U2345678901") + method(channel="C123", user_ids=["U2345678901", "U3456789012"]) + self.assertRaises(e.SlackRequestError, method, channel="C123") + await async_method(channel="C123", emails="test@example.com") + with self.assertRaises(e.SlackRequestError): await async_method(channel="C123") - elif method_name == "conversations_kick": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) - await async_method(channel="C123", user="U123") - elif method_name == "conversations_leave": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "conversations_members": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "conversations_rename": - self.api_methods_to_call.remove( - method(channel="C123", name="new-name")["method"] - ) - await async_method(channel="C123", name="new-name") - elif method_name == "conversations_replies": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "conversations_setPurpose": - self.api_methods_to_call.remove( - method(channel="C123", purpose="The purpose")["method"] - ) - await async_method(channel="C123", purpose="The purpose") - elif method_name == "conversations_setTopic": - self.api_methods_to_call.remove( - method(channel="C123", topic="The topic")["method"] - ) - await async_method(channel="C123", topic="The topic") - elif method_name == "conversations_unarchive": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "dialog_open": - self.api_methods_to_call.remove( - method(dialog={}, trigger_id="123")["method"] - ) - await async_method(dialog={}, trigger_id="123") - elif method_name == "dnd_setSnooze": - self.api_methods_to_call.remove(method(num_minutes=120)["method"]) - await async_method(num_minutes=120) - elif method_name == "dnd_teamInfo": - self.api_methods_to_call.remove( - method(users=["123", "U234"])["method"] - ) - method(users="U123,U234") - await async_method(users=["123", "U234"]) - elif method_name == "files_comments_delete": - self.api_methods_to_call.remove( - method(file="F123", id="FC123")["method"] - ) - await async_method(file="F123", id="FC123") - elif method_name == "files_delete": - self.api_methods_to_call.remove(method(file="F123")["method"]) - await async_method(file="F123") - elif method_name == "files_info": - self.api_methods_to_call.remove(method(file="F123")["method"]) - await async_method(file="F123") - elif method_name == "files_revokePublicURL": - self.api_methods_to_call.remove(method(file="F123")["method"]) - await async_method(file="F123") - elif method_name == "files_sharedPublicURL": - self.api_methods_to_call.remove(method(file="F123")["method"]) - await async_method(file="F123") - elif method_name == "files_upload": - self.api_methods_to_call.remove( - method(content="This is the content")["method"] - ) - await async_method(content="This is the content") - elif method_name == "files_remote_add": - self.api_methods_to_call.remove( - method( - external_id="123", - external_url="https://www.example.com/remote-files/123", - title="File title", - )["method"] - ) - await async_method( + elif method_name == "conversations_join": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_kick": + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) + await async_method(channel="C123", user="U123") + elif method_name == "conversations_listConnectInvites": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "conversations_leave": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_mark": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "conversations_members": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "conversations_rename": + self.api_methods_to_call.remove(method(channel="C123", name="new-name")["method"]) + await async_method(channel="C123", name="new-name") + elif method_name == "conversations_replies": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "conversations_requestSharedInvite_approve": + self.api_methods_to_call.remove(method(invite_id="I123")["method"]) + await async_method(invite_id="I123") + elif method_name == "conversations_requestSharedInvite_deny": + self.api_methods_to_call.remove(method(invite_id="I123")["method"]) + await async_method(invite_id="I123") + elif method_name == "conversations_setPurpose": + self.api_methods_to_call.remove(method(channel="C123", purpose="The purpose")["method"]) + await async_method(channel="C123", purpose="The purpose") + elif method_name == "conversations_setTopic": + self.api_methods_to_call.remove(method(channel="C123", topic="The topic")["method"]) + await async_method(channel="C123", topic="The topic") + elif method_name == "conversations_unarchive": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "dialog_open": + self.api_methods_to_call.remove(method(dialog={}, trigger_id="123")["method"]) + await async_method(dialog={}, trigger_id="123") + elif method_name == "dnd_setSnooze": + self.api_methods_to_call.remove(method(num_minutes=120)["method"]) + await async_method(num_minutes=120) + elif method_name == "dnd_teamInfo": + self.api_methods_to_call.remove(method(users=["123", "U234"])["method"]) + method(users="U123,U234") + await async_method(users=["123", "U234"]) + elif method_name == "files_comments_delete": + self.api_methods_to_call.remove(method(file="F123", id="FC123")["method"]) + await async_method(file="F123", id="FC123") + elif method_name == "files_delete": + self.api_methods_to_call.remove(method(file="F123")["method"]) + await async_method(file="F123") + elif method_name == "files_info": + self.api_methods_to_call.remove(method(file="F123")["method"]) + await async_method(file="F123") + elif method_name == "files_revokePublicURL": + self.api_methods_to_call.remove(method(file="F123")["method"]) + await async_method(file="F123") + elif method_name == "files_sharedPublicURL": + self.api_methods_to_call.remove(method(file="F123")["method"]) + await async_method(file="F123") + elif method_name == "files_upload": + self.api_methods_to_call.remove(method(content="This is the content")["method"]) + await async_method(content="This is the content") + elif method_name == "files_remote_add": + self.api_methods_to_call.remove( + method( external_id="123", external_url="https://www.example.com/remote-files/123", title="File title", - ) - elif method_name == "files_remote_share": - self.api_methods_to_call.remove( - method(channels="C123,G123")["method"] - ) - method(channels=["C123", "G123"]) - method(channels="C123,G123") - await async_method(channels="C123,G123") - elif method_name == "migration_exchange": - self.api_methods_to_call.remove(method(users="U123,U234")["method"]) - method(users="U123,U234") - await async_method(users="U123,U234") - elif method_name == "mpim_open": - self.api_methods_to_call.remove(method(users="U123,U234")["method"]) - method(users="U123,U234") - await async_method(users="U123,U234") - elif method_name == "oauth_access": - method = getattr(self.no_token_client, method_name, None) - method(client_id="123.123", client_secret="secret", code="123456") - await async_method( - client_id="123.123", client_secret="secret", code="123456" - ) - elif method_name == "oauth_v2_access": - method = getattr(self.no_token_client, method_name, None) - method(client_id="123.123", client_secret="secret", code="123456") - await async_method( - client_id="123.123", client_secret="secret", code="123456" - ) - elif method_name == "pins_add": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "pins_list": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "pins_remove": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "reactions_add": - self.api_methods_to_call.remove(method(name="eyes")["method"]) - await async_method(name="eyes") - elif method_name == "reactions_remove": - self.api_methods_to_call.remove(method(name="eyes")["method"]) - await async_method(name="eyes") - elif method_name == "reminders_add": - self.api_methods_to_call.remove( - method(text="The task", time=123)["method"] - ) - await async_method(text="The task", time=123) - elif method_name == "reminders_complete": - self.api_methods_to_call.remove(method(reminder="R123")["method"]) - await async_method(reminder="R123") - elif method_name == "reminders_delete": - self.api_methods_to_call.remove(method(reminder="R123")["method"]) - await async_method(reminder="R123") - elif method_name == "reminders_info": - self.api_methods_to_call.remove(method(reminder="R123")["method"]) - await async_method(reminder="R123") - elif method_name == "search_all": - self.api_methods_to_call.remove(method(query="Slack")["method"]) - await async_method(query="Slack") - elif method_name == "search_files": - self.api_methods_to_call.remove(method(query="Slack")["method"]) - await async_method(query="Slack") - elif method_name == "search_messages": - self.api_methods_to_call.remove(method(query="Slack")["method"]) - await async_method(query="Slack") - elif method_name == "usergroups_create": - self.api_methods_to_call.remove( - method(name="Engineering Team")["method"] - ) - await async_method(name="Engineering Team") - elif method_name == "usergroups_disable": - self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) - await async_method(usergroup="UG123") - elif method_name == "usergroups_enable": - self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) - await async_method(usergroup="UG123") - elif method_name == "usergroups_update": - self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) - await async_method(usergroup="UG123") - elif method_name == "usergroups_users_list": - self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) - await async_method(usergroup="UG123") - elif method_name == "usergroups_users_update": - self.api_methods_to_call.remove( - method(usergroup="UG123", users=["U123", "U234"])["method"] - ) - method(usergroup="UG123", users="U123,U234") - await async_method(usergroup="UG123", users="U123,U234") - elif method_name == "users_getPresence": - self.api_methods_to_call.remove(method(user="U123")["method"]) - await async_method(user="U123") - elif method_name == "users_info": - self.api_methods_to_call.remove(method(user="U123")["method"]) - await async_method(user="U123") - elif method_name == "users_lookupByEmail": - self.api_methods_to_call.remove( - method(email="test@example.com")["method"] - ) - await async_method(email="test@example.com") - elif method_name == "users_setPhoto": - self.api_methods_to_call.remove(method(image="README.md")["method"]) - await async_method(image="README.md") - elif method_name == "users_setPresence": - self.api_methods_to_call.remove(method(presence="away")["method"]) - await async_method(presence="away") - elif method_name == "views_open": - self.api_methods_to_call.remove( - method(trigger_id="123123", view={})["method"] - ) + )["method"] + ) + await async_method( + external_id="123", + external_url="https://www.example.com/remote-files/123", + title="File title", + ) + elif method_name == "files_remote_share": + self.api_methods_to_call.remove(method(external_id="xxx", channels="C123,G123")["method"]) + method(external_id="xxx", channels=["C123", "G123"]) + method(external_id="xxx", channels="C123,G123") + await async_method(external_id="xxx", channels="C123,G123") + elif method_name == "files_getUploadURLExternal": + self.api_methods_to_call.remove(method(filename="foo.png", length=123)["method"]) + await async_method(filename="foo.png", length=123) + elif method_name == "files_completeUploadExternal": + self.api_methods_to_call.remove(method(files=[{"id": "F111"}])["method"]) + await async_method(files=[{"id": "F111"}]) + elif method_name == "functions_completeSuccess": + self.api_methods_to_call.remove(method(function_execution_id="Fn111", outputs={"num": 123})["method"]) + await async_method(function_execution_id="Fn111", outputs={"num": 123}) + elif method_name == "functions_completeError": + self.api_methods_to_call.remove(method(function_execution_id="Fn111", error="something wrong")["method"]) + await async_method(function_execution_id="Fn111", error="something wrong") + elif method_name == "migration_exchange": + self.api_methods_to_call.remove(method(users="U123,U234")["method"]) + method(users="U123,U234") + await async_method(users="U123,U234") + elif method_name == "mpim_open": + self.api_methods_to_call.remove(method(users="U123,U234")["method"]) + method(users="U123,U234") + await async_method(users="U123,U234") + elif method_name == "pins_add": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "pins_list": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "pins_remove": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "reactions_add": + self.api_methods_to_call.remove(method(name="eyes", channel="C111", timestamp="111.222")["method"]) + await async_method(name="eyes", channel="C111", timestamp="111.222") + elif method_name == "reactions_remove": + self.api_methods_to_call.remove(method(name="eyes")["method"]) + await async_method(name="eyes") + elif method_name == "reminders_add": + self.api_methods_to_call.remove(method(text="The task", time=123)["method"]) + await async_method(text="The task", time=123) + elif method_name == "reminders_complete": + self.api_methods_to_call.remove(method(reminder="R123")["method"]) + await async_method(reminder="R123") + elif method_name == "reminders_delete": + self.api_methods_to_call.remove(method(reminder="R123")["method"]) + await async_method(reminder="R123") + elif method_name == "reminders_info": + self.api_methods_to_call.remove(method(reminder="R123")["method"]) + await async_method(reminder="R123") + elif method_name == "search_all": + self.api_methods_to_call.remove(method(query="Slack")["method"]) + await async_method(query="Slack") + elif method_name == "search_files": + self.api_methods_to_call.remove(method(query="Slack")["method"]) + await async_method(query="Slack") + elif method_name == "search_messages": + self.api_methods_to_call.remove(method(query="Slack")["method"]) + await async_method(query="Slack") + elif method_name == "slackLists_access_delete": + self.api_methods_to_call.remove(method(list_id="123")["method"]) + await async_method(list_id="123") + elif method_name == "slackLists_access_set": + self.api_methods_to_call.remove(method(list_id="123", access_level="private")["method"]) + await async_method(list_id="123", access_level="private") + elif method_name == "slackLists_create": + self.api_methods_to_call.remove(method(name="Backlog")["method"]) + await async_method(name="Backlog") + elif method_name == "slackLists_download_get": + self.api_methods_to_call.remove(method(list_id="123", job_id="123")["method"]) + await async_method(list_id="123", job_id="123") + elif method_name == "slackLists_download_start": + self.api_methods_to_call.remove(method(list_id="123")["method"]) + await async_method(list_id="123") + elif method_name == "slackLists_items_create": + self.api_methods_to_call.remove(method(list_id="123")["method"]) + await async_method(list_id="123") + elif method_name == "slackLists_items_delete": + self.api_methods_to_call.remove(method(list_id="123", id="123")["method"]) + await async_method(list_id="123", id="123") + elif method_name == "slackLists_items_deleteMultiple": + self.api_methods_to_call.remove(method(list_id="123", ids=["123", "456"])["method"]) + await async_method(list_id="123", ids=["123", "456"]) + elif method_name == "slackLists_items_info": + self.api_methods_to_call.remove(method(list_id="123", id="123")["method"]) + await async_method(list_id="123", id="123") + elif method_name == "slackLists_items_list": + self.api_methods_to_call.remove(method(list_id="123")["method"]) + await async_method(list_id="123") + elif method_name == "slackLists_items_update": + self.api_methods_to_call.remove( + method(list_id="123", cells=[{"column_id": "col123"}, {"row_id": "row123"}])["method"] + ) + await async_method(list_id="123", cells=[{"column_id": "col123"}, {"row_id": "row123"}]) + elif method_name == "slackLists_update": + self.api_methods_to_call.remove(method(id="123")["method"]) + await async_method(id="123") + elif method_name == "team_externalTeams_disconnect": + self.api_methods_to_call.remove(method(target_team="T111")["method"]) + await async_method(target_team="T111") + elif method_name == "tooling_tokens_rotate": + self.api_methods_to_call.remove(method(refresh_token="xoxe-refresh")["method"]) + await async_method(refresh_token="xoxe-refresh") + elif method_name == "usergroups_create": + self.api_methods_to_call.remove(method(name="Engineering Team")["method"]) + await async_method(name="Engineering Team") + elif method_name == "usergroups_disable": + self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) + await async_method(usergroup="UG123") + elif method_name == "usergroups_enable": + self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) + await async_method(usergroup="UG123") + elif method_name == "usergroups_update": + self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) + await async_method(usergroup="UG123") + elif method_name == "usergroups_users_list": + self.api_methods_to_call.remove(method(usergroup="UG123")["method"]) + await async_method(usergroup="UG123") + elif method_name == "usergroups_users_update": + self.api_methods_to_call.remove(method(usergroup="UG123", users=["U123", "U234"])["method"]) + method(usergroup="UG123", users="U123,U234") + await async_method(usergroup="UG123", users="U123,U234") + elif method_name == "users_getPresence": + self.api_methods_to_call.remove(method(user="U123")["method"]) + await async_method(user="U123") + elif method_name == "users_info": + self.api_methods_to_call.remove(method(user="U123")["method"]) + await async_method(user="U123") + elif method_name == "users_lookupByEmail": + self.api_methods_to_call.remove(method(email="test@example.com")["method"]) + await async_method(email="test@example.com") + elif method_name == "users_setPhoto": + self.api_methods_to_call.remove(method(image="README.md")["method"]) + await async_method(image="README.md") + elif method_name == "users_setPresence": + self.api_methods_to_call.remove(method(presence="away")["method"]) + await async_method(presence="away") + elif method_name == "views_open": + self.api_methods_to_call.remove(method(trigger_id="123123", view={})["method"]) + method( + trigger_id="123123", + view=View(type="modal", blocks=[DividerBlock()]), + ) + await async_method( + trigger_id="123123", + view=View(type="modal", blocks=[DividerBlock()]), + ) + elif method_name == "views_publish": + self.api_methods_to_call.remove(method(user_id="U123", view={})["method"]) + await async_method(user_id="U123", view={}) + elif method_name == "views_push": + self.api_methods_to_call.remove(method(trigger_id="123123", view={})["method"]) + await async_method(trigger_id="123123", view={}) + elif method_name == "views_update": + self.api_methods_to_call.remove(method(view_id="V123", view={})["method"]) + await async_method(view_id="V123", view={}) + elif method_name == "workflows_featured_add": + self.api_methods_to_call.remove(method(channel_id="C123", trigger_ids=["Ft123", "Ft234"])["method"]) + method(channel_id="C123", trigger_ids="Ft123,Ft234") + await async_method(channel_id="C123", trigger_ids=["Ft123", "Ft234"]) + await async_method(channel_id="C123", trigger_ids="Ft123,Ft234") + elif method_name == "workflows_featured_list": + self.api_methods_to_call.remove(method(channel_ids=["C123", "C234"])["method"]) + method(channel_ids="C123,C234") + await async_method(channel_ids=["C123", "C234"]) + await async_method(channel_ids="C123,C234") + elif method_name == "workflows_featured_remove": + self.api_methods_to_call.remove(method(channel_id="C123", trigger_ids=["Ft123", "Ft234"])["method"]) + method(channel_id="C123", trigger_ids="Ft123,Ft234") + await async_method(channel_id="C123", trigger_ids=["Ft123", "Ft234"]) + await async_method(channel_id="C123", trigger_ids="Ft123,Ft234") + elif method_name == "workflows_featured_set": + self.api_methods_to_call.remove(method(channel_id="C123", trigger_ids=["Ft123", "Ft234"])["method"]) + method(channel_id="C123", trigger_ids="Ft123,Ft234") + await async_method(channel_id="C123", trigger_ids=["Ft123", "Ft234"]) + await async_method(channel_id="C123", trigger_ids="Ft123,Ft234") + elif method_name == "workflows_stepCompleted": + self.api_methods_to_call.remove(method(workflow_step_execute_id="S123", outputs={})["method"]) + await async_method(workflow_step_execute_id="S123", outputs={}) + elif method_name == "workflows_stepFailed": + self.api_methods_to_call.remove(method(workflow_step_execute_id="S456", error={})["method"]) + await async_method(workflow_step_execute_id="S456", error={}) + elif method_name == "workflows_updateStep": + self.api_methods_to_call.remove(method(workflow_step_edit_id="S789", inputs={}, outputs=[])["method"]) + await async_method(workflow_step_edit_id="S789", inputs={}, outputs=[]) + elif method_name == "channels_archive": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "channels_create": + self.api_methods_to_call.remove(method(name="channel-name")["method"]) + await async_method(name="channel-name") + elif method_name == "channels_history": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "channels_info": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "channels_invite": + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) + await async_method(channel="C123", user="U123") + elif method_name == "channels_join": + self.api_methods_to_call.remove(method(name="channel-name")["method"]) + await async_method(name="channel-name") + elif method_name == "channels_kick": + self.api_methods_to_call.remove(method(channel="C123", user="U123")["method"]) + await async_method(channel="C123", user="U123") + elif method_name == "channels_leave": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "channels_mark": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "channels_rename": + self.api_methods_to_call.remove(method(channel="C123", name="new-name")["method"]) + await async_method(channel="C123", name="new-name") + elif method_name == "channels_replies": + self.api_methods_to_call.remove(method(channel="C123", thread_ts="123.123")["method"]) + await async_method(channel="C123", thread_ts="123.123") + elif method_name == "channels_setPurpose": + self.api_methods_to_call.remove(method(channel="C123", purpose="The purpose")["method"]) + await async_method(channel="C123", purpose="The purpose") + elif method_name == "channels_setTopic": + self.api_methods_to_call.remove(method(channel="C123", topic="The topic")["method"]) + await async_method(channel="C123", topic="The topic") + elif method_name == "channels_unarchive": + self.api_methods_to_call.remove(method(channel="C123")["method"]) + await async_method(channel="C123") + elif method_name == "groups_archive": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_create": + self.api_methods_to_call.remove(method(name="private-channel-name")["method"]) + await async_method(name="private-channel-name") + elif method_name == "groups_createChild": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_history": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_info": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_invite": + self.api_methods_to_call.remove(method(channel="G123", user="U123")["method"]) + await async_method(channel="G123", user="U123") + elif method_name == "groups_kick": + self.api_methods_to_call.remove(method(channel="G123", user="U123")["method"]) + await async_method(channel="G123", user="U123") + elif method_name == "groups_leave": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_mark": + self.api_methods_to_call.remove(method(channel="C123", ts="123.123")["method"]) + await async_method(channel="C123", ts="123.123") + elif method_name == "groups_open": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "groups_rename": + self.api_methods_to_call.remove(method(channel="G123", name="new-name")["method"]) + await async_method(channel="G123", name="x") + elif method_name == "groups_replies": + self.api_methods_to_call.remove(method(channel="G123", thread_ts="123.123")["method"]) + await async_method(channel="G123", thread_ts="x") + elif method_name == "groups_setPurpose": + self.api_methods_to_call.remove(method(channel="G123", purpose="The purpose")["method"]) + await async_method(channel="G123", purpose="x") + elif method_name == "groups_setTopic": + self.api_methods_to_call.remove(method(channel="G123", topic="The topic")["method"]) + await async_method(channel="G123", topic="x") + elif method_name == "groups_unarchive": + self.api_methods_to_call.remove(method(channel="G123")["method"]) + await async_method(channel="G123") + elif method_name == "im_close": + self.api_methods_to_call.remove(method(channel="D123")["method"]) + await async_method(channel="G123") + elif method_name == "im_history": + self.api_methods_to_call.remove(method(channel="D123")["method"]) + await async_method(channel="D123") + elif method_name == "im_mark": + self.api_methods_to_call.remove(method(channel="D123", ts="123.123")["method"]) + await async_method(channel="D123", ts="x") + elif method_name == "im_open": + self.api_methods_to_call.remove(method(user="U123")["method"]) + await async_method(user="U123") + elif method_name == "im_replies": + self.api_methods_to_call.remove(method(channel="D123", thread_ts="123.123")["method"]) + await async_method(channel="D123", thread_ts="x") + elif method_name == "mpim_close": + self.api_methods_to_call.remove(method(channel="D123")["method"]) + await async_method(channel="D123") + elif method_name == "mpim_history": + self.api_methods_to_call.remove(method(channel="D123")["method"]) + await async_method(channel="D123") + elif method_name == "mpim_mark": + self.api_methods_to_call.remove(method(channel="D123", ts="123.123")["method"]) + await async_method(channel="D123", ts="x") + elif method_name == "mpim_open": + self.api_methods_to_call.remove(method(users=["U123", "U234"])["method"]) + method(users="U123,U234") + await async_method(users=["U123", "U234"]) + elif method_name == "mpim_replies": + self.api_methods_to_call.remove(method(channel="D123", thread_ts="123.123")["method"]) + await async_method(channel="D123", thread_ts="123.123") + elif method_name == "admin_conversations_restrictAccess_addGroup": + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123")["method"]) + await async_method(channel_id="D123", group_id="G123") + elif method_name == "admin_conversations_restrictAccess_listGroups": + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123")["method"]) + await async_method(channel_id="D123", group_id="G123") + elif method_name == "admin_conversations_restrictAccess_removeGroup": + self.api_methods_to_call.remove(method(channel_id="D123", group_id="G123", team_id="T13")["method"]) + await async_method(channel_id="D123", group_id="G123", team_id="T123") + elif method_name == "admin_conversations_create": + self.api_methods_to_call.remove(method(is_private=False, name="Foo", team_id="T123")["method"]) + await async_method(is_private=False, name="Foo", team_id="T123") + elif method_name == "admin_conversations_delete": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_invite": + self.api_methods_to_call.remove(method(channel_id="C123", user_ids=["U123", "U456"])["method"]) + await async_method(channel_id="C123", user_ids=["U123", "U456"]) + elif method_name == "admin_conversations_archive": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_unarchive": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_rename": + self.api_methods_to_call.remove(method(channel_id="C123", name="Foo")["method"]) + await async_method(channel_id="C123", name="Foo") + elif method_name == "admin_conversations_search": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "admin_conversations_convertToPrivate": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_setConversationPrefs": + self.api_methods_to_call.remove( method( - trigger_id="123123", - view=View(type="modal", blocks=[DividerBlock()]), - ) - await async_method( - trigger_id="123123", - view=View(type="modal", blocks=[DividerBlock()]), - ) - elif method_name == "views_publish": - self.api_methods_to_call.remove( - method(user_id="U123", view={})["method"] - ) - await async_method(user_id="U123", view={}) - elif method_name == "views_push": - self.api_methods_to_call.remove( - method(trigger_id="123123", view={})["method"] - ) - await async_method(trigger_id="123123", view={}) - elif method_name == "views_update": - self.api_methods_to_call.remove( - method(view_id="V123", view={})["method"] - ) - await async_method(view_id="V123", view={}) - elif method_name == "workflows_stepCompleted": - self.api_methods_to_call.remove( - method(workflow_step_execute_id="S123", outputs={})["method"] - ) - await async_method(workflow_step_execute_id="S123", outputs={}) - elif method_name == "workflows_stepFailed": - self.api_methods_to_call.remove( - method(workflow_step_execute_id="S456", error={})["method"] - ) - await async_method(workflow_step_execute_id="S456", error={}) - elif method_name == "workflows_updateStep": - self.api_methods_to_call.remove( - method(workflow_step_edit_id="S789", inputs={}, outputs=[])[ - "method" - ] - ) - await async_method( - workflow_step_edit_id="S789", inputs={}, outputs=[] - ) - elif method_name == "channels_archive": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "channels_create": - self.api_methods_to_call.remove( - method(name="channel-name")["method"] - ) - await async_method(name="channel-name") - elif method_name == "channels_history": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "channels_info": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "channels_invite": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) - await async_method(channel="C123", user="U123") - elif method_name == "channels_join": - self.api_methods_to_call.remove( - method(name="channel-name")["method"] - ) - await async_method(name="channel-name") - elif method_name == "channels_kick": - self.api_methods_to_call.remove( - method(channel="C123", user="U123")["method"] - ) - await async_method(channel="C123", user="U123") - elif method_name == "channels_leave": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "channels_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "channels_rename": - self.api_methods_to_call.remove( - method(channel="C123", name="new-name")["method"] - ) - await async_method(channel="C123", name="new-name") - elif method_name == "channels_replies": - self.api_methods_to_call.remove( - method(channel="C123", thread_ts="123.123")["method"] - ) - await async_method(channel="C123", thread_ts="123.123") - elif method_name == "channels_setPurpose": - self.api_methods_to_call.remove( - method(channel="C123", purpose="The purpose")["method"] - ) - await async_method(channel="C123", purpose="The purpose") - elif method_name == "channels_setTopic": - self.api_methods_to_call.remove( - method(channel="C123", topic="The topic")["method"] - ) - await async_method(channel="C123", topic="The topic") - elif method_name == "channels_unarchive": - self.api_methods_to_call.remove(method(channel="C123")["method"]) - await async_method(channel="C123") - elif method_name == "groups_archive": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_create": - self.api_methods_to_call.remove( - method(name="private-channel-name")["method"] - ) - await async_method(name="private-channel-name") - elif method_name == "groups_createChild": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_history": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_info": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_invite": - self.api_methods_to_call.remove( - method(channel="G123", user="U123")["method"] - ) - await async_method(channel="G123", user="U123") - elif method_name == "groups_kick": - self.api_methods_to_call.remove( - method(channel="G123", user="U123")["method"] - ) - await async_method(channel="G123", user="U123") - elif method_name == "groups_leave": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_mark": - self.api_methods_to_call.remove( - method(channel="C123", ts="123.123")["method"] - ) - await async_method(channel="C123", ts="123.123") - elif method_name == "groups_open": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "groups_rename": - self.api_methods_to_call.remove( - method(channel="G123", name="new-name")["method"] - ) - await async_method(channel="G123", name="x") - elif method_name == "groups_replies": - self.api_methods_to_call.remove( - method(channel="G123", thread_ts="123.123")["method"] - ) - await async_method(channel="G123", thread_ts="x") - elif method_name == "groups_setPurpose": - self.api_methods_to_call.remove( - method(channel="G123", purpose="The purpose")["method"] - ) - await async_method(channel="G123", purpose="x") - elif method_name == "groups_setTopic": - self.api_methods_to_call.remove( - method(channel="G123", topic="The topic")["method"] - ) - await async_method(channel="G123", topic="x") - elif method_name == "groups_unarchive": - self.api_methods_to_call.remove(method(channel="G123")["method"]) - await async_method(channel="G123") - elif method_name == "im_close": - self.api_methods_to_call.remove(method(channel="D123")["method"]) - await async_method(channel="G123") - elif method_name == "im_history": - self.api_methods_to_call.remove(method(channel="D123")["method"]) - await async_method(channel="D123") - elif method_name == "im_mark": - self.api_methods_to_call.remove( - method(channel="D123", ts="123.123")["method"] - ) - await async_method(channel="D123", ts="x") - elif method_name == "im_open": - self.api_methods_to_call.remove(method(user="U123")["method"]) - await async_method(user="U123") - elif method_name == "im_replies": - self.api_methods_to_call.remove( - method(channel="D123", thread_ts="123.123")["method"] - ) - await async_method(channel="D123", thread_ts="x") - elif method_name == "mpim_close": - self.api_methods_to_call.remove(method(channel="D123")["method"]) - await async_method(channel="D123") - elif method_name == "mpim_history": - self.api_methods_to_call.remove(method(channel="D123")["method"]) - await async_method(channel="D123") - elif method_name == "mpim_mark": - self.api_methods_to_call.remove( - method(channel="D123", ts="123.123")["method"] - ) - await async_method(channel="D123", ts="x") - elif method_name == "mpim_open": - self.api_methods_to_call.remove( - method(users=["U123", "U234"])["method"] - ) - method(users="U123,U234") - await async_method(users=["U123", "U234"]) - elif method_name == "mpim_replies": - self.api_methods_to_call.remove( - method(channel="D123", thread_ts="123.123")["method"] - ) - await async_method(channel="D123", thread_ts="123.123") - elif method_name == "admin_conversations_restrictAccess_addGroup": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123")["method"] - ) - await async_method(channel_id="D123", group_id="G123") - elif method_name == "admin_conversations_restrictAccess_listGroups": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123")["method"] - ) - await async_method(channel_id="D123", group_id="G123") - elif method_name == "admin_conversations_restrictAccess_removeGroup": - self.api_methods_to_call.remove( - method(channel_id="D123", group_id="G123", team_id="T13")[ - "method" - ] - ) - await async_method( - channel_id="D123", group_id="G123", team_id="T123" - ) - elif method_name == "admin_conversations_create": - self.api_methods_to_call.remove( - method(is_private=False, name="Foo", team_id="T123")["method"] - ) - await async_method(is_private=False, name="Foo", team_id="T123") - elif method_name == "admin_conversations_delete": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_invite": - self.api_methods_to_call.remove( - method(channel_id="C123", user_ids=["U123", "U456"])["method"] - ) - await async_method(channel_id="C123", user_ids=["U123", "U456"]) - elif method_name == "admin_conversations_archive": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_unarchive": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_rename": - self.api_methods_to_call.remove( - method(channel_id="C123", name="Foo")["method"] - ) - await async_method(channel_id="C123", name="Foo") - elif method_name == "admin_conversations_search": - self.api_methods_to_call.remove(method()["method"]) - await async_method() - elif method_name == "admin_conversations_convertToPrivate": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_setConversationPrefs": - self.api_methods_to_call.remove( - method( - channel_id="C123", - prefs={ - "who_can_post": "type:admin,user:U1234,subteam:S1234" - }, - )["method"] - ) - await async_method( channel_id="C123", prefs={"who_can_post": "type:admin,user:U1234,subteam:S1234"}, - ) - elif method_name == "admin_conversations_getConversationPrefs": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_setTeams": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_getTeams": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif method_name == "admin_conversations_disconnectShared": - self.api_methods_to_call.remove(method(channel_id="C123")["method"]) - await async_method(channel_id="C123") - elif ( - method_name - == "admin_conversations_ekm_listOriginalConnectedChannelInfo" - ): - self.api_methods_to_call.remove(method()["method"]) - await async_method() - else: - self.api_methods_to_call.remove(method(*{})["method"]) - await async_method(*{}) + )["method"] + ) + await async_method( + channel_id="C123", + prefs={"who_can_post": "type:admin,user:U1234,subteam:S1234"}, + ) + elif method_name == "admin_conversations_getConversationPrefs": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_setTeams": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_getTeams": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_disconnectShared": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_ekm_listOriginalConnectedChannelInfo": + self.api_methods_to_call.remove(method()["method"]) + await async_method() + elif method_name == "admin_conversations_getCustomRetention": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_removeCustomRetention": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_setCustomRetention": + self.api_methods_to_call.remove(method(channel_id="C123", duration_days=365)["method"]) + await async_method(channel_id="C123", duration_days=365) + elif method_name == WebClient.admin_conversations_bulkArchive.__name__: + self.api_methods_to_call.remove(method(channel_ids=["C123", "C234"])["method"]) + await async_method(channel_ids=["C123", "C234"]) + elif method_name == WebClient.admin_conversations_bulkDelete.__name__: + self.api_methods_to_call.remove(method(channel_ids=["C123", "C234"])["method"]) + await async_method(channel_ids=["C123", "C234"]) + elif method_name == WebClient.admin_conversations_bulkMove.__name__: + self.api_methods_to_call.remove(method(channel_ids=["C123", "C234"], target_team_id="T123")["method"]) + await async_method(channel_ids=["C123", "C234"], target_team_id="T123") + elif method_name == "admin_conversations_convertToPublic": + self.api_methods_to_call.remove(method(channel_id="C123")["method"]) + await async_method(channel_id="C123") + elif method_name == "admin_conversations_lookup": + self.api_methods_to_call.remove(method(team_ids=["T111", "T222"], last_message_activity_before=10)["method"]) + await async_method(team_ids=["T111", "T222"], last_message_activity_before=10) + elif method_name == "users_discoverableContacts_lookup": + self.api_methods_to_call.remove(method(email="foo@example.com")["method"]) + await async_method(email="foo@example.com") else: - # Verify if the expected method is supported - self.assertTrue(callable(method), f"{method_name} is not supported yet") + self.api_methods_to_call.remove(method(*{})["method"]) + await async_method(*{}) + else: + # Verify if the expected method is supported + self.assertTrue(callable(method), f"{method_name} is not supported yet") + + @async_test + async def test_coverage(self): + print(self.api_methods_to_call) + for api_method in self.all_api_methods: + if self.api_methods_to_call.count(api_method) == 0: + continue + method_name = api_method.replace(".", "_") + method = getattr(self.client, method_name, None) + async_method = getattr(self.async_client, method_name, None) + await self.run_method(method_name, method, async_method) + + self.assertEqual(self.api_methods_to_call, [], "All methods should be supported") + + @async_test + async def test_legacy_coverage(self): + for api_method in self.all_api_methods: + if self.api_methods_to_call.count(api_method) == 0: + continue + method_name = api_method.replace(".", "_") + method = getattr(self.legacy_client, method_name, None) + async_method = getattr(self.async_client, method_name, None) + await self.run_method(method_name, method, async_method) - self.assertEqual( - self.api_methods_to_call, [], "All methods should be supported" - ) + self.assertEqual(self.api_methods_to_call, [], "All methods should be supported") diff --git a/tests/slack_sdk_async/web/test_web_client_issue_829.py b/tests/slack_sdk_async/web/test_web_client_issue_829.py index b551cca78..a7f438e18 100644 --- a/tests/slack_sdk_async/web/test_web_client_issue_829.py +++ b/tests/slack_sdk_async/web/test_web_client_issue_829.py @@ -3,18 +3,16 @@ import slack_sdk.errors as err from slack_sdk.web.async_client import AsyncWebClient from tests.helpers import async_test -from tests.slack_sdk.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestWebClient_Issue_829(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server_async(self, MockHandler) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) @async_test async def test_html_response_body_issue_829_async(self): @@ -24,7 +22,7 @@ async def test_html_response_body_issue_829_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" + "The request to the Slack API failed. (url: http://localhost:8888/users.list, status: 503)\n" "The server responded with: {}", str(e), ) diff --git a/tests/slack_sdk_async/web/test_web_client_issue_921_custom_logger.py b/tests/slack_sdk_async/web/test_web_client_issue_921_custom_logger.py new file mode 100644 index 000000000..9239206cf --- /dev/null +++ b/tests/slack_sdk_async/web/test_web_client_issue_921_custom_logger.py @@ -0,0 +1,37 @@ +import unittest +from logging import Logger + +from slack_sdk.web.async_client import AsyncWebClient +from tests.helpers import async_test +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestWebClient_Issue_921_CustomLogger(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_if_it_uses_custom_logger(self): + logger = CustomLogger("test-logger") + client = AsyncWebClient( + base_url="http://localhost:8888", + token="xoxb-api_test", + logger=logger, + ) + await client.chat_postMessage(channel="C111", text="hello") + self.assertTrue(logger.called) + + +class CustomLogger(Logger): + called: bool + + def __init__(self, name, level="DEBUG"): + Logger.__init__(self, name, level) + self.called = False + + def debug(self, msg, *args, **kwargs): + self.called = True diff --git a/tests/slack_sdk_async/web/test_web_client_msg_text_content_warnings.py b/tests/slack_sdk_async/web/test_web_client_msg_text_content_warnings.py new file mode 100644 index 000000000..085b103d9 --- /dev/null +++ b/tests/slack_sdk_async/web/test_web_client_msg_text_content_warnings.py @@ -0,0 +1,117 @@ +import unittest +import warnings + +from slack_sdk.web.async_client import AsyncWebClient +from tests.helpers import async_test +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async + + +class TestWebClientMessageTextContentWarnings(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_missing_text_warning_chat_postMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_postMessage(channel="C111", blocks=[]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_text_warning_chat_postEphemeral(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_postEphemeral(channel="C111", user="U111", blocks=[]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_text_warning_chat_scheduleMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_scheduleMessage(channel="C111", post_at="299876400", text="", blocks=[]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_text_warning_chat_update(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_update(channel="C111", ts="111.222", blocks=[]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_fallback_warning_chat_postMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = await client.chat_postMessage(channel="C111", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_fallback_warning_chat_postEphemeral(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = await client.chat_postEphemeral(channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_fallback_warning_chat_scheduleMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_scheduleMessage( + channel="C111", + post_at="299876400", + text="", + blocks=[], + attachments=[{"text": "hi"}], + ) + self.assertIsNone(resp["error"]) + + @async_test + async def test_missing_fallback_warning_chat_update(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = await client.chat_update(channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + @async_test + async def test_no_warning_when_markdown_text_is_provided_chat_postMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = await client.chat_postMessage(channel="C111", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + @async_test + async def test_no_warning_when_markdown_text_is_provided_chat_postEphemeral(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = await client.chat_postEphemeral(channel="C111", user="U111", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + @async_test + async def test_no_warning_when_markdown_text_is_provided_chat_scheduleMessage(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = await client.chat_scheduleMessage(channel="C111", post_at="299876400", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + @async_test + async def test_no_warning_when_markdown_text_is_provided_chat_update(self): + client = AsyncWebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = await client.chat_update(channel="C111", ts="111.222", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) diff --git a/tests/slack_sdk_async/web/test_web_client_url_format.py b/tests/slack_sdk_async/web/test_web_client_url_format.py new file mode 100644 index 000000000..d80786a1a --- /dev/null +++ b/tests/slack_sdk_async/web/test_web_client_url_format.py @@ -0,0 +1,67 @@ +import unittest + +from slack_sdk.web.async_client import AsyncWebClient +from tests.slack_sdk_async.helpers import async_test +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import ( + setup_mock_web_api_server_async, + cleanup_mock_web_api_server_async, + assert_received_request_count_async, +) + + +class TestAsyncWebClientUrlFormat(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + self.client = AsyncWebClient(token="xoxb-api_test", base_url="http://localhost:8888") + self.client_base_url_slash = AsyncWebClient(token="xoxb-api_test", base_url="http://localhost:8888/") + self.client_api = AsyncWebClient(token="xoxb-api_test", base_url="http://localhost:8888/api") + self.client_api_slash = AsyncWebClient(token="xoxb-api_test", base_url="http://localhost:8888/api/") + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_base_url_without_slash_api_method_without_slash(self): + await self.client.api_call("chat.postMessage") + await assert_received_request_count_async(self, "/chat.postMessage", 1) + + @async_test + async def test_base_url_without_slash_api_method_with_slash(self): + await self.client.api_call("/chat.postMessage") + await assert_received_request_count_async(self, "/chat.postMessage", 1) + + @async_test + async def test_base_url_with_slash_api_method_without_slash(self): + await self.client_base_url_slash.api_call("chat.postMessage") + await assert_received_request_count_async(self, "/chat.postMessage", 1) + + @async_test + async def test_base_url_with_slash_api_method_with_slash(self): + await self.client_base_url_slash.api_call("/chat.postMessage") + await assert_received_request_count_async(self, "/chat.postMessage", 1) + + @async_test + async def test_base_url_without_slash_api_method_with_slash_and_trailing_slash(self): + await self.client.api_call("/chat.postMessage/") + await assert_received_request_count_async(self, "/chat.postMessage/", 1) + + @async_test + async def test_base_url_with_api(self): + await self.client_api.api_call("chat.postMessage") + await assert_received_request_count_async(self, "/api/chat.postMessage", 1) + + @async_test + async def test_base_url_with_api_method_without_slash_method_with_slash(self): + await self.client_api.api_call("/chat.postMessage") + await assert_received_request_count_async(self, "/api/chat.postMessage", 1) + + @async_test + async def test_base_url_with_api_slash(self): + await self.client_api_slash.api_call("chat.postMessage") + await assert_received_request_count_async(self, "/api/chat.postMessage", 1) + + @async_test + async def test_base_url_with_api_slash_and_method_with_slash(self): + await self.client_api_slash.api_call("/chat.postMessage") + await assert_received_request_count_async(self, "/api/chat.postMessage", 1) diff --git a/tests/slack_sdk_async/webhook/test_async_webhook.py b/tests/slack_sdk_async/webhook/test_async_webhook.py index 6a2cc46f7..c84a0fc93 100644 --- a/tests/slack_sdk_async/webhook/test_async_webhook.py +++ b/tests/slack_sdk_async/webhook/test_async_webhook.py @@ -1,20 +1,20 @@ import unittest +from logging import Logger + from slack_sdk.models.attachments import Attachment, AttachmentField from slack_sdk.models.blocks import SectionBlock, ImageBlock from slack_sdk.webhook.async_client import AsyncWebhookClient, WebhookResponse from tests.slack_sdk_async.helpers import async_test -from tests.slack_sdk.webhook.mock_web_api_server import ( - cleanup_mock_web_api_server, - setup_mock_web_api_server, -) +from tests.slack_sdk.webhook.mock_web_api_server import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestAsyncWebhook(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server_async(self, MockHandler) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) @async_test async def test_send(self): @@ -59,7 +59,10 @@ async def test_send_blocks(self): "accessory": { "type": "datepicker", "initial_date": "1990-04-28", - "placeholder": {"type": "plain_text", "text": "Select a date",}, + "placeholder": { + "type": "plain_text", + "text": "Select a date", + }, }, }, ], @@ -126,12 +129,7 @@ async def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -161,9 +159,7 @@ async def test_timeout_issue_712(self): @async_test async def test_proxy_issue_714(self): - client = AsyncWebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = AsyncWebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(Exception): await client.send_dict({"text": "hello!"}) @@ -176,3 +172,46 @@ async def test_user_agent_customization_issue_769(self): ) resp = await client.send_dict({"text": "hi!"}) self.assertEqual(resp.body, "ok") + + @async_test + async def test_issue_919_response_url_flag_options(self): + client = AsyncWebhookClient("http://localhost:8888") + resp = await client.send( + text="hello!", + response_type="ephemeral", + replace_original=True, + blocks=[ + SectionBlock(text="Some text"), + ImageBlock(image_url="image.jpg", alt_text="an image"), + ], + ) + self.assertEqual("ok", resp.body) + + resp = await client.send( + text="hello!", + response_type="ephemeral", + delete_original=True, + blocks=[ + SectionBlock(text="Some text"), + ImageBlock(image_url="image.jpg", alt_text="an image"), + ], + ) + self.assertEqual("ok", resp.body) + + @async_test + async def test_if_it_uses_custom_logger_issue_921(self): + logger = CustomLogger("test-logger") + client = AsyncWebhookClient(url="http://localhost:8888", logger=logger) + await client.send_dict({"text": "hi!"}) + self.assertTrue(logger.called) + + +class CustomLogger(Logger): + called: bool + + def __init__(self, name, level="DEBUG"): + Logger.__init__(self, name, level) + self.called = False + + def debug(self, msg, *args, **kwargs): + self.called = True diff --git a/tests/slack_sdk_async/webhook/test_async_webhook_http_retry.py b/tests/slack_sdk_async/webhook/test_async_webhook_http_retry.py new file mode 100644 index 000000000..9f85b61be --- /dev/null +++ b/tests/slack_sdk_async/webhook/test_async_webhook_http_retry.py @@ -0,0 +1,41 @@ +import unittest + +from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler +from slack_sdk.webhook.async_client import AsyncWebhookClient +from tests.slack_sdk_async.helpers import async_test +from tests.slack_sdk.webhook.mock_web_api_server import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async +from ..my_retry_handler import MyRetryHandler + + +class TestAsyncWebhook_HttpRetries(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server_async(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server_async(self) + + @async_test + async def test_send(self): + retry_handler = MyRetryHandler(max_retry_count=2) + client = AsyncWebhookClient( + "http://localhost:8888/remote_disconnected", + retry_handlers=[retry_handler], + ) + try: + await client.send(text="hello!") + self.fail("An exception is expected") + except Exception as _: + pass + + self.assertEqual(2, retry_handler.call_count) + + @async_test + async def test_ratelimited(self): + client = AsyncWebhookClient( + "http://localhost:8888/ratelimited", + retry_handlers=[AsyncRateLimitErrorRetryHandler()], + ) + response = await client.send(text="hello!") + # Just running retries; no assertions for call count so far + self.assertEqual(429, response.status_code) diff --git a/tests/slack_sdk_fixture/view_modal_009.json b/tests/slack_sdk_fixture/view_modal_009.json index c8fe21df1..74640861e 100644 --- a/tests/slack_sdk_fixture/view_modal_009.json +++ b/tests/slack_sdk_fixture/view_modal_009.json @@ -35,7 +35,7 @@ "callback_id": "view_4", "external_id": "some-unique-id", "state": { - "values": [] + "values": {} }, "hash": "1569362015.55b5e41b", "clear_on_close": true, diff --git a/tests/slack_sdk_fixture/view_modal_010.json b/tests/slack_sdk_fixture/view_modal_010.json index 7530e9378..b01739874 100644 --- a/tests/slack_sdk_fixture/view_modal_010.json +++ b/tests/slack_sdk_fixture/view_modal_010.json @@ -30,7 +30,7 @@ "callback_id": "identify_your_modals", "external_id": "some-unique-id", "state": { - "values": [] + "values": {} }, "hash": "156772938.1827394", "clear_on_close": false, diff --git a/tests/slack_sdk_fixture/web_response_admin_convo_pagination.json b/tests/slack_sdk_fixture/web_response_admin_convo_pagination.json new file mode 100644 index 000000000..6b7bd7efd --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_admin_convo_pagination.json @@ -0,0 +1,28 @@ +{ + "ok": true, + "conversations": [ + { + "id": "C013T0FTKU3", + "name": "random", + "purpose": "test", + "member_count": 11, + "created": 1589700571, + "creator_id": "W111", + "is_private": false, + "is_archived": false, + "is_general": false, + "last_activity_ts": 1599130434000900, + "is_ext_shared": false, + "is_global_shared": false, + "is_org_default": false, + "is_org_mandatory": false, + "is_org_shared": false, + "is_frozen": false, + "internal_team_ids_count": 1, + "internal_team_ids_sample_team": "T111", + "pending_connected_team_ids": [], + "is_pending_ext_shared": false + } + ], + "next_cursor": "1" +} diff --git a/tests/slack_sdk_fixture/web_response_admin_convo_pagination_1.json b/tests/slack_sdk_fixture/web_response_admin_convo_pagination_1.json new file mode 100644 index 000000000..3a6a2ffa3 --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_admin_convo_pagination_1.json @@ -0,0 +1,5 @@ +{ + "ok": true, + "conversations": [], + "next_cursor": "" +} diff --git a/tests/slack_sdk_fixture/web_response_chat_stream_test.json b/tests/slack_sdk_fixture/web_response_chat_stream_test.json new file mode 100644 index 000000000..2b5f29d01 --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_chat_stream_test.json @@ -0,0 +1,4 @@ +{ + "ok": true, + "ts": "123.123" +} diff --git a/tests/slack_sdk_fixture/web_response_chat_stream_test_missing_ts.json b/tests/slack_sdk_fixture/web_response_chat_stream_test_missing_ts.json new file mode 100644 index 000000000..0287aedde --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_chat_stream_test_missing_ts.json @@ -0,0 +1,3 @@ +{ + "ok": true +} diff --git a/tests/slack_sdk_fixture/web_response_chat_stream_test_token1.json b/tests/slack_sdk_fixture/web_response_chat_stream_test_token1.json new file mode 100644 index 000000000..0287aedde --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_chat_stream_test_token1.json @@ -0,0 +1,3 @@ +{ + "ok": true +} diff --git a/tests/slack_sdk_fixture/web_response_chat_stream_test_token2.json b/tests/slack_sdk_fixture/web_response_chat_stream_test_token2.json new file mode 100644 index 000000000..0287aedde --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_chat_stream_test_token2.json @@ -0,0 +1,3 @@ +{ + "ok": true +} diff --git a/tests/slack_sdk_fixture/web_response_fatal_error_only_once.json b/tests/slack_sdk_fixture/web_response_fatal_error_only_once.json new file mode 100644 index 000000000..47971aa3c --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_fatal_error_only_once.json @@ -0,0 +1,3 @@ +{ + "ok": true +} \ No newline at end of file diff --git a/tests/slack_sdk_fixture/web_response_rate_limited_only_once.json b/tests/slack_sdk_fixture/web_response_rate_limited_only_once.json new file mode 100644 index 000000000..47971aa3c --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_rate_limited_only_once.json @@ -0,0 +1,3 @@ +{ + "ok": true +} \ No newline at end of file diff --git a/tests/slack_sdk_fixture/web_response_ratelimited_only_once.json b/tests/slack_sdk_fixture/web_response_ratelimited_only_once.json new file mode 100644 index 000000000..47971aa3c --- /dev/null +++ b/tests/slack_sdk_fixture/web_response_ratelimited_only_once.json @@ -0,0 +1,3 @@ +{ + "ok": true +} \ No newline at end of file diff --git a/tests/test_aiohttp_version_checker.py b/tests/test_aiohttp_version_checker.py new file mode 100644 index 000000000..ee1998992 --- /dev/null +++ b/tests/test_aiohttp_version_checker.py @@ -0,0 +1,42 @@ +import logging +import unittest + +from slack_sdk.aiohttp_version_checker import validate_aiohttp_version + + +class TestAiohttpVersionChecker(unittest.TestCase): + def setUp(self): + self.logger = logging.getLogger(__name__) + + def tearDown(self): + pass + + def test_not_recommended_versions(self): + state = {"counter": 0} + + def print(message: str): + state["counter"] = state["counter"] + 1 + + validate_aiohttp_version("2.1.3", print) + self.assertEqual(state["counter"], 1) + validate_aiohttp_version("3.6.3", print) + self.assertEqual(state["counter"], 2) + validate_aiohttp_version("3.7.0", print) + self.assertEqual(state["counter"], 3) + + def test_recommended_versions(self): + state = {"counter": 0} + + def print(message: str): + state["counter"] = state["counter"] + 1 + + validate_aiohttp_version("3.7.1", print) + self.assertEqual(state["counter"], 0) + validate_aiohttp_version("3.7.3", print) + self.assertEqual(state["counter"], 0) + validate_aiohttp_version("3.8.0", print) + self.assertEqual(state["counter"], 0) + validate_aiohttp_version("4.0.0", print) + self.assertEqual(state["counter"], 0) + validate_aiohttp_version("4.0.0rc1", print) + self.assertEqual(state["counter"], 0) diff --git a/tests/test_proxy_env_variable_loader.py b/tests/test_proxy_env_variable_loader.py new file mode 100644 index 000000000..3e9681f22 --- /dev/null +++ b/tests/test_proxy_env_variable_loader.py @@ -0,0 +1,40 @@ +import os +import unittest + +from slack_sdk.proxy_env_variable_loader import load_http_proxy_from_env +from tests.helpers import remove_os_env_temporarily, restore_os_env + + +class TestProxyEnvVariableLoader(unittest.TestCase): + def setUp(self): + self.old_env = remove_os_env_temporarily() + + def tearDown(self): + os.environ.clear() + restore_os_env(self.old_env) + + def test_load_lower_case(self): + os.environ["https_proxy"] = "http://localhost:9999" + url = load_http_proxy_from_env() + self.assertEqual(url, "http://localhost:9999") + + def test_load_upper_case(self): + os.environ["HTTPS_PROXY"] = "http://localhost:9999" + url = load_http_proxy_from_env() + self.assertEqual(url, "http://localhost:9999") + + def test_load_all_empty_case(self): + os.environ["HTTP_PROXY"] = "" + os.environ["http_proxy"] = "" + os.environ["HTTPS_PROXY"] = "" + os.environ["https_proxy"] = "" + url = load_http_proxy_from_env() + self.assertEqual(url, None) + + def test_proxy_url_is_none_case(self): + os.environ.pop("HTTPS_PROXY", None) + os.environ.pop("https_proxy", None) + os.environ.pop("HTTP_PROXY", None) + os.environ.pop("http_proxy", None) + url = load_http_proxy_from_env() + self.assertEqual(url, None) diff --git a/tests/web/classes/test_actions.py b/tests/web/classes/test_actions.py index 3042d8dbb..ed14b840e 100644 --- a/tests/web/classes/test_actions.py +++ b/tests/web/classes/test_actions.py @@ -47,9 +47,7 @@ def test_json(self): def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ActionButton( - name="button_1", text="Click me!", value=STRING_3001_CHARS - ).to_dict() + ActionButton(name="button_1", text="Click me!", value=STRING_3001_CHARS).to_dict() def test_style_validator(self): b = ActionButton(name="button_1", text="Click me!", value="btn_1") @@ -81,9 +79,7 @@ def setUp(self) -> None: def test_json(self): self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.options).to_dict(), { "name": "select_1", "text": "selector_1", @@ -94,9 +90,7 @@ def test_json(self): ) self.assertDictEqual( - ActionStaticSelector( - name="select_1", text="selector_1", options=self.option_group - ).to_dict(), + ActionStaticSelector(name="select_1", text="selector_1", options=self.option_group).to_dict(), { "name": "select_1", "text": "selector_1", @@ -108,9 +102,7 @@ def test_json(self): def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - ActionStaticSelector( - name="select_1", text="selector_1", options=self.options * 34 - ).to_dict() + ActionStaticSelector(name="select_1", text="selector_1", options=self.options * 34).to_dict() class DynamicActionSelectorTests(unittest.TestCase): @@ -155,9 +147,7 @@ def test_json(self): option = Option.from_single_value("one") self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", min_query_length=3 - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", min_query_length=3).to_dict(), { "name": "select_1", "text": "selector_1", @@ -168,9 +158,7 @@ def test_json(self): ) self.assertDictEqual( - ActionExternalSelector( - name="select_1", text="selector_1", selected_option=option - ).to_dict(), + ActionExternalSelector(name="select_1", text="selector_1", selected_option=option).to_dict(), { "name": "select_1", "text": "selector_1", diff --git a/tests/web/classes/test_attachments.py b/tests/web/classes/test_attachments.py index 29b8ed95d..ede2900fe 100644 --- a/tests/web/classes/test_attachments.py +++ b/tests/web/classes/test_attachments.py @@ -25,9 +25,7 @@ def setUp(self) -> None: self.simple = Attachment(text="some_text") def test_basic_json(self): - self.assertDictEqual( - Attachment(text="some text").to_dict(), {"text": "some text", "fields": []} - ) + self.assertDictEqual(Attachment(text="some text").to_dict(), {"text": "some text", "fields": []}) self.assertDictEqual( Attachment( @@ -36,10 +34,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -138,9 +133,7 @@ def test_basic_json(self): ActionLinkButton(text="navigate", url="http://google.com"), ] self.assertDictEqual( - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), { "text": "some text", "fields": [], @@ -158,10 +151,7 @@ def test_basic_json(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -200,14 +190,10 @@ def test_basic_json(self): ) def test_actions_length(self): - actions = [ - ActionButton(name="button_1", text="Click me", value="button_value_1") - ] * 6 + actions = [ActionButton(name="button_1", text="Click me", value="button_value_1")] * 6 with self.assertRaises(SlackObjectFormationError): - InteractiveAttachment( - text="some text", callback_id="abc123", actions=actions - ).to_dict(), + InteractiveAttachment(text="some text", callback_id="abc123", actions=actions).to_dict(), class BlockAttachmentTests(unittest.TestCase): @@ -218,6 +204,6 @@ def test_basic_json(self): ] self.assertDictEqual( - BlockAttachment(blocks=blocks).to_dict(), - {"blocks": [b.to_dict() for b in blocks]}, + BlockAttachment(fallback="foo", blocks=blocks).to_dict(), + {"fallback": "foo", "blocks": [b.to_dict() for b in blocks]}, ) diff --git a/tests/web/classes/test_blocks.py b/tests/web/classes/test_blocks.py index d38b922dc..4e9ce2fb2 100644 --- a/tests/web/classes/test_blocks.py +++ b/tests/web/classes/test_blocks.py @@ -19,7 +19,7 @@ from . import STRING_3001_CHARS -# https://api.slack.com/reference/block-kit/blocks +# https://docs.slack.dev/reference/block-kit/blocks class BlockTests(unittest.TestCase): @@ -131,9 +131,7 @@ def test_json(self): ], "type": "section", }, - SectionBlock( - text="some text", fields=[f"field{i}" for i in range(5)] - ).to_dict(), + SectionBlock(text="some text", fields=[f"field{i}" for i in range(5)]).to_dict(), ) button = LinkButtonElement(text="Click me!", url="http://google.com") @@ -171,9 +169,7 @@ def build_slack_block(cls, msg1, msg2, data): {"type": "section", "fields": []}, ] names = list(set(data.keys()) - set("user_comments")) - fields = [ - {"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names - ] + fields = [{"type": "mrkdwn", "text": f"*{name}*:\n{data[name]}"} for name in names] blocks[1]["fields"] = fields return blocks @@ -184,9 +180,7 @@ def build_slack_block_native(cls, msg1, msg2, data): SectionBlock(fields=[]), ] names: List[str] = list(set(data.keys()) - set("user_comments")) - fields = [ - MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names - ] + fields = [MarkdownTextObject.parse(f"*{name}*:\n{data[name]}") for name in names] blocks[1].fields = fields return list(b.to_dict() for b in blocks) @@ -215,9 +209,7 @@ def test_document(self): def test_json(self): self.assertDictEqual({"type": "divider"}, DividerBlock().to_dict()) - self.assertDictEqual( - {"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict() - ) + self.assertDictEqual({"type": "divider"}, DividerBlock(**{"type": "divider"}).to_dict()) def test_json_with_block_id(self): self.assertDictEqual( @@ -257,9 +249,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageBlock( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageBlock(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -268,15 +258,11 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() def test_title_length(self): with self.assertRaises(SlackObjectFormationError): - ImageBlock( - image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS - ).to_dict() + ImageBlock(image_url="http://google.com", alt_text="text", title=STRING_3001_CHARS).to_dict() # ---------------------------------------------- @@ -403,7 +389,7 @@ def test_json(self): ActionsBlock(elements=self.elements).to_dict(), ) with self.assertRaises(SlackObjectFormationError): - ActionsBlock(elements=self.elements * 3).to_dict() + ActionsBlock(elements=self.elements * 13).to_dict() # ---------------------------------------------- @@ -543,9 +529,19 @@ def test_document(self): }, { "type": "input", - "element": {"type": "plain_text_input",}, - "label": {"type": "plain_text", "text": "Label", "emoji": True,}, - "hint": {"type": "plain_text", "text": "some hint", "emoji": True,}, + "element": { + "type": "plain_text_input", + }, + "label": { + "type": "plain_text", + "text": "Label", + "emoji": True, + }, + "hint": { + "type": "plain_text", + "text": "some hint", + "emoji": True, + }, }, { "dispatch_action": True, diff --git a/tests/web/classes/test_dialogs.py b/tests/web/classes/test_dialogs.py index 6c8162fc0..2f40a71bd 100644 --- a/tests/web/classes/test_dialogs.py +++ b/tests/web/classes/test_dialogs.py @@ -11,6 +11,7 @@ DialogTextField, DialogUserSelector, ) + from slack.web.classes.dialogs import DialogBuilder from slack.web.classes.objects import Option from . import STRING_3001_CHARS, STRING_301_CHARS, STRING_51_CHARS @@ -28,54 +29,34 @@ def test_json_validators(self): with self.assertRaises(SlackObjectFormationError, msg="label length"): component(name="dialog", label=STRING_51_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="placeholder length" - ): - component( - name="dialog", label="Dialog", placeholder=STRING_301_CHARS - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="placeholder length"): + component(name="dialog", label="Dialog", placeholder=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="hint length"): - component( - name="dialog", label="Dialog", hint=STRING_301_CHARS - ).to_dict() + component(name="dialog", label="Dialog", hint=STRING_301_CHARS).to_dict() with self.assertRaises(SlackObjectFormationError, msg="value length"): - component( - name="dialog", label="Dialog", value=STRING_3001_CHARS - ).to_dict() + component(name="dialog", label="Dialog", value=STRING_3001_CHARS).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="min_length out of bounds"): component( name="dialog", label="Dialog", min_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="max_length out of bounds" - ): + with self.assertRaises(SlackObjectFormationError, msg="max_length out of bounds"): component( name="dialog", label="Dialog", max_length=component.max_value_length + 1, ).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="min_length > max length" - ): - component( - name="dialog", label="Dialog", min_length=100, max_length=50 - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="min_length > max length"): + component(name="dialog", label="Dialog", min_length=100, max_length=50).to_dict() - with self.assertRaises( - SlackObjectFormationError, msg="subtype invalid" - ): - component( - name="dialog", label="Dialog", subtype="abcdefg" - ).to_dict() + with self.assertRaises(SlackObjectFormationError, msg="subtype invalid"): + component(name="dialog", label="Dialog", subtype="abcdefg").to_dict() class TextFieldComponentTests(unittest.TestCase): @@ -158,9 +139,7 @@ def test_basic_json_formation(self): Option.from_single_value("three"), ] self.assertDictEqual( - DialogStaticSelector( - name="dialog", label="Dialog", options=options - ).to_dict(), + DialogStaticSelector(name="dialog", label="Dialog", options=options).to_dict(), { "optional": False, "label": "Dialog", @@ -197,13 +176,9 @@ def test_json(self): }, ) - passing_obj = component( - name="select_1", label="selector_1", value=self.selected_opt - ).to_dict() + passing_obj = component(name="select_1", label="selector_1", value=self.selected_opt).to_dict() - passing_str = component( - name="select_1", label="selector_1", value="U12345" - ).to_dict() + passing_str = component(name="select_1", label="selector_1", value="U12345").to_dict() expected = { "name": "select_1", @@ -256,9 +231,7 @@ def setUp(self) -> None: optional=True, hint="Enter your signature", ) - .text_area( - name="message", label="Message", hint="Enter message to broadcast" - ) + .text_area(name="message", label="Message", hint="Enter message to broadcast") .conversation_selector(name="target", label="Choose Target") ) diff --git a/tests/web/classes/test_elements.py b/tests/web/classes/test_elements.py index e2ba11bb6..215ec8aac 100644 --- a/tests/web/classes/test_elements.py +++ b/tests/web/classes/test_elements.py @@ -33,9 +33,7 @@ class InteractiveElementTests(unittest.TestCase): def test_action_id(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="click me!", action_id=STRING_301_CHARS, value="clickable button" - ).to_dict() + ButtonElement(text="click me!", action_id=STRING_301_CHARS, value="clickable button").to_dict() class ButtonElementTests(unittest.TestCase): @@ -62,7 +60,7 @@ def test_document_3(self): input = { "type": "button", "text": {"type": "plain_text", "text": "Link Button"}, - "url": "https://api.slack.com/block-kit", + "url": "https://docs.slack.dev/block-kit/", } self.assertDictEqual(input, ButtonElement(**input).to_dict()) self.assertDictEqual(input, LinkButtonElement(**input).to_dict()) @@ -75,9 +73,7 @@ def test_json(self): "value": "button_123", "type": "button", }, - ButtonElement( - text="button text", action_id="some_button", value="button_123" - ).to_dict(), + ButtonElement(text="button text", action_id="some_button", value="button_123").to_dict(), ) confirm = ConfirmObject(title="really?", text="are you sure?") @@ -101,28 +97,20 @@ def test_json(self): def test_text_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text=STRING_301_CHARS, action_id="button", value="click_me" - ).to_dict() + ButtonElement(text=STRING_301_CHARS, action_id="button", value="click_me").to_dict() def test_value_length(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value=STRING_3001_CHARS - ).to_dict() + ButtonElement(text="Button", action_id="button", value=STRING_3001_CHARS).to_dict() def test_invalid_style(self): with self.assertRaises(SlackObjectFormationError): - ButtonElement( - text="Button", action_id="button", value="button", style="invalid" - ).to_dict() + ButtonElement(text="Button", action_id="button", value="button", style="invalid").to_dict() class LinkButtonElementTests(unittest.TestCase): def test_json(self): - button = LinkButtonElement( - action_id="test", text="button text", url="http://google.com" - ) + button = LinkButtonElement(action_id="test", text="button text", url="http://google.com") self.assertDictEqual( { "text": {"emoji": True, "text": "button text", "type": "plain_text"}, @@ -148,9 +136,7 @@ def test_document(self): input = { "type": "checkboxes", "action_id": "this_is_an_action_id", - "initial_options": [ - {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}} - ], + "initial_options": [{"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}], "options": [ {"value": "A1", "text": {"type": "plain_text", "text": "Checkbox 1"}}, {"value": "A2", "text": {"type": "plain_text", "text": "Checkbox 2"}}, @@ -236,9 +222,7 @@ def test_json(self): "alt_text": "not really an image", "type": "image", }, - ImageElement( - image_url="http://google.com", alt_text="not really an image" - ).to_dict(), + ImageElement(image_url="http://google.com", alt_text="not really an image").to_dict(), ) def test_image_url_length(self): @@ -247,9 +231,7 @@ def test_image_url_length(self): def test_alt_text_length(self): with self.assertRaises(SlackObjectFormationError): - ImageElement( - image_url="http://google.com", alt_text=STRING_3001_CHARS - ).to_dict() + ImageElement(image_url="http://google.com", alt_text=STRING_3001_CHARS).to_dict() # ------------------------------------------------- @@ -495,9 +477,7 @@ def test_json(self): "min_query_length": 5, "type": "external_select", }, - ExternalDataSelectElement( - placeholder="selectedValue", action_id="dropdown", min_query_length=5 - ).to_dict(), + ExternalDataSelectElement(placeholder="selectedValue", action_id="dropdown", min_query_length=5).to_dict(), ) self.assertDictEqual( { @@ -551,10 +531,16 @@ def test_json(self): "action_id": "a-123", "type": "users_select", "initial_user": "U123", - "placeholder": {"type": "plain_text", "text": "abc", "emoji": True,}, + "placeholder": { + "type": "plain_text", + "text": "abc", + "emoji": True, + }, }, UserSelectElement( - placeholder="abc", action_id="a-123", initial_user="U123", + placeholder="abc", + action_id="a-123", + initial_user="U123", ).to_dict(), ) @@ -649,7 +635,7 @@ def test_document(self): }, { "text": {"type": "plain_text", "text": "*this is plain_text text*"}, - # https://api.slack.com/reference/block-kit/composition-objects#option + # https://docs.slack.dev/reference/block-kit/composition-objects/option-object "url": "https://www.example.com", }, ], diff --git a/tests/web/classes/test_messages.py b/tests/web/classes/test_messages.py new file mode 100644 index 000000000..df07cbf0b --- /dev/null +++ b/tests/web/classes/test_messages.py @@ -0,0 +1,9 @@ +import unittest + +from slack_sdk.models.messages.message import Message + + +class MessageTests(unittest.TestCase): + def test_validate_json_fails(self): + msg = Message(text="Hi there") + self.assertIsNotNone(msg) diff --git a/tests/web/classes/test_objects.py b/tests/web/classes/test_objects.py index a1b018b01..1fd986c69 100644 --- a/tests/web/classes/test_objects.py +++ b/tests/web/classes/test_objects.py @@ -41,7 +41,10 @@ class KeyValueObject(JsonObject): attributes = {"name", "value"} def __init__( - self, *, name: Optional[str] = None, value: Optional[str] = None, + self, + *, + name: Optional[str] = None, + value: Optional[str] = None, ): self.name = name self.value = value @@ -56,12 +59,8 @@ def __init__( initial: Union[dict, KeyValueObject], options: List[Union[dict, KeyValueObject]], ): - self.initial = ( - KeyValueObject(**initial) if isinstance(initial, dict) else initial - ) - self.options = [ - KeyValueObject(**o) if isinstance(o, dict) else o for o in options - ] + self.initial = KeyValueObject(**initial) if isinstance(initial, dict) else initial + self.options = [KeyValueObject(**o) if isinstance(o, dict) else o for o in options] class JsonObjectTests(unittest.TestCase): @@ -184,12 +183,8 @@ def setUp(self) -> None: self.epoch = 1234567890 def test_simple_formation(self): - datelink = DateLink( - date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}" - ) - self.assertEqual( - f"{datelink}", f"" - ) + datelink = DateLink(date=self.epoch, date_format="{date_long}", fallback=f"{self.epoch}") + self.assertEqual(f"{datelink}", f"") def test_with_url(self): datelink = DateLink( @@ -251,9 +246,7 @@ def test_basic_json(self): def test_from_string(self): plaintext = PlainTextObject(text="some text", emoji=True) - self.assertDictEqual( - plaintext.to_dict(), PlainTextObject.direct_from_string("some text") - ) + self.assertDictEqual(plaintext.to_dict(), PlainTextObject.direct_from_string("some text")) class MarkdownTextObjectTests(unittest.TestCase): @@ -270,9 +263,7 @@ def test_basic_json(self): def test_from_string(self): markdown = MarkdownTextObject(text="some text") - self.assertDictEqual( - markdown.to_dict(), MarkdownTextObject.direct_from_string("some text") - ) + self.assertDictEqual(markdown.to_dict(), MarkdownTextObject.direct_from_string("some text")) class ConfirmObjectTests(unittest.TestCase): @@ -363,15 +354,11 @@ def test_text_length_with_object(self): def test_confirm_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", confirm=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", confirm=STRING_51_CHARS).to_dict() def test_deny_length(self): with self.assertRaises(SlackObjectFormationError): - ConfirmObject( - title="title", text="Are you sure?", deny=STRING_51_CHARS - ).to_dict() + ConfirmObject(title="title", text="Are you sure?", deny=STRING_51_CHARS).to_dict() class OptionTests(unittest.TestCase): @@ -471,15 +458,11 @@ def test_action_style_json(self): def test_label_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict( - "text" - ) + OptionGroup(label=STRING_301_CHARS, options=self.common_options).to_dict("text") def test_options_length(self): with self.assertRaises(SlackObjectFormationError): - OptionGroup(label="option_group", options=self.common_options * 34).to_dict( - "text" - ) + OptionGroup(label="option_group", options=self.common_options * 34).to_dict("text") def test_confirm_style(self): obj = ConfirmObject.parse( diff --git a/tests/web/classes/test_views.py b/tests/web/classes/test_views.py index 9e2c36962..dd08426ff 100644 --- a/tests/web/classes/test_views.py +++ b/tests/web/classes/test_views.py @@ -68,9 +68,7 @@ def test_valid_construction(self): ), SectionBlock( block_id="sb-id", - text=MarkdownTextObject( - text="This is a mrkdwn text section block." - ), + text=MarkdownTextObject(text="This is a mrkdwn text section block."), fields=[ PlainTextObject(text="*this is plain_text text*", emoji=True), MarkdownTextObject(text="*this is mrkdwn text*"), @@ -80,31 +78,23 @@ def test_valid_construction(self): DividerBlock(), SectionBlock( block_id="rb-id", - text=MarkdownTextObject( - text="This is a section block with radio button accessory" - ), + text=MarkdownTextObject(text="This is a section block with radio button accessory"), accessory=RadioButtonsElement( initial_option=Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), options=[ Option( text=PlainTextObject(text="Option 1"), value="option 1", - description=PlainTextObject( - text="Description for option 1" - ), + description=PlainTextObject(text="Description for option 1"), ), Option( text=PlainTextObject(text="Option 2"), value="option 2", - description=PlainTextObject( - text="Description for option 2" - ), + description=PlainTextObject(text="Description for option 2"), ), ], ), @@ -255,14 +245,8 @@ def test_all_state_values(self): } state = ViewState( values={ - "b1": { - "a1": ViewStateValue(type="datepicker", selected_date="1990-04-12") - }, - "b2": { - "a2": ViewStateValue( - type="plain_text_input", value="This is a test" - ) - }, + "b1": {"a1": ViewStateValue(type="datepicker", selected_date="1990-04-12")}, + "b2": {"a2": ViewStateValue(type="plain_text_input", value="This is a test")}, "b3": { "a3": ViewStateValue( type="plain_text_input", @@ -270,46 +254,26 @@ def test_all_state_values(self): ) }, "b4": {"a4": ViewStateValue(type="users_select", selected_user="U123")}, - "b4-2": { - "a4-2": ViewStateValue( - type="multi_users_select", selected_users=["U123", "U234"] - ) - }, - "b5": { - "a5": ViewStateValue( - type="conversations_select", selected_conversation="C123" - ) - }, + "b4-2": {"a4-2": ViewStateValue(type="multi_users_select", selected_users=["U123", "U234"])}, + "b5": {"a5": ViewStateValue(type="conversations_select", selected_conversation="C123")}, "b5-2": { "a5-2": ViewStateValue( type="multi_conversations_select", selected_conversations=["C123", "C234"], ) }, - "b6": { - "a6": ViewStateValue( - type="channels_select", selected_channel="C123" - ) - }, - "b6-2": { - "a6-2": ViewStateValue( - type="multi_channels_select", selected_channels=["C123", "C234"] - ) - }, + "b6": {"a6": ViewStateValue(type="channels_select", selected_channel="C123")}, + "b6-2": {"a6-2": ViewStateValue(type="multi_channels_select", selected_channels=["C123", "C234"])}, "b7": { "a7": ViewStateValue( type="multi_static_select", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -320,15 +284,11 @@ def test_all_state_values(self): type="checkboxes", selected_options=[ Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-0", ), Option( - text=PlainTextObject( - text="*this is plain_text text*", emoji=True - ), + text=PlainTextObject(text="*this is plain_text text*", emoji=True), value="value-1", ), ], @@ -340,9 +300,7 @@ def test_all_state_values(self): selected_option=Option( text=PlainTextObject(text="Option 1", emoji=True), value="option 1", - description=PlainTextObject( - text="Description for option 1", emoji=True - ), + description=PlainTextObject(text="Description for option 1", emoji=True), ), ) }, @@ -400,9 +358,7 @@ def test_home_tab_construction(self): type="home", blocks=[ SectionBlock( - text=MarkdownTextObject( - text="*Here's what you can do with Project Tracker:*" - ), + text=MarkdownTextObject(text="*Here's what you can do with Project Tracker:*"), ), ActionsBlock( elements=[ @@ -416,7 +372,8 @@ def test_home_tab_construction(self): value="create_project", ), ButtonElement( - text=PlainTextObject(text="Help", emoji=True), value="help", + text=PlainTextObject(text="Help", emoji=True), + value="help", ), ], ), @@ -428,7 +385,9 @@ def test_home_tab_construction(self): ), ], ), - SectionBlock(text=MarkdownTextObject(text="*Your Configurations*"),), + SectionBlock( + text=MarkdownTextObject(text="*Your Configurations*"), + ), DividerBlock(), SectionBlock( text=MarkdownTextObject( diff --git a/tests/web/mock_web_api_server.py b/tests/web/mock_web_api_handler.py similarity index 77% rename from tests/web/mock_web_api_server.py rename to tests/web/mock_web_api_handler.py index f9a02e232..f58aa36ec 100644 --- a/tests/web/mock_web_api_server.py +++ b/tests/web/mock_web_api_handler.py @@ -1,13 +1,10 @@ import json import logging import re -import threading import time from http import HTTPStatus -from http.server import HTTPServer, SimpleHTTPRequestHandler -from typing import Type -from unittest import TestCase -from urllib.parse import urlparse, parse_qs +from http.server import SimpleHTTPRequestHandler +from urllib.parse import parse_qs, urlparse class MockHandler(SimpleHTTPRequestHandler): @@ -26,16 +23,12 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def is_valid_token(self): if self.path.startswith("oauth"): return True - return "Authorization" in self.headers and str( - self.headers["Authorization"] - ).startswith("Bearer xoxb-") + return "Authorization" in self.headers and str(self.headers["Authorization"]).startswith("Bearer xoxb-") def set_common_headers(self): self.send_header("content-type", "application/json;charset=utf-8") @@ -54,6 +47,9 @@ def set_common_headers(self): def _handle(self): try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) + if self.path in {"/oauth.access", "/oauth.v2.access"}: self.send_response(200) self.set_common_headers() @@ -61,9 +57,7 @@ def _handle(self): self.wfile.write("""{"ok":true}""".encode("utf-8")) return else: - self.wfile.write( - """{"ok":false, "error":"invalid"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false, "error":"invalid"}""".encode("utf-8")) return if self.is_valid_token() and self.is_valid_user_agent(): @@ -79,16 +73,12 @@ def _handle(self): if post_body.startswith("{"): request_body = json.loads(post_body) else: - request_body = { - k: v[0] for k, v in parse_qs(post_body).items() - } + request_body = {k: v[0] for k, v in parse_qs(post_body).items()} except UnicodeDecodeError: pass else: if parsed_path and parsed_path.query: - request_body = { - k: v[0] for k, v in parse_qs(parsed_path.query).items() - } + request_body = {k: v[0] for k, v in parse_qs(parsed_path.query).items()} header = self.headers["authorization"] pattern = str(header).split("xoxb-", 1)[1] @@ -97,13 +87,11 @@ def _handle(self): self.set_common_headers() self.wfile.write("""{"ok":false}""".encode("utf-8")) return - if pattern == "rate_limited": + if pattern == "ratelimited": self.send_response(429) - self.send_header("Retry-After", 30) + self.send_header("retry-after", 1) self.set_common_headers() - self.wfile.write( - """{"ok":false,"error":"rate_limited"}""".encode("utf-8") - ) + self.wfile.write("""{"ok":false,"error":"ratelimited"}""".encode("utf-8")) self.wfile.close() return @@ -146,11 +134,7 @@ def _handle(self): else: self.send_response(400) self.set_common_headers() - self.wfile.write( - """{"ok":false, "error":"invalid_user_agent"}""".encode( - "utf-8" - ) - ) + self.wfile.write("""{"ok":false, "error":"invalid_user_agent"}""".encode("utf-8")) self.wfile.close() return @@ -170,12 +154,8 @@ def _handle(self): if request_body: for k, v in request_body.items(): if k in ids: - if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match( - v - ): - raise Exception( - f"The parameter {k} is not a comma-separated string value: {v}" - ) + if not re.compile(r"^[^,\[\]]+?,[^,\[\]]+$").match(v): + raise Exception(f"The parameter {k} is not a comma-separated string value: {v}") body = {"ok": True, "method": parsed_path.path.replace("/", "")} else: with open(f"tests/data/web_response_{pattern}.json") as file: @@ -204,42 +184,3 @@ def do_GET(self): def do_POST(self): self._handle() - - -class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): - threading.Thread.__init__(self) - self.handler = handler - self.test = test - - def run(self): - self.server = HTTPServer(("localhost", 8888), self.handler) - self.test.server_url = "http://localhost:8888" - self.test.host, self.test.port = self.server.socket.getsockname() - self.test.server_started.set() # threading.Event() - - self.test = None - try: - self.server.serve_forever() - finally: - self.server.server_close() - - def stop(self): - self.server.shutdown() - self.join() - - -def setup_mock_web_api_server(test: TestCase): - test.server_started = threading.Event() - test.thread = MockServerThread(test) - test.thread.start() - - test.server_started.wait() - - -def cleanup_mock_web_api_server(test: TestCase): - test.thread.stop() - - test.thread = None diff --git a/tests/web/test_async_web_client.py b/tests/web/test_async_web_client.py index 7fdaf9d6d..151a6ae55 100644 --- a/tests/web/test_async_web_client.py +++ b/tests/web/test_async_web_client.py @@ -5,21 +5,20 @@ import slack.errors as err from slack import AsyncWebClient from tests.helpers import async_test -from tests.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestAsyncWebClient(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server_async(self, MockHandler) self.client = AsyncWebClient( - token="xoxp-1234", base_url="http://localhost:8888", + token="xoxp-1234", + base_url="http://localhost:8888", ) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) pattern_for_package_identifier = re.compile("slackclient/(\\S+)") @@ -63,13 +62,14 @@ async def test_slack_api_error_is_raised_on_unsuccessful_responses(self): @async_test async def test_slack_api_rate_limiting_exception_returns_retry_after(self): - self.client.token = "xoxb-rate_limited" + self.client.token = "xoxb-ratelimited" try: await self.client.api_test() except err.SlackApiError as slack_api_error: self.assertFalse(slack_api_error.response["ok"]) self.assertEqual(429, slack_api_error.response.status_code) - self.assertEqual(30, int(slack_api_error.response.headers["Retry-After"])) + self.assertEqual(1, int(slack_api_error.response.headers["retry-after"])) + self.assertEqual(1, int(slack_api_error.response.headers["Retry-After"])) @async_test async def test_the_api_call_files_argument_creates_the_expected_data(self): @@ -88,25 +88,25 @@ async def test_issue_560_bool_in_params_sync(self): async def test_issue_690_oauth_v2_access_async(self): self.client.token = "" resp = await self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee", + client_id="111.222", + client_secret="secret", + code="codeeeeeeeeee", ) self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee", + client_id="999.999", + client_secret="secret", + code="codeeeeeeeeee", ) @async_test async def test_issue_690_oauth_access_async(self): self.client.token = "" - resp = await self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_token_param_async(self): @@ -129,7 +129,7 @@ async def test_html_response_body_issue_718_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" + "The request to the Slack API failed. (url: http://localhost:8888/users.list, status: 404)\n" "The server responded with: {}", str(e), ) diff --git a/tests/web/test_web_client.py b/tests/web/test_web_client.py index 5d7e84bcd..71c8b6287 100644 --- a/tests/web/test_web_client.py +++ b/tests/web/test_web_client.py @@ -1,5 +1,4 @@ import asyncio -import gc import io import re import socket @@ -8,22 +7,25 @@ import slack.errors as err from slack import WebClient from tests.helpers import async_test -from tests.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestWebClient(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) - self.client = WebClient(token="xoxp-1234", base_url="http://localhost:8888",) + setup_mock_web_api_server_async(self, MockHandler) + self.client = WebClient( + token="xoxp-1234", + base_url="http://localhost:8888", + ) self.async_client = WebClient( - token="xoxp-1234", run_async=True, base_url="http://localhost:8888", + token="xoxp-1234", + run_async=True, + base_url="http://localhost:8888", ) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) pattern_for_package_identifier = re.compile("slackclient/(\\S+)") @@ -122,13 +124,14 @@ def test_slack_api_error_is_raised_on_unsuccessful_responses(self): self.client.api_test() def test_slack_api_rate_limiting_exception_returns_retry_after(self): - self.client.token = "xoxb-rate_limited" + self.client.token = "xoxb-ratelimited" try: self.client.api_test() except err.SlackApiError as slack_api_error: self.assertFalse(slack_api_error.response["ok"]) self.assertEqual(429, slack_api_error.response.status_code) - self.assertEqual(30, int(slack_api_error.response.headers["Retry-After"])) + self.assertEqual(1, int(slack_api_error.response.headers["retry-after"])) + self.assertEqual(1, int(slack_api_error.response.headers["Retry-After"])) def test_the_api_call_files_argument_creates_the_expected_data(self): self.client.token = "xoxb-users_setPhoto" @@ -150,49 +153,41 @@ async def test_issue_560_bool_in_params_async(self): def test_issue_690_oauth_v2_access(self): self.client.token = "" - resp = self.client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_v2_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_v2_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_v2_access_async(self): self.async_client.token = "" resp = await self.async_client.oauth_v2_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee", + client_id="111.222", + client_secret="secret", + code="codeeeeeeeeee", ) self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): await self.async_client.oauth_v2_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee", + client_id="999.999", + client_secret="secret", + code="codeeeeeeeeee", ) def test_issue_690_oauth_access(self): self.client.token = "" - resp = self.client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = self.client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - self.client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + self.client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") @async_test async def test_issue_690_oauth_access_async(self): self.async_client.token = "" - resp = await self.async_client.oauth_access( - client_id="111.222", client_secret="secret", code="codeeeeeeeeee" - ) + resp = await self.async_client.oauth_access(client_id="111.222", client_secret="secret", code="codeeeeeeeeee") self.assertIsNone(resp["error"]) with self.assertRaises(err.SlackApiError): - await self.async_client.oauth_access( - client_id="999.999", client_secret="secret", code="codeeeeeeeeee" - ) + await self.async_client.oauth_access(client_id="999.999", client_secret="secret", code="codeeeeeeeeee") def test_issue_705_no_param_request_pagination(self): self.client.token = "xoxb-users_list_pagination" @@ -231,27 +226,31 @@ async def test_timeout_issue_712_async(self): with self.assertRaises(asyncio.TimeoutError): await client.users_list(token="xoxb-timeout") - def test_unclosed_client_session_issue_645_in_async_mode(self): - def exception_handler(_, context): - nonlocal session_unclosed - if context["message"] == "Unclosed client session": - session_unclosed = True - - async def issue_645(): - client = WebClient( - base_url="http://localhost:8888", timeout=1, run_async=True - ) - try: - await client.users_list(token="xoxb-timeout") - except asyncio.TimeoutError: - pass - - session_unclosed = False - loop = asyncio.get_event_loop() - loop.set_exception_handler(exception_handler) - loop.run_until_complete(issue_645()) - gc.collect() # force Python to gc unclosed client session - self.assertFalse(session_unclosed, "Unclosed client session") + # NOTE: This test may be unstable in GitHub Actions environment. + # As we no longer recommend using this LegacyWebClient, + # let us disable this test to avoid noises in CI builds. + # --------------------- + # def test_unclosed_client_session_issue_645_in_async_mode(self): + # def exception_handler(_, context): + # nonlocal session_unclosed + # if context["message"] == "Unclosed client session": + # session_unclosed = True + # + # async def issue_645(): + # client = WebClient( + # base_url="http://localhost:8888", timeout=1, run_async=True + # ) + # try: + # await client.users_list(token="xoxb-timeout") + # except asyncio.TimeoutError: + # pass + # + # session_unclosed = False + # loop = asyncio.get_event_loop() + # loop.set_exception_handler(exception_handler) + # loop.run_until_complete(issue_645()) + # gc.collect() # force Python to gc unclosed client session + # self.assertFalse(session_unclosed, "Unclosed client session") def test_html_response_body_issue_718(self): client = WebClient(base_url="http://localhost:8888") @@ -260,9 +259,7 @@ def test_html_response_body_issue_718(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( - str(e).startswith( - "Failed to parse the response body: Expecting value: line 1 column 1 (char 0)" - ), + str(e).startswith("Received a response in a non-JSON format: "), e, ) @@ -274,8 +271,7 @@ async def test_html_response_body_issue_718_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {}", + "The request to the Slack API failed.\n" "The server responded with: {}", str(e), ) diff --git a/tests/web/test_web_client_functional.py b/tests/web/test_web_client_functional.py index 0f0c03d51..c2ece8de7 100644 --- a/tests/web/test_web_client_functional.py +++ b/tests/web/test_web_client_functional.py @@ -1,18 +1,14 @@ import unittest import slack -from tests.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server class TestWebClientFunctional(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) - self.client = slack.WebClient( - token="xoxb-api_test", base_url="http://localhost:8888" - ) + setup_mock_web_api_server(self, MockHandler) + self.client = slack.WebClient(token="xoxb-api_test", base_url="http://localhost:8888") def tearDown(self): cleanup_mock_web_api_server(self) diff --git a/tests/web/test_web_client_issue_829.py b/tests/web/test_web_client_issue_829.py index a39c8b3ca..d728b8404 100644 --- a/tests/web/test_web_client_issue_829.py +++ b/tests/web/test_web_client_issue_829.py @@ -3,22 +3,25 @@ import slack.errors as err from slack import WebClient from tests.helpers import async_test -from tests.web.mock_web_api_server import ( - setup_mock_web_api_server, - cleanup_mock_web_api_server, -) +from tests.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestWebClient_Issue_829(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) - self.client = WebClient(token="xoxp-1234", base_url="http://localhost:8888",) + setup_mock_web_api_server_async(self, MockHandler) + self.client = WebClient( + token="xoxp-1234", + base_url="http://localhost:8888", + ) self.async_client = WebClient( - token="xoxp-1234", run_async=True, base_url="http://localhost:8888", + token="xoxp-1234", + run_async=True, + base_url="http://localhost:8888", ) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) def test_html_response_body_issue_829(self): client = WebClient(base_url="http://localhost:8888") @@ -27,9 +30,7 @@ def test_html_response_body_issue_829(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertTrue( - str(e).startswith( - "Failed to parse the response body: Expecting value: " - ), + str(e).startswith("Received a response in a non-JSON format: "), e, ) @@ -41,7 +42,6 @@ async def test_html_response_body_issue_829_async(self): self.fail("SlackApiError expected here") except err.SlackApiError as e: self.assertEqual( - "The request to the Slack API failed.\n" - "The server responded with: {}", + "The request to the Slack API failed.\n" "The server responded with: {}", str(e), ) diff --git a/tests/web/test_web_client_issue_921_custom_logger.py b/tests/web/test_web_client_issue_921_custom_logger.py new file mode 100644 index 000000000..1580b9b5c --- /dev/null +++ b/tests/web/test_web_client_issue_921_custom_logger.py @@ -0,0 +1,35 @@ +import unittest +from logging import Logger + +from slack.web import WebClient +from tests.slack_sdk.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server + + +class TestWebClient_Issue_921_CustomLogger(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server(self) + + def test_if_it_uses_custom_logger(self): + logger = CustomLogger("test-logger") + client = WebClient( + base_url="http://localhost:8888", + token="xoxb-api_test", + logger=logger, + ) + client.chat_postMessage(channel="C111", text="hello") + self.assertTrue(logger.called) + + +class CustomLogger(Logger): + called: bool + + def __init__(self, name, level="DEBUG"): + Logger.__init__(self, name, level) + self.called = False + + def debug(self, msg, *args, **kwargs): + self.called = True diff --git a/tests/web/test_web_client_msg_text_content_warnings.py b/tests/web/test_web_client_msg_text_content_warnings.py new file mode 100644 index 000000000..11ca100ac --- /dev/null +++ b/tests/web/test_web_client_msg_text_content_warnings.py @@ -0,0 +1,105 @@ +import unittest +import warnings + +from slack import WebClient +from tests.web.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server + + +class TestWebClientMessageTextContentWarnings(unittest.TestCase): + def setUp(self): + setup_mock_web_api_server(self, MockHandler) + + def tearDown(self): + cleanup_mock_web_api_server(self) + warnings.resetwarnings() + + def test_missing_text_warning_chat_postMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = client.chat_postMessage(channel="C111", blocks=[]) + self.assertIsNone(resp["error"]) + + def test_missing_text_warning_chat_postEphemeral(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = client.chat_postEphemeral(channel="C111", user="U111", blocks=[]) + self.assertIsNone(resp["error"]) + + def test_missing_text_warning_chat_scheduleMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = client.chat_scheduleMessage(channel="C111", post_at="299876400", text="", blocks=[]) + self.assertIsNone(resp["error"]) + + def test_missing_text_warning_chat_update(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`text` argument is missing"): + resp = client.chat_update(channel="C111", ts="111.222", blocks=[]) + self.assertIsNone(resp["error"]) + + def test_missing_fallback_warning_chat_postMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = client.chat_postMessage(channel="C111", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + def test_missing_fallback_warning_chat_postEphemeral(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = client.chat_postEphemeral(channel="C111", user="U111", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + def test_missing_fallback_warning_chat_scheduleMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = client.chat_scheduleMessage( + channel="C111", + post_at="299876400", + text="", + blocks=[], + attachments=[{"text": "hi"}], + ) + self.assertIsNone(resp["error"]) + + def test_missing_fallback_warning_chat_update(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with self.assertWarnsRegex(UserWarning, "`fallback` argument is missing"): + resp = client.chat_update(channel="C111", ts="111.222", blocks=[], attachments=[{"text": "hi"}]) + self.assertIsNone(resp["error"]) + + def test_no_warning_when_markdown_text_is_provided_chat_postMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = client.chat_postMessage(channel="C111", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + def test_no_warning_when_markdown_text_is_provided_chat_postEphemeral(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = client.chat_postEphemeral(channel="C111", user="U111", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + def test_no_warning_when_markdown_text_is_provided_chat_scheduleMessage(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = client.chat_scheduleMessage(channel="C111", post_at="299876400", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) + + def test_no_warning_when_markdown_text_is_provided_chat_update(self): + client = WebClient(base_url="http://localhost:8888", token="xoxb-api_test") + with warnings.catch_warnings(record=True) as warning_list: + warnings.simplefilter("always") + resp = client.chat_update(channel="C111", ts="111.222", markdown_text="# hello") + + self.assertEqual(warning_list, []) + self.assertIsNone(resp["error"]) diff --git a/tests/webhook/mock_web_api_server.py b/tests/webhook/mock_web_api_handler.py similarity index 73% rename from tests/webhook/mock_web_api_server.py rename to tests/webhook/mock_web_api_handler.py index 0096a959e..9de171fee 100644 --- a/tests/webhook/mock_web_api_server.py +++ b/tests/webhook/mock_web_api_handler.py @@ -1,11 +1,9 @@ +import json import logging import re -import threading import time from http import HTTPStatus -from http.server import HTTPServer, SimpleHTTPRequestHandler -from typing import Type -from unittest import TestCase +from http.server import SimpleHTTPRequestHandler class MockHandler(SimpleHTTPRequestHandler): @@ -20,17 +18,24 @@ class MockHandler(SimpleHTTPRequestHandler): def is_valid_user_agent(self): user_agent = self.headers["User-Agent"] - return self.pattern_for_language.search( - user_agent - ) and self.pattern_for_package_identifier.search(user_agent) + return self.pattern_for_language.search(user_agent) and self.pattern_for_package_identifier.search(user_agent) def set_common_headers(self): self.send_header("content-type", "text/plain;charset=utf-8") self.send_header("connection", "close") self.end_headers() + def do_GET(self): + if self.path == "/received_requests.json": + self.send_response(200) + self.set_common_headers() + self.wfile.write(json.dumps(self.received_requests).encode("utf-8")) + return + def do_POST(self): try: + # put_nowait is common between Queue & asyncio.Queue, it does not need to be awaited + self.server.queue.put_nowait(self.path) if self.path == "/timeout": time.sleep(2) @@ -72,42 +77,3 @@ def do_POST(self): except Exception as e: self.logger.error(str(e), exc_info=True) raise - - -class MockServerThread(threading.Thread): - def __init__( - self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler - ): - threading.Thread.__init__(self) - self.handler = handler - self.test = test - - def run(self): - self.server = HTTPServer(("localhost", 8888), self.handler) - self.test.server_url = "http://localhost:8888" - self.test.host, self.test.port = self.server.socket.getsockname() - self.test.server_started.set() # threading.Event() - - self.test = None - try: - self.server.serve_forever() - finally: - self.server.server_close() - - def stop(self): - self.server.shutdown() - self.join() - - -def setup_mock_web_api_server(test: TestCase): - test.server_started = threading.Event() - test.thread = MockServerThread(test) - test.thread.start() - - test.server_started.wait() - - -def cleanup_mock_web_api_server(test: TestCase): - test.thread.stop() - - test.thread = None diff --git a/tests/webhook/test_async_webhook.py b/tests/webhook/test_async_webhook.py index 457947cd1..829ec0565 100644 --- a/tests/webhook/test_async_webhook.py +++ b/tests/webhook/test_async_webhook.py @@ -1,24 +1,19 @@ -import asyncio +from tests.helpers import async_test import unittest -import aiohttp - from slack.web.classes.attachments import Attachment, AttachmentField from slack.web.classes.blocks import SectionBlock, ImageBlock from slack.webhook import AsyncWebhookClient, WebhookResponse -from tests.helpers import async_test -from tests.webhook.mock_web_api_server import ( - cleanup_mock_web_api_server, - setup_mock_web_api_server, -) +from tests.webhook.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server_async, cleanup_mock_web_api_server_async class TestAsyncWebhook(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server_async(self, MockHandler) def tearDown(self): - cleanup_mock_web_api_server(self) + cleanup_mock_web_api_server_async(self) @async_test async def test_send(self): @@ -31,6 +26,17 @@ async def test_send(self): resp = await client.send(text="hello!", response_type="in_channel") self.assertEqual("ok", resp.body) + @async_test + async def test_send_with_url_unfurl_opts_issue_1045(self): + client = AsyncWebhookClient("http://localhost:8888") + resp: WebhookResponse = await client.send( + text="", + unfurl_links=False, + unfurl_media=False, + ) + self.assertEqual(200, resp.status_code) + self.assertEqual("ok", resp.body) + @async_test async def test_send_blocks(self): client = AsyncWebhookClient("http://localhost:8888") @@ -63,7 +69,10 @@ async def test_send_blocks(self): "accessory": { "type": "datepicker", "initial_date": "1990-04-28", - "placeholder": {"type": "plain_text", "text": "Select a date",}, + "placeholder": { + "type": "plain_text", + "text": "Select a date", + }, }, }, ], @@ -130,12 +139,7 @@ async def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -165,9 +169,7 @@ async def test_timeout_issue_712(self): @async_test async def test_proxy_issue_714(self): - client = AsyncWebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = AsyncWebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(Exception): await client.send_dict({"text": "hello!"}) diff --git a/tests/webhook/test_webhook.py b/tests/webhook/test_webhook.py index b1d7b0825..abd7f79fa 100644 --- a/tests/webhook/test_webhook.py +++ b/tests/webhook/test_webhook.py @@ -5,15 +5,13 @@ from slack.web.classes.attachments import Attachment, AttachmentField from slack.web.classes.blocks import SectionBlock, ImageBlock from slack.webhook import WebhookClient, WebhookResponse -from tests.webhook.mock_web_api_server import ( - cleanup_mock_web_api_server, - setup_mock_web_api_server, -) +from tests.webhook.mock_web_api_handler import MockHandler +from tests.mock_web_api_server import setup_mock_web_api_server, cleanup_mock_web_api_server class TestWebhook(unittest.TestCase): def setUp(self): - setup_mock_web_api_server(self) + setup_mock_web_api_server(self, MockHandler) def tearDown(self): cleanup_mock_web_api_server(self) @@ -28,6 +26,16 @@ def test_send(self): resp = client.send(text="hello!", response_type="in_channel") self.assertEqual("ok", resp.body) + def test_send_with_url_unfurl_opts_issue_1045(self): + client = WebhookClient("http://localhost:8888") + resp: WebhookResponse = client.send( + text="", + unfurl_links=False, + unfurl_media=False, + ) + self.assertEqual(200, resp.status_code) + self.assertEqual("ok", resp.body) + def test_send_blocks(self): client = WebhookClient("http://localhost:8888") @@ -59,7 +67,10 @@ def test_send_blocks(self): "accessory": { "type": "datepicker", "initial_date": "1990-04-28", - "placeholder": {"type": "plain_text", "text": "Select a date",}, + "placeholder": { + "type": "plain_text", + "text": "Select a date", + }, }, }, ], @@ -125,12 +136,7 @@ def test_send_attachments(self): fallback="fallback_text", pretext="some_pretext", title_link="link in title", - fields=[ - AttachmentField( - title=f"field_{i}_title", value=f"field_{i}_value" - ) - for i in range(5) - ], + fields=[AttachmentField(title=f"field_{i}_title", value=f"field_{i}_value") for i in range(5)], color="#FFFF00", author_name="John Doe", author_link="http://johndoeisthebest.com", @@ -163,9 +169,7 @@ def test_error_response(self): self.assertTrue(resp.body.startswith("")) def test_proxy_issue_714(self): - client = WebhookClient( - url="http://localhost:8888", proxy="http://invalid-host:9999" - ) + client = WebhookClient(url="http://localhost:8888", proxy="http://invalid-host:9999") with self.assertRaises(urllib.error.URLError): client.send_dict({"text": "hello!"}) diff --git a/tutorial/01-creating-the-slack-app.md b/tutorial/01-creating-the-slack-app.md index f617bb348..81e3de76b 100644 --- a/tutorial/01-creating-the-slack-app.md +++ b/tutorial/01-creating-the-slack-app.md @@ -9,7 +9,7 @@ ### Give your app permissions -[Scopes](https://api.slack.com/scopes) give your app permission to do things (for example, post messages) in your development workspace. +[Scopes](https://docs.slack.dev/reference/scopes) give your app permission to do things (for example, post messages) in your development workspace. - Navigate to **OAuth & Permissions** on the sidebar to add scopes to your app @@ -19,8 +19,8 @@ For now, we'll only use one scope. -- Add the [`chat:write` scope](https://api.slack.com/scopes/chat:write) to grant your app the permission to post messages in channels it's a member of. -- Add the [`im:write` scope](https://api.slack.com/scopes/im:write) to grant your app the permission to post messages in DMs. +- Add the [`chat:write` scope](https://docs.slack.dev/reference/scopes/chat.write/) to grant your app the permission to post messages in channels it's a member of. +- Add the [`im:write` scope](https://docs.slack.dev/reference/scopes/im.write/) to grant your app the permission to post messages in DMs. πŸŽ‰ You should briefly see a success banner. diff --git a/tutorial/02-building-a-message.md b/tutorial/02-building-a-message.md index fa4416d0a..9f2481a84 100644 --- a/tutorial/02-building-a-message.md +++ b/tutorial/02-building-a-message.md @@ -2,7 +2,7 @@ The code for this step is available [here](PythOnBoardingBot/onboarding_tutorial.py). -> πŸ’‘ **[Block Kit](https://api.slack.com/block-kit)** is a UI framework for Slack apps that offers a balance of control and flexibility when building experiences in messages and other surfaces. Customize the order and appearance of information and guide users through your app's capabilities by composing, updating, sequencing, and stacking blocks β€” reusable components that work almost everywhere in Slack. You can experiment and prototype with Block Kit using the [Block Kit Builder](https://api.slack.com/tools/block-kit-builder). +> πŸ’‘ **[Block Kit](https://docs.slack.dev/block-kit/)** is a UI framework for Slack apps that offers a balance of control and flexibility when building experiences in messages and other surfaces. Customize the order and appearance of information and guide users through your app's capabilities by composing, updating, sequencing, and stacking blocks β€” reusable components that work almost everywhere in Slack. You can experiment and prototype with Block Kit using the [Block Kit Builder](https://api.slack.com/tools/block-kit-builder). We're going to be using Block Kit to build our onboarding tutorial messages. diff --git a/tutorial/03-responding-to-slack-events.md b/tutorial/03-responding-to-slack-events.md index 84dd64a26..70c904e50 100644 --- a/tutorial/03-responding-to-slack-events.md +++ b/tutorial/03-responding-to-slack-events.md @@ -4,15 +4,15 @@ The code for this step is available [here](PythOnBoardingBot). ## Install the dependencies -> πŸ’‘ **[β€œRequirements files”](https://pip.pypa.io/en/stable/user_guide/#id12)** are files containing a list of items to be installed using pip install. Details on the format of the files are here: [Requirements File Format](https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format). +> πŸ’‘ **["Requirements files"](https://pip.pypa.io/en/stable/user_guide/#id12)** are files containing a list of items to be installed using pip install. Details on the format of the files are here: [Requirements File Format](https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format). - In the root directory create a "requirements.txt" file. - Add the following contents to that file and save the file. ``` slack_sdk>=3.0 -slackeventsapi>=2.1.0 -Flask>=1.1.2 +slack_bolt>=1.6.1 +certifi ``` > πŸ’‘ **[Certifi](https://github.com/certifi/python-certifi)** is a carefully curated collection of Root Certificates for validating the trustworthiness of SSL certificates while verifying the identity of TLS hosts. It has been extracted from the Requests project. @@ -33,23 +33,16 @@ The first thing we'll need to do is import the code our app needs to run. - In `app.py` add the following code: ```Python -import os import logging -from flask import Flask +from slack_bolt import App from slack_sdk.web import WebClient -from slackeventsapi import SlackEventAdapter from onboarding_tutorial import OnboardingTutorial ``` -- Next, let's create a Flask server and initialize the WebClient and SlackEventAdapter. Add the following lines to `app.py`: +- Next, create a Bolt for Python application. Add the following line to `app.py`: ```Python -# Initialize a Flask app to host the events adapter -app = Flask(__name__) -slack_events_adapter = SlackEventAdapter(os.environ['SLACK_SIGNING_SECRET'], "/slack/events", app) - -# Initialize a Web API client -slack_web_client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) +app = App() ``` Next we'll need our app to store some data. For simplicity we'll store our app data in-memory with the following data structure: `{"channel": {"user_id": OnboardingTutorial}}`. @@ -65,7 +58,7 @@ Let's add a function that's responsible for creating and sending the onboarding - Add the following lines of code to `app.py`: ```Python -def start_onboarding(user_id: str, channel: str): +def start_onboarding(user_id: str, channel: str, client: WebClient): # Create a new onboarding tutorial. onboarding_tutorial = OnboardingTutorial(channel) @@ -73,7 +66,7 @@ def start_onboarding(user_id: str, channel: str): message = onboarding_tutorial.get_message_payload() # Post the onboarding message in Slack - response = slack_web_client.chat_postMessage(**message) + response = client.chat_postMessage(**message) # Capture the timestamp of the message we've just posted so # we can use it to update the message after a user @@ -86,17 +79,11 @@ def start_onboarding(user_id: str, channel: str): onboarding_tutorials_sent[channel][user_id] = onboarding_tutorial ``` -**Note:** We're using the `WebClient` to send messages into Slack. - -> πŸ’‘ **[WebClient](/slack/web/client.py)** A WebClient allows apps to communicate with the Slack Platform's Web API. This client handles constructing and sending HTTP requests to Slack as well as parsing any responses received into a `SlackResponse` dictionary-like object. - ### Responding to events in Slack -When events occur in Slack there are two primary ways to be notified about them. We can send you an HTTP Request through our Events API (preferred) or you can stream events through a websocket connection with our RTM API. The RTM API is only recommended if you're behind a firewall and cannot receive incoming web requests from Slack. - -> ⚠️ The RTM API isn't available for default Slack apps. If you need to use RTM (possibly due to corporate firewall limitations), you can do so by creating a [classic Slack app](https://api.slack.com/apps?new_classic_app=1). If you have an existing RTM app, you can continue to use its associated tokens. You can read more [in the documentation](https://slack.dev/python-slack-sdk/real_time_messaging.html). +When events occur in Slack there are two primary ways to be notified about them. We can send you an [HTTP Request through our Events API](https://docs.slack.dev/apis/events-api/), or you can stream events through a WebSocket connection with our [Socket Mode](https://docs.slack.dev/apis/events-api/using-socket-mode/) API. If you're behind a firewall and cannot receive incoming web requests from Slack, we recommend going with Socket Mode. -In this tutorial we'll be using the Events API and the [SlackEventAdapter](https://github.com/slackapi/python-slack-events-api). If you need access to the RTM API, you can access it [via the `RTMClient`](https://slack.dev/python-slack-sdk/real_time_messaging.html). +In this tutorial we'll be using the Events API and the [Bolt for Python](https://github.com/slackapi/bolt-python). Back to our application, it's time to link our onboarding functionality to Slack events. @@ -106,35 +93,36 @@ Back to our application, it's time to link our onboarding functionality to Slack # ================ Team Join Event =============== # # When the user first joins a team, the type of the event will be 'team_join'. # Here we'll link the onboarding_message callback to the 'team_join' event. -@slack_events_adapter.on("team_join") -def onboarding_message(payload): + +# Note: Bolt provides a WebClient instance as an argument to the listener function +# we've defined here, which we then use to access Slack Web API methods like conversations_open. +# For more info, checkout: https://docs.slack.dev/tools/bolt-python/concepts/message-listening +@app.event("team_join") +def onboarding_message(event, client): """Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future. """ - event = payload.get("event", {}) - # Get the id of the Slack user associated with the incoming event user_id = event.get("user", {}).get("id") # Open a DM with the new user. - response = slack_web_client.im_open(user_id) + response = client.conversations_open(users=user_id) channel = response["channel"]["id"] # Post the onboarding message. - start_onboarding(user_id, channel) + start_onboarding(user_id, channel, client) # ============= Reaction Added Events ============= # # When a users adds an emoji reaction to the onboarding message, # the type of the event will be 'reaction_added'. # Here we'll link the update_emoji callback to the 'reaction_added' event. -@slack_events_adapter.on("reaction_added") -def update_emoji(payload): +@app.event("reaction_added") +def update_emoji(event, client): """Update the onboarding welcome message after receiving a "reaction_added" event from Slack. Update timestamp for welcome message as well. """ - event = payload.get("event", {}) - + # Get the ids of the Slack user and channel associated with the incoming event channel_id = event.get("item", {}).get("channel") user_id = event.get("user") @@ -151,22 +139,18 @@ def update_emoji(payload): message = onboarding_tutorial.get_message_payload() # Post the updated message in Slack - updated_message = slack_web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] + updated_message = client.chat_update(**message) # =============== Pin Added Events ================ # # When a users pins a message the type of the event will be 'pin_added'. -# Here we'll link the update_pin callback to the 'reaction_added' event. -@slack_events_adapter.on("pin_added") -def update_pin(payload): +# Here we'll link the update_pin callback to the 'pin_added' event. +@app.event("pin_added") +def update_pin(event, client): """Update the onboarding welcome message after receiving a "pin_added" event from Slack. Update timestamp for welcome message as well. """ - event = payload.get("event", {}) - + # Get the ids of the Slack user and channel associated with the incoming event channel_id = event.get("channel_id") user_id = event.get("user") @@ -180,41 +164,35 @@ def update_pin(payload): message = onboarding_tutorial.get_message_payload() # Post the updated message in Slack - updated_message = slack_web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] + updated_message = client.chat_update(**message) # ============== Message Events ============= # # When a user sends a DM, the event type will be 'message'. # Here we'll link the message callback to the 'message' event. -@slack_events_adapter.on("message") -def message(payload): +@app.event("message") +def message(event, client): """Display the onboarding welcome message after receiving a message that contains "start". """ - event = payload.get("event", {}) - channel_id = event.get("channel") user_id = event.get("user") text = event.get("text") - if text and text.lower() == "start": - return start_onboarding(user_id, channel_id) + return start_onboarding(user_id, channel_id, client) ``` Finally, we need to make our app runnable. -- 🏁 Add the following lines of code to the end of `app.py` and run `FLASK_ENV=development python app.py`. +- 🏁 Add the following lines of code to the end of `app.py`. ```Python if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) - app.run(port=3000) + app.start(3000) ``` **Note:** When running in a virtual environment you often need to specify the location of the SSL Certificate(`cacert.pem`). To make this easy we use Certifi's built-in `where()` function to locate the installed certificate authority (CA) bundle. @@ -226,8 +204,6 @@ import certifi ssl_context = ssl_lib.create_default_context(cafile=certifi.where()) ``` -**Final Note:** If you're interested in learning how to modify this app to run asynchronously I've adapted this code as such [here](PythOnBoardingBot/async_app.py). - --- **Next section: [04 - Running the app](04-running-the-app.md).** diff --git a/tutorial/PythOnBoardingBot/app.py b/tutorial/PythOnBoardingBot/app.py index 9cdb9ba65..7245c71ab 100644 --- a/tutorial/PythOnBoardingBot/app.py +++ b/tutorial/PythOnBoardingBot/app.py @@ -1,23 +1,17 @@ -import os import logging -from flask import Flask +from slack_bolt import App from slack_sdk.web import WebClient -from slackeventsapi import SlackEventAdapter from onboarding_tutorial import OnboardingTutorial -# Initialize a Flask app to host the events adapter -app = Flask(__name__) -slack_events_adapter = SlackEventAdapter(os.environ["SLACK_SIGNING_SECRET"], "/slack/events", app) - -# Initialize a Web API client -slack_web_client = WebClient(token=os.environ['SLACK_BOT_TOKEN']) +# Initialize a Bolt for Python app +app = App() # For simplicity we'll store our app data in-memory with the following data structure. # onboarding_tutorials_sent = {"channel": {"user_id": OnboardingTutorial}} onboarding_tutorials_sent = {} -def start_onboarding(user_id: str, channel: str): +def start_onboarding(user_id: str, channel: str, client: WebClient): # Create a new onboarding tutorial. onboarding_tutorial = OnboardingTutorial(channel) @@ -25,7 +19,7 @@ def start_onboarding(user_id: str, channel: str): message = onboarding_tutorial.get_message_payload() # Post the onboarding message in Slack - response = slack_web_client.chat_postMessage(**message) + response = client.chat_postMessage(**message) # Capture the timestamp of the message we've just posted so # we can use it to update the message after a user @@ -41,35 +35,36 @@ def start_onboarding(user_id: str, channel: str): # ================ Team Join Event =============== # # When the user first joins a team, the type of the event will be 'team_join'. # Here we'll link the onboarding_message callback to the 'team_join' event. -@slack_events_adapter.on("team_join") -def onboarding_message(payload): + +# Note: Bolt provides a WebClient instance as an argument to the listener function +# we've defined here, which we then use to access Slack Web API methods like conversations_open. +# For more info, checkout: https://docs.slack.dev/tools/bolt-python/concepts/message-listening +@app.event("team_join") +def onboarding_message(event, client): """Create and send an onboarding welcome message to new users. Save the time stamp of this message so we can update this message in the future. """ - event = payload.get("event", {}) - # Get the id of the Slack user associated with the incoming event user_id = event.get("user", {}).get("id") # Open a DM with the new user. - response = slack_web_client.im_open(user=user_id) + response = client.conversations_open(users=user_id) channel = response["channel"]["id"] # Post the onboarding message. - start_onboarding(user_id, channel) + start_onboarding(user_id, channel, client) # ============= Reaction Added Events ============= # # When a users adds an emoji reaction to the onboarding message, # the type of the event will be 'reaction_added'. # Here we'll link the update_emoji callback to the 'reaction_added' event. -@slack_events_adapter.on("reaction_added") -def update_emoji(payload): +@app.event("reaction_added") +def update_emoji(event, client): """Update the onboarding welcome message after receiving a "reaction_added" event from Slack. Update timestamp for welcome message as well. """ - event = payload.get("event", {}) - + # Get the ids of the Slack user and channel associated with the incoming event channel_id = event.get("item", {}).get("channel") user_id = event.get("user") @@ -86,22 +81,18 @@ def update_emoji(payload): message = onboarding_tutorial.get_message_payload() # Post the updated message in Slack - updated_message = slack_web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] + updated_message = client.chat_update(**message) # =============== Pin Added Events ================ # # When a users pins a message the type of the event will be 'pin_added'. # Here we'll link the update_pin callback to the 'pin_added' event. -@slack_events_adapter.on("pin_added") -def update_pin(payload): +@app.event("pin_added") +def update_pin(event, client): """Update the onboarding welcome message after receiving a "pin_added" event from Slack. Update timestamp for welcome message as well. """ - event = payload.get("event", {}) - + # Get the ids of the Slack user and channel associated with the incoming event channel_id = event.get("channel_id") user_id = event.get("user") @@ -115,33 +106,27 @@ def update_pin(payload): message = onboarding_tutorial.get_message_payload() # Post the updated message in Slack - updated_message = slack_web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] + updated_message = client.chat_update(**message) # ============== Message Events ============= # # When a user sends a DM, the event type will be 'message'. # Here we'll link the message callback to the 'message' event. -@slack_events_adapter.on("message") -def message(payload): +@app.event("message") +def message(event, client): """Display the onboarding welcome message after receiving a message that contains "start". """ - event = payload.get("event", {}) - channel_id = event.get("channel") user_id = event.get("user") text = event.get("text") - if text and text.lower() == "start": - return start_onboarding(user_id, channel_id) + return start_onboarding(user_id, channel_id, client) if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) - app.run(port=3000) + app.start(3000) diff --git a/tutorial/PythOnBoardingBot/async_app.py b/tutorial/PythOnBoardingBot/async_app.py deleted file mode 100644 index ecf153f9f..000000000 --- a/tutorial/PythOnBoardingBot/async_app.py +++ /dev/null @@ -1,150 +0,0 @@ -import os -import logging -import asyncio -import ssl as ssl_lib - -import certifi -from slack_sdk.web import WebClient -from slack_sdk.rtm import RTMClient - -from onboarding_tutorial import OnboardingTutorial - -"""This file serves as an example for how to create the same app, but running asynchronously.""" - -# For simplicity we'll store our app data in-memory with the following data structure. -# onboarding_tutorials_sent = {"channel": {"user_id": OnboardingTutorial}} -onboarding_tutorials_sent = {} - - -async def start_onboarding(web_client: WebClient, user_id: str, channel: str): - # Create a new onboarding tutorial. - onboarding_tutorial = OnboardingTutorial(channel) - - # Get the onboarding message payload - message = onboarding_tutorial.get_message_payload() - - # Post the onboarding message in Slack - response = await web_client.chat_postMessage(**message) - - # Capture the timestamp of the message we've just posted so - # we can use it to update the message after a user - # has completed an onboarding task. - onboarding_tutorial.timestamp = response["ts"] - - # Store the message sent in onboarding_tutorials_sent - if channel not in onboarding_tutorials_sent: - onboarding_tutorials_sent[channel] = {} - onboarding_tutorials_sent[channel][user_id] = onboarding_tutorial - - -# ================ Team Join Event =============== # -# When the user first joins a team, the type of the event will be 'team_join'. -# Here we'll link the onboarding_message callback to the 'team_join' event. -@RTMClient.run_on(event="team_join") -async def onboarding_message(**payload): - """Create and send an onboarding welcome message to new users. Save the - time stamp of this message so we can update this message in the future. - """ - # Get WebClient so you can communicate back to Slack. - web_client = payload["web_client"] - - # Get the id of the Slack user associated with the incoming event - user_id = payload["data"]["user"]["id"] - - # Open a DM with the new user. - response = web_client.im_open(user_id) - channel = response["channel"]["id"] - - # Post the onboarding message. - await start_onboarding(web_client, user_id, channel) - - -# ============= Reaction Added Events ============= # -# When a users adds an emoji reaction to the onboarding message, -# the type of the event will be 'reaction_added'. -# Here we'll link the update_emoji callback to the 'reaction_added' event. -@RTMClient.run_on(event="reaction_added") -async def update_emoji(**payload): - """Update the onboarding welcome message after receiving a "reaction_added" - event from Slack. Update timestamp for welcome message as well. - """ - data = payload["data"] - web_client = payload["web_client"] - channel_id = data["item"]["channel"] - user_id = data["user"] - - # Get the original tutorial sent. - onboarding_tutorial = onboarding_tutorials_sent[channel_id][user_id] - - # Mark the reaction task as completed. - onboarding_tutorial.reaction_task_completed = True - - # Get the new message payload - message = onboarding_tutorial.get_message_payload() - - # Post the updated message in Slack - updated_message = await web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] - - -# =============== Pin Added Events ================ # -# When a users pins a message the type of the event will be 'pin_added'. -# Here we'll link the update_pin callback to the 'reaction_added' event. -@RTMClient.run_on(event="pin_added") -async def update_pin(**payload): - """Update the onboarding welcome message after receiving a "pin_added" - event from Slack. Update timestamp for welcome message as well. - """ - data = payload["data"] - web_client = payload["web_client"] - channel_id = data["channel_id"] - user_id = data["user"] - - # Get the original tutorial sent. - onboarding_tutorial = onboarding_tutorials_sent[channel_id][user_id] - - # Mark the pin task as completed. - onboarding_tutorial.pin_task_completed = True - - # Get the new message payload - message = onboarding_tutorial.get_message_payload() - - # Post the updated message in Slack - updated_message = await web_client.chat_update(**message) - - # Update the timestamp saved on the onboarding tutorial object - onboarding_tutorial.timestamp = updated_message["ts"] - - -# ============== Message Events ============= # -# When a user sends a DM, the event type will be 'message'. -# Here we'll link the message callback to the 'message' event. -@RTMClient.run_on(event="message") -async def message(**payload): - """Display the onboarding welcome message after receiving a message - that contains "start". - """ - data = payload["data"] - web_client = payload["web_client"] - channel_id = data.get("channel") - user_id = data.get("user") - text = data.get("text") - - if text and text.lower() == "start": - return await start_onboarding(web_client, user_id, channel_id) - - -if __name__ == "__main__": - logger = logging.getLogger() - logger.setLevel(logging.DEBUG) - logger.addHandler(logging.StreamHandler()) - ssl_context = ssl_lib.create_default_context(cafile=certifi.where()) - slack_token = os.environ["SLACK_BOT_TOKEN"] - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - rtm_client = RTMClient( - token=slack_token, ssl=ssl_context, run_async=True, loop=loop - ) - loop.run_until_complete(rtm_client.start()) diff --git a/tutorial/PythOnBoardingBot/requirements.txt b/tutorial/PythOnBoardingBot/requirements.txt index 034746167..b22c1e59c 100644 --- a/tutorial/PythOnBoardingBot/requirements.txt +++ b/tutorial/PythOnBoardingBot/requirements.txt @@ -1,4 +1,3 @@ slack_sdk>=3.0 -slackeventsapi>=2.1.0 -Flask>=1.1.1 +slack_bolt>=1.6.1 certifi \ No newline at end of file diff --git a/tutorial/README.md b/tutorial/README.md index 0fe94c109..12d99c89c 100644 --- a/tutorial/README.md +++ b/tutorial/README.md @@ -21,14 +21,14 @@ As you complete each task you'll see the message update with a green checkmark. 1. A Slack team. Before anything else you'll need a Slack team. You can [Sign into an existing Slack workspace](https://get.slack.help/hc/en-us/articles/212681477-Sign-in-to-Slack) or you can [create a new Slack workspace](https://get.slack.help/hc/en-us/articles/206845317-Create-a-Slack-workspace) to test your app first. -2. A terminal with Python 3.6+ installed. +2. A terminal with Python 3.7+ installed. Check your installation by running the following command in your terminal: ``` $ python3 --version --> Python 3.6.7 +-> Python 3.7.17 ``` -You'll need to install Python 3.6 if you receive the following error: +You'll need to install Python 3.7 if you receive the following error: ``` -> bash: python3: command not found ``` @@ -54,7 +54,6 @@ Open up your new project folder "PythOnBoardingBot" in your text editor. ## Coming up next - Add tests to your app. - Add starring a message as an onboarding task. -- Run this app on [Glitch](https://glitch.com/). - Creating a Slack "MessageBuilder" object. This would aid in the creation of complex messages. - Running this app from the command line with [`$ click_`](https://click.palletsprojects.com/en/7.x/). - How to run this app on multiple teams.