-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.py
172 lines (147 loc) · 4.83 KB
/
webhook.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import requests
import os
import json
from datetime import datetime, timezone
from gpstrace import makeTrace
import sys
config = json.load(open("config.json", "r"))
webhookUrl = config["webhook"]
launches = 0
landings = 0
embeds = []
files = {}
# if replace returns formatted string
# else returns empty string or param
# builder("hello, {}", "world") -> "hello, world"
# builder("hello, {}", None, empty="no helllo") -> "no hello"
def builder(string: str, replace: str, empty=""):
if replace:
return string.format(replace)
return empty
b = builder
def launchPlane(flight):
global launches
generateEmbed("🛫 Launch", flight)
launches += 1
def landPlane(flight):
global landings
generateEmbed("🛬 Landing", flight)
landings += 1
def generateEmbed(event, flight):
def get(*path):
dat = flight
for key in path:
if (isinstance(dat, dict) and key in dat) or (
isinstance(dat, list) and isinstance(key, int) and len(dat) > key
):
dat = dat[key]
else:
return None
return dat
imgId = str(len(files))
trace = makeTrace(flight.get("trail", []))
print(end=".")
sys.stdout.flush()
if trace:
files[imgId] = (
f"{imgId}.webp",
trace,
"image/webp",
)
embeds.append(
{
"title": f"{event}: {get('aircraft', 'registration') or '??' }",
"description": get("status", "text") or "",
"fields": [
{
"name": "🛩️ Model:",
"value": get("aircraft", "model", "text") or "??",
"inline": True,
},
{
"name": "✈️ Operator",
"value": get("airline", "name") or "??",
"inline": True,
},
*({
"name": "ID:",
"value": get("identification", "number", "default") or "??",
"inline": True,
} if get("identification", "number", "default") else {}),
{
"name": "Callsign:",
"value": get("identification", "callsign") or "??",
"inline": True,
},
{
"name": "📍 Position:",
"value": f"[{round(get('trail',0,'lat') or 0, 2) or '??'}, {round(get('trail',0,'lng') or 0, 2) or '??'}](https://osm.org/?mlat={get('trail',0,'lat') or 0}&mlon={get('trail',0,'lng') or 0})",
"inline": True,
},
{
"name": "Altitude:",
"value": f"{round((get('trail', 0, 'alt') or 0) * 0.3048)}m",
"inline": True,
},
{
"name": "✈️ From",
"value": get("airport", "origin", "name") or "N/A",
"inline": False,
},
{
"name": "✈️ To",
"value": get("airport", "destination", "name") or "N/A",
"inline": False,
},
],
"thumbnail": {
"url": get("aircraft", "images", "large", 0, "src")
or "https://www.jetphotos.com/assets/img/placeholders/large.jpg"
},
"url": f"https://www.flightradar24.com/data/aircraft/{get('identification','callsign')}#{get('identification','id')}",
"color": int(config["embedColor"], base=16),
"timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")
+ "Z",
"image": {"url": f"attachment://{imgId}.webp"},
}
)
print(end=".")
sys.stdout.flush()
def sendMessage():
global embeds
global landings
global launches
global files
mode = config['mode']
if len(embeds) == 0:
if mode != "summary":
return # live mode
return requests.post(webhookUrl, data = {'content': "No flights today :("})
if mode == "live":
message = f'{b("🛬 {} Landings", landings)}\n{b("🛫 {} Launches", launches)}',
else:
message = f"{len(embeds)} flights today:"
payload_json = json.dumps(
{
"content": message,
"tts": False,
"username": config.get("name"),
"embeds": embeds,
"icon": config.get("icon"),
}
)
response = requests.post(
webhookUrl, files=files, data={"payload_json": payload_json}
)
if response.status_code != 200:
print("\n", response.text)
clear()
def clear():
global embeds
global landings
global launches
global files
embeds = []
files = {}
launches = 0
landings = 0