From 661fd36905f155a0be2c11df4f0c499a3ab7baf7 Mon Sep 17 00:00:00 2001 From: ChrisChrome Date: Sat, 6 Jul 2024 01:51:11 -0600 Subject: [PATCH] IT FUCKING WORKS --- index.js | 52 +++++++++++++++++++++++++++++++++------------------- package.json | 1 + shard.js | 52 ++++++++++++++++++++++++++++------------------------ 3 files changed, 62 insertions(+), 43 deletions(-) diff --git a/index.js b/index.js index d4d0ab3..5216c8b 100644 --- a/index.js +++ b/index.js @@ -3,8 +3,6 @@ const fs = require("fs"); const config = require("./config.json"); const funcs = require("./funcs.js"); 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 sattelites = require("./data/sattelites.json"); const nwrstreams = require("./data/nwrstreams.json") @@ -13,21 +11,22 @@ const { client, xml } = require("@xmpp/client"); const fetch = require("node-fetch"); const html = require("html-entities") const Discord = require("discord.js"); +const { ClusterClient, getInfo } = require('discord-hybrid-sharding'); const dVC = require("@discordjs/voice"); const colors = require("colors"); const sqlite3 = require("sqlite3").verbose(); -const ws = require("ws"); -// setup ws client to 127.0.0.1:9743 -const wsClient = new ws("ws://127.0.0.1:9743"); // Setup Discord const discord = new Discord.Client({ intents: [ "Guilds", "GuildVoiceStates", "DirectMessages" - ] + ], + shards: getInfo().SHARD_LIST, // An array of shards that will get spawned + shardCount: getInfo().TOTAL_SHARDS, // Total number of shards }); +discord.cluster = new ClusterClient(client); // initialize the Client, so we access the .broadcastEval() // Setup SQlite DB const db = new sqlite3.Database("channels.db", (err) => { @@ -252,9 +251,24 @@ var messages = 0; // START DISCORD -// listen on ws -wsClient.on("message", (data) => { +discord.cluster.on('message', async (message) => { + if (!message.type) return; + switch (message.type) { + case "updateRooms": + // Update the rooms + iem = message.rooms; + break; + case "sendMsgChannel": + console.log(`Trying to send message to ${message.channel}`); + channel = discord.channels.cache.get(message.channel); + if (!channel) return; + channel.send(message.msg).then(msg => { + if (msg.channel.type === Discord.ChannelType.GuildAnnouncement) msg.crosspost(); + }); + console.log(`Sent message to ${message.channel}`); + break; + } }); discord.on('ready', async () => { @@ -266,14 +280,14 @@ discord.on('ready', async () => { }); - //start(); - setTimeout(() => { - // Wait 10 seconds, if startup is still true, something went wrong - if (startup) { - console.log(`${colors.red("[ERROR]")} Startup failed, exiting...`); - process.exit(1); - } - }, 10000) + // //start(); + // setTimeout(() => { + // // Wait 10 seconds, if startup is still true, something went wrong + // if (startup) { + // console.log(`${colors.red("[ERROR]")} Startup failed, exiting...`); + // process.exit(1); + // } + // }, 10000) // Check all channels in DB, fetch them, if they dont exist, delete all subscriptions db.all(`SELECT channelid FROM channels`, (err, rows) => { @@ -949,20 +963,20 @@ discord.on("interactionCreate", async (interaction) => { // }) process.on("unhandledRejection", (error, promise) => { - console.log(`${colors.red("[ERROR]")} Unhandled Rejection @ ${promise}: ${error}`); + console.log(`${colors.red("[ERROR]")} Unhandled Rejection @ ${promise}: ${error.stack}`); // create errors folder if it doesnt exist if (!fs.existsSync("./error")) { fs.mkdirSync("./error"); } // write ./error/rejection_timestamp.txt - fs.writeFileSync(`./error/rejection_${Date.now()}.txt`, `ERROR:\n${error}\n\nPROMISE:\n${JSON.stringify(promise)}`); + fs.writeFileSync(`./error/rejection_${Date.now()}.txt`, `ERROR:\n${error.stack}\n\nPROMISE:\n${JSON.stringify(promise)}`); // Send discord log const myGuild = discord.guilds.cache.get(config.discord.mainGuild); const channel = myGuild.channels.cache.get(config.discord.logChannel); channel.send({ embeds: [ { - description: `Unhandled Rejection\n\`\`\`${error}\n${JSON.stringify(promise)}\`\`\``, + description: `Unhandled Rejection\n\`\`\`${error.stack}\n${JSON.stringify(promise)}\`\`\``, color: 0xff0000 } ] diff --git a/package.json b/package.json index 12f4929..f46888c 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "@xmpp/client": "^0.13.1", "@xmpp/debug": "^0.13.0", "colors": "^1.4.0", + "discord-hybrid-sharding": "^2.2.0", "discord.js": "14.14.1", "geolib": "^3.3.4", "html-entities": "^2.5.2", diff --git a/shard.js b/shard.js index f02c5eb..f6b1d80 100644 --- a/shard.js +++ b/shard.js @@ -7,7 +7,6 @@ const rest = new REST({ version: '10' }).setToken(config.discord.token); const sqlite3 = require("sqlite3").verbose(); -const ws = require("ws"); // Setup SQlite DB const db = new sqlite3.Database("channels.db", (err) => { @@ -20,8 +19,6 @@ const db = new sqlite3.Database("channels.db", (err) => { db.run(`CREATE TABLE IF NOT EXISTS userAlerts (userid TEXT, iemchannel TEXT, filter TEXT, filterEvt TEXT, minPriority INT, custommessage TEXT);`); }); -// setup ws server here for the shards to connect to -const wss = new ws.Server({ port: 9743 }); // Requires const fs = require("fs"); @@ -380,16 +377,13 @@ xmpp.on("stanza", (stanza) => { 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; - // send data to all websocket clients - wss.clients.forEach((client) => { - client.send(JSON.stringify({ - type: "DISCORD_MESSAGE_CREATE", - data: { - channelid: row.channelid, - message: thisMsg - } - })); - }); + // set channelid var in shard + channelid = row.channelid; + manager.broadcast({ + type: "sendMsgChannel", + channel: channelid, + msg: thisMsg + }) }); }).catch((err) => { setTimeout(() => { @@ -430,12 +424,10 @@ xmpp.on("stanza", (stanza) => { 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; - manager.broadcast({ - type: "SHARD_DM_MESSAGE_CREATE", - data: { - userid: row.userid, - message: thisMsg - } + manager.broadcastEval(client => { + client.users.fetch(row.userid.toString())?.then((user) => { + user.send(thisMsg) + }) }) }); }).catch((err) => { @@ -529,13 +521,13 @@ const start = () => { // END XMPP process.on("unhandledRejection", (error, promise) => { - console.log(`${colors.red("[ERROR]")} Unhandled Rejection @ ${promise}: ${error}`); + console.log(`${colors.red("[ERROR]")} Unhandled Rejection @ ${JSON.stringify(promise)}: ${error.stack}`); // create errors folder if it doesnt exist if (!fs.existsSync("./error")) { fs.mkdirSync("./error"); } // write ./error/rejection_timestamp.txt - fs.writeFileSync(`./error/rejection_${Date.now()}.txt`, `ERROR:\n${error}\n\nPROMISE:\n${JSON.stringify(promise)}`); + fs.writeFileSync(`./error/rejection_${Date.now()}.txt`, `ERROR:\n${error.stack}\n\nPROMISE:\n${JSON.stringify(promise)}`); return; }); @@ -552,11 +544,23 @@ process.on("uncaughtException", (error) => { }); const { ShardingManager } = require('discord.js'); - -const manager = new ShardingManager('./index.js', { token: config.discord.token }); +const { ClusterManager } = require('discord-hybrid-sharding'); +const manager = new ClusterManager(`${__dirname}/index.js`, { + totalShards: 'auto', // or numeric shard count + /// Check below for more options + shardsPerClusters: 2, // 2 shards per process + totalClusters: 4, + mode: 'process', // you can also choose "worker" + token: config.discord.token, +}); manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); -manager.spawn().then(() => { +manager.spawn({timeout: -1}).then(() => { start(); + console.log(`${colors.cyan("[INFO]")} Spawned all shards`); + setInterval(() => { + manager.broadcast({ type: "heartbeat" }); + manager.broadcast({ type: "updateRooms", rooms: iem}) + }, 1000) }); \ No newline at end of file