Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .flake8

This file was deleted.

17 changes: 17 additions & 0 deletions .github/workflows/ci-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 0 additions & 34 deletions .github/workflows/flake8.yml

This file was deleted.

23 changes: 23 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions requirements/dev-tools.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# pip install -r requirements/dev-tools.txt

# ruff
ruff==0.17.4
12 changes: 12 additions & 0 deletions scripts/format.sh
Original file line number Diff line number Diff line change
@@ -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/
1 change: 1 addition & 0 deletions scripts/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 11 additions & 0 deletions scripts/lint.sh
Original file line number Diff line number Diff line change
@@ -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/
2 changes: 2 additions & 0 deletions scripts/run_tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions slack_discovery_sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down
80 changes: 25 additions & 55 deletions slack_discovery_sdk/base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand All @@ -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)
Expand All @@ -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 {}
Expand All @@ -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
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand All @@ -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:
Expand All @@ -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}""")
Expand Down
Loading
Loading