talkomatic.py 0.1.2
An easy-to-use Python versatile wrapper for the Talkomatic Bot interface ensuring best practices for making bots, and handling the REST API.
 
Loading...
Searching...
No Matches
auth.py
Go to the documentation of this file.
1from datetime import datetime, UTC
2from json import dump, load
3from pathlib import Path
4from requests import post, Response
5
6
7API_AUTH_HEADERS = {"x-api-key": "tK_public_key_4f8a9b2c7d6e3f1a5g8h9i0j4k5l6m7n8o9p"}
8BOT_TOKEN_PATH = "BOT_TOKEN_DO_NOT_SHARE_OR_DELETE_OR_MODIFY"
9
10def get_auth_bot_token() -> str:
11 """
12 Fetches the bot token and returns it, by requesting it from the server if expired
13 or doesn't exist, but loads from a local file if it exists and isn't expired.
14 """
15
16 if Path(BOT_TOKEN_PATH).exists():
17 with open(BOT_TOKEN_PATH, "r") as token_file:
18 token_json: dict = load(token_file)
19 token_expiry: datetime = datetime.fromisoformat(token_json["expiresAt"])
20 if datetime.now(UTC) < token_expiry:
21 return token_json["token"]
22
23 token_res: Response = post("https://classic.talkomatic.co/api/v1/bot-tokens/request")
24 if token_res.status_code != 201:
25 raise Exception(str(token_res.json()))
26 token: str = token_res.json()["token"]
27 with open(BOT_TOKEN_PATH, "w") as token_file:
28 dump(token_res.json(), token_file)
29 return token
str get_auth_bot_token()
Definition auth.py:10