Spaces:
Running
Running
Download remote_storage.py from H3y-sam/Telegram-Bot: direct link, hf CLI and curl.
- Browser
- Download file 2.76 kB
-
https://huggingface.co/spaces/H3y-sam/Telegram-Bot/resolve/main/remote_storage.py
- Command line
-
hf download hf://spaces/H3y-sam/Telegram-Bot/remote_storage.py
-
curl -L -o remote_storage.py https://huggingface.co/spaces/H3y-sam/Telegram-Bot/resolve/main/remote_storage.py
2.76 kB
| import json | |
| import logging | |
| import requests | |
| logger = logging.getLogger(__name__) | |
| def pull_from_gist(filename: str) -> dict: | |
| """Pull a specific JSON file from the GitHub Gist.""" | |
| from config import GIST_ID, GIST_TOKEN | |
| if not GIST_ID or not GIST_TOKEN: | |
| return None | |
| try: | |
| url = f"https://api.github.com/gists/{GIST_ID}" | |
| headers = {"Authorization": f"token {GIST_TOKEN}"} | |
| resp = requests.get(url, headers=headers, timeout=10) | |
| if resp.status_code == 200: | |
| gist_data = resp.json() | |
| files = gist_data.get("files", {}) | |
| if filename in files: | |
| content = files[filename].get("content", "{}") | |
| logger.info(f"Successfully pulled {filename} from Gist") | |
| return json.loads(content) | |
| elif resp.status_code == 401: | |
| logger.error(f"Gist Pull Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.") | |
| elif resp.status_code != 404: | |
| logger.error(f"Failed to pull {filename} from Gist (Status {resp.status_code})") | |
| except Exception as e: | |
| logger.error(f"Error pulling {filename} from Gist: {e}") | |
| return None | |
| def push_to_gist(filename: str, data_dict: dict): | |
| """Push a dictionary to a specific file in the GitHub Gist.""" | |
| from config import GIST_ID, GIST_TOKEN | |
| if not GIST_ID or not GIST_TOKEN: | |
| return | |
| try: | |
| url = f"https://api.github.com/gists/{GIST_ID}" | |
| headers = {"Authorization": f"token {GIST_TOKEN}"} | |
| content = json.dumps(data_dict, indent=2) | |
| payload = { | |
| "files": { | |
| filename: { | |
| "content": content | |
| } | |
| } | |
| } | |
| resp = requests.patch(url, headers=headers, json=payload, timeout=10) | |
| if resp.status_code == 200: | |
| logger.info(f"Successfully pushed {filename} to Gist") | |
| elif resp.status_code == 401: | |
| logger.error(f"Gist Push Failed ({filename}): [401 Unauthorized] Check your GIST_TOKEN.") | |
| else: | |
| logger.error(f"Failed to push {filename} to Gist (Status {resp.status_code})") | |
| except Exception as e: | |
| logger.error(f"Error pushing {filename} to Gist: {e}") | |
| # ββ Legacy Wrappers (to avoid breaking other files) βββββββββββββββββββββββββββ | |
| def pull_history_from_gist() -> dict: | |
| from config import HISTORY_FILE_NAME | |
| return pull_from_gist(HISTORY_FILE_NAME) | |
| def push_history_to_gist(history_dict: dict): | |
| from config import HISTORY_FILE_NAME | |
| push_to_gist(HISTORY_FILE_NAME, history_dict) | |