From 674f1e2b5a874b3e8177fd2f1ec21e1acff474a1 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:48:13 -0500 Subject: [PATCH 1/3] build: replace black and flake8 with ruff Use the ruff config shared by python-slack-sdk, bolt-python, and python-slack-hooks, with format.sh and lint.sh scripts and a Lint CI job. This removes the .flake8 config and the flake8 workflow. 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 ++ 9 files changed, 70 insertions(+), 39 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 938ce38..c08febd 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 a288ac6..0d28b18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,6 +44,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 From 3d7526820ee8953576a3212f2214759630867adc Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:48:41 -0500 Subject: [PATCH 2/3] style: format with ruff Output of ./scripts/format.sh with no other changes: ruff format plus the safe ruff check fixes (one import per line, docstring blank lines, an unused import). Co-Authored-By: Claude --- slack_discovery_sdk/__init__.py | 4 +- slack_discovery_sdk/base_client.py | 70 ++++--------- slack_discovery_sdk/client.py | 99 +++++-------------- .../examples/DLP_call_pattern.py | 11 +-- slack_discovery_sdk/examples/__init__.py | 4 +- .../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 | 8 +- slack_discovery_sdk/internal_utils.py | 21 ++-- slack_discovery_sdk/proxy_support.py | 5 +- slack_discovery_sdk/rate_limit_support.py | 34 ++----- slack_discovery_sdk/response.py | 31 +++--- 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 +- 20 files changed, 148 insertions(+), 320 deletions(-) diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index 1ea2b8d..c7cc630 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -2,7 +2,9 @@ # 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.""" +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..7073049 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 {} @@ -189,6 +184,7 @@ 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) url: Complete URL (e.g., https://slack.com/api/discovery.enterprise.info) @@ -197,7 +193,6 @@ def _urllib_api_call( Returns: API response """ - # True/False -> "1"/"0" params = convert_bool_to_0_or_1(params) request_headers = self._build_urllib_request_headers( @@ -240,15 +235,16 @@ def _perform_urllib_http_request( params: Dict[str, str], ) -> Dict[str, any]: # type:ignore """Performs an HTTP request and parses the response. + Args: 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], + 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 +276,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 +289,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 +301,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 +373,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 +389,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 +412,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..444c435 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 @@ -78,9 +79,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 @@ -157,9 +156,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 @@ -182,9 +179,7 @@ def discovery_conversations_recent( 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, @@ -217,9 +212,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, @@ -240,9 +233,7 @@ def discovery_conversations_history( 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 +245,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, @@ -282,9 +271,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, @@ -306,9 +293,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, @@ -334,9 +319,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, @@ -361,9 +344,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, @@ -389,9 +370,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, @@ -422,9 +401,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 @@ -443,7 +420,6 @@ def discovery_chat_info( 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, @@ -469,7 +445,6 @@ def discovery_chat_update( 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, @@ -494,7 +469,6 @@ def discovery_chat_delete( """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, @@ -518,7 +492,6 @@ def discovery_chat_tombstone( """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 +501,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, @@ -544,7 +515,6 @@ def discovery_chat_restore( """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 +523,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 @@ -575,7 +543,6 @@ def discovery_drafts_list( """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, @@ -604,7 +571,6 @@ def discovery_draft_info( """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, @@ -636,7 +602,6 @@ def discovery_files_list( """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 +613,10 @@ 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) @@ -671,17 +633,10 @@ def discovery_file_tombstone( 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. """ @@ -691,13 +646,9 @@ 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. """ @@ -709,9 +660,7 @@ 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: + 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. Refer to https://api.slack.com/enterprise/discovery/methods#files_release for more details. @@ -722,6 +671,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/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..9d22545 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -2,6 +2,8 @@ # 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.""" +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..da87463 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" @@ -19,6 +22,7 @@ def export_json_to_file( """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. logs_type: this is the discovery API method used @@ -47,6 +51,7 @@ def create_folder_for_channel( ) -> 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. + Args: base_dir: base directory channel_id: channel ID @@ -55,7 +60,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..6e355eb 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,12 @@ 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: @@ -28,6 +30,7 @@ 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. + 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' @@ -57,6 +61,7 @@ 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. + Returns: A boolean value. """ @@ -76,9 +81,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 +90,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..29f87aa 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""" + 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..551361d 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. """ @@ -93,8 +99,10 @@ 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 +112,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 +120,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 +140,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 +158,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 +171,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 From ce9e172d99bb4ce94a3e240656512fc41c0b08f8 Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 16 Nov 2026 12:50:47 -0500 Subject: [PATCH 3/3] docs: fix docstrings flagged by ruff pydocstyle Split each docstring summary onto its own line with a blank line after it, end summaries with a period, and document the missing args, so the google convention checks pass with the same ignores as the other python repos. Co-Authored-By: Claude --- slack_discovery_sdk/__init__.py | 5 +- slack_discovery_sdk/base_client.py | 10 ++-- slack_discovery_sdk/client.py | 74 +++++++++++++++++------- slack_discovery_sdk/errors.py | 4 +- slack_discovery_sdk/examples/__init__.py | 5 +- slack_discovery_sdk/examples/utils.py | 7 ++- slack_discovery_sdk/internal_utils.py | 7 +-- slack_discovery_sdk/proxy_support.py | 2 +- slack_discovery_sdk/response.py | 1 + 9 files changed, 76 insertions(+), 39 deletions(-) diff --git a/slack_discovery_sdk/__init__.py b/slack_discovery_sdk/__init__.py index c7cc630..4af1680 100644 --- a/slack_discovery_sdk/__init__.py +++ b/slack_discovery_sdk/__init__.py @@ -1,8 +1,9 @@ # 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 diff --git a/slack_discovery_sdk/base_client.py b/slack_discovery_sdk/base_client.py index 7073049..8120919 100644 --- a/slack_discovery_sdk/base_client.py +++ b/slack_discovery_sdk/base_client.py @@ -157,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 @@ -187,6 +188,7 @@ def _urllib_api_call( 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 @@ -237,10 +239,10 @@ def _perform_urllib_http_request( """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} diff --git a/slack_discovery_sdk/client.py b/slack_discovery_sdk/client.py index 444c435..05dd924 100644 --- a/slack_discovery_sdk/client.py +++ b/slack_discovery_sdk/client.py @@ -11,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) @@ -36,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: @@ -66,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. """ @@ -94,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( @@ -117,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. """ @@ -137,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( @@ -171,8 +178,9 @@ 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. @@ -195,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( @@ -227,6 +236,7 @@ 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: @@ -259,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( @@ -283,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( @@ -307,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( @@ -331,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( @@ -358,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( @@ -385,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( @@ -416,8 +432,9 @@ 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( @@ -441,8 +458,9 @@ 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( @@ -467,6 +485,7 @@ 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( @@ -490,6 +509,7 @@ 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( @@ -513,6 +533,7 @@ 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( @@ -541,6 +562,7 @@ 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( @@ -569,6 +591,7 @@ 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( @@ -600,6 +623,7 @@ 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( @@ -615,6 +639,7 @@ def discovery_files_list( 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}) @@ -629,8 +654,9 @@ 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}) @@ -638,6 +664,7 @@ def discovery_file_tombstone( 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( @@ -650,6 +677,7 @@ def discovery_file_restore(self, *, token: Optional[str] = None, file: str, **kw 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( @@ -661,8 +689,10 @@ def discovery_file_delete(self, *, token: Optional[str] = None, file: str, **kwa 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. + """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( 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/__init__.py b/slack_discovery_sdk/examples/__init__.py index 9d22545..5f7f331 100644 --- a/slack_discovery_sdk/examples/__init__.py +++ b/slack_discovery_sdk/examples/__init__.py @@ -1,8 +1,9 @@ # # 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 diff --git a/slack_discovery_sdk/examples/utils.py b/slack_discovery_sdk/examples/utils.py index da87463..ec727ca 100644 --- a/slack_discovery_sdk/examples/utils.py +++ b/slack_discovery_sdk/examples/utils.py @@ -20,11 +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 @@ -49,8 +51,9 @@ 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 diff --git a/slack_discovery_sdk/internal_utils.py b/slack_discovery_sdk/internal_utils.py index 6e355eb..c3e7b73 100644 --- a/slack_discovery_sdk/internal_utils.py +++ b/slack_discovery_sdk/internal_utils.py @@ -13,6 +13,7 @@ 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. @@ -28,8 +29,7 @@ def convert_bool_to_0_or_1(params: Optional[Dict[str, Any]]) -> Optional[Dict[st 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. @@ -59,8 +59,7 @@ 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. diff --git a/slack_discovery_sdk/proxy_support.py b/slack_discovery_sdk/proxy_support.py index 29f87aa..ad30b3a 100644 --- a/slack_discovery_sdk/proxy_support.py +++ b/slack_discovery_sdk/proxy_support.py @@ -1,6 +1,6 @@ # 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 diff --git a/slack_discovery_sdk/response.py b/slack_discovery_sdk/response.py index 551361d..5185da1 100644 --- a/slack_discovery_sdk/response.py +++ b/slack_discovery_sdk/response.py @@ -98,6 +98,7 @@ def __getitem__(self, key): def __iter__(self): """Enables the ability to iterate over the response. + It's required for the iterator protocol. Note: