2019-12-04 19:31:58 +00:00
|
|
|
import os
|
|
|
|
import logging
|
|
|
|
from urllib.parse import urlparse
|
|
|
|
|
|
|
|
import requests
|
2019-12-04 02:58:27 +00:00
|
|
|
from restic_compose_backup.alerts.base import BaseAlert
|
|
|
|
|
2019-12-04 19:31:58 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2019-12-04 02:58:27 +00:00
|
|
|
|
|
|
|
class DiscordWebhookAlert(BaseAlert):
|
|
|
|
name = 'discord_webhook'
|
2019-12-04 19:31:58 +00:00
|
|
|
success_codes = [200]
|
2019-12-04 02:58:27 +00:00
|
|
|
|
2019-12-04 19:31:58 +00:00
|
|
|
def __init__(self, webhook_url):
|
|
|
|
self.url = webhook_url
|
2019-12-04 02:58:27 +00:00
|
|
|
|
2019-12-04 18:36:14 +00:00
|
|
|
@classmethod
|
2019-12-04 19:31:58 +00:00
|
|
|
def create_from_env(cls):
|
|
|
|
instance = cls(os.environ.get('DISCORD_WEBHOOK'))
|
|
|
|
|
|
|
|
if instance.properly_configured:
|
|
|
|
return instance
|
|
|
|
|
2019-12-04 18:36:14 +00:00
|
|
|
return None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def properly_configured(self) -> bool:
|
2019-12-04 19:31:58 +00:00
|
|
|
return isinstance(self.url, str) and self.url.startswith("https://")
|
2019-12-04 02:58:27 +00:00
|
|
|
|
2019-12-04 19:31:58 +00:00
|
|
|
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')
|