From 42157133da871518bf4b7eaf3f4efcf464c9ed27 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:47:49 -0500 Subject: [PATCH 1/4] build: move to pyproject.toml and drop python 3.6 Replace setup.py, setup.cfg, and pytest.ini with pyproject.toml, matching python-slack-sdk, bolt-python, and python-slack-hooks. The new floor is Python 3.7. A Python CI workflow runs the tests on 3.7 to 3.15 and PyPy, and tests that need live Discovery API tokens now skip without them. Co-Authored-By: Claude --- .github/dependabot.yml | 5 ++ .github/workflows/ci-build.yml | 91 +++++++++++++++++++++++++++++++ .github/workflows/flake8.yml | 3 +- .github/workflows/py_compile.yml | 39 ------------- .github/workflows/pytype.yml | 3 +- MANIFEST.in | 1 + README.md | 12 ++-- codecov.yml | 8 +++ pyproject.toml | 57 +++++++++++++++++++ pytest.ini | 10 ---- requirements/build.txt | 7 +++ requirements/testing.txt | 15 +++++ scripts/build.sh | 18 ------ scripts/build_pypi_package.sh | 14 +++++ scripts/deploy_to_test_pypi.sh | 8 +++ scripts/install.sh | 7 +++ scripts/run_all.sh | 18 ------ scripts/run_tests.sh | 15 +++++ scripts/set_env_vars.sh | 4 +- scripts/uninstall_all.sh | 9 +++ setup.cfg | 7 --- setup.py | 56 ------------------- tests/conftest.py | 14 +++++ tests/test_chat.py | 2 + tests/test_conversations.py | 1 + tests/test_draft.py | 2 + tests/test_enterprise.py | 2 + tests/test_file.py | 2 + tests/test_rate_limit_scenario.py | 1 + tests/test_users.py | 2 + 30 files changed, 274 insertions(+), 159 deletions(-) create mode 100644 .github/workflows/ci-build.yml delete mode 100644 .github/workflows/py_compile.yml create mode 100644 MANIFEST.in create mode 100644 codecov.yml create mode 100644 pyproject.toml delete mode 100644 pytest.ini create mode 100644 requirements/build.txt create mode 100644 requirements/testing.txt delete mode 100755 scripts/build.sh create mode 100755 scripts/build_pypi_package.sh create mode 100755 scripts/deploy_to_test_pypi.sh create mode 100755 scripts/install.sh delete mode 100755 scripts/run_all.sh create mode 100755 scripts/run_tests.sh create mode 100755 scripts/uninstall_all.sh delete mode 100644 setup.cfg delete mode 100644 setup.py create mode 100644 tests/conftest.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8ac6b8c..9fce184 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,5 +1,10 @@ version: 2 updates: + - package-ecosystem: "pip" + directory: "/" + schedule: + interval: "monthly" + open-pull-requests-limit: 5 - package-ecosystem: "github-actions" directory: "/" schedule: diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml new file mode 100644 index 0000000..938ce38 --- /dev/null +++ b/.github/workflows/ci-build.yml @@ -0,0 +1,91 @@ +name: Python CI + +on: + push: + branches: + - main + pull_request: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +env: + LATEST_SUPPORTED_PY: "3.15" + +jobs: + unittest: + name: Unit tests + runs-on: ubuntu-22.04 + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python-version: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" + - "3.13" + - "3.14" + - "3.15" + - "pypy3.10" + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + pip install -U pip + pip install -e . + pip install -r requirements/testing.txt + - name: Run tests + run: | + pytest --junitxml=reports/test.xml + - name: Upload test results to Codecov + if: ${{ !cancelled() }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + directory: ./reports/ + fail_ci_if_error: true + flags: ${{ matrix.python-version }} + report_type: test_results + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true + + codecov: + name: Code Coverage + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} + 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 -e . + pip install -r requirements/testing.txt + - name: Run all tests for codecov + run: | + pytest --cov=./slack_discovery_sdk/ --cov-report=xml + - name: Upload coverage to Codecov + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + fail_ci_if_error: true + report_type: coverage + token: ${{ secrets.CODECOV_TOKEN }} + verbose: true diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml index 3ca0954..8bf6459 100644 --- a/.github/workflows/flake8.yml +++ b/.github/workflows/flake8.yml @@ -26,8 +26,7 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | - pip install -U pip - pip install -e ".[testing]" + ./scripts/install.sh # We manually upgrade it to make the builds stable pip install "flake8==6.1.0" - name: Run flake8 diff --git a/.github/workflows/py_compile.yml b/.github/workflows/py_compile.yml deleted file mode 100644 index 69e785a..0000000 --- a/.github/workflows/py_compile.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Sytanx check using py_compile - -on: - push: - branches: - - main - pull_request: -jobs: - build: - runs-on: ubuntu-22.04 - timeout-minutes: 5 - strategy: - matrix: - python-version: - - "3.7" - - "3.8" - - "3.9" - - "3.10" - - "3.11" - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - pip install -U pip - pip install -e ".[testing]" - - name: Run py_compile for main code - run: | - find slack_discovery_sdk -name '*.py' | xargs python -m py_compile - - name: Run py_compile for test code - run: | - find tests -name '*.py' | xargs python -m py_compile diff --git a/.github/workflows/pytype.yml b/.github/workflows/pytype.yml index 618bd8a..e5991a7 100644 --- a/.github/workflows/pytype.yml +++ b/.github/workflows/pytype.yml @@ -26,8 +26,7 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | - pip install -U pip - pip install -e ".[testing]" + ./scripts/install.sh # As pytype can change its behavior in newer versions, we manually upgrade it pip install "pytype==2023.9.27" - name: Run pytype diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..bdd0a11 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1 @@ +include README.md LICENSE.md slack_discovery_sdk/py.typed diff --git a/README.md b/README.md index cb8a414..836665f 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ > 🚨 Note: This SDK is only accessible to customer developers with access to the Discovery API (Enterprise accounts) or partners who have been onboarded to the Security and Compliance partner program. To learn more about the Discovery APIs, please [visit our help center](https://slack.com/help/articles/360002079527-A-guide-to-Slacks-Discovery-APIs). 🚨 ## Prerequisites For Using the SDK -* Python version 3.6 or greater +* Python version 3.7 or greater * Latest version of pip * A token with discovery scopes (`discovery:read` and or `discovery:write`) > Note: Please see the [OAuth guide](https://api.slack.com/enterprise/discovery/oauth-guide) on how to get this token if you don't already have one. @@ -60,7 +60,7 @@ To view all of the methods offered by the SDK, please see the [client.py file](h In order to speed up the development process, we've provided you with a script called `set_env_vars.sh` in the scripts folder to automate a few things needed to run the SDK. The script accomplishes the following things using the following code: -* Prints your current Python version (**you will need Python version 3.6 or greater for this SDK**) +* Prints your current Python version (**you will need Python version 3.7 or greater for this SDK**) ```bash python3 --version ``` @@ -75,7 +75,7 @@ The script accomplishes the following things using the following code: ``` * Installs required packages and dependencies ```bash - pip install -e ".[testing]" + ./scripts/install.sh ``` ## 👨🏻‍💻 Adding Env Variables to Setup Script 👩🏻‍💻 @@ -238,11 +238,11 @@ And then, setting the bot / user tokens in the env variables as below: ```bash # Setup your virtual environment -python --version # make sure if you're using Python 3.6+ +python --version # make sure if you're using Python 3.7+ python -m venv .venv source .venv/bin/activate pip install -U pip -pip install -e ".[testing]" +./scripts/install.sh # Set required env variables # 1. An admin user token with discovery:read, discovery:write @@ -257,6 +257,8 @@ export SLACK_DISCOVERY_SDK_TEST_TEAM_ID=T1234567890 export SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID=C1234567890 pytest tests/ +# Without SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN, the tests that call the Discovery API are skipped + # You can check logs/pytest.log for trouble shooting ``` diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..5568e5e --- /dev/null +++ b/codecov.yml @@ -0,0 +1,8 @@ +coverage: + status: + project: + default: + threshold: 2.0% + patch: + default: + target: 50% diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a288ac6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,57 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "slack-discovery-sdk" +dynamic = ["version", "readme"] +description = "The Slack Discovery API SDK for Python" +license = { text = "MIT" } +authors = [{ name = "Slack Technologies, LLC", email = "opensource@slack.com" }] +requires-python = ">=3.7" +dependencies = [] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Topic :: Communications :: Chat", + "Topic :: Office/Business", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", +] + + +[project.urls] +Homepage = "https://github.com/slackapi/python-slack-discovery-sdk" +Documentation = "https://slack.com/help/articles/360002079527-A-guide-to-Slacks-Discovery-APIs" +Source = "https://github.com/slackapi/python-slack-discovery-sdk" + +[tool.setuptools.packages.find] +include = ["slack_discovery_sdk*"] + +[tool.setuptools.dynamic] +version = { attr = "slack_discovery_sdk.version.__version__" } +readme = { file = ["README.md"], content-type = "text/markdown" } + +[tool.pytest.ini_options] +testpaths = ["tests"] +log_file = "logs/pytest.log" +log_file_level = "DEBUG" +log_format = "%(asctime)s %(levelname)s %(message)s" +log_date_format = "%Y-%m-%d %H:%M:%S" +markers = ["live: calls the real Discovery API and needs the SLACK_DISCOVERY_SDK_TEST_* env variables"] +filterwarnings = [ + 'ignore:"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead:DeprecationWarning', + "ignore:The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.:DeprecationWarning", +] diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index db01ee0..0000000 --- a/pytest.ini +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -[pytest] -log_file = logs/pytest.log -log_file_level = DEBUG -log_format = %(asctime)s %(levelname)s %(message)s -log_date_format = %Y-%m-%d %H:%M:%S -filterwarnings = - ignore:"@coroutine" decorator is deprecated since Python 3.8, use "async def" instead:DeprecationWarning - ignore:The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.:DeprecationWarning \ No newline at end of file diff --git a/requirements/build.txt b/requirements/build.txt new file mode 100644 index 0000000..75e5969 --- /dev/null +++ b/requirements/build.txt @@ -0,0 +1,7 @@ +# pip install -r requirements/build.txt + +# twine +twine + +# build +build diff --git a/requirements/testing.txt b/requirements/testing.txt new file mode 100644 index 0000000..d8c232c --- /dev/null +++ b/requirements/testing.txt @@ -0,0 +1,15 @@ +# pip install -r requirements/testing.txt + +# slack_sdk +# Note: used by the live tests to post the messages and files that the Discovery API reads. +slack_sdk>=3.21.3,<4 + +# pytest +# Note: pytest 9 requires Python >=3.10; cap older interpreters below it. +pytest>=7.0.1,<9; python_version < "3.10" +pytest>=9.1.1,<10; python_version >= "3.10" + +# pytest-cov +# Note: pytest-cov 7.1+ requires Python >=3.9; cap older interpreters below it. +pytest-cov>=4,<7.1.0; python_version < "3.9" +pytest-cov>=7.1.0,<8; python_version >= "3.9" diff --git a/scripts/build.sh b/scripts/build.sh deleted file mode 100755 index b683a6a..0000000 --- a/scripts/build.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -script_dir=`dirname $0` -cd ${script_dir}/.. -version=`grep __version__ ./slack_discovery_sdk/version.py | awk -F'"' '{print $2}'` -while true; do - read -p "Do you wish to build a package for version ${version}? (y/N)" yn - case $yn in - [Yy]* ) make install; break;; - [Nn]* ) exit;; - * ) echo "Please answer yes or no.";; - esac -done - -pip install twine wheel && \ - rm -rf ./dist/ ./build/ *.egg-info/ && \ - python setup.py sdist bdist_wheel && \ - twine check dist/* diff --git a/scripts/build_pypi_package.sh b/scripts/build_pypi_package.sh new file mode 100755 index 0000000..7896218 --- /dev/null +++ b/scripts/build_pypi_package.sh @@ -0,0 +1,14 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Clean previous builds +rm -rf dist/ build/ slack_discovery_sdk.egg-info/ + +# Install build dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -r requirements/build.txt +fi + +# Build package +python -m build && twine check dist/* diff --git a/scripts/deploy_to_test_pypi.sh b/scripts/deploy_to_test_pypi.sh new file mode 100755 index 0000000..ac0c0e3 --- /dev/null +++ b/scripts/deploy_to_test_pypi.sh @@ -0,0 +1,8 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +./scripts/build_pypi_package.sh + +# Upload to test PyPI +twine upload --repository testpypi dist/* diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..bb50709 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,7 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +pip install -U pip +pip install -e . +pip install -r requirements/testing.txt diff --git a/scripts/run_all.sh b/scripts/run_all.sh deleted file mode 100755 index 09bbb56..0000000 --- a/scripts/run_all.sh +++ /dev/null @@ -1,18 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -#!/bin/sh - -# run enterprise info -python3 slack_discovery_sdk/examples/get_enterprise_info.py - -# run DLP -python3 slack_discovery_sdk/examples/DLP_call_pattern.py - -# run eDiscovery without edits (commented out since we will be running pattern with edits) -# python3 slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py - -# run eDiscovery -python3 slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py - -# run auditLogs -python3 slack_discovery_sdk/examples/audit_logs_pattern.py \ No newline at end of file diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh new file mode 100755 index 0000000..12ea347 --- /dev/null +++ b/scripts/run_tests.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# all: ./scripts/run_tests.sh +# single: ./scripts/run_tests.sh tests/test_rate_limit_support.py + +script_dir=$(dirname $0) +cd ${script_dir}/.. + +test_target="$1" + +# Run tests +if [[ $test_target != "" ]]; then + pytest -vv $test_target +else + pytest +fi diff --git a/scripts/set_env_vars.sh b/scripts/set_env_vars.sh index 90e2b6c..d55f929 100755 --- a/scripts/set_env_vars.sh +++ b/scripts/set_env_vars.sh @@ -2,7 +2,7 @@ #!/bin/sh -# check to make sure Python version >= 3.6 is installed +# check to make sure Python version >= 3.7 is installed echo "Your current Python version is: " python3 --version @@ -19,7 +19,7 @@ echo "Sucessfully updated pip" # Installs required packages and dependencies echo "Installing required packages" -pip install -e ".[testing]" +./scripts/install.sh echo "Sucessfully installed required packages" ############# Needed to run SDK #################################### diff --git a/scripts/uninstall_all.sh b/scripts/uninstall_all.sh new file mode 100755 index 0000000..be0fea0 --- /dev/null +++ b/scripts/uninstall_all.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +pip uninstall -y slack-discovery-sdk + +PACKAGES=$(pip freeze | grep -v "^-e" | sed 's/@.*//' | sed 's/\=\=.*//') + +for package in $PACKAGES; do + pip uninstall -y $package +done diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 5cfff35..0000000 --- a/setup.cfg +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -[bdist_wheel] -universal = 1 - -[aliases] -test=pytest \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 79ccce4..0000000 --- a/setup.py +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright 2021, Slack Technologies, LLC. All rights reserved. - -#!/usr/bin/env python -import os - -import setuptools - -here = os.path.abspath(os.path.dirname(__file__)) - -__version__ = None -exec(open(f"{here}/slack_discovery_sdk/version.py").read()) - -with open(f"{here}/README.md", "r") as fh: - long_description = fh.read() - -test_dependencies = [ - "slack_sdk>=3.21.3,<4", - "pytest>=6,<7", - "pytest-cov>=3,<4", - "black==22.8.0", # 22.10.0 or newer no longer exist for Python 3.6 -] - -setuptools.setup( - name="slack-discovery-sdk", - version=__version__, - author="Slack Technologies, LLC", - description="The Slack Discovery API SDK for Python", - long_description=long_description, - long_description_content_type="text/markdown", - packages=setuptools.find_packages( - exclude=[ - "tests", - "tests.*", - ] - ), - include_package_data=True, # MANIFEST.in - install_requires=[], - setup_requires=["pytest-runner==5.2"], - tests_require=test_dependencies, - test_suite="tests", - extras_require={ - # pip install -e ".[testing]" - "testing": test_dependencies, - }, - classifiers=[ - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: Implementation :: CPython", - "Operating System :: OS Independent", - ], - python_requires=">=3.6", -) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..7a247dc --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,14 @@ +import os + +import pytest + +from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN + + +def pytest_collection_modifyitems(items): + if os.environ.get(SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN): + return + skip_live = pytest.mark.skip(reason=f"{SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN} is not set") + for item in items: + if "live" in item.keywords: + item.add_marker(skip_live) diff --git a/tests/test_chat.py b/tests/test_chat.py index 220bf8c..b698ae0 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_sdk import WebClient from slack_discovery_sdk import DiscoveryClient from .env_variable_names import ( @@ -11,6 +12,7 @@ ) +@pytest.mark.live class TestChat: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_conversations.py b/tests/test_conversations.py index 4eb0a05..dc4f3db 100644 --- a/tests/test_conversations.py +++ b/tests/test_conversations.py @@ -16,6 +16,7 @@ ) +@pytest.mark.live class TestConversations: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_draft.py b/tests/test_draft.py index c196ddf..ea038ff 100644 --- a/tests/test_draft.py +++ b/tests/test_draft.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import ( SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN, @@ -9,6 +10,7 @@ ) +@pytest.mark.live class TestDraft: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_enterprise.py b/tests/test_enterprise.py index feeb2b2..5579d99 100644 --- a/tests/test_enterprise.py +++ b/tests/test_enterprise.py @@ -1,10 +1,12 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN +@pytest.mark.live class TestEnterprise: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_file.py b/tests/test_file.py index 2610fb8..ed9ca49 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from slack_discovery_sdk.response import DiscoveryResponse from slack_sdk import WebClient @@ -12,6 +13,7 @@ ) +@pytest.mark.live class TestFile: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_rate_limit_scenario.py b/tests/test_rate_limit_scenario.py index a957ca1..97881bc 100644 --- a/tests/test_rate_limit_scenario.py +++ b/tests/test_rate_limit_scenario.py @@ -8,6 +8,7 @@ from concurrent.futures.thread import ThreadPoolExecutor +@pytest.mark.live class TestEnterprise: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] diff --git a/tests/test_users.py b/tests/test_users.py index cfee420..9be52b7 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -1,10 +1,12 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. import os +import pytest from slack_discovery_sdk import DiscoveryClient from tests.env_variable_names import SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN +@pytest.mark.live class TestUsers: def setup_method(self): self.token = os.environ[SLACK_DISCOVERY_SDK_TEST_ENTERPRISE_TOKEN] From 4dad4a3ab0302a57db8abf3dff68ae0c5ec565aa Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 14:06:53 -0500 Subject: [PATCH 2/4] build: use pep 639 license metadata and drop pypy The license is now an SPDX expression with LICENSE.md as its license file. This needs setuptools 77 or newer, which runs on Python 3.9+, so the package is built on the latest Python. The py3-none-any wheel still installs on 3.7+. Because of this, the unit test jobs and install.sh no longer install the package (that would build it on 3.7/3.8). The tests import it from source, as in python-slack-sdk. MANIFEST.in is dropped: setuptools already ships README.md, LICENSE.md, and py.typed. PyPy is dropped from the classifiers and the test matrix since it isn't tested. Co-Authored-By: Claude --- .github/workflows/ci-build.yml | 2 -- MANIFEST.in | 1 - pyproject.toml | 7 +++---- scripts/install.sh | 1 - 4 files changed, 3 insertions(+), 8 deletions(-) delete mode 100644 MANIFEST.in diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 938ce38..120a4f1 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -30,7 +30,6 @@ jobs: - "3.13" - "3.14" - "3.15" - - "pypy3.10" permissions: contents: read steps: @@ -44,7 +43,6 @@ jobs: - name: Install dependencies run: | pip install -U pip - pip install -e . pip install -r requirements/testing.txt - name: Run tests run: | diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index bdd0a11..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1 +0,0 @@ -include README.md LICENSE.md slack_discovery_sdk/py.typed diff --git a/pyproject.toml b/pyproject.toml index a288ac6..ec82611 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,13 @@ [build-system] -requires = ["setuptools"] +requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" [project] name = "slack-discovery-sdk" dynamic = ["version", "readme"] description = "The Slack Discovery API SDK for Python" -license = { text = "MIT" } +license = "MIT" +license-files = ["LICENSE.md"] authors = [{ name = "Slack Technologies, LLC", email = "opensource@slack.com" }] requires-python = ">=3.7" dependencies = [] @@ -15,7 +16,6 @@ classifiers = [ "Intended Audience :: Developers", "Topic :: Communications :: Chat", "Topic :: Office/Business", - "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", @@ -28,7 +28,6 @@ classifiers = [ "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", ] diff --git a/scripts/install.sh b/scripts/install.sh index bb50709..8150c3c 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -3,5 +3,4 @@ script_dir=$(dirname $0) cd ${script_dir}/.. pip install -U pip -pip install -e . pip install -r requirements/testing.txt From aa614b862e9263e77b788b2e59420c42a51bc37f Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Tue, 17 Nov 2026 14:30:07 -0500 Subject: [PATCH 3/4] build: drop the setuptools 77 floor and restore run_all.sh The license goes back to license = { text = "MIT" }, like python-slack-sdk, bolt-python, and python-slack-hooks. Without the PEP 639 form, setuptools no longer needs to be 77 or newer, so the package builds and installs from source on 3.7 and 3.8 again. That lets install.sh run pip install -e . once more, so the README setup flow can import the SDK when running the examples. run_all.sh is restored because the README still points to it for running every example. Co-Authored-By: Claude --- pyproject.toml | 6 +++--- scripts/install.sh | 1 + scripts/run_all.sh | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) create mode 100755 scripts/run_all.sh diff --git a/pyproject.toml b/pyproject.toml index ec82611..0e6f728 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,12 @@ [build-system] -requires = ["setuptools>=77"] +requires = ["setuptools"] build-backend = "setuptools.build_meta" [project] name = "slack-discovery-sdk" dynamic = ["version", "readme"] description = "The Slack Discovery API SDK for Python" -license = "MIT" -license-files = ["LICENSE.md"] +license = { text = "MIT" } authors = [{ name = "Slack Technologies, LLC", email = "opensource@slack.com" }] requires-python = ">=3.7" dependencies = [] @@ -16,6 +15,7 @@ classifiers = [ "Intended Audience :: Developers", "Topic :: Communications :: Chat", "Topic :: Office/Business", + "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.7", diff --git a/scripts/install.sh b/scripts/install.sh index 8150c3c..bb50709 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -3,4 +3,5 @@ script_dir=$(dirname $0) cd ${script_dir}/.. pip install -U pip +pip install -e . pip install -r requirements/testing.txt diff --git a/scripts/run_all.sh b/scripts/run_all.sh new file mode 100755 index 0000000..09bbb56 --- /dev/null +++ b/scripts/run_all.sh @@ -0,0 +1,18 @@ +# Copyright 2021, Slack Technologies, LLC. All rights reserved. + +#!/bin/sh + +# run enterprise info +python3 slack_discovery_sdk/examples/get_enterprise_info.py + +# run DLP +python3 slack_discovery_sdk/examples/DLP_call_pattern.py + +# run eDiscovery without edits (commented out since we will be running pattern with edits) +# python3 slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py + +# run eDiscovery +python3 slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py + +# run auditLogs +python3 slack_discovery_sdk/examples/audit_logs_pattern.py \ No newline at end of file From 34d69643a3fb90f2266871d03247570d7dc6f237 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Tue, 17 Nov 2026 14:43:18 -0500 Subject: [PATCH 4/4] build: replace black and flake8 with ruff (#53) Co-authored-by: Claude --- .flake8 | 5 - .github/workflows/ci-build.yml | 17 ++ .github/workflows/flake8.yml | 34 ---- pyproject.toml | 23 +++ requirements/dev-tools.txt | 4 + scripts/format.sh | 12 ++ scripts/install.sh | 1 + scripts/lint.sh | 11 ++ scripts/run_tests.sh | 2 + slack_discovery_sdk/__init__.py | 7 +- slack_discovery_sdk/base_client.py | 80 +++----- slack_discovery_sdk/client.py | 173 ++++++++---------- slack_discovery_sdk/errors.py | 4 +- .../examples/DLP_call_pattern.py | 11 +- slack_discovery_sdk/examples/__init__.py | 7 +- .../examples/audit_logs_pattern.py | 4 +- .../examples/get_enterprise_info.py | 3 +- .../examples/user_based_eDiscovery_pattern.py | 8 +- .../user_based_eDiscovery_with_edits.py | 12 +- slack_discovery_sdk/examples/utils.py | 15 +- slack_discovery_sdk/internal_utils.py | 28 +-- slack_discovery_sdk/proxy_support.py | 7 +- slack_discovery_sdk/rate_limit_support.py | 34 +--- slack_discovery_sdk/response.py | 32 ++-- tests/test_chat.py | 12 +- tests/test_conversations.py | 86 +++------ tests/test_draft.py | 4 +- tests/test_file.py | 35 +--- tests/test_rate_limit_scenario.py | 8 +- tests/test_rate_limit_support.py | 9 +- 30 files changed, 292 insertions(+), 396 deletions(-) delete mode 100644 .flake8 delete mode 100644 .github/workflows/flake8.yml create mode 100644 requirements/dev-tools.txt create mode 100755 scripts/format.sh create mode 100755 scripts/lint.sh diff --git a/.flake8 b/.flake8 deleted file mode 100644 index b325547..0000000 --- a/.flake8 +++ /dev/null @@ -1,5 +0,0 @@ -[flake8] -max-line-length = 125 -# E401: We are fine with multiple imports in a line -# W503: This rule is not compatible with black (code formatter) -ignore = E401,W503 \ No newline at end of file diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 120a4f1..dd4437b 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -13,6 +13,23 @@ env: LATEST_SUPPORTED_PY: "3.15" jobs: + lint: + name: Lint + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Set up Python ${{ env.LATEST_SUPPORTED_PY }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ env.LATEST_SUPPORTED_PY }} + - name: Run lint verification + run: ./scripts/lint.sh + unittest: name: Unit tests runs-on: ubuntu-22.04 diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml deleted file mode 100644 index 8bf6459..0000000 --- a/.github/workflows/flake8.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Lint validation using flake8 - -on: - push: - branches: - - main - pull_request: - -jobs: - build: - runs-on: ubuntu-latest - timeout-minutes: 5 - strategy: - matrix: - python-version: - - "3.9" - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - ./scripts/install.sh - # We manually upgrade it to make the builds stable - pip install "flake8==6.1.0" - - name: Run flake8 - run: | - flake8 slack_discovery_sdk/ diff --git a/pyproject.toml b/pyproject.toml index 0e6f728..4441033 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,29 @@ include = ["slack_discovery_sdk*"] version = { attr = "slack_discovery_sdk.version.__version__" } readme = { file = ["README.md"], content-type = "text/markdown" } +[tool.ruff] +line-length = 125 + +[tool.ruff.lint] +select = ["E", "W", "F", "D"] +ignore = [ + # missing-docstring: do not add docstrings where none exist + "D100", + "D101", + "D102", + "D103", + "D104", + "D105", + "D106", + "D107", +] + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.format] +docstring-code-format = true + [tool.pytest.ini_options] testpaths = ["tests"] log_file = "logs/pytest.log" diff --git a/requirements/dev-tools.txt b/requirements/dev-tools.txt new file mode 100644 index 0000000..c8d26c9 --- /dev/null +++ b/requirements/dev-tools.txt @@ -0,0 +1,4 @@ +# pip install -r requirements/dev-tools.txt + +# ruff +ruff==0.17.4 diff --git a/scripts/format.sh b/scripts/format.sh new file mode 100755 index 0000000..79ff8fc --- /dev/null +++ b/scripts/format.sh @@ -0,0 +1,12 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Install dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -U pip + pip install -r requirements/dev-tools.txt +fi + +ruff check --fix slack_discovery_sdk/ tests/ +ruff format slack_discovery_sdk/ tests/ diff --git a/scripts/install.sh b/scripts/install.sh index bb50709..94284f0 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -5,3 +5,4 @@ cd ${script_dir}/.. pip install -U pip pip install -e . pip install -r requirements/testing.txt +pip install -r requirements/dev-tools.txt diff --git a/scripts/lint.sh b/scripts/lint.sh new file mode 100755 index 0000000..dd6b35c --- /dev/null +++ b/scripts/lint.sh @@ -0,0 +1,11 @@ +#!/bin/bash +script_dir=$(dirname $0) +cd ${script_dir}/.. + +# Install dependencies unless --no-install is specified +if [[ "$1" != "--no-install" ]]; then + pip install -U pip + pip install -r requirements/dev-tools.txt +fi + +ruff check slack_discovery_sdk/ tests/ && ruff format --check slack_discovery_sdk/ tests/ diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh index 12ea347..1df5ab5 100755 --- a/scripts/run_tests.sh +++ b/scripts/run_tests.sh @@ -7,6 +7,8 @@ cd ${script_dir}/.. test_target="$1" +./scripts/format.sh --no-install + # Run tests if [[ $test_target != "" ]]; then pytest -vv $test_target diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index 1ea2b8d..4af1680 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -1,8 +1,11 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. # pytype: skip-file -"""The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box.""" +"""The Slack Web API allows you to build applications that interact with Slack. + +It lets you interact with Slack in more complex ways than the integrations we provide out of the box. +""" + from .client import DiscoveryClient from .oauth import DiscoveryOAuthApp diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index c8fef57..8120919 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -66,9 +66,7 @@ def __init__( self.ssl = ssl self.proxy = proxy self.headers = headers or {} - self.headers["User-Agent"] = get_user_agent( - user_agent_prefix, user_agent_suffix - ) + self.headers["User-Agent"] = get_user_agent(user_agent_prefix, user_agent_suffix) self.default_params = {} if team_id is not None: self.default_params["team_id"] = team_id @@ -100,6 +98,7 @@ def api_call( # skipcq: PYL-R1710 auth: Optional[dict] = None, ) -> DiscoveryResponse: """Create a request and execute the API call to Slack. + Args: api_method (str): The target Slack API method. e.g. 'discovery.enterprise.info' @@ -115,11 +114,11 @@ def api_call( # skipcq: PYL-R1710 from the response can be accessed like a dict. If the response included 'next_cursor' it can be iterated on to execute subsequent requests. + Raises: SlackApiError: The following Slack API call failed: 'discovery.enterprise.info'. """ - api_url = _get_url(self.base_url, api_method) headers = headers or {} headers.update(self.headers) @@ -130,14 +129,10 @@ def api_call( # skipcq: PYL-R1710 headers["Authorization"] = auth elif isinstance(auth, dict): client_id, client_secret = auth["client_id"], auth["client_secret"] - value = b64encode( - f"{client_id}:{client_secret}".encode("utf-8") - ).decode("ascii") + value = b64encode(f"{client_id}:{client_secret}".encode("utf-8")).decode("ascii") headers["Authorization"] = f"Basic {value}" else: - self.logger.warning( - f"As the auth: {auth}: {type(auth)} is unsupported, skipped" - ) + self.logger.warning(f"As the auth: {auth}: {type(auth)} is unsupported, skipped") token = self.token params = params or {} @@ -162,7 +157,8 @@ def fetch_next_page( headers: Dict[str, str], params: Dict[str, str], ) -> Dict[str, any]: # type:ignore - """This method is supposed to be used only for DiscoveryResponse pagination + """This method is supposed to be used only for DiscoveryResponse pagination. + You can paginate using Python's for iterator as below: for response in client.conversations_list(limit=100): # do something with each response here @@ -189,15 +185,16 @@ def _urllib_api_call( additional_headers: Dict[str, str], ) -> DiscoveryResponse: """Performs a Slack API request and returns the result. + Args: token: Slack API Token (either bot token or user token) + http_method: HTTP method (e.g., POST) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) params: Form body params additional_headers: Request headers to append Returns: API response """ - # True/False -> "1"/"0" params = convert_bool_to_0_or_1(params) request_headers = self._build_urllib_request_headers( @@ -240,15 +237,16 @@ def _perform_urllib_http_request( params: Dict[str, str], ) -> Dict[str, any]: # type:ignore """Performs an HTTP request and parses the response. + Args: + http_method: HTTP method (e.g., POST) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) - args: args has "headers" and "params" - "headers": Dict[str, str] - "params": Dict[str, str], + headers: Request headers + params: Form body params + Returns: dict {status: int, headers: Headers, body: str} """ - url_elements = url.split("/") if len(url_elements) >= 2: api_method = url_elements[-1].split("?")[0] # remove query string @@ -280,16 +278,10 @@ def _perform_urllib_http_request( headers=headers, ) elif http_method == "GET": - url = ( - f"{url}&{url_encoded_params}" - if "?" in url - else f"{url}?{url_encoded_params}" - ) + url = f"{url}&{url_encoded_params}" if "?" in url else f"{url}?{url_encoded_params}" req = Request(method="GET", url=url, headers=headers) else: - raise DiscoveryRequestError( - f"Unsupported HTTP method: {http_method}" - ) + raise DiscoveryRequestError(f"Unsupported HTTP method: {http_method}") opener: Optional[OpenerDirector] = None if self.proxy is not None: @@ -299,9 +291,7 @@ def _perform_urllib_http_request( HTTPSHandler(context=self.ssl), ) else: - raise DiscoveryRequestError( - f"Invalid proxy detected: {self.proxy} must be a str value" - ) + raise DiscoveryRequestError(f"Invalid proxy detected: {self.proxy} must be a str value") # NOTE: BAN-B310 is already checked above resp: Optional[HTTPResponse] = None @@ -313,9 +303,7 @@ def _perform_urllib_http_request( ) charset = resp.headers.get_content_charset() or "utf-8" - url_encoded_params: str = resp.read().decode( - charset - ) # read the response body here + url_encoded_params: str = resp.read().decode(charset) # read the response body here self._print_response_debug_log( status_code=resp.code, headers=resp.headers, @@ -387,19 +375,11 @@ def _print_request_debug_log( def convert_params(values: dict) -> dict: if not values or not isinstance(values, dict): return {} - return { - k: ("(bytes)" if isinstance(v, bytes) else v) - for k, v in values.items() - } + return {k: ("(bytes)" if isinstance(v, bytes) else v) for k, v in values.items()} - headers = { - k: "(redacted)" if k.lower() == "authorization" else v - for k, v in headers.items() - } + headers = {k: "(redacted)" if k.lower() == "authorization" else v for k, v in headers.items()} self.logger.debug( - f"Sending a request - {http_method} {url}, " - f"params: {convert_params(params)}, " - f"headers: {headers}" + f"Sending a request - {http_method} {url}, params: {convert_params(params)}, headers: {headers}" ) def _print_response_debug_log( @@ -411,22 +391,14 @@ def _print_response_debug_log( ): if status_code >= 400: self.logger.error( - "Received the following response - " - f"status: {status_code}, " - f"headers: {dict(headers)}, " - f"body: {body}" + f"Received the following response - status: {status_code}, headers: {dict(headers)}, body: {body}" ) elif self.logger.level <= logging.DEBUG: self.logger.debug( - "Received the following response - " - f"status: {status_code}, " - f"headers: {dict(headers)}, " - f"body: {body}" + f"Received the following response - status: {status_code}, headers: {dict(headers)}, body: {body}" ) - def _build_urllib_request_headers( - self, *, token: str, additional_headers: dict - ) -> Dict[str, str]: + def _build_urllib_request_headers(self, *, token: str, additional_headers: dict) -> Dict[str, str]: headers = {"Content-Type": "application/x-www-form-urlencoded"} headers.update(self.headers) if token: @@ -442,9 +414,7 @@ def _do_stuff_for_rate_limit_error_prevention( ): if self.rate_limit_error_prevention_enabled is True: # Check the current traffic - sleep_duration: float = self.rate_limiter.calculate_sleep_duration( - api_method - ) + sleep_duration: float = self.rate_limiter.calculate_sleep_duration(api_method) if self.logger.level <= logging.DEBUG: report = self.rate_limiter.generate_metrics_report() self.logger.debug(f"""Rate limit metrics: {report}""") diff --git a/slack_discovery_sdk/client.py b/slack_discovery_sdk/client.py index ba746b9..05dd924 100644 --- a/slack_discovery_sdk/client.py +++ b/slack_discovery_sdk/client.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. """A Python module for interacting with Slack's Discovery APIs.""" + from typing import Optional, Union from .base_client import BaseDiscoveryClient # type:ignore @@ -10,11 +11,13 @@ class DiscoveryClient(BaseDiscoveryClient): """A DiscoveryClient allows apps to communicate with the Slack Platform's Discovery APIs. + https://api.slack.com/enterprise/discovery/methods """ def auth_test(self, **kwargs) -> DiscoveryResponse: """Checks authentication & identity. + Refer to https://api.slack.com/methods/auth.test for more details. """ return self.api_call("auth.test", http_method="POST", params=kwargs) @@ -35,6 +38,7 @@ def oauth_v2_access( **kwargs, ) -> DiscoveryResponse: """Exchanges a temporary OAuth verifier code for an access token. + Refer to https://api.slack.com/methods/oauth.v2.access for more details. """ if redirect_uri is not None: @@ -65,8 +69,9 @@ def discovery_enterprise_info( include_deleted: Optional[bool] = None, **kwargs, ) -> DiscoveryResponse: - """This method returns basic information about the Enterprise Grid org - where the app is installed, including all workspaces (teams). + """This method returns basic information about the Enterprise Grid org where the app is installed. + + It includes all workspaces (teams). The teams array is paged at 1000 items by default, but this can also be shortened with the limit parameter. Refer to https://api.slack.com/enterprise/discovery/methods#enterprise_info for more details. """ @@ -78,9 +83,7 @@ def discovery_enterprise_info( "include_deleted": include_deleted, } ) - return self.api_call( - "discovery.enterprise.info", http_method="GET", params=kwargs - ) + return self.api_call("discovery.enterprise.info", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.users @@ -95,8 +98,9 @@ def discovery_users_list( offset: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Very similar to regular users.list method. Includes an array of workspace IDs - that the user belongs to on a Grid org (teams). + """Very similar to regular users.list method. + + Includes an array of workspace IDs that the user belongs to on a Grid org (teams). Refer to https://api.slack.com/enterprise/discovery/methods#users_list for more details. """ kwargs.update( @@ -118,6 +122,7 @@ def discovery_user_info( **kwargs, ) -> DiscoveryResponse: """Get information on a single user in an Enterprise. + The processes for getting info about internal and external users are slightly different. Refer to https://api.slack.com/enterprise/discovery/methods#user_info for more details. """ @@ -138,8 +143,9 @@ def discovery_user_conversations( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """This method lists IDs for all conversations (channels and DMs, including public, private, - org-wide, and shared) a user is in. + """This method lists IDs for all conversations a user is in. + + This includes channels and DMs: public, private, org-wide, and shared. Refer to https://api.slack.com/enterprise/discovery/methods#user_conversations for more details. """ kwargs.update( @@ -157,9 +163,7 @@ def discovery_user_conversations( if offset is not None: kwargs.update({"offset": offset}) - return self.api_call( - "discovery.user.conversations", http_method="GET", params=kwargs - ) + return self.api_call("discovery.user.conversations", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.conversations @@ -174,17 +178,16 @@ def discovery_conversations_recent( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """By default this method will return all updated conversations - (including org-shared and externally-shared conversations) + """This method returns the conversations updated across the Grid org. + + By default it returns all updated conversations (including org-shared and externally-shared conversations) from the entire Grid org for the 24 hours preceding the call. You can restrict it to a specific workspace within an org, a smaller timespan, or to return data for the last 7 days by using the optional parameters. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_recent for more details. """ kwargs.update({"token": token, "team": team, "latest": latest, "limit": limit}) - return self.api_call( - "discovery.conversations.recent", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.recent", http_method="GET", params=kwargs) def discovery_conversations_list( self, @@ -200,8 +203,9 @@ def discovery_conversations_list( limit: Optional[int] = None, **kwargs, ) -> DiscoveryResponse: - """This method provides a paginated list of all conversations (channels, private channels/groups, DMs), - with just a subset of the channel information. + """This method provides a paginated list of all conversations. + + It covers channels, private channels/groups, and DMs, with just a subset of the channel information. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_list for more details. """ kwargs.update( @@ -217,9 +221,7 @@ def discovery_conversations_list( "limit": limit, } ) - return self.api_call( - "discovery.conversations.list", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.list", http_method="GET", params=kwargs) def discovery_conversations_history( self, @@ -234,15 +236,14 @@ def discovery_conversations_history( **kwargs, ) -> DiscoveryResponse: """Retrieves the history of the channel-object. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_history for more details. """ if reactions is not None: if isinstance(reactions, (int, str)): reactions = int(reactions) == 1 if not isinstance(reactions, bool): - raise DiscoveryRequestError( - f"Unexpected value type for reactions {type(reactions).__name__}" - ) + raise DiscoveryRequestError(f"Unexpected value type for reactions {type(reactions).__name__}") kwargs.update( { "token": token, @@ -254,9 +255,7 @@ def discovery_conversations_history( "limit": limit, } ) - return self.api_call( - "discovery.conversations.history", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.history", http_method="GET", params=kwargs) def discovery_conversations_edits( self, @@ -270,6 +269,7 @@ def discovery_conversations_edits( **kwargs, ) -> DiscoveryResponse: """This method will only return edit and delete records of messages. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_edits for more details. """ kwargs.update( @@ -282,9 +282,7 @@ def discovery_conversations_edits( "limit": limit, } ) - return self.api_call( - "discovery.conversations.edits", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.edits", http_method="GET", params=kwargs) def discovery_conversations_info( self, @@ -296,6 +294,7 @@ def discovery_conversations_info( **kwargs, ) -> DiscoveryResponse: """This method provides a comprehensive overview of a single channel outside of its message history. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_info for more details. """ kwargs.update( @@ -306,9 +305,7 @@ def discovery_conversations_info( "offset": offset, } ) - return self.api_call( - "discovery.conversations.info", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.info", http_method="GET", params=kwargs) def discovery_conversations_members( self, @@ -322,6 +319,7 @@ def discovery_conversations_members( **kwargs, ) -> DiscoveryResponse: """This method provides a list of everyone in a given channel, private channel, MDPM or DM. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_members for more details. """ kwargs.update( @@ -334,9 +332,7 @@ def discovery_conversations_members( "limit": limit, } ) - return self.api_call( - "discovery.conversations.members", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.members", http_method="GET", params=kwargs) def discovery_conversations_renames( self, @@ -348,8 +344,9 @@ def discovery_conversations_renames( private: Optional[bool] = None, **kwargs, ) -> DiscoveryResponse: - """You can use this endpoint to gather all channel renames that have occured for an org, - without having to call the discovery.conversations.info endpoint for each channel. + """You can use this endpoint to gather all channel renames that have occured for an org. + + This avoids calling the discovery.conversations.info endpoint for each channel. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_renames for more details. """ kwargs.update( @@ -361,9 +358,7 @@ def discovery_conversations_renames( "private": private, } ) - return self.api_call( - "discovery.conversations.renames", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.renames", http_method="GET", params=kwargs) def discovery_conversations_reactions( self, @@ -377,6 +372,7 @@ def discovery_conversations_reactions( **kwargs, ) -> DiscoveryResponse: """Use this method to gather detailed information about current message reactions in a channel. + Refer to https://api.slack.com/enterprise/discovery/methods#conversations_reactions for more details. """ kwargs.update( @@ -389,9 +385,7 @@ def discovery_conversations_reactions( "limit": limit, } ) - return self.api_call( - "discovery.conversations.reactions", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.reactions", http_method="GET", params=kwargs) def discovery_conversations_search( self, @@ -406,8 +400,9 @@ def discovery_conversations_search( offset: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """The discovery.conversations.search endpoint can be used to find channels and messages within an - instance that contain the provided search term. + """The discovery.conversations.search endpoint can be used to find channels and messages. + + It returns those within an instance that contain the provided search term. Refer to https://api.slack.com/enterprise/discovery/methods#conversations_search for more details. """ kwargs.update( @@ -422,9 +417,7 @@ def discovery_conversations_search( "offset": offset, } ) - return self.api_call( - "discovery.conversations.search", http_method="GET", params=kwargs - ) + return self.api_call("discovery.conversations.search", http_method="GET", params=kwargs) # ------------------------------------------------ # discovery.chat @@ -439,11 +432,11 @@ def discovery_chat_info( team: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """This endpoint returns a single message. If the message has been edited (or deleted), - this method returns the current, edited (or deleted) message. + """This endpoint returns a single message. + + If the message has been edited (or deleted), this method returns the current, edited (or deleted) message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_info for more details. """ - kwargs.update( { "token": token, @@ -465,11 +458,11 @@ def discovery_chat_update( attachments: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Use this method for quarantine and restoration. This method specifies text or attachments that - should be included in place of the message. + """Use this method for quarantine and restoration. + + This method specifies text or attachments that should be included in place of the message. Refer to https://api.slack.com/enterprise/discovery/methods#chat_update for more details. """ - kwargs.update( { "token": token, @@ -492,9 +485,9 @@ def discovery_chat_delete( **kwargs, ) -> DiscoveryResponse: """Deletes a message. This method purges the history, edits, and message from the Slack databases. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_delete for more details. """ - kwargs.update( { "token": token, @@ -516,9 +509,9 @@ def discovery_chat_tombstone( **kwargs, ) -> DiscoveryResponse: """Use this method to update and or obscure a message in the event that the message violated policy. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_tombstone for more details. """ - kwargs.update( { "token": token, @@ -528,9 +521,7 @@ def discovery_chat_tombstone( "content": content, } ) - return self.api_call( - "discovery.chat.tombstone", http_method="POST", params=kwargs - ) + return self.api_call("discovery.chat.tombstone", http_method="POST", params=kwargs) def discovery_chat_restore( self, @@ -542,9 +533,9 @@ def discovery_chat_restore( **kwargs, ) -> DiscoveryResponse: """Use this method to restore a tombstoned message to the client. + Refer to https://api.slack.com/enterprise/discovery/methods#chat_restore for more details. """ - kwargs.update( { "token": token, @@ -553,9 +544,7 @@ def discovery_chat_restore( "team": team, } ) - return self.api_call( - "discovery.chat.restore", http_method="POST", params=kwargs - ) + return self.api_call("discovery.chat.restore", http_method="POST", params=kwargs) # ------------------------------------------------ # discovery.draft @@ -573,9 +562,9 @@ def discovery_drafts_list( **kwargs, ) -> DiscoveryResponse: """The discovery.drafts.list method returns a list of drafts created upon the specified team. + Refer to https://api.slack.com/enterprise/discovery/methods#drafts_list for more details. """ - kwargs.update( { "token": token, @@ -602,9 +591,9 @@ def discovery_draft_info( **kwargs, ) -> DiscoveryResponse: """The discovery.draft.info endpoint provides information associated with a singular draft. + Refer to https://api.slack.com/enterprise/discovery/methods#drafts_info for more details. """ - kwargs.update( { "token": token, @@ -634,9 +623,9 @@ def discovery_files_list( **kwargs, ) -> DiscoveryResponse: """This method returns files uploaded within a specified timeframe. + Refer to https://api.slack.com/enterprise/discovery/methods#files_list for more details. """ - kwargs.update( { "token": token, @@ -648,13 +637,11 @@ def discovery_files_list( ) return self.api_call("discovery.files.list", http_method="GET", params=kwargs) - def discovery_file_info( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_info(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """All file comments are shown here. File comments are Slack's odd message type. + Refer to https://api.slack.com/enterprise/discovery/methods#file_info for more details. """ - kwargs.update({"token": token, "file": file}) return self.api_call("discovery.file.info", http_method="GET", params=kwargs) @@ -667,22 +654,17 @@ def discovery_file_tombstone( content: Optional[str] = None, **kwargs, ) -> DiscoveryResponse: - """Tombstone a file, making it inaccessible. Download the file in advance for inspection, - because it will not be accessible after tombstoning. + """Tombstone a file, making it inaccessible. + + Download the file in advance for inspection, because it will not be accessible after tombstoning. Refer to https://api.slack.com/enterprise/discovery/methods#file_tombstone for more details. """ + kwargs.update({"token": token, "file": file, "title": title, "content": content}) + return self.api_call("discovery.file.tombstone", http_method="POST", params=kwargs) - kwargs.update( - {"token": token, "file": file, "title": title, "content": content} - ) - return self.api_call( - "discovery.file.tombstone", http_method="POST", params=kwargs - ) - - def discovery_file_restore( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_restore(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Restores a tombstoned file, making it accessible again. + Refer to https://api.slack.com/enterprise/discovery/methods#file_restore for more details. """ kwargs.update( @@ -691,14 +673,11 @@ def discovery_file_restore( "file": file, } ) - return self.api_call( - "discovery.file.restore", http_method="POST", params=kwargs - ) + return self.api_call("discovery.file.restore", http_method="POST", params=kwargs) - def discovery_file_delete( - self, *, token: Optional[str] = None, file: str, **kwargs - ) -> DiscoveryResponse: + def discovery_file_delete(self, *, token: Optional[str] = None, file: str, **kwargs) -> DiscoveryResponse: """Deletes a file. + Refer to https://api.slack.com/enterprise/discovery/methods#file_delete for more details. """ kwargs.update( @@ -709,11 +688,11 @@ def discovery_file_delete( ) return self.api_call("discovery.file.delete", http_method="POST", params=kwargs) - def discovery_files_release( - self, *, token: Optional[str] = None, files: str, **kwargs - ) -> DiscoveryResponse: - """The discovery.files.release endpoint can be used to release files that that been auto-tombstoned by the - pre-processing setting. The endpoint accepts an array of files that should be released for viewing in the UI. + def discovery_files_release(self, *, token: Optional[str] = None, files: str, **kwargs) -> DiscoveryResponse: + """The discovery.files.release endpoint can be used to release files that have been auto-tombstoned. + + Files are auto-tombstoned by the pre-processing setting. + The endpoint accepts an array of files that should be released for viewing in the UI. Refer to https://api.slack.com/enterprise/discovery/methods#files_release for more details. """ kwargs.update( @@ -722,6 +701,4 @@ def discovery_files_release( "files": files, } ) - return self.api_call( - "discovery.files.release", http_method="POST", params=kwargs - ) + return self.api_call("discovery.files.release", http_method="POST", params=kwargs) diff --git a/slack_discovery_sdk/errors.py b/slack_discovery_sdk/errors.py index 8a011b9..2ccb63e 100644 --- a/slack_discovery_sdk/errors.py +++ b/slack_discovery_sdk/errors.py @@ -1,10 +1,10 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -"""Errors that can be raised by this SDK""" +"""Errors that can be raised by this SDK.""" class DiscoveryClientError(Exception): - """Base class for Client errors""" + """Base class for Client errors.""" class DiscoveryRequestError(DiscoveryClientError): diff --git a/slack_discovery_sdk/examples/DLP_call_pattern.py b/slack_discovery_sdk/examples/DLP_call_pattern.py index 8bcbdf9..582588b 100644 --- a/slack_discovery_sdk/examples/DLP_call_pattern.py +++ b/slack_discovery_sdk/examples/DLP_call_pattern.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os +import logging +import os from slack_discovery_sdk import DiscoveryClient # type: ignore from slack_sdk import WebClient @@ -34,15 +35,11 @@ # conversation from each channel for conversation in last_24_hour_conversations["channels"]: - channel_conversation = client.discovery_conversations_history( - channel=conversation["id"], team=conversation["team"] - ) + channel_conversation = client.discovery_conversations_history(channel=conversation["id"], team=conversation["team"]) for message in channel_conversation["messages"]: # Step 3 - check each message and see if it contains a credit card number. If it does, tombstone the message. # A valid credit card for our logic is something like the following: '5122-2368-7954-3214' # Please note this is just example logic, to help you understand how to use the Discovery APIs. if is_credit_card_number(message["text"]): - client.discovery_chat_tombstone( - ts=message["ts"], channel=conversation["id"], team=message["team"] - ) + client.discovery_chat_tombstone(ts=message["ts"], channel=conversation["id"], team=message["team"]) diff --git a/slack_discovery_sdk/examples/__init__.py b/slack_discovery_sdk/examples/__init__.py index 39da80d..5f7f331 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -1,7 +1,10 @@ # # Copyright 2021, Slack Technologies, LLC. All rights reserved. # pytype: skip-file -"""The Slack Web API allows you to build applications that interact with Slack -in more complex ways than the integrations we provide out of the box.""" +"""The Slack Web API allows you to build applications that interact with Slack. + +It lets you interact with Slack in more complex ways than the integrations we provide out of the box. +""" + from .. import slack_discovery_sdk # noqa from . import utils # noqa diff --git a/slack_discovery_sdk/examples/audit_logs_pattern.py b/slack_discovery_sdk/examples/audit_logs_pattern.py index 67102fc..83f2815 100644 --- a/slack_discovery_sdk/examples/audit_logs_pattern.py +++ b/slack_discovery_sdk/examples/audit_logs_pattern.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore diff --git a/slack_discovery_sdk/examples/get_enterprise_info.py b/slack_discovery_sdk/examples/get_enterprise_info.py index edc143c..cf25a4e 100644 --- a/slack_discovery_sdk/examples/get_enterprise_info.py +++ b/slack_discovery_sdk/examples/get_enterprise_info.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os +import logging +import os from slack_discovery_sdk import DiscoveryClient # type: ignore logging.basicConfig(level=logging.DEBUG) diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py index 083c96b..52797be 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_pattern.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore @@ -38,9 +40,7 @@ # Step 3 - Retrieve the message history for each conversation returned in Step 2 # using discovery.conversations.history - channel_conversation = client.discovery_conversations_history( - channel=channel_id, team=team_id - ) + channel_conversation = client.discovery_conversations_history(channel=channel_id, team=team_id) channel_conversation_json = json.dumps(channel_conversation.body, indent=4) export_json_to_file( new_items=channel_conversation_json, diff --git a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py index 3cd646c..e1fe853 100644 --- a/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py +++ b/slack_discovery_sdk/examples/user_based_eDiscovery_with_edits.py @@ -1,6 +1,8 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import logging, os, json +import logging +import os +import json from slack_discovery_sdk import DiscoveryClient # type: ignore from utils import export_json_to_file # type: ignore @@ -38,9 +40,7 @@ # Step 3 - Retrieve the message history for each conversation returned in Step 2 # using discovery.conversations.history - channel_conversation = client.discovery_conversations_history( - channel=channel_id, team=team_id - ) + channel_conversation = client.discovery_conversations_history(channel=channel_id, team=team_id) channel_conversation_json = json.dumps(channel_conversation.body, indent=4) @@ -54,9 +54,7 @@ user_id=user_id, ) else: - edits_response = client.discovery_conversations_edits( - channel=channel_id, team=team_id - ) + edits_response = client.discovery_conversations_edits(channel=channel_id, team=team_id) # If has_edits is true, merge the edits into the conversation history file. channel_conversation.body["edits"] = edits_response["edits"] edits_response_json = json.dumps(channel_conversation.body, indent=4) diff --git a/slack_discovery_sdk/examples/utils.py b/slack_discovery_sdk/examples/utils.py index 0a15b8c..ec727ca 100644 --- a/slack_discovery_sdk/examples/utils.py +++ b/slack_discovery_sdk/examples/utils.py @@ -1,6 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import datetime, os, re, shutil +import datetime +import os +import re +import shutil FILE_EXTENSION = ".json" @@ -17,10 +20,13 @@ def export_json_to_file( user_id: str, ): """This method is used to save data from the eDiscovery, DLP, and SIEM call patterns. + This is just for example use, to make our partners and customers life easier. This is not meant to be a production implementation by any means. + Args: new_items: this is the JSON response from the discovery APIs that we want to save. + base_dir: the folder where the output is written logs_type: this is the discovery API method used channel_id: channel_id i.e C02449123 user_id: The ID of the user i.e. U09123411 @@ -45,8 +51,10 @@ def create_folder_for_channel( channel_id: str, user_id: str, ) -> str: - """This method will create a folder to keep all output from the discovery calls - organized. It will create a folder based on channelID for a particular user: for example C02642201. + """This method will create a folder to keep all output from the discovery calls organized. + + It will create a folder based on channelID for a particular user: for example C02642201. + Args: base_dir: base directory channel_id: channel ID @@ -55,7 +63,6 @@ def create_folder_for_channel( Returns: Str which represents the channel """ - current_day = datetime.date.today() formatted_date = datetime.date.strftime(current_day, "%Y/%m/%d") diff --git a/slack_discovery_sdk/internal_utils.py b/slack_discovery_sdk/internal_utils.py index 8997f12..c3e7b73 100644 --- a/slack_discovery_sdk/internal_utils.py +++ b/slack_discovery_sdk/internal_utils.py @@ -1,6 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -import platform, string, random, time +import platform +import string +import random +import time import sys from typing import Dict, Union, Optional, Any from urllib.parse import urljoin @@ -8,13 +11,13 @@ from .version import __version__ # type:ignore -def convert_bool_to_0_or_1( - params: Optional[Dict[str, Any]] -) -> Optional[Dict[str, Any]]: +def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: """Converts all bool values in dict to "0" or "1". + Slack APIs safely accept "0"/"1" as boolean values. Using True/False (bool in Python) doesn't work with aiohttp. This method converts only the bool values in top-level of a given dict. + Args: params: params as a dict Returns: @@ -26,8 +29,8 @@ def convert_bool_to_0_or_1( def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None): - """Construct the user-agent header with the package info, - Python version and OS version. + """Construct the user-agent header with the package info, Python version and OS version. + Returns: The user agent string. e.g. 'Python/3.6.7 slack_discovery_sdk/1.0.0 Darwin/17.7.0' @@ -44,6 +47,7 @@ def get_user_agent(prefix: Optional[str] = None, suffix: Optional[str] = None): def _get_url(base_url: str, api_method: str) -> str: """Joins the base Slack URL and an API method to form an absolute URL. + Args: base_url (str): The base URL api_method (str): The Slack Web API method. e.g. 'discovery.chat.delete' @@ -55,8 +59,8 @@ def _get_url(base_url: str, api_method: str) -> str: def _next_cursor_is_present(data) -> bool: - """Determine if the response contains 'next_cursor' - and 'next_cursor' is not empty. + """Determine if the response contains 'next_cursor' and 'next_cursor' is not empty. + Returns: A boolean value. """ @@ -76,9 +80,7 @@ def _to_0_or_1_if_bool(v: Any) -> Union[Any, str]: def _build_unexpected_body_error_message(body: str) -> str: - body_for_logging = "".join( - [line.strip() for line in body.replace("\r", "\n").split("\n")] - ) + body_for_logging = "".join([line.strip() for line in body.replace("\r", "\n").split("\n")]) if len(body_for_logging) > 100: body_for_logging = body_for_logging[:100] + "..." message = f"Received a response in a non-JSON format: {body_for_logging}" @@ -87,9 +89,7 @@ def _build_unexpected_body_error_message(body: str) -> str: def get_random_string(length: int = 10) -> str: all_ascii_lowercase_chars = string.ascii_lowercase - random_string = "".join( - random.choice(all_ascii_lowercase_chars) for _ in range(length) - ) + random_string = "".join(random.choice(all_ascii_lowercase_chars) for _ in range(length)) return random_string diff --git a/slack_discovery_sdk/proxy_support.py b/slack_discovery_sdk/proxy_support.py index d77baab..ad30b3a 100644 --- a/slack_discovery_sdk/proxy_support.py +++ b/slack_discovery_sdk/proxy_support.py @@ -1,6 +1,7 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -"""Internal module for loading proxy-related env variables""" +"""Internal module for loading proxy-related env variables.""" + import logging import os from typing import Optional @@ -16,7 +17,5 @@ def load_http_proxy_from_env(logger: logging.Logger = _default_logger) -> Option or os.environ.get("http_proxy") ) if proxy_url is not None: - logger.debug( - f"HTTP proxy URL has been loaded from an env variable: {proxy_url}" - ) + logger.debug(f"HTTP proxy URL has been loaded from an env variable: {proxy_url}") return proxy_url diff --git a/slack_discovery_sdk/rate_limit_support.py b/slack_discovery_sdk/rate_limit_support.py index 6e53d1e..ab62eaf 100644 --- a/slack_discovery_sdk/rate_limit_support.py +++ b/slack_discovery_sdk/rate_limit_support.py @@ -76,20 +76,14 @@ def append_api_call_timestamp(self, api_method: str): with self.lock: now = time.time() self.org_call_histories_in_last_second.append(now) - api_method_histories = self.api_method_call_histories_in_last_minute.get( - api_method, [] - ) + api_method_histories = self.api_method_call_histories_in_last_minute.get(api_method, []) api_method_histories.append(now) - self.api_method_call_histories_in_last_minute[ - api_method - ] = api_method_histories + self.api_method_call_histories_in_last_minute[api_method] = api_method_histories def append_api_call_result(self, api_method: str, is_success: bool): with self.lock: if is_success is True: - new_count = ( - self.api_method_successful_call_counts.get(api_method, 0) + 1 - ) + new_count = self.api_method_successful_call_counts.get(api_method, 0) + 1 self.api_method_successful_call_counts[api_method] = new_count else: new_count = self.api_method_failed_call_counts.get(api_method, 0) + 1 @@ -100,9 +94,7 @@ def calculate_sleep_duration(self, api_method: str) -> float: sleep_seconds = 0 # The estimated count of all the requests performed in the last second - last_second_org_call_count = ( - len(self.org_call_histories_in_last_second) * self.number_of_nodes - ) + last_second_org_call_count = len(self.org_call_histories_in_last_second) * self.number_of_nodes # Calculate the sleep_seconds considering the last second traffic if last_second_org_call_count >= 10: @@ -121,10 +113,8 @@ def calculate_sleep_duration(self, api_method: str) -> float: last_minute_api_method_call_count = len(last_minutes_api_method_requests) # Calculate the sleep_seconds considering the last minute traffic toward the endpoint - max_requests_for_api_method = ( - self.max_requests_per_minute_for_each_api_method.get( - api_method, self.MAX_REQUESTS_PER_MINUTE_FOR_API_METHOD - ) + max_requests_for_api_method = self.max_requests_per_minute_for_each_api_method.get( + api_method, self.MAX_REQUESTS_PER_MINUTE_FOR_API_METHOD ) denominator = max_requests_for_api_method / 15 # this value is usually 80 if last_minute_api_method_call_count >= max_requests_for_api_method * 0.9: @@ -139,17 +129,12 @@ def calculate_sleep_duration(self, api_method: str) -> float: # Change the pace from 60 seconds to 30 seconds sleep_seconds = 30 / denominator - if ( - max_requests_for_api_method >= 120 - and last_minute_api_method_call_count >= max_requests_for_api_method / 120 - ): + if max_requests_for_api_method >= 120 and last_minute_api_method_call_count >= max_requests_for_api_method / 120: # Burst traffic: # Change the pace from 60 seconds to 180 seconds three_seconds_ago = time.time() - 3 requests_in_last_three_seconds = [ - timestamp - for timestamp in last_minutes_api_method_requests - if timestamp >= three_seconds_ago + timestamp for timestamp in last_minutes_api_method_requests if timestamp >= three_seconds_ago ] if len(requests_in_last_three_seconds) >= max_requests_for_api_method / 120: sleep_seconds = 180 / denominator @@ -166,8 +151,7 @@ def generate_metrics_report( "enterprise_id": self.enterprise_id, "last_second_requests": len(self.org_call_histories_in_last_second), "last_minute_requests_per_api_method": { - k: len(v) - for k, v in self.api_method_call_histories_in_last_minute.items() + k: len(v) for k, v in self.api_method_call_histories_in_last_minute.items() }, "successful_call_counts": self.api_method_successful_call_counts, "failed_call_counts": self.api_method_failed_call_counts, diff --git a/slack_discovery_sdk/response.py b/slack_discovery_sdk/response.py index 6fb84d7..5185da1 100644 --- a/slack_discovery_sdk/response.py +++ b/slack_discovery_sdk/response.py @@ -20,22 +20,26 @@ class DiscoveryResponse: """An iterable container of response data. + Attributes: body (dict): The json-encoded content of the response. Along with the headers and status code information. + Methods: validate: Check if the response from Slack was successful. get: Retrieves any key from the response data. next: Retrieves the next portion of results, if 'next_cursor' is present. + Example: ```python import os from slack_discovery_sdk import DiscoveryClient - client = DiscoveryClient(token=os.environ['SLACK_ORG_ADMIN_TOKEN']) + + client = DiscoveryClient(token=os.environ["SLACK_ORG_ADMIN_TOKEN"]) users = [] for page in client.discovery_users_list(): - users = users + page['members'] + users = users + page["members"] ``` Note: Some responses return collections of information @@ -81,10 +85,12 @@ def __str__(self): def __getitem__(self, key): """Retrieves any key from the data store. + Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response["ok"] + Returns: The value from data or None. """ @@ -92,9 +98,12 @@ def __getitem__(self, key): def __iter__(self): """Enables the ability to iterate over the response. + It's required for the iterator protocol. + Note: This enables Slack cursor-based pagination. + Returns: (SlackResponse) self """ @@ -104,6 +113,7 @@ def __iter__(self): def __next__(self): """Retrieves the next portion of results, if 'next_cursor' is present. + Note: Some responses return collections of information like channel and user lists. If they do it's likely @@ -111,9 +121,11 @@ def __next__(self): method allows you to iterate over the response until your code hits 'break' or there are no more results to be found. + Returns: (SlackResponse) self With the new response data now attached to this object. + Raises: SlackApiError: If the request to the Slack API failed. StopIteration: If 'next_cursor' is not present or empty. @@ -129,12 +141,7 @@ def __next__(self): # offset for https://api.slack.com/enterprise/discovery/methods#users_list etc. params.update({"offset": self.body.get("offset")}) - if any( - [ - latest_offset_api in self.api_url - for latest_offset_api in _LATEST_OFFSET_APIS - ] - ): + if any([latest_offset_api in self.api_url for latest_offset_api in _LATEST_OFFSET_APIS]): params.update({"latest": self.body.get("offset")}) response = self._client.fetch_next_page( # skipcq: PYL-W0212 @@ -152,10 +159,12 @@ def __next__(self): def get(self, key, default=None): """Retrieves any key from the response data. + Note: This is implemented so users can reference the SlackResponse object like a dictionary. e.g. response.get("ok", False) + Returns: The value from data or the specified default. """ @@ -163,17 +172,14 @@ def get(self, key, default=None): def validate(self): """Check if the response from Slack was successful. + Returns: (SlackResponse) This method returns it's own object. e.g. 'self' Raises: SlackApiError: The request to the Slack API failed. """ - if ( - self.status_code == 200 - and self.body is not None - and self.body.get("ok", False) - ): + if self.status_code == 200 and self.body is not None and self.body.get("ok", False): return self msg = "The request to the Slack API failed." raise DiscoveryApiError(message=msg, response=self) diff --git a/tests/test_chat.py b/tests/test_chat.py index b698ae0..000d39f 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -19,9 +19,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_tombstone(self): expected_message_subtype = "dlp_tombstone" @@ -112,17 +110,13 @@ def test_delete(self): ) def test_restore(self): - restore_msg_text = ( - "The Discovery API will first tombstone this message and then restore it..." - ) + restore_msg_text = "The Discovery API will first tombstone this message and then restore it..." try: conversations = self.web_client.users_conversations(team_id=self.team) assert conversations.get("error") is None tombstone_channel = conversations["channels"][0]["id"] - message_to_restore = self.web_client.chat_postMessage( - channel=tombstone_channel, text=restore_msg_text - ) + message_to_restore = self.web_client.chat_postMessage(channel=tombstone_channel, text=restore_msg_text) assert message_to_restore.get("error") is None tombstone_msg_resp = self.client.discovery_chat_tombstone( diff --git a/tests/test_conversations.py b/tests/test_conversations.py index dc4f3db..cb3aa0c 100644 --- a/tests/test_conversations.py +++ b/tests/test_conversations.py @@ -1,7 +1,9 @@ # Copyright 2021, Slack Technologies, LLC. All rights reserved. -from typing import Any -import os, pytest, time, json +import os +import pytest +import time +import json from slack_sdk import WebClient from slack_discovery_sdk import DiscoveryClient from slack_discovery_sdk.internal_utils import ( @@ -23,9 +25,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_conversations_search(self): first_msg_text = "This message will test the search API" @@ -96,9 +96,7 @@ def test_conversations_history_pagination(self): conversations = [] limit_size = 1 page_num = 0 - for page in self.client.discovery_conversations_history( - channel=self.channel, team=self.team, limit=limit_size - ): + for page in self.client.discovery_conversations_history(channel=self.channel, team=self.team, limit=limit_size): for message in page["messages"]: conversations.append(json.dumps(message)) page_num += 1 @@ -131,11 +129,7 @@ def test_conversations_history_from_one_minute_ago(self): # if there are multiple messages in the last minute, one of them should be the one from above found = next( - ( - message["text"] - for message in response["messages"] - if message["text"] == test_text - ), + (message["text"] for message in response["messages"] if message["text"] == test_text), None, ) assert found == test_text @@ -151,9 +145,7 @@ def test_conversations_history_from_one_minute_ago(self): def test_conversations_edits_from_one_minute_ago(self): # this test will create a message, edit it, and find edited messgages in the last minute - updated_text = ( - "this message has been edited via chat_updateMessage API in a test" - ) + updated_text = "this message has been edited via chat_updateMessage API in a test" msg_to_edit = None try: msg_to_edit = self.web_client.chat_postMessage( @@ -177,11 +169,7 @@ def test_conversations_edits_from_one_minute_ago(self): assert response["error"] is None # if there are more than one edits, one of them should be the one from above found = next( - ( - edit["text"] - for edit in response["edits"] - if edit["text"] == updated_text - ), + (edit["text"] for edit in response["edits"] if edit["text"] == updated_text), None, ) assert found == updated_text @@ -202,17 +190,11 @@ def test_conversations_info_for_private_channel(self): # create channel for testing purposes - make sure we can get info on this channel test_channel = self.create_channel() test_channel_creation_time = test_channel["channel"]["created"] - response = self.client.discovery_conversations_info( - team=self.team, channel=test_channel["channel"]["id"] - ) + response = self.client.discovery_conversations_info(team=self.team, channel=test_channel["channel"]["id"]) assert response["error"] is None # if there are multiple channels, ensure we can find the one we created above found = next( - ( - info["created"] - for info in response["info"] - if info["created"] == test_channel_creation_time - ), + (info["created"] for info in response["info"] if info["created"] == test_channel_creation_time), None, ) assert found == test_channel_creation_time @@ -220,30 +202,20 @@ def test_conversations_info_for_private_channel(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_members_new_channel(self): test_channel = None try: test_channel = self.create_channel() - convo_join_resp = self.web_client.conversations_join( - channel=test_channel["channel"]["id"] - ) + convo_join_resp = self.web_client.conversations_join(channel=test_channel["channel"]["id"]) channel_creator = convo_join_resp["channel"]["creator"] - response = self.client.discovery_conversations_members( - team=self.team, channel=test_channel["channel"]["id"] - ) + response = self.client.discovery_conversations_members(team=self.team, channel=test_channel["channel"]["id"]) assert response["error"] is None # loop through members to ensure the creator is one of the members of the channel found = next( - ( - member["id"] - for member in response["members"] - if member["id"] == channel_creator - ), + (member["id"] for member in response["members"] if member["id"] == channel_creator), None, ) assert found == channel_creator @@ -251,9 +223,7 @@ def test_conversations_members_new_channel(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_renames(self): test_channel = None @@ -261,23 +231,15 @@ def test_conversations_renames(self): test_channel = self.create_channel() new_channel_name = get_random_string() - self.web_client.conversations_rename( - channel=test_channel["channel"]["id"], name=new_channel_name - ) + self.web_client.conversations_rename(channel=test_channel["channel"]["id"], name=new_channel_name) # check for renames from the last minute, which should include the rename from above - response = self.client.discovery_conversations_renames( - team=self.team, oldest=get_timestamp_last_minute() - ) + response = self.client.discovery_conversations_renames(team=self.team, oldest=get_timestamp_last_minute()) assert response["error"] is None # if there are multiple renames, one of them should be the one from above found = next( - ( - rename["new_name"] - for rename in response["renames"] - if rename["new_name"] == new_channel_name - ), + (rename["new_name"] for rename in response["renames"] if rename["new_name"] == new_channel_name), None, ) assert found == new_channel_name @@ -285,9 +247,7 @@ def test_conversations_renames(self): finally: # delete the test channel we created above if test_channel is not None: - self.web_client.conversations_archive( - channel=test_channel["channel"]["id"] - ) + self.web_client.conversations_archive(channel=test_channel["channel"]["id"]) def test_conversations_reactions(self): test_text = "This message will test reactions" @@ -325,11 +285,7 @@ def test_conversations_reactions(self): assert response["error"] is None # if we have more than one reaction (which we should) check to make sure we have thumbs reaction found = next( - ( - reaction["name"] - for reaction in response["reactions"] - if reaction["name"] == smile_reaction - ), + (reaction["name"] for reaction in response["reactions"] if reaction["name"] == smile_reaction), None, ) assert found == smile_reaction diff --git a/tests/test_draft.py b/tests/test_draft.py index ea038ff..11f664c 100644 --- a/tests/test_draft.py +++ b/tests/test_draft.py @@ -45,7 +45,5 @@ def test_draft_info(self): user = response["drafts"][0]["user_id"] team = response["drafts"][0]["team_id"] draft = response["drafts"][0]["id"] - info_response = self.client.discovery_draft_info( - team=team, draft=draft, user=user, limit=resp_limit - ) + info_response = self.client.discovery_draft_info(team=team, draft=draft, user=user, limit=resp_limit) assert info_response["error"] is None diff --git a/tests/test_file.py b/tests/test_file.py index ed9ca49..cd6b6f9 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -20,9 +20,7 @@ def setup_method(self): self.team = os.environ[SLACK_DISCOVERY_SDK_TEST_TEAM_ID] self.channel = os.environ[SLACK_DISCOVERY_SDK_TEST_CHANNEL_ID] self.client = DiscoveryClient(token=self.token) - self.web_client = WebClient( - token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN] - ) + self.web_client = WebClient(token=os.environ[SLACK_DISCOVERY_SDK_TEST_BOT_TOKEN]) def test_files_list(self): resp_limit = 2 @@ -64,10 +62,7 @@ def test_file_tombstone(self): file_upload = self.create_file() file_id = file_upload["file"]["id"] file_tombstone_resp = self.client.discovery_file_tombstone(file=file_id) - assert ( - file_id == file_tombstone_resp["file"]["id"] - and file_tombstone_resp["file"]["is_tombstoned"] is True - ) + assert file_id == file_tombstone_resp["file"]["id"] and file_tombstone_resp["file"]["is_tombstoned"] is True finally: # clean up the test file - first we have to restore, then we can delete self.client.discovery_file_restore(file=file_upload["file"]["id"]) @@ -79,13 +74,8 @@ def test_file_restore(self): file_upload = self.create_file() file_id = file_upload["file"]["id"] self.client.discovery_file_tombstone(file=file_id) - file_restore_resp = self.client.discovery_file_restore( - file=file_upload["file"]["id"] - ) - assert ( - file_id == file_restore_resp["file"]["id"] - and file_restore_resp["file"]["is_tombstoned"] is False - ) + file_restore_resp = self.client.discovery_file_restore(file=file_upload["file"]["id"]) + assert file_id == file_restore_resp["file"]["id"] and file_restore_resp["file"]["is_tombstoned"] is False finally: # clean up the test file - first we have to restore, then we can delete self.web_client.files_delete(file=file_upload["file"]["id"]) @@ -95,12 +85,8 @@ def test_file_delete(self): try: file_upload = self.create_file() file_id = file_upload["file"]["id"] - file_delete_resp = self.client.discovery_file_delete( - file=file_upload["file"]["id"] - ) - assert ( - file_id == file_delete_resp["file"] and file_delete_resp["ok"] is True - ) + file_delete_resp = self.client.discovery_file_delete(file=file_upload["file"]["id"]) + assert file_id == file_delete_resp["file"] and file_delete_resp["ok"] is True finally: # can pass as we already delete file above pass @@ -114,10 +100,7 @@ def test_single_file_release(self): self.client.discovery_file_tombstone(file=file_id) # release the file files_release_resp = self.client.discovery_files_release(files=file_id) - assert ( - file_id == files_release_resp["files"][0]["file"]["id"] - and len(files_release_resp["failed_files"]) == 0 - ) + assert file_id == files_release_resp["files"][0]["file"]["id"] and len(files_release_resp["failed_files"]) == 0 finally: # clean up the test file - first we have to restore, then we can delete self.web_client.files_delete(file=file_upload["file"]["id"]) @@ -141,9 +124,7 @@ def test_multiple_file_release(self): files_to_release.append(file_id_1) files_to_release.append(file_id_2) # release the file - files_release_resp = self.client.discovery_files_release( - files=files_to_release - ) + files_release_resp = self.client.discovery_files_release(files=files_to_release) assert len(files_release_resp["failed_files"]) == 0 finally: diff --git a/tests/test_rate_limit_scenario.py b/tests/test_rate_limit_scenario.py index 97881bc..7495a1a 100644 --- a/tests/test_rate_limit_scenario.py +++ b/tests/test_rate_limit_scenario.py @@ -55,18 +55,14 @@ def test_discovery_conversations_search(self): @pytest.mark.skip def test_discovery_conversations_list(self): executor = ThreadPoolExecutor(max_workers=100) - client = DiscoveryClient( - token=self.token, rate_limit_error_prevention_enabled=True - ) + client = DiscoveryClient(token=self.token, rate_limit_error_prevention_enabled=True) def run(): for i in range(10): for page in client.discovery_conversations_list(limit=10): assert page.status_code == 200 for channel in page.get("channels"): - response = client.discovery_conversations_info( - channel=channel.get("id") - ) + response = client.discovery_conversations_info(channel=channel.get("id")) assert response.status_code == 200 try: diff --git a/tests/test_rate_limit_support.py b/tests/test_rate_limit_support.py index b5ec4c3..62dbedb 100644 --- a/tests/test_rate_limit_support.py +++ b/tests/test_rate_limit_support.py @@ -35,11 +35,4 @@ def test_cleanup(self): rate_limiter.cleanup() assert len(rate_limiter.org_call_histories_in_last_second) == 3 - assert ( - len( - rate_limiter.api_method_call_histories_in_last_minute[ - "discovery.enterprise.info" - ] - ) - == 3 - ) + assert len(rate_limiter.api_method_call_histories_in_last_minute["discovery.enterprise.info"]) == 3