aboutsummaryrefslogtreecommitdiff
path: root/modules/role/templates/cryptoportfolio/api_logger.py.erb
blob: ad296e8f429195c7ef55c5cd1c36322c037eb94c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/python

import time
import urllib3
import json
from systemd import journal

urllib3.disable_warnings()
http = urllib3.PoolManager()

webhook_url = "<%= @slack_logger %>"
webhook_username = "<%= @slack_logger_username %>"
webhook_icon = "https://git.immae.eu/releases/logger.png"

def send_to_discord(message):
    def send_chunk(chunk):
        data = {
                "avatar_url": webhook_icon,
                "username": webhook_username,
                "content": "```\n{}\n```".format(chunk),
                }
        encoded = json.dumps(data).encode('utf-8')

        r = http.request("POST", webhook_url,
                headers={'Content-Type': 'application/json'},
                body=encoded)
        if r.status == 429:
            b = json.loads(r.data)
            time.sleep(b["retry_after"] / 900)
            r = http.request("POST", webhook_url,
                    headers={'Content-Type': 'application/json'},
                    body=encoded)
        assert r.status < 299

    chunk = ""
    for line in message.split("\n"):
        if len(line) + len(chunk) > 2000 - 17:
            send_chunk(chunk)
            chunk = line
        else:
            chunk += "\n" + line
    send_chunk(chunk)

j = journal.Reader()
j.add_match(_SYSTEMD_UNIT="cryptoportfolio-app.service")
j.seek_tail()
list(j)

while True:
    lines = [entry["MESSAGE"] for entry in list(j)]
    if len(lines) > 0:
        send_to_discord("\n".join(lines))
    j.wait()