Catch errors when calling Discord API and re-try

This commit is contained in:
Deko
2023-12-31 19:32:38 +01:00
parent 3432edbb55
commit d5aff81e56
3 changed files with 139 additions and 90 deletions

View File

@@ -1,7 +1,9 @@
import os
from time import sleep
import requests
from loguru import logger
from requests import exceptions
from app.twitch_client import StreamInformation
@@ -13,10 +15,14 @@ class DiscordClient:
self._webhook_url = os.environ["DISCORD_WEBHOOK_URL"]
def send_information_to_discord(
self, stream: StreamInformation, profile_image: str
self,
stream: StreamInformation,
profile_image: str,
retry_count: int = 0,
) -> None:
logger.info("Sending a message with an embed to the webhook...")
streamer_url = f"https://www.twitch.tv/{stream.user_login}"
try:
response = requests.post(
url=f"{self._webhook_url}?wait=true",
json={
@@ -56,12 +62,28 @@ class DiscordClient:
self._notification_msg_id = response.json()["id"]
logger.info("Stream information sent with ping to Discord.")
except (exceptions.ConnectionError, exceptions.HTTPError) as err:
logger.opt(exception=err).warning(
"Could not send embed to Discord."
)
if retry_count > 5:
logger.warning("Aborted sending the embed to Discord.")
return
retry_count += 1
logger.info(f"Retrying finalize in {retry_count * 5} seconds.")
sleep(retry_count * 5)
self.send_information_to_discord(
stream=stream,
profile_image=profile_image,
retry_count=retry_count,
)
def update_information_on_discord(
self, stream: StreamInformation, profile_image: str
) -> None:
logger.info("Updating stream information on Discord...")
streamer_url = f"https://www.twitch.tv/{stream.user_login}"
try:
response = requests.patch(
url=f"{self._webhook_url}/messages/{self._notification_msg_id}",
json={
@@ -95,9 +117,14 @@ class DiscordClient:
)
response.raise_for_status()
logger.info("Message embed content updated.")
except (exceptions.ConnectionError, exceptions.HTTPError) as err:
logger.opt(exception=err).warning(
"Could not update embed content due to connection error. "
"Not retrying due to this not being important."
)
def finalize_information_on_discord(
self, streamer_name, vod_url: str | None
self, streamer_name, vod_url: str | None, retry_count: int = 0
) -> None:
logger.info("Finalizing stream information on Discord...")
if not self._notification_msg_id:
@@ -105,8 +132,9 @@ class DiscordClient:
return
if not vod_url:
vod_url = "None available. Please contact the developer."
vod_url = "None available."
try:
response = requests.patch(
url=f"{self._webhook_url}/messages/{self._notification_msg_id}",
json={
@@ -121,3 +149,21 @@ class DiscordClient:
)
response.raise_for_status()
logger.info("Message updated with VOD.")
except (exceptions.ConnectionError, exceptions.HTTPError) as err:
logger.opt(exception=err).warning(
"Could not finalize embed on Discord."
)
if retry_count > 5:
logger.warning(
"Aborted finalizing the embed on Discord. "
"It will be stuck on the last stream update."
)
return
retry_count += 1
logger.info(f"Retrying finalize in {retry_count * 5} seconds.")
sleep(retry_count * 5)
self.finalize_information_on_discord(
streamer_name=streamer_name,
vod_url=vod_url,
retry_count=retry_count,
)

View File

@@ -8,9 +8,10 @@ import pytest
def mock_loggers():
with (
mock.patch("loguru.logger.info") as info_logger,
mock.patch("loguru.logger.warning") as warning_logger,
mock.patch("loguru.logger.error") as error_logger,
):
mocked_loggers = namedtuple(
"mocked_loggers", ["info_logger", "error_logger"]
"mocked_loggers", ["info_logger", "warning_logger", "error_logger"]
)
yield mocked_loggers(info_logger, error_logger)
yield mocked_loggers(info_logger, warning_logger, error_logger)

View File

@@ -5,7 +5,6 @@ from unittest import mock
import pytest
import requests_mock
from requests import HTTPError
from app.discord_client import DiscordClient
from app.twitch_client import StreamInformation
@@ -74,12 +73,15 @@ def test_send_information_to_discord_fails(mock_loggers):
requests_mocker.post(url="https://test", status_code=400)
discord_client = DiscordClient()
with pytest.raises(HTTPError):
discord_client.send_information_to_discord(
stream=stream, profile_image=""
stream=stream, profile_image="", retry_count=6
)
assert len(mock_loggers.info_logger.call_args_list) == 1
assert mock_loggers.info_logger.call_args.args[0] == (
"Sending a message with an embed to the webhook..."
)
assert len(mock_loggers.warning_logger.call_args_list) == 1
assert mock_loggers.warning_logger.call_args.args[0] == (
"Aborted sending the embed to Discord."
)