test 1
This commit is contained in:
parent
a543386394
commit
31db7887e3
1
funcs.js
1
funcs.js
|
@ -1,4 +1,3 @@
|
||||||
const geolib = require("geolib");
|
|
||||||
// Use OSM API to get coordinates https://nominatim.openstreetmap.org/search?q=search+query&format=json&limit=1
|
// Use OSM API to get coordinates https://nominatim.openstreetmap.org/search?q=search+query&format=json&limit=1
|
||||||
const getCoordinates = async (location) => {
|
const getCoordinates = async (location) => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
|
662
index.js
662
index.js
|
@ -3,25 +3,23 @@ const fs = require("fs");
|
||||||
const config = require("./config.json");
|
const config = require("./config.json");
|
||||||
const funcs = require("./funcs.js");
|
const funcs = require("./funcs.js");
|
||||||
const wfos = require("./data/wfos.json");
|
const wfos = require("./data/wfos.json");
|
||||||
const blacklist = require("./data/blacklist.json");
|
|
||||||
const events = require("./data/events.json");
|
|
||||||
const outlookURLs = require("./data/outlook.json");
|
const outlookURLs = require("./data/outlook.json");
|
||||||
const satellites = require("./data/satellites.json");
|
const satellites = require("./data/satellites.json");
|
||||||
const nwrstreams = {callsigns:{}};
|
const nwrstreams = { callsigns: {} };
|
||||||
const Jimp = require("jimp");
|
const Jimp = require("jimp");
|
||||||
const { client, xml } = require("@xmpp/client");
|
|
||||||
const fetch = require("node-fetch");
|
const fetch = require("node-fetch");
|
||||||
const html = require("html-entities")
|
const html = require("html-entities")
|
||||||
const Discord = require("discord.js");
|
const Discord = require("discord.js");
|
||||||
const dVC = require("@discordjs/voice");
|
const dVC = require("@discordjs/voice");
|
||||||
const colors = require("colors");
|
const colors = require("colors");
|
||||||
const sqlite3 = require("sqlite3").verbose();
|
const sqlite3 = require("sqlite3").verbose();
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
satMessages = {};
|
satMessages = {};
|
||||||
|
|
||||||
// Setup Discord
|
// Setup Discord
|
||||||
const discord = new Discord.Client({
|
const discord = new Discord.Client({
|
||||||
|
|
||||||
intents: [
|
intents: [
|
||||||
"Guilds",
|
"Guilds",
|
||||||
"GuildVoiceStates",
|
"GuildVoiceStates",
|
||||||
|
@ -260,8 +258,7 @@ var iem = []
|
||||||
var startup = true;
|
var startup = true;
|
||||||
var startTimestap = new Date();
|
var startTimestap = new Date();
|
||||||
var messages = 0;
|
var messages = 0;
|
||||||
var errCount = 0;
|
|
||||||
const curUUID = generateUUID();
|
|
||||||
|
|
||||||
|
|
||||||
// nwrstreams setup
|
// nwrstreams setup
|
||||||
|
@ -282,340 +279,320 @@ const fetchNWRstreams = () => {
|
||||||
fetchNWRstreams();
|
fetchNWRstreams();
|
||||||
setInterval(fetchNWRstreams, 5 * 60 * 1000); // Every 5 minutes
|
setInterval(fetchNWRstreams, 5 * 60 * 1000); // Every 5 minutes
|
||||||
|
|
||||||
const xmpp = client({
|
|
||||||
service: "xmpp://conference.weather.im",
|
|
||||||
domain: "weather.im",
|
|
||||||
resource: `discord-weather-bot-${generateRandomString({ upper: true, lower: true, number: true }, 5)}`, // Weird fix to "Username already in use"
|
|
||||||
});
|
|
||||||
|
|
||||||
//debug(xmpp, true);
|
/* We are replacing the xmpp client with a websocket.
|
||||||
|
The new data will look something like this
|
||||||
|
{
|
||||||
|
type: 'iem-message',
|
||||||
|
data: {
|
||||||
|
channel: { room: 'botstalk', location: 'All_Bots_Talk' },
|
||||||
|
event: { priority: 1, text: 'Marine Weather Message', code: 'MWW' },
|
||||||
|
body: 'LCH updates Small Craft Advisory (expires Coastal waters from Cameron LA to High Island TX out 20 NM, Coastal waters from Intracoastal City to Cameron LA out 20 NM, Coastal waters from Lower Atchafalaya River to Intracoastal City LA out 20 NM [GM], continues Waters from Cameron LA to High Island TX from 20 to 60 NM, Waters from Intracoastal City to
|
||||||
|
Cameron LA from 20 to 60 NM, Waters from Lower Atchafalaya River to Intracoastal City LA from 20 to 60 NM [GM]) . ',
|
||||||
|
timestamp: '2025-04-20T15:12:22.000Z',
|
||||||
|
wmo: 'WHUS74',
|
||||||
|
pil: 'MWWLCH',
|
||||||
|
station: 'KLCH',
|
||||||
|
raw: '202504201512-KLCH-WHUS74-MWWLCH',
|
||||||
|
rawBody: 'LCH updates Small Craft Advisory (expires Coastal waters from Cameron LA to High Island TX out 20 NM, Coastal waters from Intracoastal City to Cameron LA out 20 NM, Coastal waters from Lower Atchafalaya River to Intracoastal City LA out 20 NM [GM], continues Waters from Cameron LA to High Island TX from 20 to 60 NM, Waters from Intracoastal City
|
||||||
|
to Cameron LA from 20 to 60 NM, Waters from Lower Atchafalaya River to Intracoastal City LA from 20 to 60 NM [GM]) . https://mesonet.agron.iastate.edu/vtec/f/2025-O-EXP-KLCH-SC-Y-0028_2025-04-20T15:12Z',
|
||||||
|
image: 'https://mesonet.agron.iastate.edu/plotting/auto/plot/208/network:WFO::wfo:LCH::year:2025::phenomenav:SC::significancev:Y::etn:28::valid:2025-04-20%201512::_r:86.png',
|
||||||
|
productText: '570 \n' +
|
||||||
|
'WHUS74 KLCH 201512\n' +
|
||||||
|
'MWWLCH\n' +
|
||||||
|
'\n' +
|
||||||
|
'URGENT - MARINE WEATHER MESSAGE\n' +
|
||||||
|
'National Weather Service Lake Charles LA\n' +
|
||||||
|
'1012 AM CDT Sun Apr 20 2025\n' +
|
||||||
|
'\n' +
|
||||||
|
'GMZ450-452-455-201615-\n' +
|
||||||
|
'/O.EXP.KLCH.SC.Y.0028.000000T0000Z-250420T1500Z/\n' +
|
||||||
|
'Coastal waters from Cameron LA to High Island TX out 20 NM-\n' +
|
||||||
|
'Coastal waters from Intracoastal City to Cameron LA out 20 NM-\n' +
|
||||||
|
'Coastal waters from Lower Atchafalaya River to Intracoastal City\n' +
|
||||||
|
'LA out 20 NM-\n' +
|
||||||
|
'1012 AM CDT Sun Apr 20 2025\n' +
|
||||||
|
'\n' +
|
||||||
|
'...SMALL CRAFT ADVISORY HAS EXPIRED...\n' +
|
||||||
|
'\n' +
|
||||||
|
'$$\n' +
|
||||||
|
'\n' +
|
||||||
|
'GMZ470-472-475-202100-\n' +
|
||||||
|
'/O.CON.KLCH.SC.Y.0028.000000T0000Z-250420T2100Z/\n' +
|
||||||
|
'Coastal waters from Cameron LA to High Island TX from 20 to 60 NM-\n' +
|
||||||
|
'Coastal waters from Intracoastal City to Cameron LA from 20 to\n' +
|
||||||
|
'60 NM-\n' +
|
||||||
|
'Coastal waters from Lower Atchafalaya River to Intracoastal City\n' +
|
||||||
|
'LA from 20 to 60 NM-\n' +
|
||||||
|
'1012 AM CDT Sun Apr 20 2025\n' +
|
||||||
|
'\n' +
|
||||||
|
'...SMALL CRAFT ADVISORY REMAINS IN EFFECT UNTIL 4 PM CDT THIS\n' +
|
||||||
|
'AFTERNOON...\n' +
|
||||||
|
'\n' +
|
||||||
|
'* WHAT...Seas 4 to 7 ft.\n' +
|
||||||
|
'\n' +
|
||||||
|
'* WHERE...Coastal waters from Cameron LA to High Island TX from \n' +
|
||||||
|
' 20 to 60 NM, Coastal waters from Intracoastal City to Cameron \n' +
|
||||||
|
' LA from 20 to 60 NM and Coastal waters from Lower Atchafalaya \n' +
|
||||||
|
' River to Intracoastal City LA from 20 to 60 NM.\n' +
|
||||||
|
'\n' +
|
||||||
|
'* WHEN...Until 4 PM CDT this afternoon.\n' +
|
||||||
|
'\n' +
|
||||||
|
'* IMPACTS...Conditions will be hazardous to small craft.\n' +
|
||||||
|
'\n' +
|
||||||
|
'PRECAUTIONARY/PREPAREDNESS ACTIONS...\n' +
|
||||||
|
'\n' +
|
||||||
|
'Inexperienced mariners, especially those operating smaller\n' +
|
||||||
|
'vessels, should avoid navigating in hazardous conditions.\n' +
|
||||||
|
'\n' +
|
||||||
|
'&&\n' +
|
||||||
|
'\n' +
|
||||||
|
'$$\n'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
xmpp.on("error", (err) => {
|
Image and product text are optional, but if they exist, they will be in the data object.
|
||||||
console.log(`${colors.red("[ERROR]")} XMPP Error: ${err}. Trying to reconnect...`);
|
|
||||||
setTimeout(() => {
|
|
||||||
xmpp.stop().then(() => {
|
|
||||||
start();
|
|
||||||
});
|
|
||||||
}, 5000);
|
|
||||||
});
|
|
||||||
|
|
||||||
xmpp.on("offline", () => {
|
*/
|
||||||
console.log(`${colors.yellow("[WARN]")} XMPP offline, trying to reconnect...`);
|
|
||||||
xmpp.disconnect().then(() => {
|
|
||||||
xmpp.stop().then(() => {
|
|
||||||
start();
|
|
||||||
})
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
var restartTimer = null;
|
const handleDiscordGuilds = function (data) {
|
||||||
|
const rawBody = data.data.body;
|
||||||
xmpp.on("stanza", (stanza) => {
|
const text = data.data.productText;
|
||||||
// Debug stuff
|
const product_id_raw = data.data.raw
|
||||||
if (config.debug >= 2) console.log(`${colors.magenta("[DEBUG]")} Stanza: ${stanza.toString()}`);
|
const product_id = data.product_data;
|
||||||
|
const fromChannel = data.data.channel.room;
|
||||||
|
const bodyData = data.data.body;
|
||||||
|
|
||||||
|
|
||||||
// Handle Room List
|
let embed = {
|
||||||
if (stanza.is("iq") && stanza.attrs.type === "result" && stanza.getChild("query")) {
|
description: `<t:${product_id.timestamp / 1000}:T> <t:${product_id.timestamp / 1000}:R> ${bodyData.string}`,
|
||||||
query = stanza.getChild("query");
|
color: parseInt(config.priorityColors[evt.priority].replace("#", ""), 16) || 0x000000,
|
||||||
if (query.attrs.xmlns === "http://jabber.org/protocol/disco#items") {
|
timestamp: product_id.timestamp,
|
||||||
query.getChildren("item").forEach((item) => {
|
footer: {
|
||||||
// Check if the JID is on the blacklist, if so, ignore it
|
text: `Station: ${product_id.station} PID: ${product_id_raw} Channel: ${fromChannel}`
|
||||||
if (blacklist.includes(item.attrs.jid)) return;
|
}
|
||||||
// get proper name from wfos
|
}
|
||||||
const wfo = getWFOByRoom(item.attrs.jid.split("@")[0]);
|
if (data.data.image) {
|
||||||
item.attrs.properName = wfo.location;
|
embed.image = {
|
||||||
iem.push(item.attrs);
|
url: data.data.image
|
||||||
console.log(`${colors.cyan("[INFO]")} Found room: ${item.attrs.jid}`);
|
|
||||||
// Join the room
|
|
||||||
//xmpp.send(xml("presence", { to: `${channel.jid}/${channel.name}/${curUUID}` }, xml("item", { role: "visitor" })));
|
|
||||||
xmpp.send(xml("presence", { to: `${item.attrs.jid}/${curUUID}` }, xml("item", { role: "visitor" })));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Get new messages and log them, ignore old messages
|
|
||||||
if (stanza.is("message") && stanza.attrs.type === "groupchat") {
|
|
||||||
clearTimeout(restartTimer)
|
|
||||||
restartTimer = setTimeout(() => {
|
|
||||||
console.log(`${colors.red("[FATAL]")} No messages from weather.im in 10 minutes, restarting!!!!!!!!!!!`)
|
|
||||||
process.exit(1)
|
|
||||||
}, 600000)
|
|
||||||
// Stops spam from getting old messages
|
|
||||||
if (startup) return;
|
|
||||||
// Get channel name
|
|
||||||
fromChannel = stanza.attrs.from.split("@")[0];
|
|
||||||
// Ignores
|
|
||||||
if (!stanza.getChild("x")) return; // No PID, ignore it
|
|
||||||
if (!stanza.getChild("x").attrs.product_id) return;
|
|
||||||
|
|
||||||
const product_id = parseProductID(stanza.getChild("x").attrs.product_id);
|
let discordMsg = {
|
||||||
const product_id_raw = stanza.getChild("x").attrs.product_id;
|
embeds: [embed],
|
||||||
// Get body of message
|
components: [
|
||||||
const body = html.decode(stanza.getChildText("body"));
|
{
|
||||||
const bodyData = getFirstURL(body);
|
type: 1,
|
||||||
// get product id from "x" tag
|
components: [
|
||||||
var evt = events[product_id.pil.substring(0, 3)];
|
|
||||||
|
|
||||||
if (!evt) {
|
|
||||||
evt = { name: "Unknown", priority: 3 }
|
|
||||||
console.log(`${colors.red("[ERROR]")} Unknown event type: ${product_id.pil.substring(0, 3)}. Fix me`);
|
|
||||||
console.log(`${colors.magenta("[DEBUG]")} ${bodyData.string}`)
|
|
||||||
const logChannel = discord.guilds.cache.get(config.discord.mainGuild).channels.cache.get(config.discord.logChannel);
|
|
||||||
logChannel.send({
|
|
||||||
embeds: [
|
|
||||||
{
|
{
|
||||||
title: "Unknown Event Type",
|
type: 2,
|
||||||
description: `Unknown event type: ${product_id.pil.substring(0, 3)}. Please check the logs for more details.`,
|
label: "Product",
|
||||||
color: 0xff0000
|
style: 5,
|
||||||
|
url: bodyData.url
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 2,
|
||||||
|
style: 1,
|
||||||
|
custom_id: `product|${product_id_raw}`,
|
||||||
|
label: "Product Text",
|
||||||
|
emoji: {
|
||||||
|
name: "📄"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
evt.code = product_id.pil.substring(0, 3);
|
|
||||||
// Check timestamp, if not within 3 minutes, ignore it
|
|
||||||
const now = new Date();
|
|
||||||
const diff = (now - product_id.timestamp) / 1000 / 60;
|
|
||||||
if (diff > 3) return;
|
|
||||||
// if (config.debug >= 1) console.log(`${colors.magenta("[DEBUG]")} New message from ${fromChannel}`);
|
|
||||||
console.log(`${colors.cyan("[INFO]")} ${getWFOByRoom(fromChannel).location} - ${evt.text} - ${product_id.timestamp}`);
|
|
||||||
messages++;
|
|
||||||
|
|
||||||
|
|
||||||
// Handle NTFY
|
|
||||||
if (config.ntfy.enabled) {
|
|
||||||
//if (config.debug >= 1) console.log(`${colors.magenta("[DEBUG]")} Sending NTFY for ${config.ntfy.prefix}${fromChannel}`)
|
|
||||||
ntfyBody = {
|
|
||||||
"topic": `${config.ntfy.prefix}${fromChannel}`,
|
|
||||||
"message": bodyData.string,
|
|
||||||
"tags": [`Timestamp: ${product_id.timestamp}`, `Station: ${product_id.station}`, `WMO: ${product_id.wmo}`, `PIL: ${product_id.pil}`, `Channel: ${fromChannel}`],
|
|
||||||
"priority": evt.priority,
|
|
||||||
"actions": [{ "action": "view", "label": "Product", "url": bodyData.url }, { "action": "view", "label": "Product Text", "url": `https://mesonet.agron.iastate.edu/api/1/nwstext/${product_id_raw}` }]
|
|
||||||
}
|
}
|
||||||
if (stanza.getChild("x").attrs.twitter_media) {
|
]
|
||||||
ntfyBody.attach = stanza.getChild("x").attrs.twitter_media;
|
}
|
||||||
}
|
// Discord Channel Handling
|
||||||
fetch(config.ntfy.server, {
|
db.all(`SELECT * FROM channels WHERE iemchannel = ?`, [fromChannel], (err, rows) => {
|
||||||
method: 'POST',
|
if (err) {
|
||||||
body: JSON.stringify(ntfyBody),
|
console.log(`${colors.red("[ERROR]")} ${err.message}`);
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${config.ntfy.token}`
|
|
||||||
}
|
|
||||||
}).then((res) => {
|
|
||||||
//if (config.debug >= 1) console.log(`${colors.magenta("[DEBUG]")} NTFY sent for ${config.ntfy.prefix}${fromChannel} with status ${res.status} ${res.statusText}`);
|
|
||||||
if (res.status !== 200) console.log(`${colors.red("[ERROR]")} NTFY failed for ${config.ntfy.prefix}${fromChannel} with status ${res.status} ${res.statusText}`);
|
|
||||||
|
|
||||||
|
|
||||||
}).catch((err) => {
|
|
||||||
console.error(err)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
if (!rows) return; // No channels to alert
|
||||||
|
rows.forEach(async (row) => {
|
||||||
|
// Get Filters as arrays
|
||||||
|
if (!row.filterEvt) row.filterEvt = "";
|
||||||
|
if (!row.filter) row.filter = "";
|
||||||
|
let filterEvt = row.filterEvt.toLowerCase().split(",");
|
||||||
|
let filters = row.filter.toLowerCase().split(",");
|
||||||
|
if (evt.priority < row.minPriority) return;
|
||||||
|
// If the event type is not in th filter, ignore it. Make sure filterEvt isnt null
|
||||||
|
if (!filterEvt[0]) filterEvt = [];
|
||||||
|
if (!filterEvt.includes(evt.code.toLowerCase()) && !filterEvt.length == 0) return;
|
||||||
|
|
||||||
|
let channel = discord.channels.cache.get(row.channelid);
|
||||||
|
if (!channel) return console.log(`${colors.red("[ERROR]")} Channel ${row.channelid} not found`);
|
||||||
|
|
||||||
// Send discord msg
|
if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return;
|
||||||
let embed = {
|
thisMsg = JSON.parse(JSON.stringify(discordMsg));
|
||||||
description: `<t:${product_id.timestamp / 1000}:T> <t:${product_id.timestamp / 1000}:R> ${bodyData.string}`,
|
thisMsg.content = row.custommessage || null;
|
||||||
color: parseInt(config.priorityColors[evt.priority].replace("#", ""), 16) || 0x000000,
|
channel.send(thisMsg).catch((err) => {
|
||||||
timestamp: product_id.timestamp,
|
console.error(err);
|
||||||
footer: {
|
}).then((msg) => {
|
||||||
text: `Station: ${product_id.station} PID: ${product_id_raw} Channel: ${fromChannel}`
|
if (msg.channel.type === Discord.ChannelType.GuildAnnouncement) msg.crosspost();
|
||||||
}
|
}).catch(() => {
|
||||||
}
|
console.log(`${colors.yellow("[WARN]")} Failed to send message to ${channel.guild.name}/${channel.name} (${channel.guild.id}/${channel.id})`);
|
||||||
if (stanza.getChild("x").attrs.twitter_media) {
|
const logChannel = discord.guilds.cache.get(config.discord.mainGuild).channels.cache.get(config.discord.logChannel);
|
||||||
embed.image = {
|
logChannel.send({
|
||||||
url: stanza.getChild("x").attrs.twitter_media
|
embeds: [
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let discordMsg = {
|
|
||||||
embeds: [embed],
|
|
||||||
components: [
|
|
||||||
{
|
|
||||||
type: 1,
|
|
||||||
components: [
|
|
||||||
{
|
{
|
||||||
type: 2,
|
title: "Failed to send message",
|
||||||
label: "Product",
|
description: `There is likely an issue with permissions. Please notify the server owner if possible.
|
||||||
style: 5,
|
Guild: ${channel.guild.name} (${channel.guild.id})
|
||||||
url: bodyData.url
|
Channel: ${channel.name} (${channel.id})
|
||||||
},
|
Guild Owner: <@${channel.guild.ownerId}> (${channel.guild.ownerId})
|
||||||
{
|
Sub Info: \`\`\`json\n${JSON.stringify(row)}\`\`\``,
|
||||||
type: 2,
|
color: 0xff0000
|
||||||
style: 1,
|
|
||||||
custom_id: `product|${product_id_raw}`,
|
|
||||||
label: "Product Text",
|
|
||||||
emoji: {
|
|
||||||
name: "📄"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
});
|
||||||
]
|
|
||||||
|
discord.users.fetch(channel.guild.ownerId).then((user) => {
|
||||||
|
user.send({
|
||||||
|
embeds: [
|
||||||
|
{
|
||||||
|
title: "Issue with your subscribed channel.",
|
||||||
|
description: `There is likely an issue with permissions. Please check that I can send messages in <#${channel.id}>\nYour subscription has been removed, and you will need to resubscribe to get alerts.`,
|
||||||
|
color: 0xff0000,
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "Guild",
|
||||||
|
value: `${channel.guild.name} (${channel.guild.id})`
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Channel",
|
||||||
|
value: `${channel.name} (${channel.id})`
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}).catch((err) => {
|
||||||
|
console.log(`${colors.red("[ERROR]")} Failed to send message to ${channel.guild.ownerId}`);
|
||||||
|
}).then(() => {
|
||||||
|
if (channel.guildId == config.discord.mainGuild) return;
|
||||||
|
db.run(`DELETE FROM channels WHERE channelid = ? AND iemchannel = ?`, [channel.id, fromChannel], (err) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err.message);
|
||||||
|
}
|
||||||
|
console.log(`${colors.cyan("[INFO]")} Deleted channel ${channel.id} from database`);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
// User DM alert handling
|
||||||
|
db.all(`SELECT * FROM userAlerts WHERE iemchannel = ?`, [fromChannel], (err, rows) => {
|
||||||
|
if (err) {
|
||||||
|
console.error(err.message);
|
||||||
}
|
}
|
||||||
// Discord Channel Handling
|
if (!rows) return; // No users to alert
|
||||||
db.all(`SELECT * FROM channels WHERE iemchannel = ?`, [fromChannel], (err, rows) => {
|
rows.forEach((row) => {
|
||||||
if (err) {
|
// Get Filters as arrays
|
||||||
console.log(`${colors.red("[ERROR]")} ${err.message}`);
|
if (!row.filterEvt) row.filterEvt = "";
|
||||||
}
|
if (!row.filter) row.filter = "";
|
||||||
if (!rows) return; // No channels to alert
|
let filterEvt = row.filterEvt.toLowerCase().split(",");
|
||||||
rows.forEach(async (row) => {
|
let filters = row.filter.toLowerCase().split(",");
|
||||||
// Get Filters as arrays
|
|
||||||
if (!row.filterEvt) row.filterEvt = "";
|
|
||||||
if (!row.filter) row.filter = "";
|
|
||||||
let filterEvt = row.filterEvt.toLowerCase().split(",");
|
|
||||||
let filters = row.filter.toLowerCase().split(",");
|
|
||||||
if (evt.priority < row.minPriority) return;
|
|
||||||
// If the event type is not in th filter, ignore it. Make sure filterEvt isnt null
|
|
||||||
if (!filterEvt[0]) filterEvt = [];
|
|
||||||
if (!filterEvt.includes(evt.code.toLowerCase()) && !filterEvt.length == 0) return;
|
|
||||||
|
|
||||||
let channel = discord.channels.cache.get(row.channelid);
|
// If priority is less than the min priority, ignore it
|
||||||
if (!channel) return console.log(`${colors.red("[ERROR]")} Channel ${row.channelid} not found`);
|
if (evt.priority < row.minPriority) return;
|
||||||
|
// If the event type is not in th filter, ignore it. Make sure filterEvt isnt null
|
||||||
|
if (!filterEvt[0]) filterEvt = [];
|
||||||
|
if (!filterEvt.includes(evt.code.toLowerCase()) && !filterEvt.length == 0) return;
|
||||||
|
let user = discord.users.cache.get(row.userid);
|
||||||
|
if (!user) return console.log(`${colors.red("[ERROR]")} User ${row.userid} not found`);
|
||||||
|
|
||||||
// fetch the product text
|
if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return;
|
||||||
trySend = () => {
|
thisMsg = JSON.parse(JSON.stringify(discordMsg));
|
||||||
fetch(`https://mesonet.agron.iastate.edu/api/1/nwstext/${product_id_raw}`).then((res) => {
|
thisMsg.content = row.custommessage || null;
|
||||||
// If neither the body nor the product text contains the filter, ignore it
|
user.send(thisMsg).catch((err) => {
|
||||||
res.text().then((text) => {
|
console.error(err);
|
||||||
if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return;
|
}).catch((err) => {
|
||||||
thisMsg = JSON.parse(JSON.stringify(discordMsg));
|
console.log(`${colors.yellow("[WARN]")} Failed to send message to ${user.tag} (${user.id})`);
|
||||||
thisMsg.content = row.custommessage || null;
|
const logChannel = discord.guilds.cache.get(config.discord.mainGuild).channels.cache.get(config.discord.logChannel);
|
||||||
channel.send(thisMsg).catch((err) => {
|
logChannel.send({
|
||||||
console.error(err);
|
embeds: [
|
||||||
}).then((msg) => {
|
{
|
||||||
if (msg.channel.type === Discord.ChannelType.GuildAnnouncement) msg.crosspost();
|
title: "Failed to send DM",
|
||||||
}).catch((err) => {
|
description: `User may have DMs disabled, or bot doesnt' share a server anymore!.
|
||||||
console.log(`${colors.yellow("[WARN]")} Failed to send message to ${channel.guild.name}/${channel.name} (${channel.guild.id}/${channel.id})`);
|
User: ${user.tag} (${user.id})
|
||||||
const logChannel = discord.guilds.cache.get(config.discord.mainGuild).channels.cache.get(config.discord.logChannel);
|
Sub Info: \`\`\`json\n${JSON.stringify(row)}\`\`\``,
|
||||||
logChannel.send({
|
color: 0xff0000
|
||||||
embeds: [
|
}
|
||||||
{
|
]
|
||||||
title: "Failed to send message",
|
}).then(() => {
|
||||||
description: `There is likely an issue with permissions. Please notify the server owner if possible.
|
db.run(`DELETE FROM userAlerts WHERE userid = ? AND iemchannel = ?`, [user.id, fromChannel], (err) => {
|
||||||
Guild: ${channel.guild.name} (${channel.guild.id})
|
if (err) {
|
||||||
Channel: ${channel.name} (${channel.id})
|
console.error(err.message);
|
||||||
Guild Owner: <@${channel.guild.ownerId}> (${channel.guild.ownerId})
|
}
|
||||||
Sub Info: \`\`\`json\n${JSON.stringify(row)}\`\`\``,
|
console.log(`${colors.cyan("[INFO]")} Deleted user ${user.id} from database`);
|
||||||
color: 0xff0000
|
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
discord.users.fetch(channel.guild.ownerId).then((user) => {
|
|
||||||
user.send({
|
|
||||||
embeds: [
|
|
||||||
{
|
|
||||||
title: "Issue with your subscribed channel.",
|
|
||||||
description: `There is likely an issue with permissions. Please check that I can send messages in <#${channel.id}>\nYour subscription has been removed, and you will need to resubscribe to get alerts.`,
|
|
||||||
color: 0xff0000,
|
|
||||||
fields: [
|
|
||||||
{
|
|
||||||
name: "Guild",
|
|
||||||
value: `${channel.guild.name} (${channel.guild.id})`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Channel",
|
|
||||||
value: `${channel.name} (${channel.id})`
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}).catch((err) => {
|
|
||||||
console.log(`${colors.red("[ERROR]")} Failed to send message to ${channel.guild.ownerId}`);
|
|
||||||
}).then(() => {
|
|
||||||
if (channel.guildId == config.discord.mainGuild) return;
|
|
||||||
db.run(`DELETE FROM channels WHERE channelid = ? AND iemchannel = ?`, [channel.id, fromChannel], (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err.message);
|
|
||||||
}
|
|
||||||
console.log(`${colors.cyan("[INFO]")} Deleted channel ${channel.id} from database`);
|
|
||||||
});
|
|
||||||
})
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}).catch((err) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
console.log(`${colors.red("[ERROR]")} Failed to fetch product text, retrying... ${err}`)
|
|
||||||
trySend();
|
|
||||||
})
|
|
||||||
});
|
});
|
||||||
}
|
})
|
||||||
trySend();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
var retries = 0;
|
||||||
|
|
||||||
|
function connectWebSocket() {
|
||||||
|
console.log('Attempting to connect to WebSocket...');
|
||||||
|
const ws = new WebSocket(config.WS_URL || "wss://iem-alerter.ko4wal.radio/iem");
|
||||||
|
|
||||||
|
ws.on('open', () => {
|
||||||
|
console.log('Connected to WebSocket');
|
||||||
|
ws.send(JSON.stringify({ type: 'subscribe', channel: '*' })); // Subscribe to all channels
|
||||||
|
retries = 0; // Reset retries on successful connection
|
||||||
|
});
|
||||||
|
|
||||||
|
ws.on('message', (data) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(data);
|
||||||
|
switch (data.type) {
|
||||||
|
case "iem-message":
|
||||||
|
handleDiscordGuilds(data);
|
||||||
|
handleDiscordDMs(data);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "internal-response":
|
||||||
|
if (data.code == 200) {
|
||||||
|
console.log(`${colors.cyan("[INFO]")} ${data.data.message}`);
|
||||||
|
} else {
|
||||||
|
console.log(`${colors.red(`[ERROR] ${data.code}`)} ${data.data.error}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "connection-info":
|
||||||
|
console.log(`${colors.cyan("[INFO]")} Connected to ${data.host} (${data.uuid})`);
|
||||||
|
iem = data.iem;
|
||||||
|
|
||||||
// User DM alert handling
|
|
||||||
db.all(`SELECT * FROM userAlerts WHERE iemchannel = ?`, [fromChannel], (err, rows) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err.message);
|
|
||||||
}
|
}
|
||||||
if (!rows) return; // No users to alert
|
} catch (err) {
|
||||||
rows.forEach((row) => {
|
console.log(`${colors.red("[ERROR]")} Error parsing WebSocket message: ${err}`);
|
||||||
// Get Filters as arrays
|
}
|
||||||
if (!row.filterEvt) row.filterEvt = "";
|
});
|
||||||
if (!row.filter) row.filter = "";
|
|
||||||
let filterEvt = row.filterEvt.toLowerCase().split(",");
|
|
||||||
let filters = row.filter.toLowerCase().split(",");
|
|
||||||
|
|
||||||
// If priority is less than the min priority, ignore it
|
ws.on('close', () => {
|
||||||
if (evt.priority < row.minPriority) return;
|
console.log('WebSocket connection closed. Reconnecting...');
|
||||||
// If the event type is not in th filter, ignore it. Make sure filterEvt isnt null
|
retries++;
|
||||||
if (!filterEvt[0]) filterEvt = [];
|
const retryDelay = Math.min(5000, Math.pow(2, retries) * 100);
|
||||||
if (!filterEvt.includes(evt.code.toLowerCase()) && !filterEvt.length == 0) return;
|
console.log(`Retrying connection in ${retryDelay} ms...`);
|
||||||
let user = discord.users.cache.get(row.userid);
|
setTimeout(connectWebSocket, retryDelay);
|
||||||
if (!user) return console.log(`${colors.red("[ERROR]")} User ${row.userid} not found`);
|
});
|
||||||
|
|
||||||
// fetch the product text
|
ws.on('error', (err) => {
|
||||||
trySend = () => {
|
console.error('WebSocket error:', err);
|
||||||
fetch(`https://mesonet.agron.iastate.edu/api/1/nwstext/${product_id_raw}`).then((res) => {
|
ws.close(); // Ensure the connection is closed before retrying
|
||||||
// If neither the body nor the product text contains the filter, ignore it
|
});
|
||||||
res.text().then((text) => {
|
}
|
||||||
if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return;
|
|
||||||
thisMsg = JSON.parse(JSON.stringify(discordMsg));
|
|
||||||
thisMsg.content = row.custommessage || null;
|
|
||||||
user.send(thisMsg).catch((err) => {
|
|
||||||
console.error(err);
|
|
||||||
}).catch((err) => {
|
|
||||||
console.log(`${colors.yellow("[WARN]")} Failed to send message to ${user.tag} (${user.id})`);
|
|
||||||
const logChannel = discord.guilds.cache.get(config.discord.mainGuild).channels.cache.get(config.discord.logChannel);
|
|
||||||
logChannel.send({
|
|
||||||
embeds: [
|
|
||||||
{
|
|
||||||
title: "Failed to send DM",
|
|
||||||
description: `User may have DMs disabled, or bot doesnt' share a server anymore!.
|
|
||||||
User: ${user.tag} (${user.id})
|
|
||||||
Sub Info: \`\`\`json\n${JSON.stringify(row)}\`\`\``,
|
|
||||||
color: 0xff0000
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}).then(() => {
|
|
||||||
db.run(`DELETE FROM userAlerts WHERE userid = ? AND iemchannel = ?`, [user.id, fromChannel], (err) => {
|
|
||||||
if (err) {
|
|
||||||
console.error(err.message);
|
|
||||||
}
|
|
||||||
console.log(`${colors.cyan("[INFO]")} Deleted user ${user.id} from database`);
|
|
||||||
});
|
|
||||||
})
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}).catch((err) => {
|
|
||||||
setTimeout(() => {
|
|
||||||
console.log(`${colors.red("[ERROR]")} Failed to fetch product text, retrying... ${err}`)
|
|
||||||
trySend();
|
|
||||||
})
|
|
||||||
});;
|
|
||||||
}
|
|
||||||
trySend();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
connectWebSocket();
|
||||||
|
|
||||||
|
// START DISCORD
|
||||||
|
|
||||||
xmpp.on("online", async (address) => {
|
discord.on('ready', async () => {
|
||||||
|
console.log(`${colors.cyan("[INFO]")} Logged in as ${discord.user.tag}`);
|
||||||
if (config["uptime-kuma"].enabled) {
|
if (config["uptime-kuma"].enabled) {
|
||||||
fetch(config["uptime-kuma"].url).then(() => {
|
fetch(config["uptime-kuma"].url).then(() => {
|
||||||
console.log(`${colors.cyan("[INFO]")} Sent heartbeat to Uptime Kuma`)
|
console.log(`${colors.cyan("[INFO]")} Sent heartbeat to Uptime Kuma`)
|
||||||
|
@ -628,73 +605,6 @@ xmpp.on("online", async (address) => {
|
||||||
}, config["uptime-kuma"].interval * 1000) // Every X seconds
|
}, config["uptime-kuma"].interval * 1000) // Every X seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
errCount = 0;
|
|
||||||
// Start listening on all channels, (dont ban me funny man)
|
|
||||||
// for (const channel in iem) {
|
|
||||||
// console.log(`Joining ${channel.name}`)
|
|
||||||
// await xmpp.send(xml("presence", { to: `${channel.jud}/${channel.name}` }));
|
|
||||||
// }
|
|
||||||
/* sub format
|
|
||||||
<presence to="botstalk@conference.weather.im/add9b8f1-038d-47ed-b708-6ed60075a82f" xmlns="jabber:client">
|
|
||||||
<x xmlns="http://jabber.org/protocol/muc#user">
|
|
||||||
<item>
|
|
||||||
<role>visitor</role>
|
|
||||||
</item>
|
|
||||||
</x>
|
|
||||||
</presence>
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Request room list
|
|
||||||
// Automatically find room list
|
|
||||||
xmpp.send(xml("iq", { type: "get", to: "conference.weather.im", id: "rooms" }, xml("query", { xmlns: "http://jabber.org/protocol/disco#items" })));
|
|
||||||
// Join all channels (Old method)
|
|
||||||
// iem.forEach((channel => {
|
|
||||||
// console.log(`${colors.cyan("[INFO]")} Joining ${channel.jid}/${channel.name}/${curUUID}`)
|
|
||||||
// //xmpp.send(xml("presence", { to: `${channel.jid}/${channel.jid.split("@")[0]}` }));
|
|
||||||
// xmpp.send(xml("presence", { to: `${channel.jid}/${channel.name}/${curUUID}` }, xml("item", { role: "visitor" })));
|
|
||||||
// }))
|
|
||||||
|
|
||||||
console.log(`${colors.cyan("[INFO]")} Connected to XMPP server as ${address.toString()}`);
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
startup = false;
|
|
||||||
console.log(`${colors.cyan("[INFO]")} Startup complete, listening for messages...`);
|
|
||||||
}, 1000)
|
|
||||||
});
|
|
||||||
|
|
||||||
xmpp.on("close", () => {
|
|
||||||
console.log(`${colors.yellow("[WARN]")} XMPP connection closed, trying to reconnect...`);
|
|
||||||
xmpp.disconnect().then(() => {
|
|
||||||
xmpp.stop().then(() => {
|
|
||||||
start();
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
const start = () => {
|
|
||||||
startup = true;
|
|
||||||
xmpp.start().catch((err) => {
|
|
||||||
errCount++;
|
|
||||||
if (errCount >= 5) {
|
|
||||||
console.log(`${colors.red("[ERROR]")} XMPP failed to start after 5 attempts, exiting...`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
console.log(`${colors.red("[ERROR]")} XMPP failed to start: ${err}.`);
|
|
||||||
xmpp.disconnect().then(() => {
|
|
||||||
xmpp.stop().then(() => {
|
|
||||||
start();
|
|
||||||
})
|
|
||||||
})
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// END XMPP
|
|
||||||
|
|
||||||
// START DISCORD
|
|
||||||
|
|
||||||
discord.on('ready', async () => {
|
|
||||||
console.log(`${colors.cyan("[INFO]")} Logged in as ${discord.user.tag}`);
|
|
||||||
|
|
||||||
// Get all guilds, and log them
|
// Get all guilds, and log them
|
||||||
discord.guilds.cache.forEach((guild) => {
|
discord.guilds.cache.forEach((guild) => {
|
||||||
console.log(`${colors.cyan("[INFO]")} In guild: ${guild.name} (${guild.id})`);
|
console.log(`${colors.cyan("[INFO]")} In guild: ${guild.name} (${guild.id})`);
|
||||||
|
@ -1557,7 +1467,7 @@ discord.on("interactionCreate", async (interaction) => {
|
||||||
interaction.respond(results.map((callsign) => ({ name: callsign, value: callsign })));
|
interaction.respond(results.map((callsign) => ({ name: callsign, value: callsign })));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue