aboutsummaryrefslogtreecommitdiffstats
path: root/slack/slack_api.py
diff options
context:
space:
mode:
authorTrygve Aaberge <trygveaa@gmail.com>2023-01-14 07:27:57 +0100
committerTrygve Aaberge <trygveaa@gmail.com>2024-02-18 11:32:53 +0100
commit70eaa484831106cb5df6eeb3d7b7fe5ef9b65d0c (patch)
tree4d8dea543597536249f10f69d9f1ec8d69d30251 /slack/slack_api.py
parentada362c5ff8d844c06c79bc98338d5aab7de9c8b (diff)
downloadwee-slack-70eaa484831106cb5df6eeb3d7b7fe5ef9b65d0c.tar.gz
Move SlackApi to a separate file
Diffstat (limited to 'slack/slack_api.py')
-rw-r--r--slack/slack_api.py48
1 files changed, 48 insertions, 0 deletions
diff --git a/slack/slack_api.py b/slack/slack_api.py
new file mode 100644
index 0000000..3761930
--- /dev/null
+++ b/slack/slack_api.py
@@ -0,0 +1,48 @@
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING, Dict, Union
+from urllib.parse import urlencode
+
+from slack.http import http_request
+from slack.shared import shared
+
+if TYPE_CHECKING:
+ from slack.slack_workspace import SlackWorkspace
+
+
+class SlackApi:
+ def __init__(self, workspace: SlackWorkspace):
+ self.workspace = workspace
+
+ def get_request_options(self):
+ return {
+ "useragent": f"wee_slack {shared.SCRIPT_VERSION}",
+ "httpheader": f"Authorization: Bearer {self.workspace.config.api_token.value}",
+ "cookie": self.workspace.config.api_cookies.value,
+ }
+
+ async def fetch(self, method: str, params: Dict[str, Union[str, int]] = {}):
+ url = f"https://api.slack.com/api/{method}?{urlencode(params)}"
+ response = await http_request(
+ url,
+ self.get_request_options(),
+ self.workspace.config.slack_timeout.value * 1000,
+ )
+ return json.loads(response)
+
+ async def fetch_list(
+ self,
+ method: str,
+ list_key: str,
+ params: Dict[str, Union[str, int]] = {},
+ pages: int = 1, # negative or 0 means all pages
+ ):
+ response = await self.fetch(method, params)
+ next_cursor = response.get("response_metadata", {}).get("next_cursor")
+ if pages != 1 and next_cursor and response["ok"]:
+ params["cursor"] = next_cursor
+ next_pages = await self.fetch_list(method, list_key, params, pages - 1)
+ response[list_key].extend(next_pages[list_key])
+ return response
+ return response