haldis/app/notification.py

58 lines
2 KiB
Python
Raw Normal View History

2019-09-10 15:17:35 +02:00
"Script that handles Haldis notifications on chat platforms"
import json
from datetime import datetime
from threading import Thread
import requests
from flask import current_app as app
from flask import url_for
2019-09-08 01:58:21 +02:00
def post_order_to_webhook(order_item) -> None:
2019-09-10 15:17:35 +02:00
"Function that sends the notification for the order"
2019-09-05 03:33:29 +02:00
message = ""
if order_item.courrier is not None:
2019-09-10 15:17:35 +02:00
message = "<!channel|@channel> {3} is going to {1}, order <{0}|here>! Deadline in {2} minutes!".format( # pylint: disable=C0301
url_for("order_bp.order_from_id", order_id=order_item.id,
_external=True),
2019-09-05 03:33:29 +02:00
order_item.location.name,
remaining_minutes(order_item.stoptime),
order_item.courrier.username.title(),
)
else:
2019-09-10 15:17:35 +02:00
message = "<!channel|@channel> New order for {}. Deadline in {} minutes. <{}|Open here.>".format( # pylint: disable=C0301
2019-09-05 03:33:29 +02:00
order_item.location.name,
remaining_minutes(order_item.stoptime),
2019-09-10 15:17:35 +02:00
url_for("order_bp.order_from_id",
order_id=order_item.id, _external=True),
2019-09-05 03:33:29 +02:00
)
2019-09-11 22:38:01 +02:00
webhookthread = WebhookSenderThread(message, app.config["SLACK_WEBHOOK"])
webhookthread.start()
class WebhookSenderThread(Thread):
2019-09-11 22:38:01 +02:00
def __init__(self, message: str, url: str) -> None:
2019-09-10 15:17:35 +02:00
"Extension of the Thread class, which sends a webhook for the notification"
super(WebhookSenderThread, self).__init__()
self.message = message
2019-09-11 22:38:01 +02:00
self.url = url
2019-09-08 01:58:21 +02:00
def run(self) -> None:
self.slack_webhook()
2019-09-08 01:58:21 +02:00
def slack_webhook(self) -> None:
2019-09-10 15:17:35 +02:00
"The webhook for the specified chat platform"
2019-09-11 22:38:01 +02:00
if self.url:
requests.post(url, json={"text": self.message})
else:
2019-09-11 22:38:01 +02:00
print(self.message)
2019-09-08 01:58:21 +02:00
def remaining_minutes(value) -> str:
2019-09-10 15:17:35 +02:00
"Return the remaining minutes until the deadline of and order"
delta = value - datetime.now()
if delta.total_seconds() < 0:
return "0"
2019-09-11 22:38:01 +02:00
minutes = delta.total_seconds() // 60
return "%02d" % minutes