Add discord plugin

This commit is contained in:
bad 2022-06-06 23:49:30 +02:00
parent 78d1f244b2
commit bde4a6d3c1
2 changed files with 67 additions and 0 deletions

66
plugins/discord.py Normal file
View file

@ -0,0 +1,66 @@
"""
Configuration:
Options:
token - Discord access token
"""
from requests.models import Response
from pronoun_update import PronounUpdate
from typing import Any, Dict
from 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})

View file

@ -12,6 +12,7 @@ setup(
"pronounomatic.plugins": [
"log = plugins.log_plugin:LogPlugin",
"mastodon = plugins.mastodon:MastodonPlugin",
"discord = plugins.discord:DiscordPlugin",
],
},
# Executables