pronoun-o-matic/src/plugins/github.py

71 lines
2.1 KiB
Python

"""
Configuration:
Options:
token - Users access token
"""
from ..core.pronoun_update import PronounUpdate
from ..core.plugin import InvalidPluginDefinitionException, Plugin
from requests.models import Response
from typing import Any, Dict
import requests
class GithubApiException(Exception):
def __init__(self, error: str) -> None:
super().__init__(f"Gitea api returned an error: {error}")
pass
class GithubApiClient:
s = requests.Session()
def __init__(self, token: str):
self.s.headers.update({"Authorization": f"token {token}"})
def verify_credentials(self) -> Response:
creds = self.s.get(f"https://api.github.com/user")
if not creds.ok:
error = creds.json().get("message", "the server didn't return an error")
raise GithubApiException(error)
return creds
def update_account(self, updated_credentials: Dict[str, Any]) -> Response:
creds = self.s.patch(
f"https://api.github.com/user", json=updated_credentials
)
if not creds.ok:
error = creds.json().get("message", "the server didn't return an error")
raise GithubApiException(error)
return creds
class GithubPlugin(Plugin):
s = requests.Session()
api_client: GithubApiClient
@classmethod
def name(cls) -> str:
return "github"
def _load_from_config(self, config: dict[str, Any]) -> None:
access_token = config.get("token", None)
if not isinstance(access_token, str):
raise InvalidPluginDefinitionException(
f"Access token needs to be set to a string with an access token, got {type(access_token)}"
)
self.access_token = access_token
self.api_client = GithubApiClient(access_token)
# Verify the credentials
self.api_client.verify_credentials()
def update_bio(self, update_pronouns: PronounUpdate) -> None:
cur_bio = self.api_client.verify_credentials().json()["bio"]
new_bio = update_pronouns.replace_pronouns_in_bio(
cur_bio
)
self.api_client.update_account({"bio": new_bio})