diff --git a/.claude/skills/managing-dependencies/SKILL.md b/.claude/skills/managing-dependencies/SKILL.md new file mode 100644 index 000000000..335ac7d0a --- /dev/null +++ b/.claude/skills/managing-dependencies/SKILL.md @@ -0,0 +1,81 @@ +--- +name: managing-dependencies +description: >- + Use when adding, bumping, pinning, or reviewing a dependency in requirements.txt or requirements/*.txt, including taking or fixing a Dependabot PR. Also use when pip install fails on some Python versions in CI but not others ("Could not find a version that satisfies the requirement", "No matching distribution found", "Requires-Python", "ResolutionImpossible"), including PyPy-only failures, and when dropping support for an old Python version. +--- + +# Managing dependencies + +This repo supports a range of Python versions, and one set of requirements files has to install on all of them. Dependabot proposes the newest release, so its bumps often raise a lower bound past what the oldest Pythons can install, and CI fails at the install step on those jobs only. The fix is to split the requirement with PEP 508 `python_version` markers so each Python gets the newest release it can install. Dropping an old Python to turn CI green is not the fix. + +## Where the facts live + +Read these instead of trusting memory; they change often. + +- **Supported Pythons:** `requires-python` and the `Programming Language :: Python :: 3.X` classifiers in `pyproject.toml`, and the CI matrix. +- **Who installs a file, on which Python:** `grep -rn requirements .github/workflows scripts requirements pyproject.toml`. This also catches `-r` includes. For a hit in a script, find the CI job that runs it and read its `python-version`. +- **Whether a file ships to users:** a file that `pyproject.toml` reads into package metadata (`dependencies` or `optional-dependencies` under `[tool.setuptools.dynamic]`) ends up in the published wheel. + +## Workflow + +- [ ] 1. Find which Pythons install the file. A file installed only on the newest Python takes the bump as-is. +- [ ] 2. Find the newest release each affected Python can install (see "Finding the ceiling"). +- [ ] 3. If every Python the line covers can install the new lower bound, take the bump as one line. Done. +- [ ] 4. Otherwise split the line (see "Splitting a line"). +- [ ] 5. Re-read the section: no Python matches two lines, and the newest line is open-ended. + +Change only the section you are fixing; don't reformat other sections in the same change. + +## File layout + +Each file starts with a `# pip install -r ` header, then one section per dependency: a `# ` line, optional `# Note:` lines, the requirement line(s), and a blank line. + +``` +# pip install -r requirements/testing.txt + +# pkg +pkg>=1.4,<2; python_version < "3.9" +pkg>=2.0,<2.3; python_version == "3.9" +pkg>=2.5.1,<3; python_version >= "3.10" + +# other-pkg +# Note: other-pkg 4.x breaks on Python 3.8 but declares no requires_python, so pip can't filter it. +other-pkg>=3,<4 +``` + +**Notes:** write one only for what the lines can't say: a cap that isn't obvious, a coupling with another package, or a release with wrong metadata. Don't restate versions or which Python gets which release; a routine split needs no note. Existing notes that only restate their lines are legacy: drop one when you edit its section, and don't copy it. + +## Finding the ceiling + +An old Python's ceiling is the first release that dropped it, not the release Dependabot proposes. If `pkg` dropped 3.9 at 2.3 and the target is 2.5.1, the 3.9 line is `<2.3`, since 2.3 through 2.5.0 are 3.10-only too. + +- **From a red CI job:** the failing install log is ground truth. The lowest version on its `Ignored the following versions that require a different python version` line is that Python's ceiling. +- **For any Python:** `pip index versions --python-version 3.9` lists what 3.9 can install, newest first. Run it again for the next Python up; the first release newer than 3.9's newest is 3.9's ceiling. +- **The pre-bump lower bound** is in the Dependabot PR title (`update pkg requirement from <3,>=2.0 to >=2.5.1,<3`) or `git diff`. + +## Splitting a line + +Split only the Pythons that the bumped line covers and the new lower bound excludes. Leave existing bands for older Pythons alone, even when they are coarser than they could be. + +- Lines run oldest Python to newest. The newest line takes the bump and stays open-ended (`>= "X.Y"`). +- Each band that splits off keeps the line's pre-bump lower bound and gets its ceiling from "Finding the ceiling". Pythons that share a ceiling share a band. +- Marker style: `pkg>=1,<2; python_version == "3.9"`. Spaces around operators, double-quoted `"X.Y"`, one space after `;`. A one-Python band is `== "X.Y"`; a band spanning several is `>= "X.Y" and < "X.Z"`, or `< "X.Z"` when it is the oldest. Boundaries use `>=` and `<` so each Python lands on exactly one side. `python_version` is major.minor only (3.9.5 reports `"3.9"`), so `== "3.9"` covers every 3.9 patch; don't use `python_full_version` here, where `== "3.9"` matches only 3.9.0. + +A section with a single gated line (installed only on the newest Python, or only on PyPy) is intentional; don't fill in the other Pythons. + +## Gotchas + +- **Dependabot rewrites only the last line** of a split section, the open-ended one. When it bumps a split package, check which Pythons that line covers; the new lower bound may exclude the oldest of them, which then splits off. +- **Releases with no `requires_python`** can't be filtered by pip, so they install on Pythons they don't support and fail at import or test time rather than at install. `pip index` lists them too. Pin an explicit ceiling with a note saying why. When the culprit comes in loosely through another package, pin it in that package's section so the coupling stays visible. +- **Only PyPy jobs fail:** the release usually dropped PyPy wheels. Gate on the implementation instead of downgrading CPython: `pkg<46; implementation_name == "pypy" and python_version == "3.10"`. Lowercase `pypy`, and `implementation_name`, not `platform_python_implementation`. No unmarked companion line is needed. +- **Files that ship:** full-line comments only; an inline comment breaks the package build. Their lower bounds are the minimum users must install, so raise one only for a reason. +- **Not this pattern:** a real test failure, or an install failure on every Python. Investigate the bump normally. + +## Dropping a Python version + +When a Python leaves the classifiers and the CI matrix, merge any band that only served it into its neighbor. If a section is left with one line, remove its marker and the `;`. + +## Leave alone + +- `requires-python`, the classifiers, and the CI matrix. Changing which Pythons are supported is its own decision. +- Packages under `ignore` in `.github/dependabot.yml`: maintainers bump those by hand on purpose. Prefer a marker split over adding a new `ignore`, which freezes the package on every Python. diff --git a/.flake8 b/.flake8 deleted file mode 100644 index 9960c210e..000000000 --- a/.flake8 +++ /dev/null @@ -1,3 +0,0 @@ -[flake8] -max-line-length = 125 -ignore = F841,F821,W503,E402 diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 9e2a40167..c7ded07e2 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,2 +1,8 @@ # change black settings 0e4cd56b69e8f83166cd262f762802b7f18c3d21 + +# apply ruff format across the codebase (#1566) +5814077ee7ef79eaa4df6e4602260c179536a814 + +# add docstring formatting + linting (#1567) +5007ee3248fcea2171efa7c293ae9d4a46afa71f diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4a08579c2..f152f56e8 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,7 +1,7 @@ # Salesforce Open Source project configuration # Learn more: https://github.com/salesforce/oss-template #ECCN:Open Source -#GUSINFO:Open Source,Open Source Workflow +#GUSINFO:Slack Developer Experience,Open Source # @slackapi/slack-platform-python # are code reviewers for all changes in this repo. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..0efa3a2d1 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ +### Summary + + + +### Testing + + + +### Category + +- [ ] `slack_bolt.App` and/or its core components +- [ ] `slack_bolt.async_app.AsyncApp` and/or its core components +- [ ] Adapters in `slack_bolt.adapter` +- [ ] Document pages under `/docs` +- [ ] Others + +### Requirements + +- [ ] I've read and understood the [Contributing Guidelines](https://github.com/slackapi/bolt-python/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 have signed the [Salesforce CLA](https://cla.salesforce.com/sign-cla) (required before your PR can be reviewed or merged). +- [ ] I've run `./scripts/install_all_and_run_tests.sh` after making the changes. diff --git a/.github/maintainers_guide.md b/.github/maintainers_guide.md index f8edeeabd..47d9ccd58 100644 --- a/.github/maintainers_guide.md +++ b/.github/maintainers_guide.md @@ -71,8 +71,8 @@ If you make changes to `slack_bolt/adapter/*`, please verify if it surely works ```sh # Install all optional dependencies -$ pip install -r requirements/adapter.txt -$ pip install -r requirements/adapter_testing.txt +$ pip install -r requirements/adapter_dev.txt +$ pip install -r requirements/test_adapter.txt # Set required env variables $ export SLACK_SIGNING_SECRET=*** diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 4dcfd152a..000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,23 +0,0 @@ -## Summary - - - -### Testing - - - -### Category - -* [ ] `slack_bolt.App` and/or its core components -* [ ] `slack_bolt.async_app.AsyncApp` and/or its core components -* [ ] Adapters in `slack_bolt.adapter` -* [ ] Document pages under `/docs` -* [ ] Others - -## Requirements - -Please read the [Contributing guidelines](https://github.com/slackapi/bolt-python/blob/main/.github/contributing.md) and [Code of Conduct](https://slackhq.github.io/code-of-conduct) before creating this issue or pull request. By submitting, you are agreeing to those rules. - -* [ ] I've read and understood the [Contributing Guidelines](https://github.com/slackapi/bolt-python/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 `./scripts/install_all_and_run_tests.sh` after making the changes. diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index b158c72ea..0cb3e60d1 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -10,7 +10,7 @@ on: workflow_dispatch: env: - LATEST_SUPPORTED_PY: "3.14" + LATEST_SUPPORTED_PY: "3.15" jobs: lint: @@ -20,11 +20,11 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ env.LATEST_SUPPORTED_PY }} - name: Run lint verification @@ -37,24 +37,24 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ env.LATEST_SUPPORTED_PY }} - name: Install synchronous dependencies run: | pip install -U pip pip install -U . - pip install -r requirements/tools.txt + pip install -r requirements/dev_tools.txt - name: Type check synchronous modules run: mypy --config-file pyproject.toml --exclude "async_|/adapter/" - name: Install async and adapter dependencies run: | - pip install -r requirements/async.txt - pip install -r requirements/adapter.txt + pip install -r requirements/async_dev.txt + pip install -r requirements/adapter_dev.txt - name: Type check all modules run: mypy --config-file pyproject.toml @@ -74,29 +74,30 @@ jobs: - "3.12" - "3.13" - "3.14" + - "3.15" permissions: contents: read steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python-version }} - name: Install synchronous dependencies run: | pip install -U pip pip install . - pip install -r requirements/testing_without_asyncio.txt + pip install -r requirements/test.txt - name: Run tests without aiohttp run: | pytest tests/slack_bolt/ --junitxml=reports/test_slack_bolt.xml pytest tests/scenario_tests/ --junitxml=reports/test_scenario.xml - name: Install adapter dependencies run: | - pip install -r requirements/adapter.txt - pip install -r requirements/adapter_testing.txt + pip install -r requirements/adapter_dev.txt + pip install -r requirements/test_adapter.txt - name: Run tests for HTTP Mode adapters run: | pytest tests/adapter_tests/ \ @@ -105,14 +106,14 @@ jobs: --junitxml=reports/test_adapter.xml - name: Install async dependencies run: | - pip install -r requirements/async.txt + pip install -r requirements/async_dev.txt - name: Run tests for Socket Mode adapters run: | # Requires async test dependencies pytest tests/adapter_tests/socket_mode/ --junitxml=reports/test_adapter_socket_mode.xml - name: Install all dependencies run: | - pip install -r requirements/testing.txt + pip install -r requirements/test_async.txt - name: Run tests for HTTP Mode adapters (ASGI) run: | # Requires async test dependencies @@ -126,10 +127,10 @@ jobs: pytest tests/scenario_tests_async/ --junitxml=reports/test_scenario_async.xml - name: Upload test results to Codecov if: ${{ !cancelled() }} - uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: directory: ./reports/ - fail_ci_if_error: true + fail_ci_if_error: false flags: ${{ matrix.python-version }} report_type: test_results token: ${{ secrets.CODECOV_TOKEN }} @@ -144,25 +145,25 @@ jobs: env: BOLT_PYTHON_CODECOV_RUNNING: "1" steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ env.LATEST_SUPPORTED_PY }} - name: Install dependencies run: | pip install -U pip pip install . - pip install -r requirements/adapter.txt - pip install -r requirements/testing.txt - pip install -r requirements/adapter_testing.txt + pip install -r requirements/adapter_dev.txt + pip install -r requirements/test_async.txt + pip install -r requirements/test_adapter.txt - name: Run all tests for codecov run: | pytest --cov=./slack_bolt/ --cov-report=xml - name: Upload coverage to Codecov - uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: fail_ci_if_error: true report_type: coverage @@ -179,7 +180,7 @@ jobs: if: ${{ !success() && github.ref == 'refs/heads/main' && github.event_name != 'workflow_dispatch' }} steps: - name: Send notifications of failing tests - uses: slackapi/slack-github-action@45a88b9581bfab2566dc881e2cd66d334e621e2c # v3.0.3 + uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0 with: errors: true webhook: ${{ secrets.SLACK_REGRESSION_FAILURES_WEBHOOK_URL }} diff --git a/.github/workflows/pypi-release.yml b/.github/workflows/pypi-release.yml index 964eb2c77..c98e64afc 100644 --- a/.github/workflows/pypi-release.yml +++ b/.github/workflows/pypi-release.yml @@ -18,13 +18,13 @@ jobs: contents: read steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.event.release.tag_name || github.ref }} persist-credentials: false - name: Set up Python - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.x" @@ -33,7 +33,7 @@ jobs: scripts/build_pypi_package.sh - name: Persist dist folder - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-dist path: dist/ @@ -52,7 +52,7 @@ jobs: steps: - name: Retrieve dist folder - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-dist path: dist/ @@ -60,7 +60,7 @@ jobs: - 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@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: repository-url: https://test.pypi.org/legacy/ @@ -76,7 +76,7 @@ jobs: steps: - name: Retrieve dist folder - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-dist path: dist/ @@ -84,4 +84,24 @@ jobs: - 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@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + + notify: + if: github.event_name == 'release' && !github.event.release.prerelease && github.repository == 'slackapi/bolt-python' + runs-on: ubuntu-latest + needs: + - pypi-publish + permissions: + contents: read + + steps: + - name: Notify Slack + uses: slackapi/slack-github-action@dcb1066f776dd043e64d0e8ba94ca15cc7e1875d # v4.0.0 + with: + errors: true + webhook: ${{ secrets.SLACK_RELEASE_ANNOUNCEMENTS_WEBHOOK_URL }} + webhook-type: webhook-trigger + payload: | + action_url: "${{ github.event.release.html_url }}" + message: "bolt-python ${{ github.event.release.tag_name }}" + repository: "${{ github.repository }}" diff --git a/.github/workflows/triage-issues.yml b/.github/workflows/triage-issues.yml index c29bface2..adad546b8 100644 --- a/.github/workflows/triage-issues.yml +++ b/.github/workflows/triage-issues.yml @@ -16,7 +16,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.2.0 + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 with: days-before-issue-stale: 30 days-before-issue-close: 10 diff --git a/.gitignore b/.gitignore index 2549060e7..37a5fdd9a 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,9 @@ pip # JetBrains PyCharm settings .idea/ +# VS Code settings +.vscode/ + tmp.txt .DS_Store logs/ diff --git a/AGENTS.md b/AGENTS.md index 892a858e7..2ab2f9ce2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ Slack Bolt for Python -- a framework for building Slack apps in Python. ## Environment Setup -You can verify the venv is active by checking `echo $VIRTUAL_ENV`. If tools like `black`, `flake8`, `mypy` or `pytest` are not found, ask the user to activate the venv. +You can verify the venv is active by checking `echo $VIRTUAL_ENV`. If tools like `ruff`, `mypy` or `pytest` are not found, ask the user to activate the venv. A python virtual environment (`venv`) should be activated before running any commands. @@ -65,10 +65,10 @@ Always use the project scripts instead of calling `pytest` directly: ### Formatting, Linting, Type Checking ```bash -# Format -- Black, configured in pyproject.toml +# Format -- Ruff formatter (+ lint autofix), configured in pyproject.toml ./scripts/format.sh --no-install -# Lint -- Flake8, configured in .flake8 +# Lint -- Ruff linter, configured in pyproject.toml ./scripts/lint.sh --no-install # Type check -- mypy, configured in pyproject.toml @@ -183,7 +183,7 @@ Then wire it into `BoltContext` (`slack_bolt/context/context.py`) and `AsyncBolt 1. Create `slack_bolt/adapter//` 2. Add `__init__.py` and `handler.py` (or `async_handler.py` for async frameworks) 3. The handler converts the framework's request to `BoltRequest`, calls `app.dispatch()`, and converts `BoltResponse` back -4. Add the framework to `requirements/adapter.txt` with version constraints +4. Add the framework to `requirements/adapter_dev.txt` with version constraints 5. Add adapter tests in `tests/adapter_tests/` (sync) or `tests/adapter_tests_async/` (async) ### Adding a Kwargs-Injectable Argument @@ -205,15 +205,17 @@ The core package has a **single required runtime dependency**: `slack_sdk` (defi **`requirements/` directory structure:** -- `async.txt` -- async runtime deps (`aiohttp`, `websockets`) -- `adapter.txt` -- all framework adapter deps (Flask, Django, FastAPI, etc.) -- `testing.txt` -- test runner deps (`pytest`, `pytest-asyncio`, includes `async.txt`) -- `testing_without_asyncio.txt` -- test deps without async (`pytest`, `pytest-cov`) -- `adapter_testing.txt` -- adapter-specific test deps (`moto`, `boddle`, `sanic-testing`) -- `tools.txt` -- dev tools (`mypy`, `flake8`, `black`) +- `async_dev.txt` -- async runtime deps (`aiohttp`, `websockets`) +- `adapter_dev.txt` -- all framework adapter deps (Flask, Django, FastAPI, etc.) +- `test_async.txt` -- test runner deps (`pytest`, `pytest-asyncio`, includes `async_dev.txt`) +- `test.txt` -- test deps without async (`pytest`, `pytest-cov`) +- `test_adapter.txt` -- adapter-specific test deps (`moto`, `boddle`, `sanic-testing`) +- `dev_tools.txt` -- dev tools (`mypy`, `ruff`) When adding a new dependency: add it to the appropriate `requirements/*.txt` file with version constraints, never to `pyproject.toml` `dependencies` (unless it's a core runtime dep, which is very rare). +Before adding, bumping, pinning, or reviewing any dependency in `requirements/*.txt` -- whether a Dependabot PR or a manual edit -- follow the `managing-dependencies` skill in `.claude/skills/`. It defines the layout and `python_version` marker conventions that keep one set of pins working across the full CPython 3.7--3.15 matrix. + ## Test Organization and CI ### Directory Structure @@ -234,13 +236,13 @@ GitHub Actions (`.github/workflows/ci-build.yml`) runs on every push to `main` a - **Lint** -- `./scripts/lint.sh` on latest Python - **Typecheck** -- `./scripts/run_mypy.sh` on latest Python -- **Unit tests** -- full test suite across Python 3.7--3.14 matrix +- **Unit tests** -- full test suite across Python 3.7--3.15 matrix - **Code coverage** -- uploaded to Codecov ## PR and Commit Guidelines - PRs target the `main` branch - You MUST run `./scripts/install_all_and_run_tests.sh` before submitting -- PR template (`.github/pull_request_template.md`) requires: Summary, Testing steps, Category checkboxes (`App`, `AsyncApp`, Adapters, Docs, Others) +- PR template (`.github/PULL_REQUEST_TEMPLATE.md`) requires: Summary, Testing steps, Category checkboxes (`App`, `AsyncApp`, Adapters, Docs, Others) - Requirements: CLA signed, test suite passes, code review approval - Commits should be atomic with descriptive messages. Reference related issue numbers. diff --git a/README.md b/README.md index 39747df40..d46490693 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Documentation

-A Python framework to build Slack apps in a flash with the latest platform features. Read the [getting started guide](https://docs.slack.dev/tools/bolt-python/getting-started) and look at our [code examples](https://github.com/slackapi/bolt-python/tree/main/examples) to learn how to build apps using Bolt. The Python module documents are available [here](https://docs.slack.dev/tools/bolt-python/reference/). +A Python framework to build Slack apps in a flash with the latest platform features. Read the [Creating an app guide](https://docs.slack.dev/tools/bolt-python/creating-an-app) and look at our [code examples](https://github.com/slackapi/bolt-python/tree/main/examples) to learn how to build apps using Bolt. The Python module documents are available [here](https://docs.slack.dev/tools/bolt-python/reference/). ## Setup diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..06dfdb664 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,63 @@ +# Security Policy + +Slack takes the security of its software and services seriously, including all open-source repositories managed through the [slackapi](https://github.com/slackapi) GitHub organization. + +## Reporting a Vulnerability + +**Do NOT report security vulnerabilities through public GitHub issues, pull requests, or discussions.** + +If you believe you have found a security vulnerability in `slack-bolt`, please report it through the Slack bug bounty program on HackerOne: + +**** + +Even if `slack-bolt` is not explicitly listed as an in-scope asset on the HackerOne program page, reports for vulnerabilities in this package should still be submitted there. The Slack security team triages reports for all `slackapi` open-source repositories through this program. + +If HackerOne is inaccessible, you may alternatively report the issue to [security@salesforce.com](mailto:security@salesforce.com). + +Please do not discuss potential vulnerabilities in public without first coordinating with the security team. + +## What to Include + +To help us triage and respond quickly, please include: + +- Type of vulnerability (e.g., signature bypass, token leakage, denial of service) +- Affected version(s) of `slack-bolt` +- Step-by-step reproduction instructions +- Proof-of-concept code or payloads, if available +- Impact assessment: what an attacker could achieve +- Any specific configuration required to trigger the vulnerability +- Affected source file paths, if known + +## Threat Model + +Bolt for Python is a framework that sits between the Slack platform and developer application code. Its security boundary covers the integrity and confidentiality of that interface. + +### In Scope + +The following are considered framework vulnerabilities: + +- Bypass of request signature verification (HMAC-SHA256 validation) +- OAuth token leakage or cross-tenant token exposure during authorization flows +- Denial of service caused by malformed or specially crafted payloads processed by framework internals +- Authentication or authorization bypass in any built-in adapter +- Information disclosure through framework error responses or timing side channels +- Bypass of the `ssl_check` endpoint protections + +### Out of Scope + +The following are NOT framework vulnerabilities: + +- Vulnerabilities in the Python runtime, operating system, or hosting infrastructure +- Security issues in developer application logic built on top of Bolt (e.g., SQL injection caused by passing unsanitized payload data to a database) +- Vulnerabilities in third-party PyPI packages chosen and installed by the developer outside of Bolt's direct dependencies +- Vulnerabilities in Slack's server-side platform infrastructure (report those directly under Slack's main HackerOne scope) +- Attacks that require possession of a valid signing secret or bot token +- Arbitrary attribute injection or unsafe deserialization caused by developer code handling untrusted input +- Issues that only affect end-of-life versions with no reproduction on supported versions + +## Disclosure Policy + +This project follows coordinated disclosure: + +- Allow a reasonable timeframe for the team to investigate, develop, and release a fix before any public disclosure. +- Researchers who follow responsible disclosure practices are eligible for recognition and bounty consideration through the Slack HackerOne program. diff --git a/docs/english/_sidebar.json b/docs/english/_sidebar.json index 79721bdcd..17e6a6a32 100644 --- a/docs/english/_sidebar.json +++ b/docs/english/_sidebar.json @@ -5,8 +5,6 @@ "label": "Bolt for Python", "className": "sidebar-title" }, - "tools/bolt-python/getting-started", - { "type": "html", "value": "
" }, "tools/bolt-python/creating-an-app", { "type": "category", @@ -102,7 +100,6 @@ "label": "Legacy", "items": ["tools/bolt-python/legacy/steps-from-apps"] }, - { "type": "html", "value": "
" }, { "type": "category", "label": "Tutorials", @@ -116,107 +113,9 @@ "tools/bolt-python/tutorial/modals/modals" ] }, - { "type": "html", "value": "
" }, { "type": "link", "label": "Reference", "href": "https://docs.slack.dev/tools/bolt-python/reference/index.html" - }, - { "type": "html", "value": "
" }, - { - "type": "category", - "label": "日本語 (日本)", - "items": [ - "tools/bolt-python/ja-jp/getting-started", - { - "type": "category", - "label": "Slack API コール", - "items": [ - "tools/bolt-python/ja-jp/concepts/message-sending", - "tools/bolt-python/ja-jp/concepts/web-api" - ] - }, - { - "type": "category", - "label": "イベント API", - "items": [ - "tools/bolt-python/ja-jp/concepts/message-listening", - "tools/bolt-python/ja-jp/concepts/event-listening" - ] - }, - { - "type": "category", - "label": "インタラクティビティ & ショートカット", - "items": [ - "tools/bolt-python/ja-jp/concepts/acknowledge", - "tools/bolt-python/ja-jp/concepts/shortcuts", - "tools/bolt-python/ja-jp/concepts/commands", - "tools/bolt-python/ja-jp/concepts/actions", - "tools/bolt-python/ja-jp/concepts/opening-modals", - "tools/bolt-python/ja-jp/concepts/updating-pushing-views", - "tools/bolt-python/ja-jp/concepts/view-submissions", - "tools/bolt-python/ja-jp/concepts/select-menu-options", - "tools/bolt-python/ja-jp/concepts/app-home" - ] - }, - { - "type": "category", - "label": "App の設定", - "items": [ - "tools/bolt-python/ja-jp/concepts/socket-mode", - "tools/bolt-python/ja-jp/concepts/errors", - "tools/bolt-python/ja-jp/concepts/logging", - "tools/bolt-python/ja-jp/concepts/async" - ] - }, - { - "type": "category", - "label": "ミドルウェア & コンテキスト", - "items": [ - "tools/bolt-python/ja-jp/concepts/global-middleware", - "tools/bolt-python/ja-jp/concepts/listener-middleware", - "tools/bolt-python/ja-jp/concepts/context" - ] - }, - "tools/bolt-python/ja-jp/concepts/lazy-listeners", - { - "type": "category", - "label": "アダプター", - "items": [ - "tools/bolt-python/ja-jp/concepts/adapters", - "tools/bolt-python/ja-jp/concepts/custom-adapters" - ] - }, - { - "type": "category", - "label": "認可 & セキュリティ", - "items": [ - "tools/bolt-python/ja-jp/concepts/authenticating-oauth", - "tools/bolt-python/ja-jp/concepts/authorization", - "tools/bolt-python/ja-jp/concepts/token-rotation" - ] - }, - { - "type": "category", - "label": "レガシー(非推奨)", - "items": ["tools/bolt-python/ja-jp/legacy/steps-from-apps"] - } - ] - }, - { "type": "html", "value": "
" }, - { - "type": "link", - "label": "Release notes", - "href": "https://github.com/slackapi/bolt-python/releases" - }, - { - "type": "link", - "label": "Code on GitHub", - "href": "https://github.com/SlackAPI/bolt-python" - }, - { - "type": "link", - "label": "Contributors Guide", - "href": "https://github.com/SlackAPI/bolt-python/blob/main/.github/contributing.md" } ] diff --git a/docs/english/concepts/adding-agent-features.md b/docs/english/concepts/adding-agent-features.md index cbd164630..f420a219a 100644 --- a/docs/english/concepts/adding-agent-features.md +++ b/docs/english/concepts/adding-agent-features.md @@ -10,7 +10,7 @@ The code snippets throughout this guide are from our [Support Agent sample app]( View our [agent quickstart](/ai/agent-quickstart) to get up and running with Casey. Otherwise, read on for exploration and explanation of agent-focused Bolt features found within Casey. ::: -Your agent can utilize features applicable to messages throughout Slack, like [chat streaming](#text-streaming) and [feedback buttons](#adding-and-handling-feedback). They can also [utilize the `Assistant` class](/tools/bolt-python/concepts/assistant-class) for a side-panel view designed with AI in mind. +Your agent can utilize features applicable to messages throughout Slack, like [chat streaming](#text-streaming) and [feedback buttons](#adding-and-handling-feedback). They can also [utilize the `Assistant` class](/tools/bolt-python/concepts/using-the-assistant-class) for a side-panel view designed with AI in mind. If you're unfamiliar with using these feature within Slack, you may want to read the [API docs on the subject](/ai/). Then come back here to implement them with Bolt! @@ -42,7 +42,7 @@ slack install -E local 5. Enable MCP for your app: - Run `slack app settings` to open your app's settings - - Navigate to **Agents & AI Apps** in the left-side navigation + - Navigate to **Agents** in the left-side navigation - Toggle **Model Context Protocol** on 6. Update your `.env` OAuth environment variables: @@ -80,11 +80,10 @@ Agents can be invoked throughout Slack, such as via @mentions in channels, messa import re from logging import Logger -from agents import Runner from slack_bolt import BoltContext, Say, SayStream, SetStatus from slack_sdk import WebClient -from agent import CaseyDeps, casey_agent +from agent import CaseyDeps, run_casey from thread_context import conversation_store from listeners.views.feedback_builder import build_feedback_blocks @@ -190,7 +189,7 @@ def handle_message( # Add eyes reaction only to the first message (DMs only — channel # threads already have the reaction from the initial app_mention) if is_dm and not existing_session_id: - await client.reactions_add( + client.reactions_add( channel=channel_id, timestamp=event["ts"], name="eyes", @@ -201,14 +200,62 @@ def handle_message( - + :::tip[Using the Assistant side panel] -The Assistant side panel requires additional setup. See the [Assistant class guide](/tools/bolt-python/concepts/assistant-class). +The assistant messaging experience requires additional setup. See the [Assistant class guide](/tools/bolt-python/concepts/using-the-assistant-class). ::: +How you greet a user and set suggested prompts when they open the agent's DM depends on which [messaging experience](/ai/developing-agents) your app uses: -```py +* The **agent messaging experience** (`agent_view`) is the default and the only experience available to apps going forward. Conversations happen in the app's **Messages** tab, so you listen for the [`app_home_opened`](/reference/events/app_home_opened) event and check for the `messages` tab to detect when a user opens the DM, then set suggested prompts at the top of the tab (no `thread_ts` required). Casey uses this approach. +* The **assistant messaging experience** (`assistant_view`) is the legacy experience, with separate **Chat** and **History** tabs. You listen for the [`assistant_thread_started`](/reference/events/assistant_thread_started) event to detect a thread, then set suggested prompts on it. Existing apps can continue to use this but should migrate to the agent messaging experience. + +Refer to the [agent messaging experience changelog entry](/changelog/2026/06/30/agent-messages-tab) for the full list of changes and a migration checklist. + + + + +```python +from logging import Logger + +from slack_bolt import BoltContext +from slack_sdk import WebClient + +SUGGESTED_PROMPTS = [ + {"title": "Reset Password", "message": "I need to reset my password"}, + {"title": "Request Access", "message": "I need access to a system or tool"}, + {"title": "Network Issues", "message": "I'm having network connectivity issues"}, +] + + +def handle_app_home_opened( + client: WebClient, event: dict, context: BoltContext, logger: Logger +): + """Handle app_home_opened events. + + Under agent_view, this event fires for both the Home tab and the Messages + tab (the agent DM). Branch on ``event["tab"]``. + """ + try: + if event.get("tab") == "messages": + # Suggested prompts pin to the top of the Messages tab; no thread_ts required. + client.assistant_threads_setSuggestedPrompts( + channel_id=event["channel"], + title="How can I help you today?", + prompts=SUGGESTED_PROMPTS, + ) + return + + # event["tab"] == "home": publish your App Home Block Kit view here + except Exception as e: + logger.exception(f"Failed to handle app_home_opened: {e}") +``` + + + + +```python from logging import Logger from slack_bolt.context.set_suggested_prompts import SetSuggestedPrompts @@ -236,6 +283,9 @@ def handle_assistant_thread_started( + + + --- ## Setting status {#setting-assistant-status} @@ -274,7 +324,7 @@ The `say_stream` utility streamlines calling the Python Slack SDK's [`WebClient. | `recipient_team_id` | Sourced from the event `team_id` (`enterprise_id` if the app is installed on an org). | `recipient_user_id` | Sourced from the `user_id` of the event. -If neither a `channel_id` or `thread_ts` can be sourced, then the utility will be `None`. +If either `channel_id` or `thread_ts` cannot be sourced, the utility will be `None`. ```python streamer = say_stream() @@ -395,7 +445,7 @@ from logging import Logger from slack_bolt import BoltContext, Say, SayStream, SetStatus from slack_sdk import WebClient -from agent import CaseyDeps, casey_agent, get_model +from agent import CaseyDeps, run_casey from thread_context import conversation_store from listeners.views.feedback_builder import build_feedback_blocks @@ -456,13 +506,9 @@ def handle_app_mentioned( channel_id=channel_id, thread_ts=thread_ts, message_ts=event["ts"], + user_token=context.user_token, ) - result = casey_agent.run_sync( - cleaned_text, - model=get_model(), - deps=deps, - message_history=history, - ) + result = run_casey(cleaned_text, deps, message_history=history) # Stream response in thread with feedback buttons streamer = say_stream() @@ -554,6 +600,7 @@ def handle_app_mentioned( channel_id=channel_id, thread_ts=thread_ts, message_ts=event["ts"], + user_token=context.user_token, ) response_text, new_session_id = run_casey_agent( cleaned_text, session_id=existing_session_id, deps=deps @@ -571,7 +618,7 @@ def handle_app_mentioned( except Exception as e: logger.exception(f"Failed to handle app mention: {e}") - await say( + say( text=f":warning: Something went wrong! ({e})", thread_ts=event.get("thread_ts") or event["ts"], ) @@ -583,11 +630,10 @@ def handle_app_mentioned( import re from logging import Logger -from agents import Runner from slack_bolt import BoltContext, Say, SayStream, SetStatus from slack_sdk import WebClient -from agent import CaseyDeps, casey_agent +from agent import CaseyDeps, run_casey from thread_context import conversation_store from listeners.views.feedback_builder import build_feedback_blocks @@ -654,8 +700,9 @@ def handle_app_mentioned( channel_id=channel_id, thread_ts=thread_ts, message_ts=event["ts"], + user_token=context.user_token, ) - result = Runner.run_sync(casey_agent, input=input_items, context=deps) + result = run_casey(input_items, deps) # Stream response in thread with feedback buttons streamer = say_stream() diff --git a/docs/english/concepts/authorization.md b/docs/english/concepts/authorization.md index f6a258491..9d0086ca7 100644 --- a/docs/english/concepts/authorization.md +++ b/docs/english/concepts/authorization.md @@ -2,9 +2,10 @@ Authorization is the process of determining which Slack credentials should be available while processing an incoming Slack request. -Apps installed on a single workspace can simply pass their bot token into the `App` constructor using the `token` parameter. However, if your app will be installed on multiple workspaces, you have two options. The easier option is to use the built-in OAuth support. This will handle setting up OAuth routes and verifying state. Read the section on [authenticating with OAuth](/tools/bolt-python/concepts/authenticating-oauth) for details. +Apps installed on a single workspace can pass their bot token into the `App` constructor using the `token` parameter. However, if your app will be installed on multiple workspaces, you have two options: -For a more custom solution, you can set the `authorize` parameter to a function upon `App` instantiation. The `authorize` function should return [an instance of `AuthorizeResult`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/authorization/authorize_result.py), which contains information about who and where the request is coming from. +* Use the built-in OAuth support. This will handle setting up OAuth routes and verifying state. See [authenticating with OAuth](/tools/bolt-python/concepts/authenticating-oauth) for more details. +* Set the `authorize` parameter to a function upon `App` instantiation. The `authorize` function should return [an instance of `AuthorizeResult`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/authorization/authorize_result.py), which contains information about who and where the request is coming from. `AuthorizeResult` should have a few specific properties, all of type `str`: - Either **`bot_token`** (xoxb) *or* **`user_token`** (xoxp) are **required**. Most apps will use `bot_token` by default. Passing a token allows built-in functions (like `say()`) to work. @@ -62,3 +63,11 @@ app = App( authorize=authorize ) ``` + +## Handling failed token lookups {#handling-failed-token-lookups} + +In the event that you receive events from disconnected teams, make sure to gracefully drop these unauthorized payloads by returning `None` to silently drop the payload as follows. + +In the custom `authorize` callback, if a token lookup fails due to an `unknown team_id`, you should return `None` rather than raising an exception (such as `BoltUnauthorizedError`). Bolt's authorization middleware will recognize the `None` response as an authorization failure and immediately halt execution, silently dropping the payload without generating server error logs. + +Additionally, the `user_facing_authorize_error_message` parameter strictly controls the ephemeral message sent back to the end user via the Slack UI. It does not suppress internal server logs or exceptions. To achieve both the desired UI behavior and clean server logs, pair this parameter with returning `None` in your authorize function. diff --git a/docs/english/concepts/custom-steps-dynamic-options.md b/docs/english/concepts/custom-steps-dynamic-options.md index 9a152daa0..dfe95a323 100644 --- a/docs/english/concepts/custom-steps-dynamic-options.md +++ b/docs/english/concepts/custom-steps-dynamic-options.md @@ -88,13 +88,13 @@ The `inputs` attribute defines the parameters to be passed as inputs to the step The following format can be used to reference any input parameter defined by the step: `{{input_parameters.}}`. -In addition, the `{{client.query}}` parameter can be used as a placeholder for an input value. The `{{client.builder_context}}` parameter will inject the [`slack#/types/user_context`](/tools/deno-slack-sdk/reference/slack-types/#usercontext) of the user building the workflow as the value to the input parameter. +In addition, the `{{client.query}}` parameter can be used as a placeholder for an input value. The `{{client.builder_context}}` parameter will inject the [`slack#/types/user_context`](/reference/types/user_context-type) of the user building the workflow as the value to the input parameter. ### Types of dynamic options UIs {#dynamic-option-UIs} The above example demonstrates one possible UI to be rendered for builders: a single-select drop-down menu of dynamic options. However, dynamic options in Workflow Builder can be rendered in one of two ways: as a drop-down menu (single-select or multi-select), or as a set of fields. -The type is dictated by the output parameter of the custom step used as a dynamic option. In order to use a custom step in a dynamic option context, its output must adhere to a defined interface, that is, it must have an `options` parameter of type [`options_select`](/tools/deno-slack-sdk/reference/slack-types#options_select) or [`options_field`](/tools/deno-slack-sdk/reference/slack-types#options_field), as shown in the following code snippet. +The type is dictated by the output parameter of the custom step used as a dynamic option. In order to use a custom step in a dynamic option context, its output must adhere to a defined interface, that is, it must have an `options` parameter of type [`options_select`](/reference/types/options_select-type) or [`options_field`](/reference/types/options_field-type), as shown in the following code snippet. ```js "output_parameters": { @@ -109,9 +109,9 @@ The type is dictated by the output parameter of the custom step used as a dynami #### Drop-down menus {#drop-down} -Your dynamic input parameter can be rendered as a drop-down menu, which will use the options obtained from a custom step with an `options` output parameter of the type [`options_select`](/tools/deno-slack-sdk/reference/slack-types#options_select). +Your dynamic input parameter can be rendered as a drop-down menu, which will use the options obtained from a custom step with an `options` output parameter of the type [`options_select`](/reference/types/options_select-type). -The drop-down menu UI component can be rendered in two ways: single-select, or multi-select. To render the dynamic input as a single-select menu, the input parameter defining the dynamic option must be of the type [`string`](/tools/deno-slack-sdk/reference/slack-types#string). +The drop-down menu UI component can be rendered in two ways: single-select, or multi-select. To render the dynamic input as a single-select menu, the input parameter defining the dynamic option must be of the type [`string`](/reference/types/string-type). ```js "step-with-dynamic-input": { @@ -133,7 +133,7 @@ The drop-down menu UI component can be rendered in two ways: single-select, or m } ``` -To render the dynamic input as a multi-select menu, the input parameter defining the dynamic option must be of the type [`array`](/tools/deno-slack-sdk/reference/slack-types#array), and its `items` must be of type [`string`](/tools/deno-slack-sdk/reference/slack-types#string). +To render the dynamic input as a multi-select menu, the input parameter defining the dynamic option must be of the type [`array`](/reference/types/array-type), and its `items` must be of type [`string`](/reference/types/string-type). ```js "step-with-dynamic-input": { @@ -159,9 +159,9 @@ To render the dynamic input as a multi-select menu, the input parameter defining #### Fields {#fields} -In the code snippet below, the input parameter is rendered as a set of fields with keys and values. The option fields are obtained from a custom step with an `options` output parameter of type [`options_field`](/tools/deno-slack-sdk/reference/slack-types#options_field). +In the code snippet below, the input parameter is rendered as a set of fields with keys and values. The option fields are obtained from a custom step with an `options` output parameter of type [`options_field`](/reference/types/options_field-type). -The input parameter that defines the dynamic option must be of type [`object`](/tools/deno-slack-sdk/reference/slack-types#object), as the completed set of fields in Workflow Builder will be passed to the custom step as an [untyped object](/tools/deno-slack-sdk/reference/slack-types#untyped-object) during workflow execution. +The input parameter that defines the dynamic option must be of type [`object`](/reference/types/object-type), as the completed set of fields in Workflow Builder will be passed to the custom step as an [untyped object](/reference/types/object-type#untyped-object) during workflow execution. ```js "test-field-dynamic-options": { @@ -185,15 +185,15 @@ The input parameter that defines the dynamic option must be of type [`object`](/ ### Dynamic option types {#dynamic-option-types} -As mentioned earlier, in order to use a custom step as a dynamic option, its output must adhere to a defined interface: it must have an `options` output parameter of the type either [`options_select`](/tools/deno-slack-sdk/reference/slack-types#options_select) or [`options_field`](/tools/deno-slack-sdk/reference/slack-types#options_field). +As mentioned earlier, in order to use a custom step as a dynamic option, its output must adhere to a defined interface: it must have an `options` output parameter of the type either [`options_select`](/reference/types/options_select-type) or [`options_field`](/reference/types/options_field-type). -To take a look at these in more detail, refer to our [Options Slack type](/tools/deno-slack-sdk/reference/slack-types#options) documentation. +To take a look at these in more detail, refer to our [Options Slack type](/reference/types) documentation. ## Dynamic options handler {#dynamic-option-handler} Each custom step defined in the manifest needs a corresponding handler in your Slack app. Although implemented similarly to existing function execution event handlers, there are two key differences between regular custom step invocations and those used for dynamic options: -* The custom step must have an `options` output parameter that is of type [`options_select`](/tools/deno-slack-sdk/reference/slack-types#options_select) or [`options_field`](/tools/deno-slack-sdk/reference/slack-types#options_field). +* The custom step must have an `options` output parameter that is of type [`options_select`](/reference/types/options_select-type) or [`options_field`](/reference/types/options_field-type). * The [`function_executed`](/reference/events/function_executed) event must be handled synchronously. This optimizes the response time of returned dynamic options and provides a crisp builder experience. ### Asynchronous event handling {#async} diff --git a/docs/english/concepts/message-sending.md b/docs/english/concepts/message-sending.md index 090503ff2..67b70d9b0 100644 --- a/docs/english/concepts/message-sending.md +++ b/docs/english/concepts/message-sending.md @@ -17,7 +17,7 @@ def ask_who(message, say): `say()` accepts more complex message payloads to make it easy to add functionality and structure to your messages. -To explore adding rich message layouts to your app, read through [the guide on our API site](/messaging/#structure) and look through templates of common app flows [in the Block Kit Builder](https://api.slack.com/tools/block-kit-builder?template=1). +To explore adding rich message layouts to your app, read through [the guide on our API site](/messaging/#structure) and look through templates of common app flows [in the Block Kit Builder](https://app.slack.com/block-kit-builder). ```python # Sends a section block with datepicker when someone reacts with a 📅 emoji @@ -54,7 +54,7 @@ The `say_stream` utility streamlines calling the Python Slack SDK's [`WebClient. | `recipient_team_id` | Sourced from the event `team_id` (`enterprise_id` if the app is installed on an org). | `recipient_user_id` | Sourced from the `user_id` of the event. -If neither a `channel_id` or `thread_ts` can be sourced, then the utility will be `None`. +If either `channel_id` or `thread_ts` cannot be sourced, the utility will be `None`. For information on calling the `chat_*Stream` API methods directly, see the [_Sending streaming messages_](/tools/python-slack-sdk/web#sending-streaming-messages) section of the Python Slack SDK docs. @@ -79,7 +79,7 @@ def handle_app_mention(client: WebClient, say_stream: SayStream): def handle_message(client: WebClient, say_stream: SayStream): stream = say_stream() - stream.append(markdown_text="Let me consult my *vast knowledge database*...) + stream.append(markdown_text="Let me consult my *vast knowledge database*...") stream.stop() if __name__ == "__main__": diff --git a/docs/english/concepts/shortcuts.md b/docs/english/concepts/shortcuts.md index b28f0b352..86186e035 100644 --- a/docs/english/concepts/shortcuts.md +++ b/docs/english/concepts/shortcuts.md @@ -40,7 +40,7 @@ def open_modal(ack, shortcut, client): "elements": [ { "type": "mrkdwn", - "text": "Psssst this modal was designed using " + "text": "Psssst this modal was designed using " } ] } @@ -79,7 +79,7 @@ def open_modal(ack, shortcut, client): "elements": [ { "type": "mrkdwn", - "text": "Psssst this modal was designed using " + "text": "Psssst this modal was designed using " } ] } diff --git a/docs/english/concepts/updating-pushing-views.md b/docs/english/concepts/updating-pushing-views.md index 8c05e79c8..ce285c814 100644 --- a/docs/english/concepts/updating-pushing-views.md +++ b/docs/english/concepts/updating-pushing-views.md @@ -1,6 +1,6 @@ # Updating & pushing views -Modals contain a stack of views. When you call [`views_open`](https://api./reference/methods/views.open/slack.com/methods/views.open), you add the root view to the modal. After the initial call, you can dynamically update a view by calling [`views_update`](/reference/methods/views.update/), or stack a new view on top of the root view by calling [`views_push`](/reference/methods/views.push/) +Modals contain a stack of views. When you call [`views_open`](/reference/methods/views.open/), you add the root view to the modal. After the initial call, you can dynamically update a view by calling [`views_update`](/reference/methods/views.update/), or stack a new view on top of the root view by calling [`views_push`](/reference/methods/views.push/) ## The `views_update` method diff --git a/docs/english/concepts/using-the-assistant-class.md b/docs/english/concepts/using-the-assistant-class.md index ed004dc35..55ca3d110 100644 --- a/docs/english/concepts/using-the-assistant-class.md +++ b/docs/english/concepts/using-the-assistant-class.md @@ -4,7 +4,11 @@ If you don't have a paid workspace for development, you can join the [Developer Program](https://api.slack.com/developer-program) and provision a sandbox with access to all Slack features for free. ::: -The `Assistant` class can be used to handle the incoming events expected from a user interacting with an app in Slack that has the Agents & AI Apps feature enabled. +The `Assistant` class can be used to handle the incoming events expected from a user interacting with an app in Slack that has the **Agents** feature enabled. + +:::warning[The `Assistant` class targets the assistant messaging experience] +The `Assistant` class handles the [assistant messaging experience](/ai/developing-agents) (`assistant_view`), in which agent conversations happen in separate Chat and History tabs. Apps going forward use the agent messaging experience (`agent_view`) by default, where conversations happen in the Messages tab and you handle events such as [`app_home_opened`](/reference/events/app_home_opened) and [`message.im`](/reference/events/message.im) directly. Refer to [Adding agent features](/tools/bolt-python/concepts/adding-agent-features) and the [agent messaging experience changelog entry](/changelog/2026/06/30/agent-messages-tab) for the default experience and migration guidance. +::: A typical flow would look like: @@ -51,14 +55,14 @@ You _could_ go it alone and [listen](/tools/bolt-python/concepts/event-listening While the `assistant_thread_started` and `assistant_thread_context_changed` events do provide Slack-client thread context information, the `message.im` event does not. Any subsequent user message events won't contain thread context data. For that reason, Bolt not only provides a way to store thread context — the `threadContextStore` property — but it also provides a `DefaultThreadContextStore` instance that is utilized by default. This implementation relies on storing and retrieving [message metadata](/messaging/message-metadata/) as the user interacts with the app. -If you do provide your own `threadContextStore` property, it must feature `get` and `save` methods. +If you do provide your own `threadContextStore` property, it must feature `find` and `save` methods. :::tip[Refer to the [reference docs](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) to learn the available listener arguments.] ::: ## Configuring your app to support the `Assistant` class {#configuring-assistant-class} -1. Within [App Settings](https://api.slack.com/apps), enable the **Agents & AI Apps** feature. +1. Within [App Settings](https://api.slack.com/apps), enable the **Agents** feature. 2. Within the App Settings **OAuth & Permissions** page, add the following scopes: * [`assistant:write`](/reference/scopes/assistant.write) @@ -138,10 +142,10 @@ Messages sent to the app do not contain a [subtype](/reference/events/message#su There are three utilities that are particularly useful in curating the user experience: * [`say`](https://docs.slack.dev/tools/bolt-python/reference/#slack_bolt.Say) -* [`setTitle`](https://docs.slack.dev/tools/bolt-python/reference/#slack_bolt.SetTitle) -* [`setStatus`](https://docs.slack.dev/tools/bolt-python/reference/#slack_bolt.SetStatus) +* [`set_title`](https://docs.slack.dev/tools/bolt-python/reference/#slack_bolt.SetTitle) +* [`set_status`](https://docs.slack.dev/tools/bolt-python/reference/#slack_bolt.SetStatus) -Within the `setStatus` utility, you can cycle through strings passed into a `loading_messages` array. +Within the `set_status` utility, you can cycle through strings passed into a `loading_messages` list. ```python # This listener is invoked when the human user sends a reply in the assistant thread @@ -326,4 +330,4 @@ def respond_to_bot_messages(logger: logging.Logger, set_status: SetStatus, say: See the [_Creating agents: adding and handling feedback_](/tools/bolt-python/concepts/adding-agent-features#adding-and-handling-feedback) section for adding feedback buttons with Block Kit. -Want to see the functionality described throughout this guide in action? We've created a [App Agent Template](https://github.com/slack-samples/bolt-python-assistant-template) repo for you to build from. \ No newline at end of file +Want to see the functionality described throughout this guide in action? We've created a [Starter Agent Template](https://github.com/slack-samples/bolt-python-starter-agent) repo for you to build from. \ No newline at end of file diff --git a/docs/english/concepts/view-submissions.md b/docs/english/concepts/view-submissions.md index 4ff4c2da7..b961e0376 100644 --- a/docs/english/concepts/view-submissions.md +++ b/docs/english/concepts/view-submissions.md @@ -90,6 +90,6 @@ def handle_submission(ack, body, client, view, logger): # Message the user try: client.chat_postMessage(channel=user, text=msg) - except e: + except Exception as e: logger.exception(f"Failed to post a message {e}") ``` diff --git a/docs/english/creating-an-app.md b/docs/english/creating-an-app.md index 7f06e9d42..0901588a8 100644 --- a/docs/english/creating-an-app.md +++ b/docs/english/creating-an-app.md @@ -4,10 +4,14 @@ sidebar_label: Creating an app # Creating an app with Bolt for Python -This guide is meant to walk you through getting up and running with a Slack app using Bolt for Python. Along the way, we’ll create a new Slack app, set up your local environment, and develop an app that listens and responds to messages from a Slack workspace. +:::tip[More doing, less reading] +This guide is a more thorough explanation on creating a Slack app. If you want a running app as fast as possible, follow our [Quickstart](/quickstart) that harnesses the power of Bolt and the [Slack CLI](/tools/slack-cli). +::: + +Follow along to get up and running with a Slack app using Bolt for Python. Along the way, we’ll create a new Slack app, set up your local environment, and develop an app that listens and responds to messages from a Slack workspace. When you're finished, you'll have created the [Getting Started app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started) to run, modify, and make your own. ⚡️ - + --- ### Create a new app {#create-an-app} @@ -15,7 +19,7 @@ First thing's first: before you start developing with Bolt, you'll want to [crea :::tip[A place to test and learn] -We recommend using a workspace where you won't disrupt real work getting done — [you can create a new one for free](https://slack.com/get-started#create). +We recommend using a workspace where you won't disrupt real work getting done, like a [developer sandbox](/tools/developer-sandboxes). ::: @@ -55,7 +59,7 @@ We're going to use bot and app-level tokens for this guide. :::tip[Not sharing is sometimes caring] -Treat your tokens like passwords and [keep them safe](/security). Your app uses tokens to post and retrieve information from Slack workspaces. +Treat your tokens like passwords and [keep them safe](/concepts/security). Your app uses tokens to post and retrieve information from Slack workspaces. ::: @@ -103,7 +107,7 @@ $ export SLACK_APP_TOKEN= :::warning[Keep it secret. Keep it safe.] -Remember to keep your tokens secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we've done above. Check out the API documentation for more on [best practices for app security](/security). +Remember to keep your tokens secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we've done above. Check out the API documentation for more on [best practices for app security](/concepts/security). ::: diff --git a/docs/english/experiments.md b/docs/english/experiments.md index 13adf0a32..443a334be 100644 --- a/docs/english/experiments.md +++ b/docs/english/experiments.md @@ -1,30 +1,11 @@ # Experiments -Bolt for Python includes experimental features still under active development. These features may be fleeting, may not be perfectly polished, and should be thought of as available for use "at your own risk." +Bolt for Python occasionally includes experimental features still under active development. These features may be fleeting, may not be perfectly polished, and should be thought of as available for use "at your own risk." Experimental features are categorized as `semver:patch` until the experimental status is removed. We love feedback from our community, so we encourage you to explore and interact with the [GitHub repo](https://github.com/slackapi/bolt-python). Contributions, bug reports, and any feedback are all helpful; let us nurture the Slack CLI together to help make building Slack apps more pleasant for everyone. ## Available experiments -* [Agent listener argument](#agent) -## Agent listener argument {#agent} - -The `agent: BoltAgent` listener argument provides access to AI agent-related features. - -The `BoltAgent` and `AsyncBoltAgent` classes offer a `chat_stream()` method that comes pre-configured with event context defaults: `channel_id`, `thread_ts`, `team_id`, and `user_id` fields. - -The listener argument is wired into the Bolt `kwargs` injection system, so listeners can declare it as a parameter or access it via the `context.agent` property. - -### Example - -```python -from slack_bolt import BoltAgent - -@app.event("app_mention") -def handle_mention(agent: BoltAgent): - stream = agent.chat_stream() - stream.append(markdown_text="Hello!") - stream.stop() -``` +There are currently no active experiments. We're steadily staying stable. diff --git a/docs/english/getting-started.md b/docs/english/getting-started.md deleted file mode 100644 index 6964df23b..000000000 --- a/docs/english/getting-started.md +++ /dev/null @@ -1,288 +0,0 @@ ---- -sidebar_label: Quickstart -title: Quickstart guide with Bolt for Python ---- - -This quickstart guide aims to help you get a Slack app using Bolt for Python up and running as soon as possible! - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -When complete, you'll have a local environment configured with a customized [app](https://github.com/slack-samples/bolt-python-getting-started-app) running to modify and make your own. - -:::tip[Reference for readers] - -In search of the complete guide to building an app from scratch? Check out the [building an app](/tools/bolt-python/building-an-app) guide. - -::: - -#### Prerequisites - -A few tools are needed for the following steps. We recommend using the [**Slack CLI**](/tools/slack-cli/) for the smoothest experience, but other options remain available. - -You can also begin by installing git and downloading [Python 3.7 or later](https://www.python.org/downloads/), or the latest stable version of Python. Refer to [Python's setup and building guide](https://devguide.python.org/getting-started/setup-building/) for more details. - -Install the latest version of the Slack CLI to get started: - -- [Slack CLI for macOS & Linux](/tools/slack-cli/guides/installing-the-slack-cli-for-mac-and-linux) -- [Slack CLI for Windows](/tools/slack-cli/guides/installing-the-slack-cli-for-windows) - -Then confirm a successful installation with the following command: - -```sh -$ slack version -``` - -An authenticated login is also required if this hasn't been done before: - -```sh -$ slack login -``` - -:::info[A place to belong] - -A workspace where development can happen is also needed. - -We recommend using [developer sandboxes](/tools/developer-sandboxes) to avoid disruptions where real work gets done. - -::: - -## Creating a project {#creating-a-project} - -With the toolchain configured, it's time to set up a new Bolt project. This contains the code that handles logic for your app. - -If you don’t already have a project, let’s create a new one! - - - - -A starter template can be used to start with project scaffolding: - -```sh -$ slack create first-bolt-app --template slack-samples/bolt-python-getting-started-app -$ cd first-bolt-app -``` - -After a project is created you'll have a `requirements.txt` file for app dependencies and a `.slack` directory for Slack CLI configuration. - -A few other files exist too, but we'll visit these later. - - - - -A starter template can be cloned to start with project scaffolding: - -```sh -$ git clone https://github.com/slack-samples/bolt-python-getting-started-app first-bolt-app -$ cd first-bolt-app -``` - -Outlines of a project are taking shape, so we can move on to running the app! - - - - -We recommend using a [Python virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment) to manage your project's dependencies. This is a great way to prevent conflicts with your system's Python packages. Let's create and activate a new virtual environment with [Python 3.7 or later](https://www.python.org/downloads/): - -```sh -$ python3 -m venv .venv -$ source .venv/bin/activate -$ pip install -r requirements.txt -``` - -Confirm the virtual environment is active by checking that the path to `python3` is _inside_ your project ([a similar command is available on Windows](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment)): - -```sh -$ which python3 -# Output: /path/to/first-bolt-app/.venv/bin/python3 -``` - -## Running the app {#running-the-app} - -Before you can start developing with Bolt, you will want a running Slack app. - - - - -The getting started app template contains a `manifest.json` file with details about an app that we will use to get started. Use the following command and select "Create a new app" to install the app to the team of choice: - -```sh -$ slack run -... -⚡️ Bolt app is running! -``` - -With the app running, you can test it out with the following steps in Slack: - -1. Open a direct message with your app or invite the bot `@first-bolt-app (local)` to a public channel. -2. Send "hello" to the current conversation and wait for a response. -3. Click the attached button labelled "Click Me" to post another reply. - -After confirming the app responds, celebrate, then interrupt the process by pressing `CTRL+C` in the terminal to stop your app from running. - - - - -Navigate to your list of apps and [create a new Slack app](https://api.slack.com/apps/new) using the "from a manifest" option: - -1. Select the workspace to develop your app in. -2. Copy and paste the `manifest.json` file contents to create your app. -3. Confirm the app features and click "Create". - -You'll then land on your app's **Basic Information** page, which is an overview of your app and which contains important credentials: - -![Basic Information page](/img/bolt-python/basic-information-page.png "Basic Information page") - -To listen for events happening in Slack (such as a new posted message) without opening a port or exposing an endpoint, we will use [Socket Mode](/tools/bolt-python/concepts/socket-mode). This connection requires a specific app token: - -1. On the **Basic Information** page, scroll to the **App-Level Tokens** section and click **Generate Token and Scopes**. -2. Name the token "Development" or something similar and add the `connections:write` scope, then click **Generate**. -3. Save the generated `xapp` token as an environment variable within your project: - -```sh -$ export SLACK_APP_TOKEN= -``` - -The above command works on Linux and macOS but [similar commands are available on Windows](https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line/212153#212153). - -:::warning[Keep it secret. Keep it safe.] - -Treat your tokens like a password and [keep it safe](/security). Your app uses these to retrieve and send information to Slack. - -::: - -A bot token is also needed to interact with the Web API methods as your app's bot user. We can gather this as follows: - -1. Navigate to the **OAuth & Permissions** on the left sidebar and install your app to your workspace to generate a token. -2. After authorizing the installation, you'll return to the **OAuth & Permissions** page and find a **Bot User OAuth Token**: - -![OAuth Tokens](/img/bolt-python/bot-token.png "Bot OAuth Token") - -3. Copy the bot token beginning with `xoxb` from the **OAuth & Permissions page** and then store it in a new environment variable: - -```sh -$ export SLACK_BOT_TOKEN=xoxb- -``` - -After saving tokens for the app you created, it is time to run it: - -```sh -$ python3 app.py -... -⚡️ Bolt app is running! -``` - -With the app running, you can test it out with the following steps in Slack: - -1. Open a direct message with your app or invite the bot `@BoltApp` to a public channel. -2. Send "hello" to the current conversation and wait for a response. -3. Click the attached button labelled "Click Me" to post another reply. - -After confirming the app responds, celebrate, then interrupt the process by pressing `CTRL+C` in the terminal to stop your app from running. - - - - -## Updating the app - -At this point, you've successfully run the getting started Bolt for Python [app](https://github.com/slack-samples/bolt-python-getting-started-app)! - -The defaults included leave opportunities abound, so to personalize this app let's now edit the code to respond with a kind farewell. - -#### Responding to a farewell - -Chat is a common thing apps do and responding to various types of messages can make conversations more interesting. - -Using an editor of choice, open the `app.py` file and add the following import to the top of the file, and message listener after the "hello" handler: - -```python -import random - -@app.message("goodbye") -def message_goodbye(say): - responses = ["Adios", "Au revoir", "Farewell"] - parting = random.choice(responses) - say(f"{parting}!") -``` - -Once the file is updated, save the changes and then we'll make sure those changes are being used. - - - - -Run the following command and select the app created earlier to start, or restart, your app with the latest changes: - -```sh -$ slack run -... -⚡️ Bolt app is running! -``` - -After finding the above output appears, open Slack to perform these steps: - -1. Return to the direct message or public channel with your bot. -2. Send "goodbye" to the conversation. -3. Receive a parting response from before and repeat "goodbye" to find another one. - -Your app can be stopped again by pressing `CTRL+C` in the terminal to end these chats. - - - - -Run the following command to start, or restart, your app with the latest changes: - -```sh -$ python3 app.py -... -⚡️ Bolt app is running! -``` - -After finding the above output appears, open Slack to perform these steps: - -1. Return to the direct message or public channel with your bot. -2. Send "goodbye" to the conversation. -3. Receive a parting response from before and repeat "goodbye" to find another one. - -Your app can be stopped again by pressing `CTRL+C` in the terminal to end these chats. - - - - -#### Customizing app settings - -The created app will have some placeholder values and a small set of [scopes](/reference/scopes) to start, but we recommend exploring the customizations possible on app settings. - - - - -Open app settings for your app with the following command: - -```sh -$ slack app settings -``` - -This will open the following page in a web browser: - -![Basic Information page](/img/bolt-python/basic-information-page.png "Basic Information page") - - - - -Browse to https://api.slack.com/apps and select your app "Getting Started Bolt App" from the list. - -This will open the following page: - -![Basic Information page](/img/bolt-python/basic-information-page.png "Basic Information page") - - - - -On these pages you're free to make changes such as updating your app icon, configuring app features, and perhaps even distributing your app! - -## Next steps {#next-steps} - -You can now continue customizing your app with various features to make it right for whatever job's at hand. Here are some ideas about what to explore next: - -- Follow along with the steps that went into making this app on the [creating an app](/tools/bolt-python/creating-an-app) guide for an educational overview. -- Check out the [Agent quickstart](/ai/agent-quickstart) to get up and running with an agent. -- Browse our [curated catalog of samples](/samples) for more apps to use as a starting point for development. \ No newline at end of file diff --git a/docs/english/index.md b/docs/english/index.md index 212bd9690..d38ecd274 100644 --- a/docs/english/index.md +++ b/docs/english/index.md @@ -1,6 +1,6 @@ # Bolt for Python -Bolt for Python is a Python framework to build Slack apps with the latest Slack platform features. Read the [Getting Started Guide](/tools/bolt-python/getting-started) to set up and run your first Bolt app. +Bolt for Python is a Python framework to build Slack apps with the latest Slack platform features. Read the [Creating an app guide](/tools/bolt-python/creating-an-app) to set up and run your first Bolt app. Then, explore the rest of the pages within the Guides section. The documentation there will help you build a Bolt app for whatever use case you may have. @@ -13,6 +13,10 @@ If you otherwise get stuck, we're here to help. The following are the best ways * [Issue Tracker](http://github.com/slackapi/bolt-python/issues) for questions, bug reports, feature requests, and general discussion related to Bolt for Python. Try searching for an existing issue before creating a new one. * [Email](mailto:support@slack.com) our developer support team: `support@slack.com`. +## Release notes + +Check out the [Bolt for Python release notes](https://github.com/slackapi/bolt-python/releases) for all the latest happenings. + ## Contributing These docs live within the [Bolt-Python](https://github.com/slackapi/bolt-python/) repository and are open source. diff --git a/docs/english/tutorial/ai-chatbot/ai-chatbot.md b/docs/english/tutorial/ai-chatbot/ai-chatbot.md index 2fcc16e9a..427d626bc 100644 --- a/docs/english/tutorial/ai-chatbot/ai-chatbot.md +++ b/docs/english/tutorial/ai-chatbot/ai-chatbot.md @@ -195,7 +195,7 @@ To test this, leave the channel you just invited Bolty to and rejoin it. This wi ![Channel summary](7.png) -The central part of this functionality is shown in the following code snippet. Note the use of the [`user_context`](/tools/deno-slack-sdk/reference/slack-types#usercontext) object, a Slack type that represents the user who is interacting with our workflow, as well as the `history` of the channel that will be summarized, which includes the ten most recent messages. +The central part of this functionality is shown in the following code snippet. Note the use of the [`user_context`](/reference/types/user_context-type) object, a Slack type that represents the user who is interacting with our workflow, as well as the `history` of the channel that will be summarized, which includes the ten most recent messages. ```python from ai.providers import get_provider_response @@ -241,5 +241,5 @@ You can also navigate to **Bolty** in your **Apps** list and select the **Messag Congratulations! You've successfully integrated the power of AI into your workspace. Check out these links to take the next steps in your Bolt for Python journey. -- To learn more about Bolt for Python, refer to the [Getting started](/tools/bolt-python/getting-started) documentation. +- To learn more about Bolt for Python, refer to the [Creating an app](/tools/bolt-python/creating-an-app) documentation. - For more details about creating workflow steps using the Bolt SDK, refer to the [workflow steps for Bolt](/workflows/workflow-steps) guide. \ No newline at end of file diff --git a/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md b/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md index d74b82b8e..3aaff96f9 100644 --- a/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md +++ b/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md @@ -167,6 +167,6 @@ When finished, you can click the **Disconnect Account** button in the home tab t Congratulations! You've successfully customized your workspace with custom steps in Workflow Builder. Check out these links to take the next steps in your journey. -* To learn more about Bolt for Python, refer to the [getting started](/tools/bolt-python/getting-started) documentation. +* To learn more about Bolt for Python, refer to the [Creating an app](/tools/bolt-python/creating-an-app) documentation. * For more details about creating workflow steps using the Bolt SDK, refer to the [workflow steps for Bolt](/workflows/workflow-steps) guide. * For information about custom steps dynamic options, refer to [custom steps dynamic options in Workflow Builder](/tools/bolt-python/concepts/custom-steps-dynamic-options). diff --git a/docs/english/tutorial/custom-steps-workflow-builder-existing/custom-steps-workflow-builder-existing.md b/docs/english/tutorial/custom-steps-workflow-builder-existing/custom-steps-workflow-builder-existing.md index c3c5e2af7..9a5e3ee50 100644 --- a/docs/english/tutorial/custom-steps-workflow-builder-existing/custom-steps-workflow-builder-existing.md +++ b/docs/english/tutorial/custom-steps-workflow-builder-existing/custom-steps-workflow-builder-existing.md @@ -14,7 +14,7 @@ In this tutorial we will: ## Prerequisites {#prereqs} -The custom steps feature is compatible with Bolt version 1.20.0 and above. First, update your `package.json` file to reflect version 1.20.0 of Bolt, then run the following command in your terminal: +The custom steps feature is compatible with Bolt version 1.20.0 and above. First, update your `requirements.txt` file to reflect version 1.20.0 of Bolt (e.g., `slack-bolt>=1.20.0`), then run the following commands in your terminal: ```sh python3 -m venv .venv @@ -215,9 +215,8 @@ def manager_resp_handler(ack: Ack, action, body: dict, client: WebClient, comple client.chat_update( channel=body['channel']['id'], - message=body['message'], ts=body["message"]["ts"], - text=f'Request {"approved" if request_decision == 'approve' else "denied"}!' + text=f"Request {'approved' if request_decision == 'approve' else 'denied'}!" ) complete({ diff --git a/docs/english/tutorial/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md b/docs/english/tutorial/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md index 1dceed45a..d8941f70f 100644 --- a/docs/english/tutorial/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md +++ b/docs/english/tutorial/custom-steps-workflow-builder-new/custom-steps-workflow-builder-new.md @@ -47,7 +47,9 @@ You can also open a terminal window from inside VSCode like this: `Ctrl` + `~` Once in VSCode, open the terminal. Let's install our package dependencies: run the following command(s) in the terminal inside VSCode: ```sh -npm install +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt ``` We now have a Bolt app ready for development! Open the `manifest.json` file and copy its contents; you'll need this in the next step. @@ -68,7 +70,7 @@ All of your app's settings can be configured within these screens. By creating a Navigate to **Event Subscriptions** and expand **Subscribe to bot events** to see that we have subscribed to the `function_executed` event. This is also a requirement for adding workflow steps to our app, as it lets our app know when a step has been triggered, allowing our app to respond to it. -Another configuration setting to note is **Socket Mode**. We have turned this on for our local development, but socket mode is not intended for use in a production environment. When you are satisfied with your app and ready to deploy it to a production environment, you should switch to using public HTTP request URLs. Read more about getting started with HTTP in [Bolt for Python here](/tools/bolt-python/getting-started). +Another configuration setting to note is **Socket Mode**. We have turned this on for our local development, but socket mode is not intended for use in a production environment. When you are satisfied with your app and ready to deploy it to a production environment, you should switch to using public HTTP request URLs. Read more about getting started with HTTP in [Bolt for Python here](/tools/bolt-python/creating-an-app). Clicking on **Workflow Steps** in the left nav will show you that one workflow step has been added! This reflects the `function` defined in our manifest: functions are workflow steps. We will get to this step's implementation later. @@ -99,7 +101,7 @@ You will then have a bot token. Again, copy that value and save it somewhere acc ## Starting your local development server {#local} -While building your app, you can see your changes appear in your workspace in real-time with `npm start`. Soon we'll start our local development server and see what our sample code is all about! But first, we need to store those tokens we gathered as environment variables. +While building your app, you can see your changes appear in your workspace in real-time with `python app.py`. Soon we'll start our local development server and see what our sample code is all about! But first, we need to store those tokens we gathered as environment variables. Navigate back to VSCode. Rename the `.env.sample` file to `.env`. Open this file and update `SLACK_APP_TOKEN` and `SLACK_BOT_TOKEN` with the values you previously saved. It will look like this, with your actual token values where you see `` and ``: @@ -111,7 +113,7 @@ SLACK_BOT_TOKEN= Now save the file and try starting your app: ```sh -npm start +python app.py ``` You'll know the local development server is up and running successfully when it emits a bunch of `[DEBUG]` statements to your terminal, the last one containing `connected:ready`. diff --git a/docs/english/tutorial/custom-steps.md b/docs/english/tutorial/custom-steps.md index 66dc16198..50bd723ce 100644 --- a/docs/english/tutorial/custom-steps.md +++ b/docs/english/tutorial/custom-steps.md @@ -111,9 +111,9 @@ Here is a sample app manifest laying out a step definition. This definition tell "name": "user_id" } }, - "required": { + "required": [ "user_id" - } + ] }, "output_parameters": { "properties": { @@ -124,9 +124,9 @@ Here is a sample app manifest laying out a step definition. This definition tell "name": "user_id" } }, - "required": { + "required": [ "user_id" - } + ] }, } } @@ -157,7 +157,7 @@ Notice in the example code here that the name of the step, `sample_step`, is the ```py @app.function("sample_step") -def handle_sample_step_event(inputs: dict, fail: Fail, complete: Complete,logger: logging.Logger): +def handle_sample_step_event(client: WebClient, inputs: dict, fail: Fail, complete: Complete, logger: logging.Logger): user_id = inputs["user_id"] try: client.chat_postMessage( @@ -226,7 +226,7 @@ The second argument is the callback function, or the logic that will run when yo Field | Description ------|------------ `client` | A `WebClient` instance used to make things happen in Slack. From sending messages to opening modals, `client` makes it all happen. For a full list of available methods, refer to the [Web API methods](/reference/methods). Read more about the `WebClient` for Bolt Python [here](https://docs.slack.dev/tools/bolt-python/concepts/web-api/). -`complete` | A utility method that invokes `functions.completeSuccess`. This method indicates to Slack that a step has completed successfully without issue. When called, `complete` requires you include an `outputs` object that matches your step definition in [`output_parameters`](#inputs-outputs). +`complete` | A utility method that invokes `functions.completeSuccess`. This method indicates to Slack that a step has completed successfully without issue. When called, `complete` accepts an optional `outputs` object that matches your step definition in [`output_parameters`](#inputs-outputs). `fail` | A utility method that invokes `functions.completeError`. True to its name, this method signals to Slack that a step has failed to complete. The `fail` method requires an argument of `error` to be sent along with it, which is used to help users understand what went wrong. `inputs` | An alias for the `input_parameters` that were provided to the step upon execution. diff --git a/docs/english/tutorial/modals/modals.md b/docs/english/tutorial/modals/modals.md index d25470b97..6e2aa11ee 100644 --- a/docs/english/tutorial/modals/modals.md +++ b/docs/english/tutorial/modals/modals.md @@ -131,4 +131,4 @@ All done! 🎉 You've created your first slash command using Block Kit and modal ## Next steps {#next-steps} -If you want to learn more about Bolt for Python, refer to the [Getting Started guide](https://docs.slack.dev/tools/bolt-python/getting-started). \ No newline at end of file +If you want to learn more about Bolt for Python, refer to the [Creating an app guide](https://docs.slack.dev/tools/bolt-python/creating-an-app). \ No newline at end of file diff --git a/docs/japanese/concepts/acknowledge.md b/docs/japanese/concepts/acknowledge.md deleted file mode 100644 index 36ba6cba4..000000000 --- a/docs/japanese/concepts/acknowledge.md +++ /dev/null @@ -1,27 +0,0 @@ -# リクエストの確認 - -アクション(action)、コマンド(command)、ショートカット(shortcut)、オプション(options)、およびモーダルからのデータ送信(view_submission)の各リクエストは、**必ず** `ack()` 関数を使って確認を行う必要があります。これによってリクエストが受信されたことが Slack に認識され、Slack のユーザーインターフェイスが適切に更新されます。 - -リクエストの種類によっては、確認で通知方法が異なる場合があります。例えば、外部データソースを使用する選択メニューのオプションのリクエストに対する確認では、適切な[オプション](/reference/block-kit/composition-objects/option-object)のリストとともに `ack()` を呼び出します。モーダルからのデータ送信に対する確認では、 `response_action` を渡すことで[モーダルの更新](/tools/bolt-python/concepts/view-submissions)などを行えます。 - -確認までの猶予は 3 秒しかないため、新しいメッセージの送信やデータベースからの情報の取得といった時間のかかる処理は、`ack()` を呼び出した後で行うことをおすすめします。 - - FaaS / serverless 環境を使う場合、 `ack()` するタイミングが異なります。 これに関する詳細は [Lazy listeners (FaaS)](/tools/bolt-python/concepts/lazy-listeners) を参照してください。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# 外部データを使用する選択メニューオプションに応答するサンプル -@app.options("menu_selection") -def show_menu_options(ack): - options = [ - { - "text": {"type": "plain_text", "text":"Option 1"}, - "value":"1-1", - }, - { - "text": {"type": "plain_text", "text":"Option 2"}, - "value":"1-2", - }, - ] - ack(options=options) -``` diff --git a/docs/japanese/concepts/actions.md b/docs/japanese/concepts/actions.md deleted file mode 100644 index 8f1d1180e..000000000 --- a/docs/japanese/concepts/actions.md +++ /dev/null @@ -1,70 +0,0 @@ -# アクション - -## アクションのリスニング - -Bolt アプリは `action` メソッドを用いて、ボタンのクリック、メニューの選択、メッセージショートカットなどのユーザーのアクションをリッスンすることができます。 - -アクションは `str` 型または `re.Pattern` 型の `action_id` でフィルタリングできます。`action_id` は、Slack プラットフォーム上のインタラクティブコンポーネントを区別する一意の識別子として機能します。 - -`action()` を使ったすべての例で `ack()` が使用されていることに注目してください。アクションのリスナー内では、Slack からのリクエストを受信したことを確認するために、`ack()` 関数を呼び出す必要があります。これについては、[リクエストの確認](/tools/bolt-python/concepts/acknowledge)セクションで説明しています。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# 'approve_button' という action_id のブロックエレメントがトリガーされるたびに、このリスナーが呼び出させれる -@app.action("approve_button") -def update_message(ack): - ack() - # アクションへの反応としてメッセージを更新 -``` - -### 制約付きオブジェクトを使用したアクションのリスニング - -制約付きのオブジェクトを使用すると、`block_id` と `action_id` をそれぞれ、または任意に組み合わせてリッスンできます。オブジェクト内の制約は、`str` 型または `re.Pattern` 型で指定できます。 - -```python -# この関数は、block_id が 'assign_ticket' に一致し -# かつ action_id が 'select_user' に一致する場合にのみ呼び出される -@app.action({ - "block_id": "assign_ticket", - "action_id": "select_user" -}) -def update_message(ack, body, client): - ack() - - if "container" in body and "message_ts" in body["container"]: - client.reactions_add( - name="white_check_mark", - channel=body["channel"]["id"], - timestamp=body["container"]["message_ts"], - ) -``` - -## アクションへの応答 - -アクションへの応答には、主に 2 つの方法があります。1 つ目の最も一般的なやり方は `say()` を使用する方法です。そのリクエストが発生した会話(チャンネルや DM)にメッセージを返します。 - -2 つ目は、`respond()` を使用する方法です。これは、アクションに関連づけられた `response_url` を使ったメッセージ送信を行うためのユーティリティです。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# 'approve_button' という action_id のインタラクティブコンポーネントがトリガーされると、このリスナーが呼ばれる -@app.action("approve_button") -def approve_request(ack, say): - # アクションのリクエストを確認 - ack() - say("Request approved 👍") -``` - -### respond() の利用 - -`respond()` は `response_url` を使って送信するときに便利なメソッドで、これらと同じような動作をします。投稿するメッセージのペイロードには、全ての[メッセージペイロードのプロパティ](/messaging/#payloads)とオプションのプロパティとして `response_type`(値は `"in_channel"` または `"ephemeral"`)、`replace_original`、`delete_original`、`unfurl_links`、`unfurl_media` などを指定できます。こうすることによってアプリから送信されるメッセージは、やり取りの発生元に反映されます。 - -```python -# 'user_select' という action_id を持つアクションのトリガーをリッスン -@app.action("user_select") -def select_user(ack, action, respond): - ack() - respond(f"You selected <@{action['selected_user']}>") -``` diff --git a/docs/japanese/concepts/adapters.md b/docs/japanese/concepts/adapters.md deleted file mode 100644 index 6ed804c26..000000000 --- a/docs/japanese/concepts/adapters.md +++ /dev/null @@ -1,38 +0,0 @@ -# アダプター - -アダプターは Slack から届く受信リクエストの受付とパーズを担当し、それらのリクエストを [`BoltRequest`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/request/request.py) の形式に変換して Bolt アプリに引き渡します。 - -デフォルトでは、Bolt の組み込みの [`HTTPServer`](https://docs.python.org/3/library/http.server.html) アダプターが使われます。このアダプターは、ローカルで開発するのには問題がありませんが、**本番環境での利用は推奨されていません**。Bolt for Python には複数の組み込みのアダプターが用意されており、必要に応じてインポートしてアプリで使用することができます。組み込みのアダプターは Flask、Django、Starlette をはじめとする様々な人気の Python フレームワークをサポートしています。これらのアダプターは、あなたが選択した本番環境で利用可能な Webサーバーとともに利用することができます。 - -アダプターを使用するには、任意のフレームワークを使ってアプリを開発し、そのコードに対応するアダプターをインポートします。その後、アダプターのインスタンスを初期化して、受信リクエストの受付とパーズを行う関数を呼び出します。 - -すべてのアダプターの一覧と、設定や使い方のサンプルは、リポジトリの [`examples` フォルダ](https://github.com/slackapi/bolt-python/tree/main/examples)をご覧ください。 - -```python -from slack_bolt import App -app = App( - signing_secret=os.environ.get("SLACK_SIGNING_SECRET"), - token=os.environ.get("SLACK_BOT_TOKEN") -) - -# ここには Flask 固有の記述はありません -# App はフレームワークやランタイムに一切依存しません -@app.command("/hello-bolt") -def hello(body, ack): - ack(f"Hi <@{body['user_id']}>!") - -# Flask アプリを初期化します -from flask import Flask, request -flask_app = Flask(__name__) - -# SlackRequestHandler は WSGI のリクエストを Bolt のインターフェイスに合った形に変換します -# Bolt レスポンスからの WSGI レスポンスの作成も行います -from slack_bolt.adapter.flask import SlackRequestHandler -handler = SlackRequestHandler(app) - -# Flask アプリへのルートを登録します -@flask_app.route("/slack/events", methods=["POST"]) -def slack_events(): - # handler はアプリのディスパッチメソッドを実行します - return handler.handle(request) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/app-home.md b/docs/japanese/concepts/app-home.md deleted file mode 100644 index d950221ad..000000000 --- a/docs/japanese/concepts/app-home.md +++ /dev/null @@ -1,40 +0,0 @@ -# ホームタブの更新 - -[ホームタブ](/surfaces/app-home)は、サイドバーや検索画面からアクセス可能なサーフェスエリアです。アプリはこのエリアを使ってユーザーごとのビューを表示することができます。アプリ設定ページで App Home の機能を有効にすると、[`views.publish`](/reference/methods/views.publish) API メソッドの呼び出しで `user_id` と[ビューのペイロード](/reference/interaction-payloads/view-interactions-payload/#view_submission)を指定して、ホームタブを公開・更新することができるようになります。 - -[`app_home_opened`](/reference/events/app_home_opened) イベントをサブスクライブすると、ユーザーが App Home を開く操作をリッスンできます。 - -指定可能な引数の一覧は [モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -@app.event("app_home_opened") -def update_home_tab(client, event, logger): - try: - # 組み込みのクライアントを使って views.publish を呼び出す - client.views_publish( - # イベントに関連づけられたユーザー ID を使用 - user_id=event["user"], - # アプリの設定で予めホームタブが有効になっている必要がある - view={ - "type": "home", - "blocks": [ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": "*Welcome home, <@" + event["user"] + "> :house:*" - } - }, - { - "type": "section", - "text": { - "type": "mrkdwn", - "text":"Learn how home tabs can be more useful and interactive ." - } - } - ] - } - ) - except Exception as e: - logger.error(f"Error publishing home tab: {e}") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/async.md b/docs/japanese/concepts/async.md deleted file mode 100644 index 6687dcff5..000000000 --- a/docs/japanese/concepts/async.md +++ /dev/null @@ -1,67 +0,0 @@ -# Async(asyncio)の使用 - -非同期バージョンの Bolt を使用する場合は、`App` の代わりに `AsyncApp` インスタンスをインポートして初期化します。`AsyncApp` では [AIOHTTP](https://docs.aiohttp.org/) を使って API リクエストを行うため、`aiohttp` をインストールする必要があります(`requirements.txt` に追記するか、`pip install aiohttp` を実行します)。 - -非同期バージョンのプロジェクトのサンプルは、リポジトリの [`examples` フォルダ](https://github.com/slackapi/bolt-python/tree/main/examples)にあります。 - -```python -# aiohttp のインストールが必要です -from slack_bolt.async_app import AsyncApp -app = AsyncApp() - -@app.event("app_mention") -async def handle_mentions(event, client, say): # 非同期関数 - api_response = await client.reactions_add( - channel=event["channel"], - timestamp=event["ts"], - name="eyes", - ) - await say("What's up?") - -if __name__ == "__main__": - app.start(3000) -``` - -## 他のフレームワークを使用する - -`AsyncApp#start()` では内部的に [`AIOHTTP`](https://docs.aiohttp.org/) のWebサーバーが実装されています。必要に応じて、受信リクエストの処理に `AIOHTTP` 以外のフレームワークを使用することができます。 - -この例では [Sanic](https://sanicframework.org/) を使用しています。すべてのアダプターのリストについては、[`adapter` フォルダ](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter) を参照してください。 - -以下のコマンドを実行すると、必要なパッケージをインストールして、Sanic サーバーをポート 3000 で起動します。 - -```bash -# 必要なパッケージをインストールします -pip install slack_bolt sanic uvicorn -# ソースファイルを async_app.py として保存します -uvicorn async_app:api --reload --port 3000 --log-level debug -``` - -```python -from slack_bolt.async_app import AsyncApp -app = AsyncApp() - -# ここには Sanic に固有の記述はありません -# AsyncApp はフレームワークやランタイムに依存しません -@app.event("app_mention") -async def handle_app_mentions(say): - await say("What's up?") - -import os -from sanic import Sanic -from sanic.request import Request -from slack_bolt.adapter.sanic import AsyncSlackRequestHandler - -# App のインスタンスから Sanic 用のアダプターを作成します -app_handler = AsyncSlackRequestHandler(app) -# Sanic アプリを作成します -api = Sanic(name="awesome-slack-app") - -@api.post("/slack/events") -async def endpoint(req: Request): - # app_handler では内部的にアプリのディスパッチメソッドが実行されます - return await app_handler.handle(req) - -if __name__ == "__main__": - api.run(host="0.0.0.0", port=int(os.environ.get("PORT", 3000))) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/authenticating-oauth.md b/docs/japanese/concepts/authenticating-oauth.md deleted file mode 100644 index e09443d64..000000000 --- a/docs/japanese/concepts/authenticating-oauth.md +++ /dev/null @@ -1,86 +0,0 @@ -# OAuth を使った認証 - -Slack アプリを複数のワークスペースにインストールできるようにするためには、OAuth フローを実装した上で、アクセストークンなどのインストールに関する情報をセキュアな方法で保存する必要があります。アプリを初期化する際に `client_id`、`client_secret`、`scopes`、`installation_store`、`state_store` を指定することで、OAuth のエンドポイントのルート情報や stateパラメーターの検証をBolt for Python にハンドリングさせることができます。カスタムのアダプターを実装する場合は、SDK が提供する組み込みの[OAuth ライブラリ](/tools/python-slack-sdk/oauth/)を利用するのが便利です。これは Slack が開発したモジュールで、Bolt for Python 内部でも利用しています。 - -Bolt for Python によって `slack/oauth_redirect` という**リダイレクト URL** が生成されます。Slack はアプリのインストールフローを完了させたユーザーをこの URL にリダイレクトします。この**リダイレクト URL** は、アプリの設定の「**OAuth and Permissions**」であらかじめ追加しておく必要があります。この URL は、後ほど説明するように `OAuthSettings` というコンストラクタの引数で指定することもできます。 - -Bolt for Python は `slack/install` というルートも生成します。これはアプリを直接インストールするための「**Add to Slack**」ボタンを表示するために使われます。すでにワークスペースへのアプリのインストールが済んでいる場合に追加で各ユーザーのユーザートークンなどの情報を取得する場合や、カスタムのインストール用の URL を動的に生成したい場合などは、`oauth_settings` の `authorize_url_generator` でカスタムの URL ジェネレーターを指定することができます。 - -バージョン 1.1.0 以降の Bolt for Python では、[OrG 全体へのインストール](/enterprise)がデフォルトでサポートされています。OrG 全体へのインストールは、アプリの設定の「**Org Level Apps**」で有効化できます。 - -Slack での OAuth を使ったインストールフローについて詳しくは、[API ドキュメントを参照してください](/authentication/installing-with-oauth)。 - -```python -import os -from slack_bolt import App -from slack_bolt.oauth.oauth_settings import OAuthSettings -from slack_sdk.oauth.installation_store import FileInstallationStore -from slack_sdk.oauth.state_store import FileOAuthStateStore - -oauth_settings = OAuthSettings( - client_id=os.environ["SLACK_CLIENT_ID"], - client_secret=os.environ["SLACK_CLIENT_SECRET"], - scopes=["channels:read", "groups:read", "chat:write"], - installation_store=FileInstallationStore(base_dir="./data/installations"), - state_store=FileOAuthStateStore(expiration_seconds=600, base_dir="./data/states") -) - -app = App( - signing_secret=os.environ["SLACK_SIGNING_SECRET"], - oauth_settings=oauth_settings -) -``` - -## OAuth デフォルト設定をカスタマイズ - -`oauth_settings` を使って OAuth モジュールのデフォルト設定を上書きすることができます。このカスタマイズされた設定は App の初期化時に渡します。以下の情報を変更可能です: - -- `install_path` : 「Add to Slack」ボタンのデフォルトのパスを上書きするために使用 -- `redirect_uri` : リダイレクト URL のデフォルトのパスを上書きするために使用 -- `callback_options` : OAuth フローの最後に表示するカスタムの成功ページと失敗ページの表示処理を提供するために使用 -- `state_store` : 組み込みの `FileOAuthStateStore` に代わる、カスタムの stateに関するデータストアを指定するために使用 -- `installation_store` : 組み込みの `FileInstallationStore` に代わる、カスタムのデータストアを指定するために使用 - -```python -from slack_bolt.oauth.callback_options import CallbackOptions, SuccessArgs, FailureArgs -from slack_bolt.response import BoltResponse - -def success(args:SuccessArgs) -> BoltResponse: - assert args.request is not None - return BoltResponse( - status=200, # ユーザーをリダイレクトすることも可能 - body="Your own response to end-users here" - ) - -def failure(args:FailureArgs) -> BoltResponse: - assert args.request is not None - assert args.reason is not None - return BoltResponse( - status=args.suggested_status_code, - body="Your own response to end-users here" - ) - -callback_options = CallbackOptions(success=success, failure=failure) - -import os -from slack_bolt import App -from slack_bolt.oauth.oauth_settings import OAuthSettings -from slack_sdk.oauth.installation_store import FileInstallationStore -from slack_sdk.oauth.state_store import FileOAuthStateStore - -app = App( - signing_secret=os.environ.get("SLACK_SIGNING_SECRET"), - installation_store=FileInstallationStore(base_dir="./data/installations"), - oauth_settings=OAuthSettings( - client_id=os.environ.get("SLACK_CLIENT_ID"), - client_secret=os.environ.get("SLACK_CLIENT_SECRET"), - scopes=["app_mentions:read", "channels:history", "im:history", "chat:write"], - user_scopes=[], - redirect_uri=None, - install_path="/slack/install", - redirect_uri_path="/slack/oauth_redirect", - state_store=FileOAuthStateStore(expiration_seconds=600, base_dir="./data/states"), - callback_options=callback_options, - ), -) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/authorization.md b/docs/japanese/concepts/authorization.md deleted file mode 100644 index b6a14b30a..000000000 --- a/docs/japanese/concepts/authorization.md +++ /dev/null @@ -1,64 +0,0 @@ -# 認可(Authorization) - -認可(Authorization)は、Slack からの受信リクエストを処理するにあたって、どのようなSlack -クレデンシャル (ボットトークンなど) を使用可能にするかを決定するプロセスです。 - -単一のワークスペースにインストールされるアプリでは、`token` パラメーターを使って `App` のコンストラクターにボットトークンを渡すという、シンプルな方法が使えます。それに対して、複数のワークスペースにインストールされるアプリでは、次の 2 つの方法のいずれかを使用する必要があります。簡単なのは、組み込みの OAuth サポートを使用する方法です。OAuth サポートは、OAuth フロー用のURLのセットアップとstateの検証を行います。詳細は「[OAuth を使った認証](/tools/bolt-python/concepts/authenticating-oauth)」セクションを参照してください。 - -よりカスタマイズできる方法として、`App` をインスタンス化する関数に`authorize` パラメーターを指定する方法があります。`authorize` 関数から返される [`AuthorizeResult` のインスタンス](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/authorization/authorize_result.py)には、どのユーザーがどこで発生させたリクエストかを示す情報が含まれます。 - -`AuthorizeResult` には、いくつか特定のプロパティを指定する必要があり、いずれも `str` 型です。 - -- **`bot_token`**(xoxb)*または* **`user_token`**(xoxp): どちらか一方が**必須**です。ほとんどのアプリでは、デフォルトの `bot_token` を使用すればよいでしょう。トークンを渡すことで、`say()` などの組み込みの関数を機能させることができます。 -- **`bot_user_id`** および **`bot_id`** : `bot_token` を使用する場合に指定します。 -- **`enterprise_id`** および **`team_id`** : アプリに届いたリクエストから見つけることができます。 -- **`user_id`** : `user_token` を使用する場合に必須です。 - -```python -import os -from slack_bolt import App -# AuthorizeResult クラスをインポートします -from slack_bolt.authorization import AuthorizeResult - -# これはあくまでサンプル例です(ユーザートークンがないことを想定しています) -# 実際にはセキュアな DB に認可情報を保存してください -installations = [ - { - "enterprise_id":"E1234A12AB", - "team_id":"T12345", - "bot_token": "xoxb-123abc", - "bot_id":"B1251", - "bot_user_id":"U12385" - }, - { - "team_id":"T77712", - "bot_token": "xoxb-102anc", - "bot_id":"B5910", - "bot_user_id":"U1239", - "enterprise_id":"E1234A12AB" - } -] - -def authorize(enterprise_id, team_id, logger): - # トークンを取得するためのあなたのロジックをここに記述します - for team in installations: - # 一部のチームは enterprise_id を持たない場合があります - is_valid_enterprise = "enterprise_id" not in team or enterprise_id == team["enterprise_id"] - if is_valid_enterprise and team["team_id"] == team_id: - # AuthorizeResult のインスタンスを返します - # bot_id と bot_user_id を保存していない場合、bot_token を使って `from_auth_test_response` を呼び出すと、自動的に取得できます - return AuthorizeResult( - enterprise_id=enterprise_id, - team_id=team_id, - bot_token=team["bot_token"], - bot_id=team["bot_id"], - bot_user_id=team["bot_user_id"] - ) - - logger.error("No authorization information was found") - -app = App( - signing_secret=os.environ["SLACK_SIGNING_SECRET"], - authorize=authorize -) -``` diff --git a/docs/japanese/concepts/commands.md b/docs/japanese/concepts/commands.md deleted file mode 100644 index ebb43c4d3..000000000 --- a/docs/japanese/concepts/commands.md +++ /dev/null @@ -1,19 +0,0 @@ -# コマンドのリスニングと応答 - -スラッシュコマンドが実行されたリクエストをリッスンするには、`command()` メソッドを使用します。このメソッドでは `str` 型の `command_name` の指定が必要です。 - -コマンドリクエストをアプリが受信し確認したことを Slack に通知するため、`ack()` を呼び出す必要があります。 - -スラッシュコマンドに応答する方法は 2 つあります。1 つ目は `say()` を使う方法で、文字列または JSON のペイロードを渡すことができます。2 つ目は `respond()` を使う方法です。これは `response_url` がある場合に活躍します。これらの方法は[アクションへの応答](/tools/bolt-python/concepts/actions)セクションで詳しく説明しています。 - -アプリの設定でコマンドを登録するときは、リクエスト URL の末尾に `/slack/events` をつけます。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# echoコマンドは受け取ったコマンドをそのまま返す -@app.command("/echo") -def repeat_text(ack, respond, command): - # command リクエストを確認 - ack() - respond(f"{command['text']}") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/context.md b/docs/japanese/concepts/context.md deleted file mode 100644 index 13a287728..000000000 --- a/docs/japanese/concepts/context.md +++ /dev/null @@ -1,65 +0,0 @@ -# コンテキストの追加 - -すべてのリスナーは `context` ディクショナリにアクセスできます。リスナーはこれを使ってリクエストの付加情報を得ることができます。受信リクエストに含まれる `user_id`、`team_id`、`channel_id`、`enterprise_id` などの情報は、Bolt によって自動的に設定されます。 - -`context` は単純なディクショナリで、変更を直接加えることもできます。 - -```python -# ユーザーID を使って外部のシステムからタスクを取得するリスナーミドルウェア -def fetch_tasks(context, event, next): - user = event["user"] - try: - # get_tasks は、ユーザー ID に対応するタスクのリストを DB から取得します - user_tasks = db.get_tasks(user) - tasks = user_tasks - except Exception: - # タスクが見つからなかった場合 get_tasks() は例外を投げます - tasks = [] - finally: - # ユーザーのタスクを context に設定します - context["tasks"] = tasks - next() - -# section のブロックのリストを作成するリスナーミドルウェア -def create_sections(context, next): - task_blocks = [] - # 先ほどのミドルウェアを使って context に追加した各タスクについて、処理を繰り返します - for task in context["tasks"]: - task_blocks.append( - { - "type": "section", - "text": { - "type": "mrkdwn", - "text": f"*{task['title']}* -{task['body']}" - }, - "accessory": { - "type": "button", - "text": { - "type": "plain_text", - "text":"See task" - }, - "url": task["url"], - } - } - ) - # ブロックのリストを context に設定します - context["blocks"] = task_blocks - next() - -# ユーザーがアプリのホームを開くのをリッスンします -# fetch_tasks ミドルウェアを含めます -@app.event( - event = "app_home_opened", - middleware = [fetch_tasks, create_sections] -) -def show_tasks(event, client, context): - # ユーザーのホームタブにビューを表示します - client.views_publish( - user_id=event["user"], - view={ - "type": "home", - "blocks": context["blocks"] - } - ) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/custom-adapters.md b/docs/japanese/concepts/custom-adapters.md deleted file mode 100644 index 584893511..000000000 --- a/docs/japanese/concepts/custom-adapters.md +++ /dev/null @@ -1,65 +0,0 @@ -# カスタムのアダプター - -[アダプター](/tools/bolt-python/concepts/adapters)はフレキシブルで、あなたが使用したいフレームワークに合わせた調整も可能です。アダプターでは、次の 2 つの要素が必須となっています。 - -- `__init__(app:App)` : コンストラクター。Bolt の `App` のインスタンスを受け取り、保持します。 -- `handle(req:Request)` : Slack からの受信リクエストを受け取り、解析を行う関数。通常は `handle()` という名前です。リクエストを [`BoltRequest`](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/request/request.py) のインスタンスに合った形にして、保持している Bolt アプリに引き渡します。 - -`BoltRequest` のインスタンスの作成では、以下の 4 種類のパラメーターを指定できます。 - -| パラメーター | 説明 | 必須 | -|-----------|-------------|-----------| -| `body: str` | そのままのリクエストボディ | **Yes** | -| `query: any` | クエリストリング | No | -| `headers:Dict[str, Union[str, List[str]]]` | リクエストヘッダー | No | -| `context:BoltContext` | リクエストのコンテキスト情報 | No | - -アダプターは、Bolt アプリからの [`BoltResponse` のインスタンス](https://github.com/slackapi/bolt-python/blob/main/slack_bolt/response/response.py)を返します。 - -カスタムのアダプターに関連した詳しいサンプルについては、[組み込みのアダプター](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter)の実装を参考にしてください。 - -```python -# Flask で必要なパッケージをインポートします -from flask import Request, Response, make_response - -from slack_bolt.app import App -from slack_bolt.request import BoltRequest -from slack_bolt.response import BoltResponse - -# この例は Flask アダプターを簡略化したものです -# もう少し詳しい完全版のサンプルは、adapter フォルダをご覧ください -# github.com/slackapi/bolt-python/blob/main/slack_bolt/adapter/flask/handler.py - -# HTTP リクエストを取り込み、標準の BoltRequest に変換します -def to_bolt_request(req:Request) -> BoltRequest: - return BoltRequest( - body=req.get_data(as_text=True), - query=req.query_string.decode("utf-8"), - headers=req.headers, - ) - -# BoltResponse を取り込み、標準の Flask レスポンスに変換します -def to_flask_response(bolt_resp:BoltResponse) -> Response: - resp:Response = make_response(bolt_resp.body, bolt_resp.status) - for k, values in bolt_resp.headers.items(): - for v in values: - resp.headers.add_header(k, v) - return resp - -# アプリからインスタンス化します -# Flask アプリを受け取ります -class SlackRequestHandler: - def __init__(self, app:App): - self.app = app - - # Slack からリクエストが届いたときに - # Flask アプリの handle() を呼び出します - def handle(self, req:Request) -> Response: - # この例では OAuth に関する部分は扱いません - if req.method == "POST": - # Bolt へのリクエストをディスパッチし、処理とルーティングを行います - bolt_resp:BoltResponse = self.app.dispatch(to_bolt_request(req)) - return to_flask_response(bolt_resp) - - return make_response("Not Found", 404) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/errors.md b/docs/japanese/concepts/errors.md deleted file mode 100644 index 2e8e27f90..000000000 --- a/docs/japanese/concepts/errors.md +++ /dev/null @@ -1,12 +0,0 @@ -# エラーの処理 - -リスナー内でエラーが発生した場合に try/except ブロックを使用して直接エラーを処理することができます。アプリに関連するエラーは、`BoltError` 型です。Slack API の呼び出しに関連するエラーは、`SlackApiError` 型となります。 - -デフォルトでは、すべての処理されなかった例外のログはグローバルのエラーハンドラーによってコンソールに出力されます。グローバルのエラーを開発者自身で処理するには、`app.error(fn)` 関数を使ってグローバルのエラーハンドラーをアプリに設定します。 - -```python -@app.error -def custom_error_handler(error, body, logger): - logger.exception(f"Error: {error}") - logger.info(f"Request body: {body}") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/event-listening.md b/docs/japanese/concepts/event-listening.md deleted file mode 100644 index 7b21f1fa4..000000000 --- a/docs/japanese/concepts/event-listening.md +++ /dev/null @@ -1,33 +0,0 @@ -# イベントのリスニング - -`event()` メソッドを使うと、[Events API](/reference/events) の任意のイベントをリッスンできます。リッスンするイベントは、アプリの設定であらかじめサブスクライブしておく必要があります。これを利用することで、アプリがインストールされたワークスペースで何らかのイベント(例:ユーザーがメッセージにリアクションをつけた、ユーザーがチャンネルに参加した)が発生したときに、アプリに何らかのアクションを実行させることができます。 - -`event()` メソッドには `str` 型の `eventType` を指定する必要があります。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# ユーザーがワークスペースに参加した際に、自己紹介を促すメッセージを指定のチャンネルに送信 -@app.event("team_join") -def ask_for_introduction(event, say): - welcome_channel_id = "C12345" - user_id = event["user"] - text = f"Welcome to the team, <@{user_id}>! 🎉 You can introduce yourself in this channel." - say(text=text, channel=welcome_channel_id) -``` - -## メッセージのサブタイプのフィルタリング - -`message()` リスナーは `event("message")` と等価の機能を提供します。 - -`subtype` という追加のキーを指定して、イベントのサブタイプでフィルタリングすることもできます。よく使われるサブタイプには、`bot_message` や `message_replied` があります。詳しくは[メッセージイベントページ](/reference/events/message#subtypes)を参照してください。サブタイプなしのイベントだけにフィルターするために明に `None` を指定することもできます。 - -```python -# 変更されたすべてのメッセージに一致 -@app.event({ - "type": "message", - "subtype": "message_changed" -}) -def log_message_change(logger, event): - user, text = event["user"], event["text"] - logger.info(f"The user {user} changed the message to {text}") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/global-middleware.md b/docs/japanese/concepts/global-middleware.md deleted file mode 100644 index 01ca417ac..000000000 --- a/docs/japanese/concepts/global-middleware.md +++ /dev/null @@ -1,29 +0,0 @@ -# グローバルミドルウェア - -グローバルミドルウェアは、すべての受信リクエストに対して、リスナーミドルウェアが呼ばれる前に実行されるものです。ミドルウェア関数を `app.use()` に渡すことで、アプリにはグローバルミドルウェアをいくつでも追加できます。ミドルウェア関数で受け取れる引数はリスナー関数と同じものに加えて`next()` 関数があります。 - -グローバルミドルウェアでもリスナーミドルウェアでも、次のミドルウェアに実行チェーンの制御をリレーするために、`next()` を呼び出す必要があります。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -@app.use -def auth_abc(client, context, logger, payload, next): - slack_user_id = payload["user"] - help_channel_id = "C12345" - - try: - # Slack のユーザー ID を使って外部のシステムでユーザーを検索します - user = abc.lookup_by_id(slack_user_id) - # 結果を context に保存します - context["user"] = user - except Exception: - client.chat_postEphemeral( - channel=payload["channel"], - user=slack_user_id, - text=f"Sorry <@{slack_user_id}>, you aren't registered in ABC or there was an error with authentication.Please post in <#{help_channel_id}> for assistance" - ) - - # 次のミドルウェアに実行権を渡します - next() -``` \ No newline at end of file diff --git a/docs/japanese/concepts/lazy-listeners.md b/docs/japanese/concepts/lazy-listeners.md deleted file mode 100644 index 029f61d99..000000000 --- a/docs/japanese/concepts/lazy-listeners.md +++ /dev/null @@ -1,100 +0,0 @@ -# Lazy リスナー(FaaS - -Lazy リスナー関数は、FaaS 環境への Slack アプリのデプロイを容易にする機能です。この機能は Bolt for Python でのみ利用可能で、他の Bolt フレームワークでこの機能に対応することは予定していません。 - -通常、アクション(action)、コマンド(command)、ショートカット(shortcut)、オプション(options)、およびモーダルからのデータ送信(view_submission)をハンドルするとき、 `ack()` を呼び出し、Slack からのリクエストを 3 秒以内に確認する必要があります。`ack()` を呼び出すと Slack に HTTP ステータスが 200 OK の応答が返されます。こうすることで、アプリがリクエストの応答を処理中であることを Slack に伝えられます。通常であれば、この確認処理を処理関数の最初のステップとして行うことを推奨しています。 - -しかし、FaaS 環境や類似のランタイムで実行されるアプリでは、 **HTTP レスポンスを返したあとにスレッドやプロセスの実行を続けることができない** ため、確認の応答を送信した後で時間のかかる処理をするという通常のパターンに従うことができません。こうした環境で動作させるためには、 `process_before_response` フラグを `True` に設定します。このフラグが `True` に設定されている場合、Bolt はリスナー関数での処理が完了するまで HTTP レスポンスの送信を遅延させます。そのため 3 秒以内にリスナーのすべての処理が完了しなかった場合は Slack 上でタイムアウトのエラー表示となってしまいます。また、Events API に応答するリスナーでは明示的な `ack()` メソッドの呼び出しを必要としませんが、この設定を有効にしている場合、リスナーの処理を 3 秒以内に完了させる必要があることにも注意してください。 - -処理関数の中で時間のかかる処理を実行できるようにするために、私たちは Lazy リスナーという関数を実行する仕組みを導入しました。Lazy リスナーは、デコレーターとして動作させるのではなく、以下の 2 つのキーワード引数を受け取ります。 -* `ack: Callable`: 3 秒以内での `ack()` メソッドの呼び出しを担当します。 -* `lazy: List[Callable]` : リクエストに関する時間のかかる処理のハンドリングを担当します。Lazy 関数からは `ack()` にアクセスすることはできません。 - -```python -def respond_to_slack_within_3_seconds(body, ack): - text = body.get("text") - if text is None or len(text) == 0: - ack(f":x:Usage: /start-process (description here)") - else: - ack(f"Accepted! (task: {body['text']})") - -import time -def run_long_process(respond, body): - time.sleep(5) # 3 秒より長い時間を指定します - respond(f"Completed! (task: {body['text']})") - -app.command("/start-process")( - # この場合でも ack() は 3 秒以内に呼ばれます - ack=respond_to_slack_within_3_seconds, - # Lazy 関数がイベントの処理を担当します - lazy=[run_long_process] -) -``` - -## AWS Lambda を使用した例 - -このサンプルは、[AWS Lambda](https://aws.amazon.com/lambda/) にコードをデプロイします。[`examples` フォルダ](https://github.com/slackapi/bolt-python/tree/main/examples/aws_lambda)にはほかにもサンプルが用意されています。 - -```bash -pip install slack_bolt -# ソースコードを main.py として保存します -# config.yaml を設定してハンドラーを `handler: main.handler` で参照できるようにします - -# https://pypi.org/project/python-lambda/ -pip install python-lambda - -# config.yml を適切に設定します -# lazy リスナーの実行には lambda:InvokeFunction と lambda:GetFunction が必要です -export SLACK_SIGNING_SECRET=*** -export SLACK_BOT_TOKEN=xoxb-*** -echo 'slack_bolt' > requirements.txt -lambda deploy --config-file config.yaml --requirements requirements.txt -``` - -```python -from slack_bolt import App -from slack_bolt.adapter.aws_lambda import SlackRequestHandler - -# FaaS で実行するときは process_before_response を True にする必要があります -app = App(process_before_response=True) - -def respond_to_slack_within_3_seconds(body, ack): - text = body.get("text") - if text is None or len(text) == 0: - ack(":x: Usage: /start-process (description here)") - else: - ack(f"Accepted! (task: {body['text']})") - -import time -def run_long_process(respond, body): - time.sleep(5) # 3 秒より長い時間を指定します - respond(f"Completed! (task: {body['text']})") - -app.command("/start-process")( - ack=respond_to_slack_within_3_seconds, # `ack()` の呼び出しを担当します - lazy=[run_long_process] # `ack()` の呼び出しはできません。複数の関数を持たせることができます。 -) - -def handler(event, context): - slack_handler = SlackRequestHandler(app=app) - return slack_handler.handle(event, context) -``` - -このサンプルアプリを実行するには、以下の IAM 権限が必要になります。 - -```json -{ - "Version": "2012-10-17", - "Statement": [ - { - "Sid": "VisualEditor0", - "Effect": "Allow", - "Action": [ - "lambda:InvokeFunction", - "lambda:GetFunction" - ], - "Resource": "*" - } - ] -} -``` \ No newline at end of file diff --git a/docs/japanese/concepts/listener-middleware.md b/docs/japanese/concepts/listener-middleware.md deleted file mode 100644 index 425ae4ea7..000000000 --- a/docs/japanese/concepts/listener-middleware.md +++ /dev/null @@ -1,31 +0,0 @@ -# リスナーミドルウェア - -リスナーミドルウェアは、それを渡したリスナーでのみ実行されるミドルウェアです。リスナーには、`middleware` パラメーターを使ってミドルウェア関数をいくつでも渡すことができます。このパラメーターには、1 つまたは複数のミドルウェア関数からなるリストを指定します。 - -非常にシンプルなリスナーミドルウェアの場合であれば、`next()` メソッドを呼び出す代わりに `bool` 値(処理を継続したい場合は `True`)を返すだけで済む「リスナーマッチャー」を使うとよいでしょう。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# ボットからのメッセージをフィルタリングするリスナーミドルウェア -def no_bot_messages(message, next): - if "bot_id" not in message: - next() - -# このリスナーは人間によって送信されたメッセージのみを受け取ります -@app.event(event="message", middleware=[no_bot_messages]) -def log_message(logger, event): - logger.info(f"(MSG) User: {event['user']}\nMessage: {event['text']}") - -# リスナーマッチャー: 簡略化されたバージョンのリスナーミドルウェア -def no_bot_messages(message) -> bool: - return "bot_id" not in message - -@app.event( - event="message", - matchers=[no_bot_messages] - # or matchers=[lambda message: message.get("subtype") != "bot_message"] -) -def log_message(logger, event): - logger.info(f"(MSG) User: {event['user']}\nMessage: {event['text']}") -``` diff --git a/docs/japanese/concepts/logging.md b/docs/japanese/concepts/logging.md deleted file mode 100644 index 3afa46539..000000000 --- a/docs/japanese/concepts/logging.md +++ /dev/null @@ -1,21 +0,0 @@ -# ロギング - -デフォルトでは、アプリからのログ情報は、既定の出力先に出力されます。`logging` モジュールをインポートすれば、`basicConfig()` の `level` パラメーターでrootのログレベルを変更することができます。指定できるログレベルは、重要度の低い方から `debug`、`info`、`warning`、`error`、および `critical` です。 - -グローバルのコンテキストとは別に、指定のログレベルに応じて単一のメッセージをログ出力することもできます。Bolt では [Python 標準の logging モジュール](https://docs.python.org/3/library/logging.html)が使われているため、このモジュールが持つすべての機能を利用できます。 - -```python -import logging - -# グローバルのコンテキストの logger です -# logging をインポートする必要があります -logging.basicConfig(level=logging.DEBUG) - -@app.event("app_mention") -def handle_mention(body, say, logger): - user = body["event"]["user"] - # 単一の logger の呼び出しです - # グローバルの logger がリスナーに渡されています - logger.debug(body) - say(f"{user} mentioned your app") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/message-listening.md b/docs/japanese/concepts/message-listening.md deleted file mode 100644 index dae729b51..000000000 --- a/docs/japanese/concepts/message-listening.md +++ /dev/null @@ -1,28 +0,0 @@ -# メッセージのリスニング - -[あなたのアプリがアクセス権限を持つ](/messaging/retrieving-messages)メッセージの投稿イベントをリッスンするには `message()` メソッドを利用します。このメソッドは `type` が `message` ではないイベントを処理対象から除外します。 - -`message()` の引数には `str` 型または `re.Pattern` オブジェクトを指定できます。この条件のパターンに一致しないメッセージは除外されます。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# '👋' が含まれるすべてのメッセージに一致 -@app.message(":wave:") -def say_hello(message, say): - user = message['user'] - say(f"Hi there, <@{user}>!") -``` - -## 正規表現パターンの利用 - -文字列の代わりに `re.compile()` メソッドを使用すれば、より細やかな条件指定ができます。 - -```python -import re - -@app.message(re.compile("(hi|hello|hey)")) -def say_hello_regex(say, context): - # 正規表現のマッチ結果は context.matches に設定される - greeting = context['matches'][0] - say(f"{greeting}, how are you?") -``` \ No newline at end of file diff --git a/docs/japanese/concepts/message-sending.md b/docs/japanese/concepts/message-sending.md deleted file mode 100644 index ace67051b..000000000 --- a/docs/japanese/concepts/message-sending.md +++ /dev/null @@ -1,41 +0,0 @@ -# メッセージの送信 - -リスナー関数内では、関連づけられた会話(例:リスナー実行のトリガーとなったイベントまたはアクションの発生元の会話)がある場合はいつでも `say()` を使用できます。`say()` には文字列または JSON ペイロードを指定できます。文字列の場合、送信できるのはテキストベースの単純なメッセージです。より複雑なメッセージを送信するには JSON ペイロードを指定します。指定したメッセージのペイロードは、関連づけられた会話内のメッセージとして送信されます。 - -リスナー関数の外でメッセージを送信したい場合や、より高度な処理(特定のエラーの処理など)を実行したい場合は、[Bolt インスタンスにアタッチされたクライアント](/tools/bolt-python/concepts/web-api)の `client.chat_postMessage` を呼び出します。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# 'knock knock' が含まれるメッセージをリッスンし、イタリック体で 'Who's there?' と返信 -@app.message("knock knock") -def ask_who(message, say): - say("_Who's there?_") -``` - -## ブロックを用いたメッセージの送信 - -`say()` は、より複雑なメッセージペイロードを受け付けるので、メッセージに機能やリッチな構造を与えることが容易です。 - -リッチなメッセージレイアウトをアプリに追加する方法については、[API サイトのガイド](/messaging/#structure)を参照してください。また、[Block Kit ビルダー](https://api.slack.com/tools/block-kit-builder?template=1)の一般的なアプリフローのテンプレートも見てみてください。 - -```python -# ユーザーが 📅 のリアクションをつけたら、日付ピッカーのついた section ブロックを送信 -@app.event("reaction_added") -def show_datepicker(event, say): - reaction = event["reaction"] - if reaction == "calendar": - blocks = [{ - "type": "section", - "text": {"type": "mrkdwn", "text":"Pick a date for me to remind you"}, - "accessory": { - "type": "datepicker", - "action_id": "datepicker_remind", - "initial_date":"2020-05-04", - "placeholder": {"type": "plain_text", "text":"Select a date"} - } - }] - say( - blocks=blocks, - text="Pick a date for me to remind you" - ) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/opening-modals.md b/docs/japanese/concepts/opening-modals.md deleted file mode 100644 index 65342afb1..000000000 --- a/docs/japanese/concepts/opening-modals.md +++ /dev/null @@ -1,51 +0,0 @@ -# モーダルの開始 - -[モーダル](/surfaces/modals)は、ユーザーからのデータの入力を受け付けたり、動的な情報を表示したりするためのインターフェイスです。組み込みの APIクライアントの [`views.open`](/reference/methods/views.open/) メソッドに、有効な `trigger_id` と[ビューのペイロード](/reference/interaction-payloads/view-interactions-payload/#view_submission)を指定してモーダルを開始します。 - -ショートカットの実行、ボタンを押下、選択メニューの操作などの操作の場合、Request URL に送信されるペイロードには `trigger_id` が含まれます。 - -モーダルの生成方法についての詳細は、[API ドキュメント](/surfaces/modals#composing_views)を参照してください。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# ショートカットの呼び出しをリッスン -@app.shortcut("open_modal") -def open_modal(ack, body, client): - # コマンドのリクエストを確認 - ack() - # 組み込みのクライアントで views_open を呼び出し - client.views_open( - # 受け取りから 3 秒以内に有効な trigger_id を渡す - trigger_id=body["trigger_id"], - # ビューのペイロード - view={ - "type": "modal", - # ビューの識別子 - "callback_id": "view_1", - "title": {"type": "plain_text", "text":"My App"}, - "submit": {"type": "plain_text", "text":"Submit"}, - "blocks": [ - { - "type": "section", - "text": {"type": "mrkdwn", "text":"Welcome to a modal with _blocks_"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text":"Click me!"}, - "action_id": "button_abc" - } - }, - { - "type": "input", - "block_id": "input_c", - "label": {"type": "plain_text", "text":"What are your hopes and dreams?"}, - "element": { - "type": "plain_text_input", - "action_id": "dreamy_input", - "multiline":True - } - } - ] - } - ) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/select-menu-options.md b/docs/japanese/concepts/select-menu-options.md deleted file mode 100644 index 4f3a5f357..000000000 --- a/docs/japanese/concepts/select-menu-options.md +++ /dev/null @@ -1,32 +0,0 @@ -# オプションのリスニングと応答 - -`options()` メソッドは、Slack からのオプション(セレクトメニュー内の動的な選択肢)をリクエストするペイロードをリッスンします。 [`action()` と同様に](/tools/bolt-python/concepts/actions)、文字列型の `action_id` または制約付きオブジェクトが必要です。 - -外部データソースを使って選択メニューをロードするためには、末部に `/slack/events` が付加された URL を Options Load URL として予め設定しておく必要があります。 - -`external_select` メニューでは `action_id` を指定することをおすすめしています。ただし、ダイアログを利用している場合、ダイアログが Block Kit に対応していないため、`callback_id` をフィルタリングするための制約オブジェクトを使用する必要があります。 - -オプションのリクエストに応答するときは、有効なオプションを含む `options` または `option_groups` のリストとともに `ack()` を呼び出す必要があります。API サイトにある[外部データを使用する選択メニューに応答するサンプル例](/reference/block-kit/block-elements/multi-select-menu-element#external_multi_select)と、[ダイアログでの応答例](/legacy/legacy-dialogs/#dynamic_select_elements_external)を参考にしてください。 - -さらに、ユーザーが入力したキーワードに基づいたオプションを返すようフィルタリングロジックを適用することもできます。 これは `payload` という引数の ` value` の値に基づいて、それぞれのパターンで異なるオプションの一覧を返すように実装することができます。 Bolt for Python のすべてのリスナーやミドルウェアでは、[多くの有用な引数](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)にアクセスすることができますので、チェックしてみてください。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# 外部データを使用する選択メニューオプションに応答するサンプル例 -@app.options("external_action") -def show_options(ack, payload): - options = [ - { - "text": {"type": "plain_text", "text": "Option 1"}, - "value": "1-1", - }, - { - "text": {"type": "plain_text", "text": "Option 2"}, - "value": "1-2", - }, - ] - keyword = payload.get("value") - if keyword is not None and len(keyword) > 0: - options = [o for o in options if keyword in o["text"]["text"]] - ack(options=options) -``` diff --git a/docs/japanese/concepts/shortcuts.md b/docs/japanese/concepts/shortcuts.md deleted file mode 100644 index 39fb10ba8..000000000 --- a/docs/japanese/concepts/shortcuts.md +++ /dev/null @@ -1,90 +0,0 @@ -# ショートカットのリスニングと応答 - -`shortcut()` メソッドは、[グローバルショートカット](/interactivity/implementing-shortcuts#global)と[メッセージショートカット](/interactivity/implementing-shortcuts#messages)の 2 つをサポートしています。 - -ショートカットは、いつでも呼び出せるアプリのエントリーポイントを提供するものです。グローバルショートカットは Slack のテキスト入力エリアや検索ウィンドウからアクセスできます。メッセージショートカットはメッセージのコンテキストメニューからアクセスできます。アプリは、ショートカットリクエストをリッスンするために `shortcut()` メソッドを使用します。このメソッドには `str` 型または `re.Pattern` 型の `callback_id` パラメーターを指定します。 - -ショートカットリクエストがアプリによって確認されたことを Slack に伝えるため、`ack()` を呼び出す必要があります。 - -ショートカットのペイロードには `trigger_id` が含まれます。アプリはこれを使って、ユーザーにやろうとしていることを確認するための[モーダルを開く](/tools/bolt-python/concepts/opening-modals)ことができます。 - -アプリの設定でショートカットを登録する際は、他の URL と同じように、リクエスト URL の末尾に `/slack/events` をつけます。 - -⚠️ グローバルショートカットのペイロードにはチャンネル ID が **含まれません**。アプリでチャンネル ID を取得する必要がある場合は、モーダル内に [`conversations_select`](/reference/block-kit/block-elements/multi-select-menu-element#conversation_multi_select) エレメントを配置します。メッセージショートカットにはチャンネル ID が含まれます。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -# 'open_modal' という callback_id のショートカットをリッスン -@app.shortcut("open_modal") -def open_modal(ack, shortcut, client): - # ショートカットのリクエストを確認 - ack() - # 組み込みのクライアントを使って views_open メソッドを呼び出す - client.views_open( - trigger_id=shortcut["trigger_id"], - # モーダルで表示するシンプルなビューのペイロード - view={ - "type": "modal", - "title": {"type": "plain_text", "text":"My App"}, - "close": {"type": "plain_text", "text":"Close"}, - "blocks": [ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text":"About the simplest modal you could conceive of :smile:\n\nMaybe or ." - } - }, - { - "type": "context", - "elements": [ - { - "type": "mrkdwn", - "text":"Psssst this modal was designed using " - } - ] - } - ] - } - ) -``` - -## 制約付きオブジェクトを使用したショートカットのリスニング - -制約付きオブジェクトを使って `callback_id` や `type` によるリッスンできます。オブジェクト内の制約は `str` 型または `re.Pattern` オブジェクトを使用できます。 - -```python -# このリスナーが呼び出されるのは、callback_id が 'open_modal' と一致し -# かつ type が 'message_action' と一致するときのみ -@app.shortcut({"callback_id": "open_modal", "type": "message_action"}) -def open_modal(ack, shortcut, client): - # ショートカットのリクエストを確認 - ack() - # 組み込みのクライアントを使って views_open メソッドを呼び出す - client.views_open( - trigger_id=shortcut["trigger_id"], - view={ - "type": "modal", - "title": {"type": "plain_text", "text":"My App"}, - "close": {"type": "plain_text", "text":"Close"}, - "blocks": [ - { - "type": "section", - "text": { - "type": "mrkdwn", - "text":"About the simplest modal you could conceive of :smile:\n\nMaybe or ." - } - }, - { - "type": "context", - "elements": [ - { - "type": "mrkdwn", - "text":"Psssst this modal was designed using " - } - ] - } - ] - } - ) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/socket-mode.md b/docs/japanese/concepts/socket-mode.md deleted file mode 100644 index 92922d2de..000000000 --- a/docs/japanese/concepts/socket-mode.md +++ /dev/null @@ -1,57 +0,0 @@ -# ソケットモードの利用 - -[ソケットモード](/apis/events-api/using-socket-mode)は、アプリに WebSocket での接続と、そのコネクション経由でのデータ受信を可能とします。Bolt for Python は、バージョン 1.2.0 からこれに対応しています。 - -ソケットモードでは、Slack からのペイロード送信を受け付けるエンドポイントをホストする HTTP サーバーを起動する代わりに WebSocket で Slack に接続し、そのコネクション経由でデータを受信します。ソケットモードを使う前に、アプリの管理画面でソケットモードの機能が有効になっていることを確認しておいてください。 - -ソケットモードを使用するには、環境変数に `SLACK_APP_TOKEN` を追加します。アプリのトークン(App-Level Token)は、アプリの設定の「**Basic Information**」セクションで確認できます。 - -[組み込みのソケットモードアダプター](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter/socket_mode/builtin)を使用するのがおすすめですが、サードパーティ製ライブラリを使ったアダプターの実装もいくつか存在しています。利用可能なアダプターの一覧です。 - -|内部的に利用する PyPI プロジェクト名|Bolt アダプター| -|-|-| -|[slack_sdk](https://pypi.org/project/slack-sdk/)|[slack_bolt.adapter.socket_mode](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter/socket_mode/builtin)| -|[websocket_client](https://pypi.org/project/websocket_client/)|[slack_bolt.adapter.socket_mode.websocket_client](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter/socket_mode/websocket_client)| -|[aiohttp](https://pypi.org/project/aiohttp/) (asyncio-based)|[slack_bolt.adapter.socket_mode.aiohttp](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter/socket_mode/aiohttp)| -|[websockets](https://pypi.org/project/websockets/) (asyncio-based)|[slack_bolt.adapter.socket_mode.websockets](https://github.com/slackapi/bolt-python/tree/main/slack_bolt/adapter/socket_mode/websockets)| - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# 事前に Slack アプリをインストールし 'xoxb-' で始まるトークンを入手 -app = App(token=os.environ["SLACK_BOT_TOKEN"]) - -# ここでミドルウェアとリスナーの追加を行います - -if __name__ == "__main__": - # export SLACK_APP_TOKEN=xapp-*** - # export SLACK_BOT_TOKEN=xoxb-*** - handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]) - handler.start() -``` - -## Async (asyncio) の利用 - -aiohttp のような asyncio をベースとしたアダプターを使う場合、アプリケーション全体が asyncio の async/await プログラミングモデルで実装されている必要があります。`AsyncApp` を動作させるためには `AsyncSocketModeHandler` とその async なミドルウェアやリスナーを利用します。 - -`AsyncApp` の使い方についての詳細は、[Async (asyncio) の利用](/tools/bolt-python/concepts/async)や、関連する[サンプルコード例](https://github.com/slackapi/bolt-python/tree/main/examples)を参考にしてください。 - -```python -from slack_bolt.app.async_app import AsyncApp -# デフォルトは aiohttp を使った実装 -from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler - -app = AsyncApp(token=os.environ["SLACK_BOT_TOKEN"]) - -# ここでミドルウェアとリスナーの追加を行います - -async def main(): - handler = AsyncSocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]) - await handler.start_async() - -if __name__ == "__main__": - import asyncio - asyncio.run(main()) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/token-rotation.md b/docs/japanese/concepts/token-rotation.md deleted file mode 100644 index 25a0c735b..000000000 --- a/docs/japanese/concepts/token-rotation.md +++ /dev/null @@ -1,9 +0,0 @@ -# トークンのローテーション - -Bolt for Python [v1.7.0](https://github.com/slackapi/bolt-python/releases/tag/v1.7.0) から、アクセストークンのさらなるセキュリティ強化のレイヤーであるトークンローテーションの機能に対応しています。トークンローテーションは [OAuth V2 の RFC](https://datatracker.ietf.org/doc/html/rfc6749#section-10.4) で規定されているものです。 - -既存の Slack アプリではアクセストークンが無期限に存在し続けるのに対して、トークンローテーションを有効にしたアプリではアクセストークンが失効するようになります。リフレッシュトークンを利用して、アクセストークンを長期間にわたって更新し続けることができます。 - -[Bolt for Python の組み込みの OAuth 機能](/tools/bolt-python/concepts/authenticating-oauth) を使用していれば、Bolt for Python が自動的にトークンローテーションの処理をハンドリングします。 - -トークンローテーションに関する詳細は [API ドキュメント](/authentication/using-token-rotation)を参照してください。 \ No newline at end of file diff --git a/docs/japanese/concepts/updating-pushing-views.md b/docs/japanese/concepts/updating-pushing-views.md deleted file mode 100644 index 2bbaf5ae5..000000000 --- a/docs/japanese/concepts/updating-pushing-views.md +++ /dev/null @@ -1,48 +0,0 @@ -# モーダルの更新と多重表示 - -モーダル内では、複数のモーダルをスタックのように重ねることができます。[`views_open`](/reference/methods/views.open/) という APIを呼び出すと、親となるとなるモーダルビューが追加されます。この最初の呼び出しの後、[`views_update`](/reference/methods/views.update/) を呼び出すことでそのビューを更新することができます。また、[`views_push`](/reference/methods/views.push) を呼び出すと、親のモーダルの上にさらに新しいモーダルビューを重ねることもできます。 - -**`views_update`** - -モーダルの更新は、組み込みのクライアントで `views_update` API を呼び出します。この API呼び出しでは、ビューを開いた時に生成された `view_id` と、更新後の `blocks` のリストを含む新しい `view` を指定します。既存のモーダルに含まれるエレメントをユーザーが操作した時にビューを更新する場合は、リクエストの `body` に含まれる `view_id` が利用できます。 - -**`views_push`** - -既存のモーダルの上に新しいモーダルをスタックのように追加する場合は、組み込みのクライアントで `views_push` API を呼び出します。この API 呼び出しでは、有効な `trigger_id` と新しい[ビューのペイロード](/reference/interaction-payloads/view-interactions-payload/#view_submission)を指定します。`views_push` の引数は [モーダルの開始](#creating-modals) と同じです。モーダルを開いた後、このモーダルのスタックに追加できるモーダルビューは 2 つまでです。 - -モーダルの更新と多重表示に関する詳細は、[API ドキュメント](/surfaces/modals)を参照してください。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# モーダルに含まれる、`button_abc` という action_id のボタンの呼び出しをリッスン -@app.action("button_abc") -def update_modal(ack, body, client): - # ボタンのリクエストを確認 - ack() - # 組み込みのクライアントで views_update を呼び出し - client.views_update( - # view_id を渡すこと - view_id=body["view"]["id"], - # 競合状態を防ぐためのビューの状態を示す文字列 - hash=body["view"]["hash"], - # 更新後の blocks を含むビューのペイロード - view={ - "type": "modal", - # ビューの識別子 - "callback_id": "view_1", - "title": {"type": "plain_text", "text":"Updated modal"}, - "blocks": [ - { - "type": "section", - "text": {"type": "plain_text", "text":"You updated the modal!"} - }, - { - "type": "image", - "image_url": "https://media.giphy.com/media/SVZGEcYt7brkFUyU90/giphy.gif", - "alt_text":"Yay!The modal was updated" - } - ] - } - ) -``` \ No newline at end of file diff --git a/docs/japanese/concepts/view-submissions.md b/docs/japanese/concepts/view-submissions.md deleted file mode 100644 index f82922004..000000000 --- a/docs/japanese/concepts/view-submissions.md +++ /dev/null @@ -1,95 +0,0 @@ -# モーダルの送信のリスニング - -[モーダルのペイロード](/reference/interaction-payloads/view-interactions-payload/#view_submission)に `input` ブロックを含める場合、その入力値を受け取るために`view_submission` リクエストをリッスンする必要があります。`view_submission` リクエストのリッスンには、組み込みの`view()` メソッドを利用することができます。`view()` の引数には、`str` 型または `re.Pattern` 型の `callback_id` を指定します。 - -`input` ブロックの値にアクセスするには `state` オブジェクトを参照します。`state` 内には `values` というオブジェクトがあり、`block_id` と一意の `action_id` に紐づける形で入力値を保持しています。 - ---- - -##### モーダル送信でのビューの更新 - -`view_submission` リクエストに対してモーダルを更新するには、リクエストの確認の中で `update` という `response_action` と新しく作成した `view` を指定します。 - -```python -# モーダル送信でのビューの更新 -@app.view("view_1") -def handle_submission(ack, body): - # build_new_view() method はモーダルビューを返します - # モーダルの構築には Block Kit Builder を試してみてください: - # https://app.slack.com/block-kit-builder/#%7B%22type%22:%22modal%22,%22callback_id%22:%22view_1%22,%22title%22:%7B%22type%22:%22plain_text%22,%22text%22:%22My%20App%22,%22emoji%22:true%7D,%22blocks%22:%5B%5D%7D - ack(response_action="update", view=build_new_view(body)) -``` -この例と同様に、モーダルでの送信リクエストに対して、[エラーを表示する](/surfaces/modals#displaying_errors)ためのオプションもあります。 - -モーダルの送信について詳しくは、[API ドキュメント](/surfaces/modals#interactions)を参照してください。 - ---- - -##### モーダルが閉じられたときの対応 - -`view_closed` リクエストをリッスンするためには `callback_id` を指定して、かつ `notify_on_close` 属性をモーダルのビューに設定する必要があります。以下のコード例をご覧ください。 - -よく詳しい情報は、[API ドキュメント](/surfaces/modals#interactions)を参照してください。 - -```python -client.views_open( - trigger_id=body.get("trigger_id"), - view={ - "type": "modal", - "callback_id": "modal-id", # view_closed の処理時に必要 - "title": { - "type": "plain_text", - "text": "Modal title" - }, - "blocks": [], - "close": { - "type": "plain_text", - "text": "Cancel" - }, - "notify_on_close": True, # この属性は必須 - } -) -# view_closed リクエストを処理する -@app.view_closed("modal-id") -def handle_view_closed(ack, body, logger): - ack() - logger.info(body) -``` - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -```python -# view_submission リクエストを処理 -@app.view("view_1") -def handle_submission(ack, body, client, view, logger): - # `input_c`という block_id に `dreamy_input` を持つ input ブロックがある場合 - hopes_and_dreams = view["state"]["values"]["input_c"]["dreamy_input"] - user = body["user"]["id"] - # 入力値を検証 - errors = {} - if hopes_and_dreams is not None and len(hopes_and_dreams) <= 5: - errors["input_c"] = "The value must be longer than 5 characters" - if len(errors) > 0: - ack(response_action="errors", errors=errors) - return - # view_submission リクエストの確認を行い、モーダルを閉じる - ack() - # 入力されたデータを使った処理を実行。このサンプルでは DB に保存する処理を行う - # そして入力値の検証結果をユーザーに送信 - - # ユーザーに送信するメッセージ - msg = "" - try: - # DB に保存 - msg = f"Your submission of {hopes_and_dreams} was successful" - except Exception as e: - # エラーをハンドリング - msg = "There was an error with your submission" - - # ユーザーにメッセージを送信 - try: - client.chat_postMessage(channel=user, text=msg) - except e: - logger.exception(f"Failed to post a message {e}") - -``` \ No newline at end of file diff --git a/docs/japanese/concepts/web-api.md b/docs/japanese/concepts/web-api.md deleted file mode 100644 index abb8e4121..000000000 --- a/docs/japanese/concepts/web-api.md +++ /dev/null @@ -1,19 +0,0 @@ -# Web API の使い方 - -`app.client`、またはミドルウェア・リスナーの引数 `client` として Bolt アプリに提供されている `WebClient` は必要な権限を付与されており、これを利用することで[あらゆる Web API メソッド](/reference/methods)を呼び出すことができます。このクライアントのメソッドを呼び出すと `SlackResponse` という Slack からの応答情報を含むオブジェクトが返されます。 - -Bolt の初期化に使用するトークンは `context` オブジェクトに設定されます。このトークンは、多くの Web API メソッドを呼び出す際に必要となります。 - -指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 -```python -@app.message("wake me up") -def say_hello(client, message): - # 2020 年 9 月 30 日午後 11:59:59 を示す Unix エポック秒 - when_september_ends = 1601510399 - channel_id = message["channel"] - client.chat_scheduleMessage( - channel=channel_id, - post_at=when_september_ends, - text="Summer has come and passed" - ) -``` \ No newline at end of file diff --git a/docs/japanese/getting-started.md b/docs/japanese/getting-started.md deleted file mode 100644 index 41e6ae5cd..000000000 --- a/docs/japanese/getting-started.md +++ /dev/null @@ -1,463 +0,0 @@ -# Bolt 入門ガイド - -このガイドでは、Bolt for Python を使った Slack アプリの設定と起動の方法について説明します。ここで説明する手順では、まず新しい Slack アプリを作成し、ローカルの開発環境をセットアップし、Slack ワークスペースからのメッセージをリッスンして応答するアプリを開発するという流れになります。 - - -この手順を全て終わらせたら、あなたはきっと ⚡️[Slack アプリのはじめ方](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)のサンプルアプリを動作させたり、それに変更を加えたり、自分のアプリを作ったりすることができるようになるでしょう。 - ---- - -### アプリを作成する {#create-an-app} -最初にやるべきこと : Bolt での開発を始める前に、[Slack アプリを作成](https://api.slack.com/apps/new)します。 - -:::tip[通常の業務の妨げにならないよう、別の開発用のワークスペースを使用することをおすすめします。[新しいワークスペースは無料で作成できます](https://slack.com/get-started#create)] - -::: - -アプリ名を入力し(_後で変更可能_)、インストール先のワークスペースを選択して「`Create App`」ボタンをクリックすると、アプリの **Basic Information** ページが表示されます。 - -このページでは、アプリの概要や重要な認証情報を確認できます。これらの情報は後ほど参照します。 - -![Basic Information ページ](/img/bolt-python/basic-information-page.png "Basic Information ページ") - -ひと通り確認して、アプリのアイコンと説明を追加したら、アプリのプロジェクトの構成 🔩 を始めましょう。 - ---- - -### トークンとアプリのインストール {#tokens-and-installing-apps} -Slack アプリでは、[Slack API へのアクセスの管理に OAuth を使用します](/authentication/installing-with-oauth)。アプリがインストールされると、トークンが発行されます。アプリはそのトークンを使って API メソッドを呼び出すことができます。 - -Slack アプリで使用できるトークンには、ユーザートークン(`xoxp`)とボットトークン(`xoxb`)、アプリレベルトークン(`xapp`)の 3 種類があります。 -- [ユーザートークン](/authentication/tokens#user) を使用すると、アプリをインストールまたは認証したユーザーに成り代わって API メソッドを呼び出すことができます。1 つのワークスペースに複数のユーザートークンが存在する可能性があります。 -- [ボットトークン](/authentication/tokens#bot) はボットユーザーに関連づけられ、1 つのワークスペースでは最初に誰かがそのアプリをインストールした際に一度だけ発行されます。どのユーザーがインストールを実行しても、アプリが使用するボットトークンは同じになります。_ほとんど_のアプリで使用されるのは、ボットトークンです。 -- [アプリレベルトークン](/authentication/tokens#app-level) は、全ての組織(とその配下のワークスペースでの個々のユーザーによるインストール)を横断して、あなたのアプリを代理するものです。アプリレベルトークンは、アプリの WebSocket コネクションを確立するためによく使われます。 - -このガイドではボットトークンとアプリレベルトークンを使用します。 - -1. 左サイドバーの「**OAuth & Permissions**」をクリックし、「**Bot Token Scopes**」セクションまで下にスクロールします。「**Add an OAuth Scope**」をクリックします。 - -2. ここでは [`chat:write`](/reference/scopes/chat.write) というスコープのみを追加します。このスコープはアプリが参加しているチャンネルにメッセージを投稿することを許可します。 - -3. OAuth & Permissions ページの一番上までスクロールし、「**Install App to Workspace**」をクリックします。Slack の OAuth 確認画面 が表示されます。この画面で開発用ワークスペースへのアプリのインストールを承認します。 - -4. インストールを承認すると **OAuth & Permissions** ページが表示され、**Bot User OAuth Access Token** を確認できるでしょう。 - -![OAuth トークン](/img/bolt-python/bot-token.png "ボット用 OAuth トークン") - -5. 次に「**Basic Informationのページ**」まで戻り、アプリレベルトークンのセクションまで下にスクロールし「**Generate Token and Scopes**」をクリックしてアプリレベルトークンを作成します。このトークンに `connections:write` のスコープを付与し、作成された `xapp` トークンを保存します。これらのトークンは後ほど利用します。 - -6. 左サイドメニューの「**Socket Mode**」を有効にします。 - -:::tip[トークンはパスワードと同様に取り扱い、[安全な方法で保管してください](/security)。アプリはこのトークンを使って Slack ワークスペースで投稿をしたり、情報の取得をしたりします。] - -::: - ---- - -### プロジェクトをセットアップする {#setting-up-your-project} -初期設定が終わったら、新しい Bolt プロジェクトのセットアップを行いましょう。このプロジェクトが、あなたのアプリのロジックを処理するコードを配置する場所となります。 - -プロジェクトをまだ作成していない場合は、新しく作成しましょう。空のディレクトリを作成します。 - -```shell -mkdir first-bolt-app -cd first-bolt-app -``` - -次に、プロジェクトの依存ライブラリを管理する方法として、[Python 仮想環境](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment)を使ったおすすめの方法を紹介します。これはシステム Python に存在するパッケージとのコンフリクトを防ぐために推奨されている優れた方法です。[Python 3.7 以降](https://www.python.org/downloads/)の仮想環境を作成し、アクティブにしてみましょう。 - -```shell -python3 -m venv .venv -source .venv/bin/activate -``` - -`python3` へのパスがプロジェクトの中を指していることを確かめることで、仮想環境がアクティブになっていることを確認できます([Windows でもこれに似たコマンドが利用できます](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment))。 - -```shell -which python3 -# 出力結果: /path/to/first-bolt-app/.venv/bin/python3 -``` - -Bolt for Python のパッケージを新しいプロジェクトにインストールする前に、アプリの設定時に作成された **ボットトークン** と **アプリレベルトークン** を保存しましょう。 - -1. **OAuth & Permissions ページのボットトークン (xoxb) をコピー**して、新しい環境変数に保存します。以下のコマンド例は Linux と macOS で利用できます。[Windows でもこれに似たコマンドが利用できます](https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line/212153#212153)。 -```shell -export SLACK_BOT_TOKEN=xoxb-<ボットトークン> -``` - -2. **Basic Information ページのアプリレベルトークン(xapp)をコピー**して、別の環境変数に保存します。 -```shell -export SLACK_APP_TOKEN=<アプリレベルトークン> -``` -:::warning[🔒 全てのトークンは安全に保管してください。] - -少なくともパブリックなバージョン管理にチェックインするようなことは避けるべきでしょう。また、上にあった例のように環境変数を介してアクセスするようにしてください。詳細な情報は [アプリのセキュリティのベストプラクティス](/security)のドキュメントを参照してください。 - -::: - -完了したら、いよいよアプリを作っていきましょう。以下のコマンドを使って、仮想環境に Python の `slack_bolt` パッケージをインストールします。 - -```shell -pip install slack_bolt -``` - -このディレクトリに「`app.py`」という名前の新しいファイルを作成し、以下のコードを追加します。 - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# ボットトークンとソケットモードハンドラーを使ってアプリを初期化します -app = App(token=os.environ.get("SLACK_BOT_TOKEN")) - -# アプリを起動します -if __name__ == "__main__": - SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() -``` - -このようにトークンさえあれば、最初の Bolt アプリを作成することができます。「`app.py`」という名前でファイルを保存して、コマンドラインで以下を実行します。 - -```script -python3 app.py -``` - -アプリが起動し、実行中であることが表示されるはずです 🎉 - ---- - -### イベントを設定する {#setting-up-events} -アプリはワークスペース内の他のメンバーと同じように振る舞い、メッセージを投稿したり、絵文字リアクションを追加したり、イベントをリッスンして返答したりできます。 - -Slack ワークスペースで発生するイベント(メッセージが投稿されたときや、メッセージに対するリアクションがつけられたときなど)をリッスンするには、[Events API を使って特定の種類のイベントをサブスクライブします](/apis/events-api/)。 - -このチュートリアルの序盤でソケットモードを有効にしました。ソケットモードを使うことで、アプリが公開された HTTP エンドポイントを公開せずに Events API やインタラクティブコンポーネントを利用できるようになります。このことは、開発時やファイヤーウォールの裏からのリクエストを受ける際に便利です。HTTP での方式は、ホスティング環境にデプロイするアプリや Slack App Directory で配布されるアプリの開発・運用に適しています。 - -それでは、このアプリがどのイベントをリッスンしたいかを Slack に伝えましょう。 - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - - - - -1. アプリの構成ページに移動します ([アプリ設定ページから](https://api.slack.com/apps) アプリをクリックします)。左側のメニューで **ソケット モード** に移動し、有効に切り替えます。 - -2. [**基本情報**] に移動し、[アプリレベル トークン] セクションの下にスクロールして、[**トークンとスコープの生成**] をクリックしてアプリ トークンを生成します。このトークンに `connections:write` スコープを追加し、生成された `xapp` トークンを保存します。これはすぐに使用します。 - -3. 最後に、聞きたいイベントを Slack に伝えます。 **イベント サブスクリプション** で、**イベントを有効にする** というラベルのスイッチを切り替えます。 - -イベントが発生すると、そのイベントをトリガーしたユーザーやイベントが発生したチャンネルなど、イベントに関する情報が Slack からアプリに送信されます。アプリではこれらの情報を処理して、適切な応答を返します。 - - - - -1. アプリ構成ページに戻ります ([アプリ管理ページから](https://api.slack.com/apps) アプリをクリックします)。左側のサイドバーで [**イベント サブスクリプション**] をクリックします。 **イベントを有効にする**というラベルの付いたスイッチを切り替えます。 - -2. リクエスト URL を追加します。 Slack は、イベントに対応する HTTP POST リクエストをこの [リクエスト URL](/apis/events-api/#subscribing) に送信します。 Bolt は、`/slack/events` パスを使用して、すべての受信リクエスト (ショートカット、イベント、対話性ペイロードなど) をリッスンします。アプリ構成内でリクエスト URL を構成する場合は、`/slack/events` を追加します。 「https://あなたのドメイン/slack/events」。 💡 Bolt アプリが実行されている限り、URL は検証されるはずです。 - -:::tip - -ローカル開発の場合、ngrok などのプロキシ サービスを使用してパブリック URL を作成し、リクエストを開発環境にトンネリングできます。このトンネルの作成方法については、[ngrok のスタート ガイド](https://ngrok.com/docs#getting-started-expose) を参照してください。アプリをホスティングする際には、Slack 開発者がアプリをホストするために使用する最も一般的なホスティング プロバイダーを [API サイト](/app-management/hosting-slack-apps) に集めました。 - -::: - - - - -左側のサイドバーから **Event Subscriptions** にアクセスして、機能を有効にしてください。 **Subscribe to Bot Events** 配下で、ボットが受け取れるイベントを追加することができます。4つのメッセージに関するイベントがあります。 -- [`message.channels`](/reference/events/message.channels) アプリが参加しているパブリックチャンネルのメッセージをリッスン -- [`message.groups`](/reference/events/message.groups) アプリが参加しているプライベートチャンネルのメッセージをリッスン -- [`message.im`](/reference/events/message.im) あなたのアプリとユーザーのダイレクトメッセージをリッスン -- [`message.mpim`](/reference/events/message.mpim) あなたのアプリが追加されているグループ DM をリッスン - -ボットが参加するすべての場所のメッセージをリッスンさせるには、これら 4 つのメッセージイベントをすべて選択します。ボットにリッスンさせるメッセージイベントの種類を選択したら、「**Save Changes**」ボタンをクリックします。 - ---- - -### メッセージをリッスンして応答する {#listening-and-responding-to-a-message} -アプリにロジックを組み込む準備が整いました。まずは `message()` メソッドを使用して、メッセージのリスナーをアタッチしましょう。 - -次の例では、アプリが参加するチャンネルとダイレクトメッセージに投稿されるすべてのメッセージをリッスンし、「こんにちは」というメッセージに応答を返します。 - - - - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# ボットトークンを渡してアプリを初期化します -app = App(token=os.environ.get("SLACK_BOT_TOKEN")) - -# 'こんにちは' を含むメッセージをリッスンします -# 指定可能なリスナーのメソッド引数の一覧は以下のモジュールドキュメントを参考にしてください: -# https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html -@app.message("こんにちは") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say(f"こんにちは、<@{message['user']}> さん!") - -if __name__ == "__main__": - # アプリを起動して、ソケットモードで Slack に接続します - SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() -``` - - - - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -# 指定可能なリスナーのメソッド引数の一覧は以下のモジュールドキュメントを参考にしてください: -# https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say(f"Hey there <@{message['user']}>!") - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - - - - -アプリを再起動して、ボットユーザーが参加しているチャンネル・ダイレクトメッセージに「こんにちは」というメッセージを投稿すると、アプリが返答を返すでしょう。 - -これはごく基本的なコード例ですが、最終的にやりたいことを実現するためにアプリをカスタマイズしていく土台として利用できます。次は、シンプルなテキストの返答を送信する代わりにメッセージ内にボタンを表示するという、もう少しインタラクティブな動作を試してみましょう。 - ---- - -### アクションを送信して応答する {#sending-and-responding-to-actions} - -インタラクティブ機能を有効にすると、ボタン、選択メニュー、日付ピッカー、モーダル、ショートカットなどの機能が利用できるようになります。アプリ設定ページの「**Interactivity & Shortcuts**」にアクセスしてください。 - - - - -ソケット モードをオンにすると、基本的な対話機能がデフォルトで有効になるため、それ以上の操作は必要ありません。 - - - - -イベントと同様に、Slack がアクション (*ユーザーがボタンをクリックした* など) を送信するには、URL を指定する必要があります。アプリ構成ページに戻り、左側にある **対話性とショートカット** をクリックします。別の **リクエスト URL** ボックスがあることがわかります。 - -:::tip - -ソケットモードを有効にしているとき、デフォルトで基本的なインタラクティブ機能が有効になっていることに気づくでしょう。追加のアクションは不要です。もし HTTP を使っている場合、Slack からのイベント送信先である Request URL を設定する必要があります。 - -::: - - - - -インタラクティビティが有効化されていれば、ショートカット、モーダル、インタラクティブコンポーネント (例:ボタン、選択メニュー、日付ピッカー) とのインタラクションはイベントとしてあなたのアプリに送信されます。 - -それでは、アプリのコードに戻り、これらのイベントを処理する為のロジックを追加しましょう。 -- まず、インタラクティブコンポーネント(ここではボタン)を含んだメッセージをアプリから送信します。 -- 次に、ユーザーから返されるボタンクリックのアクションをリッスンし、それに応答します。 - -以下のコードの後の部分を編集し、文字列だけのメッセージの代わりに、ボタンを含んだメッセージを送信するようにしてみます。 - - - - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# ボットトークンを渡してアプリを初期化します -app = App(token=os.environ.get("SLACK_BOT_TOKEN")) - -# 'こんにちは' を含むメッセージをリッスンします -@app.message("こんにちは") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"こんにちは、<@{message['user']}> さん!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text": "クリックしてください"}, - "action_id": "button_click" - } - } - ], - text=f"こんにちは、<@{message['user']}> さん!", - ) - -if __name__ == "__main__": - # アプリを起動して、ソケットモードで Slack に接続します - SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() -``` - - - - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text":"Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - - - - -`say()` の中の値を `blocks` という配列のオブジェクトに変えました。ブロックは Slack メッセージを構成するコンポーネントであり、テキストや画像、日付ピッカーなど、さまざまなタイプのブロックがあります。この例では `accessory` に `button` を持たせた「section」のブロックを、アプリからの応答に含めています。`blocks` を使用する場合、`text` は通知やアクセシビリティのためのフォールバックとなります。 - -ボタンを含む `accessory` オブジェクトでは、`action_id` を指定していることがわかります。これは、ボタンを一意に示す識別子として機能します。これを使って、アプリをどのアクションに応答させるかを指定できます。 - -:::tip[[Block Kit Builder](https://app.slack.com/block-kit-builder) を使用すると、インタラクティブなメッセージのプロトタイプを簡単に作成できます。] - -自分自身やチームメンバーがメッセージのモックアップを作成し、生成される JSON をアプリに直接貼りつけることができます。 - -::: - -アプリを再起動し、アプリが参加しているチャンネルで「こんにちは」と入力すると、ボタン付きのメッセージが表示されるようになりました。ただし、ボタンをクリックしても、*まだ* 何も起こりません。 - -ハンドラーを追加して、ボタンがクリックされたときにフォローアップメッセージを送信するようにしてみましょう。 - - - - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# ボットトークンを渡してアプリを初期化します -app = App(token=os.environ.get("SLACK_BOT_TOKEN")) - -# 'こんにちは' を含むメッセージをリッスンします -@app.message("こんにちは") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"こんにちは、<@{message['user']}> さん!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text": "クリックしてください"}, - "action_id": "button_click" - } - } - ], - text=f"こんにちは、<@{message['user']}> さん!", - ) - -@app.action("button_click") -def action_button_click(body, ack, say): - # アクションを確認したことを即時で応答します - ack() - # チャンネルにメッセージを投稿します - say(f"<@{body['user']['id']}> さんがボタンをクリックしました!") - -if __name__ == "__main__": - # アプリを起動して、ソケットモードで Slack に接続します - SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() -``` - - - - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text":"Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -@app.action("button_click") -def action_button_click(body, ack, say): - # アクションを確認したことを即時で応答します - ack() - # チャンネルにメッセージを投稿します - say(f"<@{body['user']['id']}> clicked the button") - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - - - - -`app.action()` を使って、先ほど命名した `button_click` という `action_id` をリッスンしています。アプリを再起動し、ボタンをクリックすると、アプリからの「クリックしました!」というメッセージが新たに表示されるでしょう。 - ---- - -### 次のステップ {#next-steps} -はじめての [Bolt for Python アプリ](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)を構築することができました。🎉 - -ここまでで基本的なアプリをセットアップして実行することはできたので、次は自分だけの Bolt アプリを作る方法について調べてみてください。参考になりそうなリソースをいくつかご紹介します。 - -* 基本的な概念について読んでみてください。Bolt アプリがアクセスできるさまざまメソッドや機能について知ることができます。 -* [`app.event()` メソッド](/tools/bolt-python/concepts/event-listening)でボットがリッスンできるイベントをほかにも試してみましょう。すべてのイベントの一覧は [API サイト](/reference/events)で確認できます。 -* Bolt では、アプリにアタッチされたクライアントから [Web API メソッドを呼び出す](/tools/bolt-python/concepts/web-api)ことができます。API サイトに [220 以上のメソッド](/reference/methods)を一覧しています。 -* [API サイト](/authentication/tokens)でほかのタイプのトークンを確認してみてください。アプリで実行したいアクションによって、異なるトークンが必要になる場合があります。 diff --git a/docs/japanese/legacy/steps-from-apps.md b/docs/japanese/legacy/steps-from-apps.md deleted file mode 100644 index 802802ab3..000000000 --- a/docs/japanese/legacy/steps-from-apps.md +++ /dev/null @@ -1,184 +0,0 @@ -# ワークフローステップの概要 - -(アプリによる)ワークフローステップでは、処理をアプリ側で行うカスタムのワークフローステップを提供することができます。ユーザーは[ワークフロービルダー](/workflows/workflow-builder)を使ってこれらのステップをワークフローに追加できます。 - -ワークフローステップは、次の 3 つのユーザーイベントで構成されます。 - -- ワークフローステップをワークフローに追加・変更する -- ワークフロー内のステップの設定内容を更新する -- エンドユーザーがそのステップを実行する - -ワークフローステップを機能させるためには、これら 3 つのイベントすべてに対応する必要があります。 - -## ステップの定義 - -ワークフローステップの作成には、Bolt が提供する `WorkflowStep` クラスを利用します。 - -ステップの `callback_id` と設定オブジェクトを指定して、`WorkflowStep` の新しいインスタンスを作成します。 - -設定オブジェクトは、`edit`、`save`、`execute` という 3 つのキーを持ちます。それぞれのキーは、単一のコールバック、またはコールバックのリストである必要があります。すべてのコールバックは、ワークフローステップのイベントに関する情報を保持する `step` オブジェクトにアクセスできます。 - -`WorkflowStep` のインスタンスを作成したら、それを`app.step()` メソッドに渡します。これによって、アプリがワークフローステップのイベントをリッスンし、設定オブジェクトで指定されたコールバックを使ってそれに応答できるようになります。 - -また、デコレーターとして利用できる `WorkflowStepBuilder` クラスを使ってワークフローステップを定義することもできます。 詳細は、[こちらのドキュメント](https://docs.slack.dev/tools/bolt-python/reference/workflows/step/step.html#slack_bolt.workflows.step.step.WorkflowStepBuilder)のコード例などを参考にしてください。 - -指定可能な引数の一覧はモジュールドキュメントを参考にしてください([共通](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) / [ステップ用](https://docs.slack.dev/tools/bolt-python/reference/workflows/step/utilities/index.html)) - -```python -import os -from slack_bolt import App -from slack_bolt.workflows.step import WorkflowStep - -# いつも通りBolt アプリを起動する -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -def edit(ack, step, configure): - pass - -def save(ack, view, update): - pass - -def execute(step, complete, fail): - pass - -# WorkflowStep の新しいインスタンスを作成する -ws = WorkflowStep( - callback_id="add_task", - edit=edit, - save=save, - execute=execute, -) -# ワークフローステップを渡してリスナーを設定する -app.step(ws) -``` - -## ステップの追加・編集 - -作成したワークフローステップがワークフローに追加またはその設定を変更されるタイミングで、`workflow_step_edit` イベントがアプリに送信されます。このイベントがアプリに届くと、`WorkflowStep` で設定した `edit` コールバックが実行されます。 - -ステップの追加と編集のどちらが行われるときも、ワークフローステップの設定モーダルをビルダーに送信する必要があります。このモーダルは、そのステップ独自の設定を選択するための場所です。通常のモーダルより制限が強く、例えば `title`、`submit`、`close` のプロパティを含めることができません。設定モーダルの `callback_id` は、デフォルトではワークフローステップと同じものになります。 - -`edit` コールバック内で `configure()` ユーティリティを使用すると、対応する `blocks` 引数にビューのblocks 部分だけを渡して、ステップの設定モーダルを簡単に表示させることができます。必要な入力内容が揃うまで設定の保存を無効にするには、`True` の値をセットした `submit_disabled` を渡します。 - -指定可能な引数の一覧はモジュールドキュメントを参考にしてください([共通](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) / [ステップ用](https://docs.slack.dev/tools/bolt-python/reference/workflows/step/utilities/index.html)) - -```python -def edit(ack, step, configure): - ack() - - blocks = [ - { - "type": "input", - "block_id": "task_name_input", - "element": { - "type": "plain_text_input", - "action_id": "name", - "placeholder": {"type": "plain_text", "text":"Add a task name"}, - }, - "label": {"type": "plain_text", "text":"Task name"}, - }, - { - "type": "input", - "block_id": "task_description_input", - "element": { - "type": "plain_text_input", - "action_id": "description", - "placeholder": {"type": "plain_text", "text":"Add a task description"}, - }, - "label": {"type": "plain_text", "text":"Task description"}, - }, - ] - configure(blocks=blocks) - -ws = WorkflowStep( - callback_id="add_task", - edit=edit, - save=save, - execute=execute, -) -app.step(ws) -``` - -## ステップの設定の保存 - -設定モーダルを開いた後、アプリは `view_submission` イベントをリッスンします。このイベントがアプリに届くと、`WorkflowStep` で設定した `save` コールバックが実行されます。 - -`save` コールバック内では、`update()` メソッドを使って、ワークフローに追加されたステップの設定を保存することができます。このメソッドには次の引数を指定します。 - -- `inputs` : ユーザーがワークフローステップを実行したときにアプリが受け取る予定のデータを表す辞書型の値です。 -- `outputs` : ワークフローステップの完了時にアプリが出力するデータが設定されたオブジェクトのリストです。この outputs は、ワークフローの後続のステップで利用することができます。 -- `step_name` : ステップのデフォルトの名前をオーバーライドします。 -- `step_image_url` : ステップのデフォルトの画像をオーバーライドします。 - -指定可能な引数の一覧はモジュールドキュメントを参考にしてください([共通](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) / [ステップ用](https://docs.slack.dev/tools/bolt-python/reference/workflows/step/utilities/index.html)) - -```python -def save(ack, view, update): - ack() - - values = view["state"]["values"] - task_name = values["task_name_input"]["name"] - task_description = values["task_description_input"]["description"] - - inputs = { - "task_name": {"value": task_name["value"]}, - "task_description": {"value": task_description["value"]} - } - outputs = [ - { - "type": "text", - "name": "task_name", - "label":"Task name", - }, - { - "type": "text", - "name": "task_description", - "label":"Task description", - } - ] - update(inputs=inputs, outputs=outputs) - -ws = WorkflowStep( - callback_id="add_task", - edit=edit, - save=save, - execute=execute, -) -app.step(ws) -``` - -## ステップの実行 - -エンドユーザーがワークフローステップを実行すると、アプリに `workflow_step_execute` イベントが送信されます。このイベントがアプリに届くと、`WorkflowStep` で設定した `execute` コールバックが実行されます。 - -`save` コールバックで取り出した `inputs` を使って、サードパーティの API を呼び出す、情報をデータベースに保存する、ユーザーのホームタブを更新するといった処理を実行することができます。また、ワークフローの後続のステップで利用する出力値を `outputs` オブジェクトに設定します。 - -`execute` コールバック内では、`complete()` を呼び出してステップの実行が成功したことを示すか、`fail()` を呼び出してステップの実行が失敗したことを示す必要があります。 - -指定可能な引数の一覧はモジュールドキュメントを参考にしてください([共通](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) / [ステップ用](https://docs.slack.dev/tools/bolt-python/reference/workflows/step/utilities/index.html)) - -```python -def execute(step, complete, fail): - inputs = step["inputs"] - # すべての処理が成功した場合 - outputs = { - "task_name": inputs["task_name"]["value"], - "task_description": inputs["task_description"]["value"], - } - complete(outputs=outputs) - - # 失敗した処理がある場合 - error = {"message":"Just testing step failure!"} - fail(error=error) - -ws = WorkflowStep( - callback_id="add_task", - edit=edit, - save=save, - execute=execute, -) -app.step(ws) -``` \ No newline at end of file diff --git a/docs/reference/adapter/asgi/base_handler.html b/docs/reference/adapter/asgi/base_handler.html index b8a6da68f..74358683e 100644 --- a/docs/reference/adapter/asgi/base_handler.html +++ b/docs/reference/adapter/asgi/base_handler.html @@ -88,15 +88,13 @@

Classes

return AsgiHttpResponse(status=bolt_response.status, headers=bolt_response.headers, body=bolt_response.body) return AsgiHttpResponse(status=404, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Not Found") - async def _handle_lifespan(self, receive: Callable) -> Dict[str, str]: - while True: - lifespan = await receive() - if lifespan["type"] == "lifespan.startup": - """Do something before startup""" - return {"type": "lifespan.startup.complete"} - if lifespan["type"] == "lifespan.shutdown": - """Do something before shutdown""" - return {"type": "lifespan.shutdown.complete"} + async def _handle_lifespan(self, receive: Callable, send: Callable) -> None: + message = await receive() + if message["type"] == "lifespan.startup": + await send({"type": "lifespan.startup.complete"}) + message = await receive() + if message["type"] == "lifespan.shutdown": + await send({"type": "lifespan.shutdown.complete"}) async def __call__(self, scope: scope_type, receive: Callable, send: Callable) -> None: if scope["type"] == "http": @@ -107,7 +105,7 @@

Classes

await send(response.get_response_body()) return if scope["type"] == "lifespan": - await send(await self._handle_lifespan(receive)) + await self._handle_lifespan(receive, send) return raise TypeError(f"Unsupported scope type: {scope['type']!r}") diff --git a/docs/reference/adapter/asgi/http_response.html b/docs/reference/adapter/asgi/http_response.html index 86e368f6e..0c42d9a9f 100644 --- a/docs/reference/adapter/asgi/http_response.html +++ b/docs/reference/adapter/asgi/http_response.html @@ -60,11 +60,14 @@

Classes

def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): self.status: int = status - self.raw_headers: List[Tuple[bytes, bytes]] = [ - (bytes(key, ENCODING), bytes(value[0], ENCODING)) for key, value in headers.items() - ] - self.raw_headers.append((b"content-length", bytes(str(len(body)), ENCODING))) self.body: bytes = bytes(body, ENCODING) + self.raw_headers: List[Tuple[bytes, bytes]] = [] + for key, values in headers.items(): + if key.lower() == "content-length": + continue + for v in values: + self.raw_headers.append((bytes(key, ENCODING), bytes(v, ENCODING))) + self.raw_headers.append((b"content-length", bytes(str(len(self.body)), ENCODING))) def get_response_start(self) -> Dict[str, Union[str, int, Iterable[Tuple[bytes, bytes]]]]: return { @@ -94,11 +97,14 @@

Instance variables

def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): self.status: int = status - self.raw_headers: List[Tuple[bytes, bytes]] = [ - (bytes(key, ENCODING), bytes(value[0], ENCODING)) for key, value in headers.items() - ] - self.raw_headers.append((b"content-length", bytes(str(len(body)), ENCODING))) self.body: bytes = bytes(body, ENCODING) + self.raw_headers: List[Tuple[bytes, bytes]] = [] + for key, values in headers.items(): + if key.lower() == "content-length": + continue + for v in values: + self.raw_headers.append((bytes(key, ENCODING), bytes(v, ENCODING))) + self.raw_headers.append((b"content-length", bytes(str(len(self.body)), ENCODING))) def get_response_start(self) -> Dict[str, Union[str, int, Iterable[Tuple[bytes, bytes]]]]: return { @@ -127,11 +133,14 @@

Instance variables

def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): self.status: int = status - self.raw_headers: List[Tuple[bytes, bytes]] = [ - (bytes(key, ENCODING), bytes(value[0], ENCODING)) for key, value in headers.items() - ] - self.raw_headers.append((b"content-length", bytes(str(len(body)), ENCODING))) self.body: bytes = bytes(body, ENCODING) + self.raw_headers: List[Tuple[bytes, bytes]] = [] + for key, values in headers.items(): + if key.lower() == "content-length": + continue + for v in values: + self.raw_headers.append((bytes(key, ENCODING), bytes(v, ENCODING))) + self.raw_headers.append((b"content-length", bytes(str(len(self.body)), ENCODING))) def get_response_start(self) -> Dict[str, Union[str, int, Iterable[Tuple[bytes, bytes]]]]: return { @@ -160,11 +169,14 @@

Instance variables

def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): self.status: int = status - self.raw_headers: List[Tuple[bytes, bytes]] = [ - (bytes(key, ENCODING), bytes(value[0], ENCODING)) for key, value in headers.items() - ] - self.raw_headers.append((b"content-length", bytes(str(len(body)), ENCODING))) self.body: bytes = bytes(body, ENCODING) + self.raw_headers: List[Tuple[bytes, bytes]] = [] + for key, values in headers.items(): + if key.lower() == "content-length": + continue + for v in values: + self.raw_headers.append((bytes(key, ENCODING), bytes(v, ENCODING))) + self.raw_headers.append((b"content-length", bytes(str(len(self.body)), ENCODING))) def get_response_start(self) -> Dict[str, Union[str, int, Iterable[Tuple[bytes, bytes]]]]: return { diff --git a/docs/reference/adapter/falcon/async_resource.html b/docs/reference/adapter/falcon/async_resource.html index f43ab11ef..0dbba1ad4 100644 --- a/docs/reference/adapter/falcon/async_resource.html +++ b/docs/reference/adapter/falcon/async_resource.html @@ -85,9 +85,9 @@

Classes

await self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..." async def on_post(self, req: Request, resp: Response): bolt_req = await self._to_bolt_request(req) @@ -149,9 +149,9 @@

Methods

await self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..."
diff --git a/docs/reference/adapter/falcon/index.html b/docs/reference/adapter/falcon/index.html index 82a2a57e2..bfc21828f 100644 --- a/docs/reference/adapter/falcon/index.html +++ b/docs/reference/adapter/falcon/index.html @@ -91,9 +91,9 @@

Classes

self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..." def on_post(self, req: Request, resp: Response): bolt_req = self._to_bolt_request(req) @@ -159,9 +159,9 @@

Methods

self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..."
diff --git a/docs/reference/adapter/falcon/resource.html b/docs/reference/adapter/falcon/resource.html index 73860adc1..13f9a2177 100644 --- a/docs/reference/adapter/falcon/resource.html +++ b/docs/reference/adapter/falcon/resource.html @@ -80,9 +80,9 @@

Classes

self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..." def on_post(self, req: Request, resp: Response): bolt_req = self._to_bolt_request(req) @@ -148,9 +148,9 @@

Methods

self._write_response(bolt_resp, resp) return - resp.status = "404" - # Falcon 4.x w/ mypy fails to correctly infer the str type here - resp.body = "The page is not found..." + resp.status = HTTPStatus.NOT_FOUND + resp.content_type = MEDIA_TEXT + resp.text = "The page is not found..."
diff --git a/docs/reference/adapter/socket_mode/async_internals.html b/docs/reference/adapter/socket_mode/async_internals.html index d2e300efa..c0b23b1de 100644 --- a/docs/reference/adapter/socket_mode/async_internals.html +++ b/docs/reference/adapter/socket_mode/async_internals.html @@ -54,7 +54,7 @@

Functions

Expand source code
async def run_async_bolt_app(app: AsyncApp, req: SocketModeRequest):
-    bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload)
+    bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
     bolt_resp: BoltResponse = await app.async_dispatch(bolt_req)
     return bolt_resp
diff --git a/docs/reference/adapter/socket_mode/internals.html b/docs/reference/adapter/socket_mode/internals.html index 55d96b054..ba7d2f226 100644 --- a/docs/reference/adapter/socket_mode/internals.html +++ b/docs/reference/adapter/socket_mode/internals.html @@ -45,6 +45,25 @@

Module slack_bolt.adapter.socket_mode.internals

Functions

+
+def build_headers(req: slack_sdk.socket_mode.request.SocketModeRequest) ‑> Dict[str, str | Sequence[str]] | None +
+
+
+ +Expand source code + +
def build_headers(req: SocketModeRequest) -> Optional[Dict[str, Union[str, Sequence[str]]]]:
+    # Mirror the HTTP mode retry headers so middleware/listeners can detect Events API retries
+    headers: Dict[str, Union[str, Sequence[str]]] = {}
+    if req.retry_attempt is not None:
+        headers["x-slack-retry-num"] = str(req.retry_attempt)
+    if req.retry_reason is not None:
+        headers["x-slack-retry-reason"] = req.retry_reason
+    return headers or None
+
+
+
def run_bolt_app(app: App,
req: slack_sdk.socket_mode.request.SocketModeRequest)
@@ -54,7 +73,7 @@

Functions

Expand source code
def run_bolt_app(app: App, req: SocketModeRequest):
-    bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload)
+    bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
     bolt_resp: BoltResponse = app.dispatch(bolt_req)
     return bolt_resp
@@ -111,6 +130,7 @@

Functions

  • Functions

    diff --git a/docs/reference/adapter/wsgi/handler.html b/docs/reference/adapter/wsgi/handler.html index 204499a05..a6ea85ca4 100644 --- a/docs/reference/adapter/wsgi/handler.html +++ b/docs/reference/adapter/wsgi/handler.html @@ -117,17 +117,20 @@

    Classes

    def __call__( self, - environ: Dict[str, Any], - start_response: Callable[[str, List[Tuple[str, str]]], None], + environ: "WSGIEnvironment", + start_response: "StartResponse", ) -> Iterable[bytes]: request = WsgiHttpRequest(environ) - if "HTTP" in request.protocol: + if request.protocol.startswith("HTTP"): response: WsgiHttpResponse = self._get_http_response( request=request, ) - start_response(response.status, response.get_headers()) - return response.get_body() - raise TypeError(f"Unsupported SERVER_PROTOCOL: {request.protocol}") + else: + response = WsgiHttpResponse( + status=400, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Bad Request" + ) + start_response(response.status, response.get_headers()) + return response.get_body()

    Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers. This can be used for production deployments.

    diff --git a/docs/reference/adapter/wsgi/http_request.html b/docs/reference/adapter/wsgi/http_request.html index fa845dd93..72c5f28be 100644 --- a/docs/reference/adapter/wsgi/http_request.html +++ b/docs/reference/adapter/wsgi/http_request.html @@ -48,7 +48,7 @@

    Classes

    class WsgiHttpRequest -(environ: Dict[str, Any]) +(environ: WSGIEnvironment)
    @@ -64,7 +64,7 @@

    Classes

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -85,7 +85,7 @@

    Classes

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)

    This Class uses the PEP 3333 standard to extract request information @@ -108,7 +108,7 @@

    Instance variables

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -129,7 +129,7 @@

    Instance variables

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    @@ -149,7 +149,7 @@

    Instance variables

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -170,7 +170,7 @@

    Instance variables

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    @@ -190,7 +190,7 @@

    Instance variables

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -211,7 +211,7 @@

    Instance variables

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    @@ -231,7 +231,7 @@

    Instance variables

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -252,7 +252,7 @@

    Instance variables

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    @@ -272,7 +272,7 @@

    Instance variables

    __slots__ = ("method", "path", "query_string", "protocol", "environ") - def __init__(self, environ: Dict[str, Any]): + def __init__(self, environ: "WSGIEnvironment"): self.method: str = environ.get("REQUEST_METHOD", "GET") self.path: str = environ.get("PATH_INFO", "") self.query_string: str = environ.get("QUERY_STRING", "") @@ -293,7 +293,7 @@

    Instance variables

    def get_body(self) -> str: if "wsgi.input" not in self.environ: return "" - content_length = int(self.environ.get("CONTENT_LENGTH", 0)) + content_length = int(self.environ.get("CONTENT_LENGTH") or 0) return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    @@ -312,7 +312,7 @@

    Methods

    def get_body(self) -> str:
         if "wsgi.input" not in self.environ:
             return ""
    -    content_length = int(self.environ.get("CONTENT_LENGTH", 0))
    +    content_length = int(self.environ.get("CONTENT_LENGTH") or 0)
         return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
    diff --git a/docs/reference/adapter/wsgi/http_response.html b/docs/reference/adapter/wsgi/http_response.html index da7dc33f0..726332c77 100644 --- a/docs/reference/adapter/wsgi/http_response.html +++ b/docs/reference/adapter/wsgi/http_response.html @@ -48,7 +48,7 @@

    Classes

    class WsgiHttpResponse -(status: int, headers: Dict[str, Sequence[str]] = {}, body: str = '') +(status: int, headers: Dict[str, Sequence[str]] | None = None, body: str = '')
    @@ -64,18 +64,19 @@

    Classes

    __slots__ = ("status", "_headers", "_body") - def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): + def __init__(self, status: int, headers: Optional[Dict[str, Sequence[str]]] = None, body: str = ""): _status = HTTPStatus(status) self.status = f"{_status.value} {_status.phrase}" - self._headers = headers + self._headers = headers or {} self._body = bytes(body, ENCODING) def get_headers(self) -> List[Tuple[str, str]]: headers: List[Tuple[str, str]] = [] - for key, value in self._headers.items(): + for key, values in self._headers.items(): if key.lower() == "content-length": continue - headers.append((key, value[0])) + for v in values: + headers.append((key, v)) headers.append(("content-length", str(len(self._body)))) return headers @@ -103,18 +104,19 @@

    Instance variables

    __slots__ = ("status", "_headers", "_body") - def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""): + def __init__(self, status: int, headers: Optional[Dict[str, Sequence[str]]] = None, body: str = ""): _status = HTTPStatus(status) self.status = f"{_status.value} {_status.phrase}" - self._headers = headers + self._headers = headers or {} self._body = bytes(body, ENCODING) def get_headers(self) -> List[Tuple[str, str]]: headers: List[Tuple[str, str]] = [] - for key, value in self._headers.items(): + for key, values in self._headers.items(): if key.lower() == "content-length": continue - headers.append((key, value[0])) + for v in values: + headers.append((key, v)) headers.append(("content-length", str(len(self._body)))) return headers @@ -150,10 +152,11 @@

    Methods

    def get_headers(self) -> List[Tuple[str, str]]:
         headers: List[Tuple[str, str]] = []
    -    for key, value in self._headers.items():
    +    for key, values in self._headers.items():
             if key.lower() == "content-length":
                 continue
    -        headers.append((key, value[0]))
    +        for v in values:
    +            headers.append((key, v))
     
         headers.append(("content-length", str(len(self._body))))
         return headers
    diff --git a/docs/reference/adapter/wsgi/index.html b/docs/reference/adapter/wsgi/index.html index c3cfafea1..186d1adf6 100644 --- a/docs/reference/adapter/wsgi/index.html +++ b/docs/reference/adapter/wsgi/index.html @@ -136,17 +136,20 @@

    Classes

    def __call__( self, - environ: Dict[str, Any], - start_response: Callable[[str, List[Tuple[str, str]]], None], + environ: "WSGIEnvironment", + start_response: "StartResponse", ) -> Iterable[bytes]: request = WsgiHttpRequest(environ) - if "HTTP" in request.protocol: + if request.protocol.startswith("HTTP"): response: WsgiHttpResponse = self._get_http_response( request=request, ) - start_response(response.status, response.get_headers()) - return response.get_body() - raise TypeError(f"Unsupported SERVER_PROTOCOL: {request.protocol}") + else: + response = WsgiHttpResponse( + status=400, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Bad Request" + ) + start_response(response.status, response.get_headers()) + return response.get_body()

    Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers. This can be used for production deployments.

    diff --git a/docs/reference/app/app.html b/docs/reference/app/app.html index bf0d5ee00..737597548 100644 --- a/docs/reference/app/app.html +++ b/docs/reference/app/app.html @@ -118,7 +118,7 @@

    Classes

    if __name__ == "__main__": app.start(port=int(os.environ.get("PORT", 3000))) - Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details. + Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details. If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app. @@ -1438,7 +1438,7 @@

    Classes

    if __name__ == "__main__": app.start(port=int(os.environ.get("PORT", 3000))) -

    Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.

    +

    Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.

    If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.

    Args

    diff --git a/docs/reference/app/index.html b/docs/reference/app/index.html index 32e006944..5581b98e7 100644 --- a/docs/reference/app/index.html +++ b/docs/reference/app/index.html @@ -137,7 +137,7 @@

    Classes

    if __name__ == "__main__": app.start(port=int(os.environ.get("PORT", 3000))) - Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details. + Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details. If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app. @@ -1457,7 +1457,7 @@

    Classes

    if __name__ == "__main__": app.start(port=int(os.environ.get("PORT", 3000))) -

    Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.

    +

    Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.

    If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.

    Args

    diff --git a/docs/reference/async_app.html b/docs/reference/async_app.html index 3494ec289..670ba58d0 100644 --- a/docs/reference/async_app.html +++ b/docs/reference/async_app.html @@ -5291,6 +5291,9 @@

    Class variables

    recipient_team_id: Optional[str] = None, recipient_user_id: Optional[str] = None, thread_ts: Optional[str] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> AsyncChatStream: """Starts a new chat stream with context.""" @@ -5308,6 +5311,9 @@

    Class variables

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) return await self.client.chat_stream( @@ -5315,6 +5321,9 @@

    Class variables

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) @@ -5371,6 +5380,9 @@

    Class variables

    self, status: str, loading_messages: Optional[List[str]] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> AsyncSlackResponse: return await self.client.assistant_threads_setStatus( @@ -5378,6 +5390,9 @@

    Class variables

    thread_ts=self.thread_ts, status=status, loading_messages=loading_messages, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) @@ -5400,7 +5415,7 @@

    Class variables

    class AsyncSetSuggestedPrompts -(client: slack_sdk.web.async_client.AsyncWebClient,
    channel_id: str,
    thread_ts: str)
    +(client: slack_sdk.web.async_client.AsyncWebClient,
    channel_id: str,
    thread_ts: str | None = None)
    @@ -5410,13 +5425,13 @@

    Class variables

    class AsyncSetSuggestedPrompts:
         client: AsyncWebClient
         channel_id: str
    -    thread_ts: str
    +    thread_ts: Optional[str]
     
         def __init__(
             self,
             client: AsyncWebClient,
             channel_id: str,
    -        thread_ts: str,
    +        thread_ts: Optional[str] = None,
         ):
             self.client = client
             self.channel_id = channel_id
    @@ -5426,6 +5441,7 @@ 

    Class variables

    self, prompts: Sequence[Union[str, Dict[str, str]]], title: Optional[str] = None, + thread_ts: Optional[str] = None, ) -> AsyncSlackResponse: prompts_arg: List[Dict[str, str]] = [] for prompt in prompts: @@ -5436,7 +5452,7 @@

    Class variables

    return await self.client.assistant_threads_setSuggestedPrompts( channel_id=self.channel_id, - thread_ts=self.thread_ts, + thread_ts=thread_ts if thread_ts is not None else self.thread_ts, prompts=prompts_arg, title=title, )
    @@ -5452,7 +5468,7 @@

    Class variables

    The type of the None singleton.

    -
    var thread_ts : str
    +
    var thread_ts : str | None

    The type of the None singleton.

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

    Classes

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

    Class variables

    Static methods

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

    Classes

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

    Class variables

    Static methods

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

    Classes

    # When moving this code to Bolt internals, no need to raise an exception for this pattern raise ValueError(f"Cannot instantiate Assistant for this event pattern ({self.payload})") - def is_valid(self) -> bool: - return self.channel_id is not None and self.thread_ts is not None - - @property - def set_status(self) -> SetStatus: - warnings.warn( - "AssistantUtilities.set_status is deprecated. " - "Use the set_status argument directly in your listener function " - "or access it via context.set_status instead.", - DeprecationWarning, - stacklevel=2, - ) - return SetStatus(self.client, self.channel_id, self.thread_ts) - @property def set_title(self) -> SetTitle: return SetTitle(self.client, self.channel_id, self.thread_ts) - @property - def set_suggested_prompts(self) -> SetSuggestedPrompts: - return SetSuggestedPrompts(self.client, self.channel_id, self.thread_ts) - @property def say(self) -> Say: def build_metadata() -> Optional[dict]: @@ -204,37 +186,6 @@

    Instance variables

    -
    prop set_status : SetStatus
    -
    -
    - -Expand source code - -
    @property
    -def set_status(self) -> SetStatus:
    -    warnings.warn(
    -        "AssistantUtilities.set_status is deprecated. "
    -        "Use the set_status argument directly in your listener function "
    -        "or access it via context.set_status instead.",
    -        DeprecationWarning,
    -        stacklevel=2,
    -    )
    -    return SetStatus(self.client, self.channel_id, self.thread_ts)
    -
    -
    -
    -
    prop set_suggested_prompts : SetSuggestedPrompts
    -
    -
    - -Expand source code - -
    @property
    -def set_suggested_prompts(self) -> SetSuggestedPrompts:
    -    return SetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
    -
    -
    -
    prop set_title : SetTitle
    @@ -248,22 +199,6 @@

    Instance variables

    -

    Methods

    -
    -
    -def is_valid(self) ‑> bool -
    -
    -
    - -Expand source code - -
    def is_valid(self) -> bool:
    -    return self.channel_id is not None and self.thread_ts is not None
    -
    -
    -
    -
    @@ -286,12 +221,9 @@

    channel_id

  • client
  • get_thread_context
  • -
  • is_valid
  • payload
  • save_thread_context
  • say
  • -
  • set_status
  • -
  • set_suggested_prompts
  • set_title
  • thread_context_store
  • thread_ts
  • diff --git a/docs/reference/context/assistant/async_assistant_utilities.html b/docs/reference/context/assistant/async_assistant_utilities.html index fc77b80cb..70f4d0d23 100644 --- a/docs/reference/context/assistant/async_assistant_utilities.html +++ b/docs/reference/context/assistant/async_assistant_utilities.html @@ -86,28 +86,10 @@

    Classes

    # When moving this code to Bolt internals, no need to raise an exception for this pattern raise ValueError(f"Cannot instantiate Assistant for this event pattern ({self.payload})") - def is_valid(self) -> bool: - return self.channel_id is not None and self.thread_ts is not None - - @property - def set_status(self) -> AsyncSetStatus: - warnings.warn( - "AsyncAssistantUtilities.set_status is deprecated. " - "Use the set_status argument directly in your listener function " - "or access it via context.set_status instead.", - DeprecationWarning, - stacklevel=2, - ) - return AsyncSetStatus(self.client, self.channel_id, self.thread_ts) - @property def set_title(self) -> AsyncSetTitle: return AsyncSetTitle(self.client, self.channel_id, self.thread_ts) - @property - def set_suggested_prompts(self) -> AsyncSetSuggestedPrompts: - return AsyncSetSuggestedPrompts(self.client, self.channel_id, self.thread_ts) - @property def say(self) -> AsyncSay: return AsyncSay( @@ -198,37 +180,6 @@

    Instance variables

    -
    prop set_status : AsyncSetStatus
    -
    -
    - -Expand source code - -
    @property
    -def set_status(self) -> AsyncSetStatus:
    -    warnings.warn(
    -        "AsyncAssistantUtilities.set_status is deprecated. "
    -        "Use the set_status argument directly in your listener function "
    -        "or access it via context.set_status instead.",
    -        DeprecationWarning,
    -        stacklevel=2,
    -    )
    -    return AsyncSetStatus(self.client, self.channel_id, self.thread_ts)
    -
    -
    -
    -
    prop set_suggested_prompts : AsyncSetSuggestedPrompts
    -
    -
    - -Expand source code - -
    @property
    -def set_suggested_prompts(self) -> AsyncSetSuggestedPrompts:
    -    return AsyncSetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
    -
    -
    -
    prop set_title : AsyncSetTitle
    @@ -242,22 +193,6 @@

    Instance variables

    -

    Methods

    -
    -
    -def is_valid(self) ‑> bool -
    -
    -
    - -Expand source code - -
    def is_valid(self) -> bool:
    -    return self.channel_id is not None and self.thread_ts is not None
    -
    -
    -
    -
    @@ -280,12 +215,9 @@

    channel_id
  • client
  • get_thread_context
  • -
  • is_valid
  • payload
  • save_thread_context
  • say
  • -
  • set_status
  • -
  • set_suggested_prompts
  • set_title
  • thread_context_store
  • thread_ts
  • diff --git a/docs/reference/context/assistant/thread_context_store/file/index.html b/docs/reference/context/assistant/thread_context_store/file/index.html index cbb4e4db6..4a5d944e1 100644 --- a/docs/reference/context/assistant/thread_context_store/file/index.html +++ b/docs/reference/context/assistant/thread_context_store/file/index.html @@ -48,7 +48,7 @@

    Classes

    class FileAssistantThreadContextStore -(base_dir: str = '/Users/eden.zimbelman/.bolt-app-assistant-thread-contexts') +(base_dir: str = '/Users/wbergamin/.bolt-app-assistant-thread-contexts')
    diff --git a/docs/reference/context/say_stream/async_say_stream.html b/docs/reference/context/say_stream/async_say_stream.html index 4010b284d..3a1978299 100644 --- a/docs/reference/context/say_stream/async_say_stream.html +++ b/docs/reference/context/say_stream/async_say_stream.html @@ -85,6 +85,9 @@

    Classes

    recipient_team_id: Optional[str] = None, recipient_user_id: Optional[str] = None, thread_ts: Optional[str] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> AsyncChatStream: """Starts a new chat stream with context.""" @@ -102,6 +105,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) return await self.client.chat_stream( @@ -109,6 +115,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, )
    diff --git a/docs/reference/context/say_stream/index.html b/docs/reference/context/say_stream/index.html index 645942c72..5ed62587b 100644 --- a/docs/reference/context/say_stream/index.html +++ b/docs/reference/context/say_stream/index.html @@ -96,6 +96,9 @@

    Classes

    recipient_team_id: Optional[str] = None, recipient_user_id: Optional[str] = None, thread_ts: Optional[str] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> ChatStream: """Starts a new chat stream with context.""" @@ -113,6 +116,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) return self.client.chat_stream( @@ -120,6 +126,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) diff --git a/docs/reference/context/say_stream/say_stream.html b/docs/reference/context/say_stream/say_stream.html index 784a58bbe..e7bc33bff 100644 --- a/docs/reference/context/say_stream/say_stream.html +++ b/docs/reference/context/say_stream/say_stream.html @@ -85,6 +85,9 @@

    Classes

    recipient_team_id: Optional[str] = None, recipient_user_id: Optional[str] = None, thread_ts: Optional[str] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> ChatStream: """Starts a new chat stream with context.""" @@ -102,6 +105,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) return self.client.chat_stream( @@ -109,6 +115,9 @@

    Classes

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) diff --git a/docs/reference/context/set_status/async_set_status.html b/docs/reference/context/set_status/async_set_status.html index 06efd6447..770583e4a 100644 --- a/docs/reference/context/set_status/async_set_status.html +++ b/docs/reference/context/set_status/async_set_status.html @@ -74,6 +74,9 @@

    Classes

    self, status: str, loading_messages: Optional[List[str]] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> AsyncSlackResponse: return await self.client.assistant_threads_setStatus( @@ -81,6 +84,9 @@

    Classes

    thread_ts=self.thread_ts, status=status, loading_messages=loading_messages, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) diff --git a/docs/reference/context/set_status/index.html b/docs/reference/context/set_status/index.html index aa11815e3..380e37f4f 100644 --- a/docs/reference/context/set_status/index.html +++ b/docs/reference/context/set_status/index.html @@ -85,6 +85,9 @@

    Classes

    self, status: str, loading_messages: Optional[List[str]] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> SlackResponse: return self.client.assistant_threads_setStatus( @@ -92,6 +95,9 @@

    Classes

    thread_ts=self.thread_ts, status=status, loading_messages=loading_messages, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) diff --git a/docs/reference/context/set_status/set_status.html b/docs/reference/context/set_status/set_status.html index e4d839f64..b0a0a9ee7 100644 --- a/docs/reference/context/set_status/set_status.html +++ b/docs/reference/context/set_status/set_status.html @@ -74,6 +74,9 @@

    Classes

    self, status: str, loading_messages: Optional[List[str]] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> SlackResponse: return self.client.assistant_threads_setStatus( @@ -81,6 +84,9 @@

    Classes

    thread_ts=self.thread_ts, status=status, loading_messages=loading_messages, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) diff --git a/docs/reference/context/set_suggested_prompts/async_set_suggested_prompts.html b/docs/reference/context/set_suggested_prompts/async_set_suggested_prompts.html index 4feda52ba..1c7656456 100644 --- a/docs/reference/context/set_suggested_prompts/async_set_suggested_prompts.html +++ b/docs/reference/context/set_suggested_prompts/async_set_suggested_prompts.html @@ -48,7 +48,7 @@

    Classes

    class AsyncSetSuggestedPrompts -(client: slack_sdk.web.async_client.AsyncWebClient,
    channel_id: str,
    thread_ts: str)
    +(client: slack_sdk.web.async_client.AsyncWebClient,
    channel_id: str,
    thread_ts: str | None = None)
    @@ -58,13 +58,13 @@

    Classes

    class AsyncSetSuggestedPrompts:
         client: AsyncWebClient
         channel_id: str
    -    thread_ts: str
    +    thread_ts: Optional[str]
     
         def __init__(
             self,
             client: AsyncWebClient,
             channel_id: str,
    -        thread_ts: str,
    +        thread_ts: Optional[str] = None,
         ):
             self.client = client
             self.channel_id = channel_id
    @@ -74,6 +74,7 @@ 

    Classes

    self, prompts: Sequence[Union[str, Dict[str, str]]], title: Optional[str] = None, + thread_ts: Optional[str] = None, ) -> AsyncSlackResponse: prompts_arg: List[Dict[str, str]] = [] for prompt in prompts: @@ -84,7 +85,7 @@

    Classes

    return await self.client.assistant_threads_setSuggestedPrompts( channel_id=self.channel_id, - thread_ts=self.thread_ts, + thread_ts=thread_ts if thread_ts is not None else self.thread_ts, prompts=prompts_arg, title=title, )
    @@ -100,7 +101,7 @@

    Class variables

    The type of the None singleton.

    -
    var thread_ts : str
    +
    var thread_ts : str | None

    The type of the None singleton.

    diff --git a/docs/reference/context/set_suggested_prompts/index.html b/docs/reference/context/set_suggested_prompts/index.html index 12d864dde..cf606ae2f 100644 --- a/docs/reference/context/set_suggested_prompts/index.html +++ b/docs/reference/context/set_suggested_prompts/index.html @@ -59,7 +59,7 @@

    Classes

    class SetSuggestedPrompts -(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str) +(client: slack_sdk.web.client.WebClient,
    channel_id: str,
    thread_ts: str | None = None)
    @@ -69,13 +69,13 @@

    Classes

    class SetSuggestedPrompts:
         client: WebClient
         channel_id: str
    -    thread_ts: str
    +    thread_ts: Optional[str]
     
         def __init__(
             self,
             client: WebClient,
             channel_id: str,
    -        thread_ts: str,
    +        thread_ts: Optional[str] = None,
         ):
             self.client = client
             self.channel_id = channel_id
    @@ -85,6 +85,7 @@ 

    Classes

    self, prompts: Sequence[Union[str, Dict[str, str]]], title: Optional[str] = None, + thread_ts: Optional[str] = None, ) -> SlackResponse: prompts_arg: List[Dict[str, str]] = [] for prompt in prompts: @@ -95,7 +96,7 @@

    Classes

    return self.client.assistant_threads_setSuggestedPrompts( channel_id=self.channel_id, - thread_ts=self.thread_ts, + thread_ts=thread_ts if thread_ts is not None else self.thread_ts, prompts=prompts_arg, title=title, )
    @@ -111,7 +112,7 @@

    Class variables

    The type of the None singleton.

    -
    var thread_ts : str
    +
    var thread_ts : str | None

    The type of the None singleton.

    diff --git a/docs/reference/context/set_suggested_prompts/set_suggested_prompts.html b/docs/reference/context/set_suggested_prompts/set_suggested_prompts.html index 6c0385e57..f034fc677 100644 --- a/docs/reference/context/set_suggested_prompts/set_suggested_prompts.html +++ b/docs/reference/context/set_suggested_prompts/set_suggested_prompts.html @@ -48,7 +48,7 @@

    Classes

    class SetSuggestedPrompts -(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str) +(client: slack_sdk.web.client.WebClient,
    channel_id: str,
    thread_ts: str | None = None)
    @@ -58,13 +58,13 @@

    Classes

    class SetSuggestedPrompts:
         client: WebClient
         channel_id: str
    -    thread_ts: str
    +    thread_ts: Optional[str]
     
         def __init__(
             self,
             client: WebClient,
             channel_id: str,
    -        thread_ts: str,
    +        thread_ts: Optional[str] = None,
         ):
             self.client = client
             self.channel_id = channel_id
    @@ -74,6 +74,7 @@ 

    Classes

    self, prompts: Sequence[Union[str, Dict[str, str]]], title: Optional[str] = None, + thread_ts: Optional[str] = None, ) -> SlackResponse: prompts_arg: List[Dict[str, str]] = [] for prompt in prompts: @@ -84,7 +85,7 @@

    Classes

    return self.client.assistant_threads_setSuggestedPrompts( channel_id=self.channel_id, - thread_ts=self.thread_ts, + thread_ts=thread_ts if thread_ts is not None else self.thread_ts, prompts=prompts_arg, title=title, )
    @@ -100,7 +101,7 @@

    Class variables

    The type of the None singleton.

    -
    var thread_ts : str
    +
    var thread_ts : str | None

    The type of the None singleton.

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

    Subclasses

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

    Package slack_bolt

    -

    A Python framework to build Slack apps in a flash with the latest platform features.Read the getting started guide and look at our code examples to learn how to build apps using Bolt.

    +

    A Python framework to build Slack apps in a flash with the latest platform features.Read the getting started guide and look at our code examples to learn how to build apps using Bolt.

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

    Class variables

    recipient_team_id: Optional[str] = None, recipient_user_id: Optional[str] = None, thread_ts: Optional[str] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> ChatStream: """Starts a new chat stream with context.""" @@ -5932,6 +5935,9 @@

    Class variables

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, ) return self.client.chat_stream( @@ -5939,6 +5945,9 @@

    Class variables

    recipient_team_id=recipient_team_id or self.recipient_team_id, recipient_user_id=recipient_user_id or self.recipient_user_id, thread_ts=thread_ts, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, )
    @@ -5995,6 +6004,9 @@

    Class variables

    self, status: str, loading_messages: Optional[List[str]] = None, + icon_emoji: Optional[str] = None, + icon_url: Optional[str] = None, + username: Optional[str] = None, **kwargs, ) -> SlackResponse: return self.client.assistant_threads_setStatus( @@ -6002,6 +6014,9 @@

    Class variables

    thread_ts=self.thread_ts, status=status, loading_messages=loading_messages, + icon_emoji=icon_emoji, + icon_url=icon_url, + username=username, **kwargs, )
    @@ -6024,7 +6039,7 @@

    Class variables

    class SetSuggestedPrompts -(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str) +(client: slack_sdk.web.client.WebClient,
    channel_id: str,
    thread_ts: str | None = None)
    @@ -6034,13 +6049,13 @@

    Class variables

    class SetSuggestedPrompts:
         client: WebClient
         channel_id: str
    -    thread_ts: str
    +    thread_ts: Optional[str]
     
         def __init__(
             self,
             client: WebClient,
             channel_id: str,
    -        thread_ts: str,
    +        thread_ts: Optional[str] = None,
         ):
             self.client = client
             self.channel_id = channel_id
    @@ -6050,6 +6065,7 @@ 

    Class variables

    self, prompts: Sequence[Union[str, Dict[str, str]]], title: Optional[str] = None, + thread_ts: Optional[str] = None, ) -> SlackResponse: prompts_arg: List[Dict[str, str]] = [] for prompt in prompts: @@ -6060,7 +6076,7 @@

    Class variables

    return self.client.assistant_threads_setSuggestedPrompts( channel_id=self.channel_id, - thread_ts=self.thread_ts, + thread_ts=thread_ts if thread_ts is not None else self.thread_ts, prompts=prompts_arg, title=title, )
    @@ -6076,7 +6092,7 @@

    Class variables

    The type of the None singleton.

    -
    var thread_ts : str
    +
    var thread_ts : str | None

    The type of the None singleton.

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

    Functions

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

    Functions

    -def warning_unhandled_request(req: BoltRequest | ForwardRef('AsyncBoltRequest')) ‑> str +def warning_unhandled_request(req: BoltRequest | AsyncBoltRequest) ‑> str
    diff --git a/docs/reference/middleware/async_builtins.html b/docs/reference/middleware/async_builtins.html index 1ddea9222..8f7b1ba4f 100644 --- a/docs/reference/middleware/async_builtins.html +++ b/docs/reference/middleware/async_builtins.html @@ -70,34 +70,50 @@

    Classes

    next: Callable[[], Awaitable[BoltResponse]], ) -> Optional[BoltResponse]: event = to_event(req.body) - if event is not None: - if is_assistant_event(req.body): - assistant = AsyncAssistantUtilities( - payload=event, - context=req.context, - thread_context_store=self.thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context + if event is None: + return await next() + if req.context.channel_id is None: + return await next() + + if is_assistant_event(req.body): + # TODO: eventually we might remove this assistant specific logic + assistant = AsyncAssistantUtilities( + payload=event, + context=req.context, + thread_context_store=self.thread_context_store, + ) + req.context["say"] = assistant.say + req.context["set_title"] = assistant.set_title + req.context["get_thread_context"] = assistant.get_thread_context + req.context["save_thread_context"] = assistant.save_thread_context + + if ( + is_im_message_event(req.body) + or is_assistant_thread_started_event(req.body) + or is_assistant_thread_context_changed_event(req.body) + or is_app_home_opened_event(req.body, tab="messages") + ): + req.context["set_suggested_prompts"] = AsyncSetSuggestedPrompts( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=req.context.thread_ts, + ) - # TODO: in the future we might want to introduce a "proper" extract_ts utility - thread_ts = req.context.thread_ts or event.get("ts") - if req.context.channel_id and thread_ts: - req.context["set_status"] = AsyncSetStatus( - client=req.context.client, - channel_id=req.context.channel_id, - thread_ts=thread_ts, - ) - req.context["say_stream"] = AsyncSayStream( - client=req.context.client, - channel=req.context.channel_id, - recipient_team_id=req.context.team_id or req.context.enterprise_id, - recipient_user_id=req.context.user_id, - thread_ts=thread_ts, - ) + # TODO: in the future we might want to introduce a "proper" extract_ts utility + thread_ts_or_ts = req.context.thread_ts or event.get("ts") + if thread_ts_or_ts: + req.context["set_status"] = AsyncSetStatus( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=thread_ts_or_ts, + ) + req.context["say_stream"] = AsyncSayStream( + client=req.context.client, + channel=req.context.channel_id, + recipient_team_id=req.context.team_id or req.context.enterprise_id, + recipient_user_id=req.context.user_id, + thread_ts=thread_ts_or_ts, + ) return await next()

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

    diff --git a/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html b/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html index a0f5bdf85..e2bbe7045 100644 --- a/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html +++ b/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html @@ -70,34 +70,50 @@

    Classes

    next: Callable[[], Awaitable[BoltResponse]], ) -> Optional[BoltResponse]: event = to_event(req.body) - if event is not None: - if is_assistant_event(req.body): - assistant = AsyncAssistantUtilities( - payload=event, - context=req.context, - thread_context_store=self.thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context + if event is None: + return await next() + if req.context.channel_id is None: + return await next() - # TODO: in the future we might want to introduce a "proper" extract_ts utility - thread_ts = req.context.thread_ts or event.get("ts") - if req.context.channel_id and thread_ts: - req.context["set_status"] = AsyncSetStatus( - client=req.context.client, - channel_id=req.context.channel_id, - thread_ts=thread_ts, - ) - req.context["say_stream"] = AsyncSayStream( - client=req.context.client, - channel=req.context.channel_id, - recipient_team_id=req.context.team_id or req.context.enterprise_id, - recipient_user_id=req.context.user_id, - thread_ts=thread_ts, - ) + if is_assistant_event(req.body): + # TODO: eventually we might remove this assistant specific logic + assistant = AsyncAssistantUtilities( + payload=event, + context=req.context, + thread_context_store=self.thread_context_store, + ) + req.context["say"] = assistant.say + req.context["set_title"] = assistant.set_title + req.context["get_thread_context"] = assistant.get_thread_context + req.context["save_thread_context"] = assistant.save_thread_context + + if ( + is_im_message_event(req.body) + or is_assistant_thread_started_event(req.body) + or is_assistant_thread_context_changed_event(req.body) + or is_app_home_opened_event(req.body, tab="messages") + ): + req.context["set_suggested_prompts"] = AsyncSetSuggestedPrompts( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=req.context.thread_ts, + ) + + # TODO: in the future we might want to introduce a "proper" extract_ts utility + thread_ts_or_ts = req.context.thread_ts or event.get("ts") + if thread_ts_or_ts: + req.context["set_status"] = AsyncSetStatus( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=thread_ts_or_ts, + ) + req.context["say_stream"] = AsyncSayStream( + client=req.context.client, + channel=req.context.channel_id, + recipient_team_id=req.context.team_id or req.context.enterprise_id, + recipient_user_id=req.context.user_id, + thread_ts=thread_ts_or_ts, + ) return await next()

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

    diff --git a/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html b/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html index 8a1911323..e9d558fec 100644 --- a/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html +++ b/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html @@ -64,34 +64,50 @@

    Classes

    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]: event = to_event(req.body) - if event is not None: - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=event, - context=req.context, - thread_context_store=self.thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context + if event is None: + return next() + if req.context.channel_id is None: + return next() - # TODO: in the future we might want to introduce a "proper" extract_ts utility - thread_ts = req.context.thread_ts or event.get("ts") - if req.context.channel_id and thread_ts: - req.context["set_status"] = SetStatus( - client=req.context.client, - channel_id=req.context.channel_id, - thread_ts=thread_ts, - ) - req.context["say_stream"] = SayStream( - client=req.context.client, - channel=req.context.channel_id, - recipient_team_id=req.context.team_id or req.context.enterprise_id, - recipient_user_id=req.context.user_id, - thread_ts=thread_ts, - ) + if is_assistant_event(req.body): + # TODO: eventually we might remove this assistant specific logic + assistant = AssistantUtilities( + payload=event, + context=req.context, + thread_context_store=self.thread_context_store, + ) + req.context["say"] = assistant.say + req.context["set_title"] = assistant.set_title + req.context["get_thread_context"] = assistant.get_thread_context + req.context["save_thread_context"] = assistant.save_thread_context + + if ( + is_im_message_event(req.body) + or is_assistant_thread_started_event(req.body) + or is_assistant_thread_context_changed_event(req.body) + or is_app_home_opened_event(req.body, tab="messages") + ): + req.context["set_suggested_prompts"] = SetSuggestedPrompts( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=req.context.thread_ts, + ) + + # TODO: in the future we might want to introduce a "proper" extract_ts utility + thread_ts_or_ts = req.context.thread_ts or event.get("ts") + if thread_ts_or_ts: + req.context["set_status"] = SetStatus( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=thread_ts_or_ts, + ) + req.context["say_stream"] = SayStream( + client=req.context.client, + channel=req.context.channel_id, + recipient_team_id=req.context.team_id or req.context.enterprise_id, + recipient_user_id=req.context.user_id, + thread_ts=thread_ts_or_ts, + ) return next()

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

    diff --git a/docs/reference/middleware/attaching_conversation_kwargs/index.html b/docs/reference/middleware/attaching_conversation_kwargs/index.html index 308a52712..38da4442e 100644 --- a/docs/reference/middleware/attaching_conversation_kwargs/index.html +++ b/docs/reference/middleware/attaching_conversation_kwargs/index.html @@ -75,34 +75,50 @@

    Classes

    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]: event = to_event(req.body) - if event is not None: - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=event, - context=req.context, - thread_context_store=self.thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context + if event is None: + return next() + if req.context.channel_id is None: + return next() - # TODO: in the future we might want to introduce a "proper" extract_ts utility - thread_ts = req.context.thread_ts or event.get("ts") - if req.context.channel_id and thread_ts: - req.context["set_status"] = SetStatus( - client=req.context.client, - channel_id=req.context.channel_id, - thread_ts=thread_ts, - ) - req.context["say_stream"] = SayStream( - client=req.context.client, - channel=req.context.channel_id, - recipient_team_id=req.context.team_id or req.context.enterprise_id, - recipient_user_id=req.context.user_id, - thread_ts=thread_ts, - ) + if is_assistant_event(req.body): + # TODO: eventually we might remove this assistant specific logic + assistant = AssistantUtilities( + payload=event, + context=req.context, + thread_context_store=self.thread_context_store, + ) + req.context["say"] = assistant.say + req.context["set_title"] = assistant.set_title + req.context["get_thread_context"] = assistant.get_thread_context + req.context["save_thread_context"] = assistant.save_thread_context + + if ( + is_im_message_event(req.body) + or is_assistant_thread_started_event(req.body) + or is_assistant_thread_context_changed_event(req.body) + or is_app_home_opened_event(req.body, tab="messages") + ): + req.context["set_suggested_prompts"] = SetSuggestedPrompts( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=req.context.thread_ts, + ) + + # TODO: in the future we might want to introduce a "proper" extract_ts utility + thread_ts_or_ts = req.context.thread_ts or event.get("ts") + if thread_ts_or_ts: + req.context["set_status"] = SetStatus( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=thread_ts_or_ts, + ) + req.context["say_stream"] = SayStream( + client=req.context.client, + channel=req.context.channel_id, + recipient_team_id=req.context.team_id or req.context.enterprise_id, + recipient_user_id=req.context.user_id, + thread_ts=thread_ts_or_ts, + ) return next()

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

    diff --git a/docs/reference/middleware/index.html b/docs/reference/middleware/index.html index ce2629224..153342bc1 100644 --- a/docs/reference/middleware/index.html +++ b/docs/reference/middleware/index.html @@ -136,34 +136,50 @@

    Classes

    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]: event = to_event(req.body) - if event is not None: - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=event, - context=req.context, - thread_context_store=self.thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context + if event is None: + return next() + if req.context.channel_id is None: + return next() - # TODO: in the future we might want to introduce a "proper" extract_ts utility - thread_ts = req.context.thread_ts or event.get("ts") - if req.context.channel_id and thread_ts: - req.context["set_status"] = SetStatus( - client=req.context.client, - channel_id=req.context.channel_id, - thread_ts=thread_ts, - ) - req.context["say_stream"] = SayStream( - client=req.context.client, - channel=req.context.channel_id, - recipient_team_id=req.context.team_id or req.context.enterprise_id, - recipient_user_id=req.context.user_id, - thread_ts=thread_ts, - ) + if is_assistant_event(req.body): + # TODO: eventually we might remove this assistant specific logic + assistant = AssistantUtilities( + payload=event, + context=req.context, + thread_context_store=self.thread_context_store, + ) + req.context["say"] = assistant.say + req.context["set_title"] = assistant.set_title + req.context["get_thread_context"] = assistant.get_thread_context + req.context["save_thread_context"] = assistant.save_thread_context + + if ( + is_im_message_event(req.body) + or is_assistant_thread_started_event(req.body) + or is_assistant_thread_context_changed_event(req.body) + or is_app_home_opened_event(req.body, tab="messages") + ): + req.context["set_suggested_prompts"] = SetSuggestedPrompts( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=req.context.thread_ts, + ) + + # TODO: in the future we might want to introduce a "proper" extract_ts utility + thread_ts_or_ts = req.context.thread_ts or event.get("ts") + if thread_ts_or_ts: + req.context["set_status"] = SetStatus( + client=req.context.client, + channel_id=req.context.channel_id, + thread_ts=thread_ts_or_ts, + ) + req.context["say_stream"] = SayStream( + client=req.context.client, + channel=req.context.channel_id, + recipient_team_id=req.context.team_id or req.context.enterprise_id, + recipient_user_id=req.context.user_id, + thread_ts=thread_ts_or_ts, + ) return next()

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

    @@ -720,9 +736,17 @@

    Inherited members

    signing_secret: The signing secret base_logger: The base logger """ - self.verifier = SignatureVerifier(signing_secret=signing_secret) + self._signing_secret = signing_secret + self._verifier: Optional[SignatureVerifier] = None self.logger = get_bolt_logger(RequestVerification, base_logger=base_logger) + @property + def verifier(self) -> SignatureVerifier: + # Defer initialization to avoid errors during start up + if self._verifier is None: + self._verifier = SignatureVerifier(signing_secret=self._signing_secret) + return self._verifier + def process( self, *, @@ -749,7 +773,7 @@

    Inherited members

    @staticmethod def _can_skip(mode: str, body: Dict[str, Any]) -> bool: - return mode == "socket_mode" or (body is not None and body.get("ssl_check") == "1") + return mode == "socket_mode" @staticmethod def _build_error_response() -> BoltResponse: @@ -779,6 +803,24 @@

    Subclasses

    +

    Instance variables

    +
    +
    prop verifier : slack_sdk.signature.SignatureVerifier
    +
    +
    + +Expand source code + +
    @property
    +def verifier(self) -> SignatureVerifier:
    +    # Defer initialization to avoid errors during start up
    +    if self._verifier is None:
    +        self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
    +    return self._verifier
    +
    +
    +
    +

    Inherited members

    • Middleware: @@ -1139,6 +1181,9 @@

      RequestVerification

      +
    • SingleTeamAuthorization

      diff --git a/docs/reference/middleware/request_verification/index.html b/docs/reference/middleware/request_verification/index.html index 5dfd6ed82..50a8676b5 100644 --- a/docs/reference/middleware/request_verification/index.html +++ b/docs/reference/middleware/request_verification/index.html @@ -77,9 +77,17 @@

      Classes

      signing_secret: The signing secret base_logger: The base logger """ - self.verifier = SignatureVerifier(signing_secret=signing_secret) + self._signing_secret = signing_secret + self._verifier: Optional[SignatureVerifier] = None self.logger = get_bolt_logger(RequestVerification, base_logger=base_logger) + @property + def verifier(self) -> SignatureVerifier: + # Defer initialization to avoid errors during start up + if self._verifier is None: + self._verifier = SignatureVerifier(signing_secret=self._signing_secret) + return self._verifier + def process( self, *, @@ -106,7 +114,7 @@

      Classes

      @staticmethod def _can_skip(mode: str, body: Dict[str, Any]) -> bool: - return mode == "socket_mode" or (body is not None and body.get("ssl_check") == "1") + return mode == "socket_mode" @staticmethod def _build_error_response() -> BoltResponse: @@ -136,6 +144,24 @@

      Subclasses

      +

      Instance variables

      +
      +
      prop verifier : slack_sdk.signature.SignatureVerifier
      +
      +
      + +Expand source code + +
      @property
      +def verifier(self) -> SignatureVerifier:
      +    # Defer initialization to avoid errors during start up
      +    if self._verifier is None:
      +        self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
      +    return self._verifier
      +
      +
      +
      +

      Inherited members

      • Middleware: @@ -169,6 +195,9 @@

        Inherited members

      • diff --git a/docs/reference/middleware/request_verification/request_verification.html b/docs/reference/middleware/request_verification/request_verification.html index 99134110a..4ee2ed1b1 100644 --- a/docs/reference/middleware/request_verification/request_verification.html +++ b/docs/reference/middleware/request_verification/request_verification.html @@ -66,9 +66,17 @@

        Classes

        signing_secret: The signing secret base_logger: The base logger """ - self.verifier = SignatureVerifier(signing_secret=signing_secret) + self._signing_secret = signing_secret + self._verifier: Optional[SignatureVerifier] = None self.logger = get_bolt_logger(RequestVerification, base_logger=base_logger) + @property + def verifier(self) -> SignatureVerifier: + # Defer initialization to avoid errors during start up + if self._verifier is None: + self._verifier = SignatureVerifier(signing_secret=self._signing_secret) + return self._verifier + def process( self, *, @@ -95,7 +103,7 @@

        Classes

        @staticmethod def _can_skip(mode: str, body: Dict[str, Any]) -> bool: - return mode == "socket_mode" or (body is not None and body.get("ssl_check") == "1") + return mode == "socket_mode" @staticmethod def _build_error_response() -> BoltResponse: @@ -125,6 +133,24 @@

        Subclasses

        +

        Instance variables

        +
        +
        prop verifier : slack_sdk.signature.SignatureVerifier
        +
        +
        + +Expand source code + +
        @property
        +def verifier(self) -> SignatureVerifier:
        +    # Defer initialization to avoid errors during start up
        +    if self._verifier is None:
        +        self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
        +    return self._verifier
        +
        +
        +
        +

        Inherited members

        • Middleware: @@ -152,6 +178,9 @@

          Inherited members

        • diff --git a/docs/reference/oauth/async_oauth_settings.html b/docs/reference/oauth/async_oauth_settings.html index 5e6a543c4..3b8c04edb 100644 --- a/docs/reference/oauth/async_oauth_settings.html +++ b/docs/reference/oauth/async_oauth_settings.html @@ -48,7 +48,7 @@

          Classes

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

          Classes

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

          Functions

          if isinstance(payload.get("event"), dict): return extract_team_id(payload["event"]) if isinstance(payload.get("user"), dict): - return payload["user"]["team_id"] + return payload["user"].get("team_id") if isinstance(payload.get("view"), dict): - return payload["view"]["team_id"] + return payload["view"].get("team_id") return None
          diff --git a/docs/reference/request/payload_utils.html b/docs/reference/request/payload_utils.html index 4fe75fd81..b583c3a51 100644 --- a/docs/reference/request/payload_utils.html +++ b/docs/reference/request/payload_utils.html @@ -63,6 +63,39 @@

          Functions

          +
          +def is_any_im_message_event(body: Dict[str, Any]) ‑> bool +
          +
          +
          + +Expand source code + +
          def is_any_im_message_event(body: Dict[str, Any]) -> bool:
          +    if is_message_event(body):
          +        # Any message event with no subtype or any subtype (message_changed, message_deleted, etc.)
          +        return body["event"].get("channel_type") == "im"
          +    return False
          +
          +
          +
          +
          +def is_app_home_opened_event(body: Dict[str, Any], tab: str | None = None) ‑> bool +
          +
          +
          + +Expand source code + +
          def is_app_home_opened_event(body: Dict[str, Any], tab: Optional[str] = None) -> bool:
          +    if is_event(body) and body["event"]["type"] == "app_home_opened":
          +        if tab is not None:
          +            return body["event"].get("tab") == tab
          +        return True
          +    return False
          +
          +
          +
          def is_assistant_event(body: Dict[str, Any]) ‑> bool
          @@ -159,10 +192,9 @@

          Functions

          Expand source code
          def is_bot_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
          -    if is_event(body):
          +    if is_any_im_message_event(body):
                   return (
          -            is_message_event_in_assistant_thread(body)
          -            and body["event"].get("subtype") is None
          +            body["event"].get("subtype") is None
                       and body["event"].get("thread_ts") is not None
                       and body["event"].get("bot_id") is not None
                   )
          @@ -248,17 +280,32 @@ 

          Functions

    -
    -def is_message_event_in_assistant_thread(body: Dict[str, Any]) ‑> bool +
    +def is_im_message_event(body: Dict[str, Any]) ‑> bool +
    +
    +
    + +Expand source code + +
    def is_im_message_event(body: Dict[str, Any]) -> bool:
    +    if is_any_im_message_event(body):
    +        return body["event"].get("subtype") in (None, "file_share")
    +    return False
    +
    +
    +
    +
    +def is_message_event(body: Dict[str, Any]) ‑> bool
    Expand source code -
    def is_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
    +
    def is_message_event(body: Dict[str, Any]) -> bool:
         if is_event(body):
    -        return body["event"]["type"] == "message" and body["event"].get("channel_type") == "im"
    +        return body["event"]["type"] == "message"
         return False
    @@ -299,14 +346,10 @@

    Functions

    def is_other_message_sub_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
         # message_changed, message_deleted etc.
    -    if is_event(body):
    -        return (
    -            is_message_event_in_assistant_thread(body)
    -            and not is_user_message_event_in_assistant_thread(body)
    -            and (
    -                _is_other_message_sub_event(body["event"].get("message"))
    -                or _is_other_message_sub_event(body["event"].get("previous_message"))
    -            )
    +    if is_any_im_message_event(body):
    +        return not is_user_message_event_in_assistant_thread(body) and (
    +            _is_other_message_sub_event(body["event"].get("message"))
    +            or _is_other_message_sub_event(body["event"].get("previous_message"))
             )
         return False
    @@ -347,13 +390,8 @@

    Functions

    Expand source code
    def is_user_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
    -    if is_event(body):
    -        return (
    -            is_message_event_in_assistant_thread(body)
    -            and body["event"].get("subtype") in (None, "file_share")
    -            and body["event"].get("thread_ts") is not None
    -            and body["event"].get("bot_id") is None
    -        )
    +    if is_im_message_event(body):
    +        return body["event"].get("thread_ts") is not None and body["event"].get("bot_id") is None
         return False
    @@ -491,7 +529,7 @@

    Functions

    Expand source code
    def to_message(body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    -    if is_event(body) and body["event"]["type"] == "message":
    +    if is_message_event(body):
             return to_event(body)
         return None
    @@ -582,6 +620,8 @@

    Functions

  • Functions

    • is_action
    • +
    • is_any_im_message_event
    • +
    • is_app_home_opened_event
    • is_assistant_event
    • is_assistant_thread_context_changed_event
    • is_assistant_thread_started_event
    • @@ -595,7 +635,8 @@

      Functions

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