activity: basic webhook alerts for automation failures

This commit is contained in:
Iain Learmonth 2022-05-14 10:18:00 +01:00
parent eb372bec59
commit ac4f9b4942
12 changed files with 300 additions and 3 deletions

View file

@ -38,6 +38,13 @@ class AbstractResource(db.Model):
deprecation_reason = db.Column(db.String(), nullable=True)
destroyed = db.Column(db.DateTime(), nullable=True)
def __init__(self, **kwargs):
super().__init__(**kwargs)
if self.added is None:
self.added = datetime.utcnow()
if self.updated is None:
self.updated = datetime.utcnow()
def deprecate(self, *, reason: str):
self.deprecated = datetime.utcnow()
self.deprecation_reason = reason

46
app/models/activity.py Normal file
View file

@ -0,0 +1,46 @@
import datetime
import requests
from app.models import AbstractConfiguration
from app.extensions import db
class Activity(db.Model):
id = db.Column(db.Integer(), primary_key=True)
group_id = db.Column(db.Integer(), nullable=True)
activity_type = db.Column(db.String(20), nullable=False)
text = db.Column(db.Text(), nullable=False)
added = db.Column(db.DateTime(), nullable=False)
def __init__(self, **kwargs):
if type(kwargs["activity_type"]) != str or len(kwargs["activity_type"]) > 20 or kwargs["activity_type"] == "":
raise TypeError("expected string for activity type between 1 and 20 characters")
if type(kwargs["text"]) != str:
raise TypeError("expected string for text")
if "added" not in kwargs:
kwargs["added"] = datetime.datetime.utcnow()
super().__init__(**kwargs)
def notify(self) -> int:
count = 0
hooks = Webhook.query.filter(
Webhook.destroyed == None
)
for hook in hooks:
hook.send(self.text)
count += 1
return count
class Webhook(AbstractConfiguration):
format = db.Column(db.String(20))
url = db.Column(db.String(255))
def send(self, text: str):
if self.format == "telegram":
data = {"text": text}
else:
# Matrix as default
data = {"body": text}
r = requests.post(self.url, json=data)