Add D-ATIS from clowd.io

This commit is contained in:
Skylar Grant 2024-06-22 09:17:24 -04:00
parent 6700e36907
commit 444bad7935
4 changed files with 104 additions and 12 deletions

File diff suppressed because one or more lines are too long

24
dot-commands/datis.js Normal file
View File

@ -0,0 +1,24 @@
const fn = require('../functions');
module.exports = {
name: 'datis',
description: 'Lookup dATIS for an airport',
usage: 'ICAO.datis',
alias: [ 'atis' ],
async execute(message, commandData) {
try {
const icaoId = commandData.args;
if (icaoId.length !== 4) throw new Error('Not enough or too many ICAO IDs!')
const datisData = await fn.avWx.datis.getData(icaoId);
const messagePayload = fn.avWx.datis.parseData(datisData[0]);
message.reply(messagePayload);
} catch (e) {
try {
message.reply(`Something went wrong while retrieving the METAR: ${e.name}\n\n${e.message}`);
console.error(e);
} catch (e) {
console.error(e);
}
}
}
}

View File

@ -14,6 +14,7 @@ const ownerId = process.env.ownerId;
// filesystem // filesystem
const fs = require('fs'); const fs = require('fs');
const zlib = require('zlib');
// Discord.js // Discord.js
const Discord = require('discord.js'); const Discord = require('discord.js');
@ -25,6 +26,9 @@ const FuzzySearch = require('fuzzy-search');
// const OpenAI = require("openai"); // const OpenAI = require("openai");
// const openai = new OpenAI(); // const openai = new OpenAI();
// Axios for APIs
const axios = require('axios');
// Various imports from other files // Various imports from other files
const config = require('./config.json'); const config = require('./config.json');
const strings = require('./strings.json'); const strings = require('./strings.json');
@ -34,7 +38,6 @@ const dotCommandFiles = fs.readdirSync('./dot-commands/').filter(file => file.en
// MySQL database connection // MySQL database connection
const mysql = require('mysql'); const mysql = require('mysql');
const { GifData, PastaData } = require('./CustomModules/NodBot'); const { GifData, PastaData } = require('./CustomModules/NodBot');
const axios = require('axios');
const db = new mysql.createPool({ const db = new mysql.createPool({
connectionLimit: 10, connectionLimit: 10,
host: dbHost, host: dbHost,
@ -401,18 +404,32 @@ const functions = {
}); });
const embed = new Discord.MessageEmbed() const embed = new Discord.MessageEmbed()
.setAuthor({ name: `${metarData.name} [${metarData.icaoId}] METAR`, iconURL: "https://aviationweather.gov/img/icons/awc-logo-180.png"}) .setAuthor({ name: `${metarData.name} [${metarData.icaoId}] METAR`, iconURL: "https://aviationweather.gov/img/icons/awc-logo-180.png"})
.setImage("https://media.discordapp.net/stickers/1175134632845516821.webp") // .setImage("https://media.discordapp.net/stickers/1175134632845516821.webp")
.setDescription(`**Not for real world use!**\n\n${metarData.rawOb}`) .setDescription(`**Not for real world use!**\n\n${metarData.rawOb}`)
.setFooter({ text: "METAR by AviationWeather.gov for CumbHub LLC" }) .setFooter({ text: "METAR by AviationWeather.gov for CumbHub LLC" })
.addFields( .addFields(
{ name: 'Observation Time', value: `${metarData.reportTime}Z` }, { name: 'Observation Time', value: `${metarData.reportTime}Z` },
{ name: 'Temperature', value: `${metarData.temp}ºC/${metarData.dewp}ºC`}, { name: 'Temperature', value: `${metarData.temp}ºC/${metarData.dewp}ºC`},
{ name: 'Winds', value: `${metarData.wdir}º@${metarData.wspd}${wgst} kts`}, { name: 'Winds', value: `${metarData.wdir.toString().padStart(3, '0')}º@${metarData.wspd}${wgst} kts`},
{ name: 'Visibility', value: `${metarData.visib} SM` }, { name: 'Visibility', value: `${metarData.visib} SM` },
{ name: 'Clouds', value: clouds.join('\n') }, { name: 'Clouds', value: clouds.join('\n') },
{ name: 'Altimeter', value: `${altim} inHg` } { name: 'Altimeter', value: `${altim} inHg` }
) )
return { embeds: [embed] }; return { embeds: [embed] };
},
datis(datisData) {
const messageEmbed = new Discord.MessageEmbed()
.setAuthor({ name: `${datisData.airport} Digital ATIS` })
// .setImage('https://media.discordapp.net/stickers/1175134632845516821.webp')
.setDescription(`**Do not use for real world flight planning or navigation.**\n\n${datisData.datis}`)
.addFields(
{ name: 'Information', value: `${datisData.code}` },
{ name: 'Retreival Time', value: `${new Date().toISOString()}` }
)
.setFooter({ text: 'D-ATIS by Clowd.io for CumbHub LLC' })
const messagePayload = { embeds: [ messageEmbed ] };
return messagePayload;
} }
} }
}, },
@ -760,13 +777,42 @@ const functions = {
}, },
metar: { metar: {
async getAllICAOs() { async getAllICAOs() {
const reqUrl = `https://aviationweather.gov/api/data/metar?format=json` const reqUrl = `https://aviationweather.gov/data/cache/stations.cache.json.gz`
const response = await axios.get(reqUrl); try {
let icaoArray = []; // Step 1: Download the GZipped file
response.data.forEach(e => { const response = await axios({
icaoArray.push(e.icaoId) url: reqUrl,
method: 'GET',
responseType: 'arraybuffer', // Ensure we get the raw binary data
headers: {
'Accept-Encoding': 'gzip' // Ensure the server sends gzipped content
}
}); });
return icaoArray;
// Step 2: Decompress the GZipped content
const buffer = Buffer.from(response.data);
zlib.gunzip(buffer, (err, decompressedBuffer) => {
if (err) {
console.error('An error occurred during decompression:', err);
return;
}
// Step 3: Parse the decompressed JSON
const jsonString = decompressedBuffer.toString('utf-8');
try {
const jsonData = JSON.parse(jsonString);
// console.log('Parsed JSON data:', jsonData);
jsonData.forEach(airport => {
config.icaoIds.push(airport.icaoId);
});
// console.log(`ICAO IDs: ${config.icaoIds.length}\n\n${config.icaoIds}`)
} catch (jsonError) {
console.error('An error occurred while parsing JSON:', jsonError);
}
});
} catch (error) {
console.error('An error occurred during the HTTP request:', error);
}
}, },
async getData(icaoList) { async getData(icaoList) {
const reqUrl = `https://aviationweather.gov/api/data/metar?ids=${icaoList}&format=json`; const reqUrl = `https://aviationweather.gov/api/data/metar?ids=${icaoList}&format=json`;
@ -780,6 +826,27 @@ const functions = {
}) })
return messages; return messages;
} }
},
datis: {
async getAllICAOs() {
const reqUrl = 'https://datis.clowd.io/api/stations';
const response = await axios.get(reqUrl);
response.forEach(icaoId => {
config.datisICAOs.push(icaoId);
});
},
validate(icaoId) {
return config.datisICAOs.includes(icaoId);
},
async getData(icaoId) {
const reqUrl = `https://datis.clowd.io/api/${icaoId}`;
const response = await axios.get(reqUrl);
if (response.error !== undefined) throw new Error('The D-ATIS API returned an error:\n' + response.error);
return response.data;
},
parseData(datisData) {
return functions.embeds.avWx.datis(datisData);
}
} }
}, },
generateErrorId() { generateErrorId() {

View File

@ -42,7 +42,7 @@ client.once('ready', async () => {
await fn.download.strains(client); await fn.download.strains(client);
await fn.download.medicalAdvice(client); await fn.download.medicalAdvice(client);
console.log('Ready!'); console.log('Ready!');
// const icaoArray = await fn.avWx.metar.getAllICAOs(); await fn.avWx.metar.getAllICAOs();
// console.log(JSON.stringify(icaoArray)); // console.log(JSON.stringify(icaoArray));
client.channels.fetch(statusChannelId).then(channel => { client.channels.fetch(statusChannelId).then(channel => {
channel.send(`${new Date().toISOString()} -- <@${process.env.ownerId}>\nStartup Sequence Complete`); channel.send(`${new Date().toISOString()} -- <@${process.env.ownerId}>\nStartup Sequence Complete`);