Implement video message configuration

* Config is update when new key is added (always fully explicit)
This commit is contained in:
BreadTube 2025-10-29 21:32:45 +09:00
commit f59982f745
3 changed files with 36 additions and 9 deletions

View file

@ -30,6 +30,7 @@ class ApiEncoder(json.JSONEncoder):
class DiscordManager:
MIN_API_VERSION = 9
TOO_MANY_REQUEST_STATUS = 429
@dataclass
class RateLimit:
@ -88,15 +89,31 @@ class DiscordManager:
else:
request.add_header('Content-Type', 'application/json')
request.add_header('Authorization', f'Bot {self._bot_token}')
try:
def _request() -> tuple[int, dict, bytes | None]:
nonlocal request, request_timeout
with urllib.request.urlopen(request, timeout=request_timeout) as response:
if response.status != expected_code:
raise RuntimeError(
f'Unexpected code {response.status} (expected: {expected_code}) -> {response.read().decode()}')
body = response.read()
headers = dict(response.getheaders())
return response.status, headers, response.read()
try:
body = b''
try:
status, headers, body = _request()
except urllib.error.HTTPError as error:
if error.status != self.TOO_MANY_REQUEST_STATUS:
raise error
status = error.status
headers = dict(error.headers)
self._update_rate_limit(headers)
if status == self.TOO_MANY_REQUEST_STATUS:
self._logger.warning('Warning: too many request -> retrying')
status, headers, body = _request()
self._update_rate_limit(headers)
return headers, json.loads(body.decode()) if body else None
if status != expected_code:
raise RuntimeError(f'Unexpected code {status} (expected: {expected_code}) -> {body}')
return headers, json.loads(body.decode()) if body else None
except urllib.error.HTTPError as error:
raise RuntimeError(
f'HTTP error calling API ({url}): {error}:\nHeaders:\n{error.headers}Body:\n{error.read()}') from error