67 lines
2 KiB
Python
67 lines
2 KiB
Python
|
"""
|
||
|
Configuration:
|
||
|
Options:
|
||
|
token - Discord access token
|
||
|
"""
|
||
|
|
||
|
from requests.models import Response
|
||
|
from ..core.pronoun_update import PronounUpdate
|
||
|
from typing import Any, Dict
|
||
|
from ..core.plugin import InvalidPluginDefinitionException, Plugin
|
||
|
import requests
|
||
|
|
||
|
|
||
|
class DiscordApiException(Exception):
|
||
|
def __init__(self, error: str) -> None:
|
||
|
super().__init__(f"Discord api returned an error: {error}")
|
||
|
|
||
|
pass
|
||
|
|
||
|
|
||
|
class DiscordApiClient:
|
||
|
host: str
|
||
|
s = requests.Session()
|
||
|
|
||
|
def __init__(self, token: str):
|
||
|
self.s.headers.update({"Authorization": token})
|
||
|
|
||
|
def verify_credentials(self) -> Response:
|
||
|
user_data = self.s.get("https://discord.com/api/v9/users/@me")
|
||
|
if not user_data.ok:
|
||
|
raise DiscordApiException(user_data.json()["message"])
|
||
|
print(user_data.json())
|
||
|
return user_data
|
||
|
|
||
|
def updated_data(self, updated_data: Dict[str, Any]) -> Response:
|
||
|
resp = self.s.patch(
|
||
|
"https://discord.com/api/v9/users/@me", json=updated_data,
|
||
|
)
|
||
|
if not resp.ok:
|
||
|
raise DiscordApiException(resp.json()["message"])
|
||
|
return resp
|
||
|
|
||
|
|
||
|
class DiscordPlugin(Plugin):
|
||
|
s = requests.Session()
|
||
|
api_client:DiscordApiClient
|
||
|
|
||
|
@classmethod
|
||
|
def name(cls) -> str:
|
||
|
return "discord"
|
||
|
|
||
|
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.api_client = DiscordApiClient(access_token)
|
||
|
|
||
|
self.api_client.verify_credentials()
|
||
|
|
||
|
def update_bio(self, update_pronouns: PronounUpdate) -> None:
|
||
|
current_bio = self.api_client.verify_credentials().json()["bio"]
|
||
|
bio = update_pronouns.replace_pronouns_in_bio(current_bio)
|
||
|
# TODO: discord seems to be getting a pronoun field, maybe use that
|
||
|
self.api_client.updated_data({"bio": bio})
|