-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
173 lines (146 loc) · 7.42 KB
/
server.js
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
173
const config = require("./config.json");
const fetch = (...args) => import("node-fetch").then(({ default: fetch }) => fetch(...args));
const tmi = require("tmi.js");
const airportData = require("./data/airport-codes.json");
const regionData = require("./data/iso_3166_2_region.json");
console.log("Twitch Plane Bot Starting...");
console.log(`oauth address: https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=${config.twitchAPI.clientId}&redirect_uri=http://localhost&scope=chat:edit+chat:read`);
const client = new tmi.Client({
options: { debug: config.twitchAPI.debug ?? false },
identity: {
username: config.twitchAPI.botUsername,
password: `oauth:${config.twitchAPI.token}`
},
channels: config.chatChannels
});
client.connect().catch(console.error);
client.on("message", (channel, tags, message, self) => {
if (self) return;
if (message.toLowerCase().trim().startsWith("!plane")) {
(async() => {
const data = await getFlightData();
if (data && data.flights) {
if (data.flights.length > 0) {
const nearestFlight = data.flights[0];
console.log("Nearest flight: ", nearestFlight);
// We will always have distance.
function getDistanceText() {
return ` It is ${nearestFlight.distanceToCenter.toFixed(1)} miles away!`;
}
function getModelText() {
if (nearestFlight.model !== "") {
function isVowel(str) {
return (str.toLowerCase().startsWith("a") || str.toLowerCase().startsWith("e") || str.toLowerCase().startsWith("i") || str.toLowerCase().startsWith("o") || str.toLowerCase().startsWith("u"));
}
return ` is ${isVowel(nearestFlight.model) ? "an" : "a"} ${nearestFlight.model}`;
}
}
function getCallsignOrFlightText() {
if (nearestFlight.callsign !== "") {
return ` flight ${nearestFlight.callsign}`;
}
else if (nearestFlight.flight !== "") {
return ` flight ${nearestFlight.flight}`;
}
else {
return "";
}
}
function getCountryNameFromISO(isoCountry) {
const countrySet = regionData[isoCountry];
if (!countrySet) {
return isoCountry;
}
return countrySet.name;
}
function getRegionNameFromISO(isoCountry, isoRegion) {
const countrySet = regionData[isoCountry];
const region = countrySet.divisions[isoRegion];
return region;
}
function getOriginText() {
if (nearestFlight.origin !== "") {
const airport = airportData.filter(a => a.iata_code === nearestFlight.origin)[0];
console.log("airport", airport);
if (!airport) {
return ` from ${nearestFlight.origin}`;
}
else {
// Replace US with state, as a primarily American audience is more familiar with this nomenclature.
if (airport.iso_country === "US") {
return ` from ${airport.municipality}, ${getRegionNameFromISO(airport.iso_country, airport.iso_region)}`;
}
else {
return ` from ${airport.municipality}, ${getCountryNameFromISO(airport.iso_country)}`;
}
}
}
else {
return "";
}
}
function getDestinationText() {
if (nearestFlight.destination !== "") {
const airport = airportData.filter(a => a.iata_code === nearestFlight.destination)[0];
console.log("airport", airport);
if (!airport) {
return ` to ${nearestFlight.destination}`;
}
else {
// Replace US with state, as a primarily American audience is more familiar with this nomenclature.
if (airport.iso_country === "US") {
return ` to ${airport.municipality}, ${getRegionNameFromISO(airport.iso_country, airport.iso_region)}`;
}
else {
return ` to ${airport.municipality}, ${getCountryNameFromISO(airport.iso_country)}`;
}
}
}
else {
return "";
}
}
client.say(channel, `The nearest plane${getModelText()},${getCallsignOrFlightText()}${getOriginText()}${getDestinationText()}.${getDistanceText()}`);
}
else {
client.say(channel, `There are no known planes within ${config.expandRadiusMiles} miles of the streamer.`);
}
}
else {
client.say(channel, "Could not retreive the streamer's location.");
}
})();
}
});
async function getFlightData() {
try {
const locationResponse = await fetch(`${config.relayAPI.host}:${config.relayAPI.port}${config.relayAPI.endpoint}`);
const locationData = await locationResponse.json();
console.log("Location data:", locationData);
if (Date.now() - locationData.reportedAt > (config.stalenessTimeoutMinutes * 60 * 1000)) {
console.log("Location data is stale.");
return null;
}
if (locationData.latitude && locationData.longitude) {
const params = new URLSearchParams();
params.append("north_lat", locationData.latitude);
params.append("west_long", locationData.longitude);
params.append("south_lat", locationData.latitude);
params.append("east_long", locationData.longitude);
params.append("center_lat", locationData.latitude);
params.append("center_long", locationData.longitude);
params.append("expand_radius", config.expandRadiusMiles * 0.0144927536231884);
const flightResponse = await fetch(`${config.flightAPI.host}:${config.flightAPI.port}/getflights?${params}`);
const flightData = await flightResponse.json();
console.log(`Found ${flightData.flights.length} flights`);
return flightData;
}
else {
console.log("Location could not be retreived at this time.");
}
}
catch (e) {
console.log(`Error: ${e}`);
return null;
}
}