From 850df45a69d8dcd5199760c4c47b6c915e73e820 Mon Sep 17 00:00:00 2001 From: Einar Forselv Date: Wed, 4 Dec 2019 20:31:58 +0100 Subject: [PATCH] Working discord webhook --- restic_compose_backup/alerts/discord.py | 39 +++++++++++++++++++++---- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/restic_compose_backup/alerts/discord.py b/restic_compose_backup/alerts/discord.py index 3fa918b..fc6ce48 100644 --- a/restic_compose_backup/alerts/discord.py +++ b/restic_compose_backup/alerts/discord.py @@ -1,19 +1,46 @@ +import os +import logging +from urllib.parse import urlparse + +import requests from restic_compose_backup.alerts.base import BaseAlert +logger = logging.getLogger(__name__) + class DiscordWebhookAlert(BaseAlert): name = 'discord_webhook' + success_codes = [200] - def __init__(self): - pass + def __init__(self, webhook_url): + self.url = webhook_url @classmethod - def create_from_env(self): + def create_from_env(cls): + instance = cls(os.environ.get('DISCORD_WEBHOOK')) + + if instance.properly_configured: + return instance + return None @property def properly_configured(self) -> bool: - return False + return isinstance(self.url, str) and self.url.startswith("https://") - def send(self, subject: str = None, attachment: str = None, alert_type: str = None): - pass + def send(self, subject: str = None, body: str = None, alert_type: str = None): + """Send basic webhook request. Max embed size is 6000""" + logger.info("Triggering discord webhook") + data = { + 'embeds': [ + { + 'title': subject, + 'description': body[:5000], + }, + ] + } + response = requests.post(self.url, params={'wait': True}, json=data) + if response.status_code not in self.success_codes: + log.error("Discord webhook failed: %s: %s", response.status_code, response.content) + else: + logger.info('Discord webhook successful')