From eadd7118f7e70dc4b26893e3f423b0939ed7d1f4 Mon Sep 17 00:00:00 2001 From: ChrisChrome Date: Sat, 6 Jul 2024 12:03:54 -0600 Subject: [PATCH] Doing things --- index.js | 97 +++++++++++++++++++++++++++++++------------------------- shard.js | 22 ++++++++----- 2 files changed, 68 insertions(+), 51 deletions(-) diff --git a/index.js b/index.js index 5216c8b..6f70003 100644 --- a/index.js +++ b/index.js @@ -23,17 +23,21 @@ const discord = new Discord.Client({ "DirectMessages" ], shards: getInfo().SHARD_LIST, // An array of shards that will get spawned - shardCount: getInfo().TOTAL_SHARDS, // Total number of shards + shardCount: getInfo().TOTAL_SHARDS, // Total number of shards }); discord.cluster = new ClusterClient(client); // initialize the Client, so we access the .broadcastEval() +var myId; +const shardLog = function (msg) { + console.log(`${colors.cyan(`[SHARD ${myId}]`)} ${msg}`); +} // Setup SQlite DB const db = new sqlite3.Database("channels.db", (err) => { if (err) { - console.log(`${colors.red("[ERROR]")} Error connecting to database: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Error connecting to database: ${err.message}`); } - console.log(`${colors.cyan("[INFO]")} Connected to the database`); + shardLog(`${colors.cyan("[INFO]")} Connected to the database`); }); @@ -259,24 +263,31 @@ discord.cluster.on('message', async (message) => { 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; + case "sendMsgUser": + discord.users.fetch(message.user).then(usr => { + if (!usr) return; + usr.send(message.msg); + }); + break; + case "yourId": + myId = message.data; break; } }); discord.on('ready', async () => { - console.log(`${colors.cyan("[INFO]")} Logged in as ${discord.user.tag}`); + shardLog(`${colors.cyan("[INFO]")} Logged in as ${discord.user.tag}`); // Get all guilds, and log them discord.guilds.cache.forEach((guild) => { - console.log(`${colors.cyan("[INFO]")} In guild: ${guild.name} (${guild.id})`); + shardLog(`${colors.cyan("[INFO]")} In guild: ${guild.name} (${guild.id})`); }); @@ -284,30 +295,30 @@ discord.on('ready', async () => { // setTimeout(() => { // // Wait 10 seconds, if startup is still true, something went wrong // if (startup) { - // console.log(`${colors.red("[ERROR]")} Startup failed, exiting...`); + // shardLog(`${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) => { - if (err) { - console.error(err.message); - } - rows.forEach((row) => { - const channel = discord.channels.cache.get(row.channelid); - if (!channel) { - // Delete the channel from the database and return - return db.run(`DELETE FROM channels WHERE channelid = ?`, [row.channelid], (err) => { - if (err) { - console.error(err.message); - } - console.log(`${colors.cyan("[INFO]")} Deleted channel ${row.channelid} from database`); - }); - }; - }); - }); - + // db.all(`SELECT channelid FROM channels`, (err, rows) => { + // if (err) { + // console.error(err.message); + // } + // rows.forEach((row) => { + // const channel = discord.channels.cache.get(row.channelid); + // if (!channel) { + // // Delete the channel from the database and return + // return db.run(`DELETE FROM channels WHERE channelid = ?`, [row.channelid], (err) => { + // if (err) { + // console.error(err.message); + // } + // shardLog(`${colors.cyan("[INFO]")} Deleted channel ${row.channelid} from database`); + // }); + // }; + // }); + // }); + // Not do this anymore, sharding manager will handle it in the future // Get all users in userAlerts and fetch them db.all(`SELECT userid FROM userAlerts`, (err, rows) => { if (err) { @@ -523,10 +534,10 @@ discord.on("interactionCreate", async (interaction) => { embeds: [ { title: "Temp About Me", - description: "I am currently running a very early beta of sharding, so for the time being, this is all you get for the About Me, as collecting all the data is a bit more difficult.\n\nIf something is broken please report it to the support server [here](https://discord.gg/XthJjfU8TU)", + description: "I am currently running a very early beta of sharding, so for the time being, this is all you get for the About Me, as collecting all the data is a bit more difficult.\n\nIf something is broken please report it to the support server [here](https://discord.gg/XthJjfU8TU)\n" + "I am shard " + myId, } ] - }) + }) }); break; case "rooms": @@ -534,7 +545,7 @@ discord.on("interactionCreate", async (interaction) => { // let roomList = ""; // iem.forEach((channel) => { // room = channel.jid.split("@")[0] - // console.log(getWFOByRoom(room)) + // shardLog(getWFOByRoom(room)) // roomList += `\`${room}\`: ${getWFOByRoom(room).location}\n`; // }); // const roomEmbed = { @@ -573,7 +584,7 @@ discord.on("interactionCreate", async (interaction) => { // wfos is object "wfo": {"location": "Text Name", "room": "roomname"} for (let i = 0; i < total; i += chunkSize) { chunks.push(iem.slice(i, i + chunkSize)); - console.log(iem.slice(i, i + chunkSize)) + shardLog(iem.slice(i, i + chunkSize)) } @@ -584,7 +595,7 @@ discord.on("interactionCreate", async (interaction) => { name: categoryName, type: Discord.ChannelType.GuildCategory }).then((newCategory) => { - console.log(`${colors.cyan("[INFO]")} Created category ${newCategory.name}`); + shardLog(`${colors.cyan("[INFO]")} Created category ${newCategory.name}`); chunk.forEach((channel) => { channelName = `${channel.jid.split("@")[0]}_${getWFOByRoom(channel.jid.split("@")[0]).location}` if (channelName == "Unknown") channelName = channel.jid.split("@")[0] @@ -594,19 +605,19 @@ discord.on("interactionCreate", async (interaction) => { parent: newCategory, topic: `Weather.im room for ${getWFOByRoom(channel.jid.split("@")[0]).location} - ${channel.jid.split("@")[0]}` }).then((newChannel) => { - console.log(`${colors.cyan("[INFO]")} Created channel ${newChannel.name}`); + shardLog(`${colors.cyan("[INFO]")} Created channel ${newChannel.name}`); db.run(`INSERT INTO channels (channelid, iemchannel, custommessage) VALUES (?, ?, ?)`, [newChannel.id, channel.jid.split("@")[0], null], (err) => { if (err) { console.error(err.message); } - console.log(`${colors.cyan("[INFO]")} Added channel ${newChannel.id} to database`); + shardLog(`${colors.cyan("[INFO]")} Added channel ${newChannel.id} to database`); }); }).catch((err) => { - console.log(`${colors.red("[ERROR]")} Failed to create channel: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to create channel: ${err.message}`); }); }); }).catch((err) => { - console.log(`${colors.red("[ERROR]")} Failed to create category: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to create category: ${err.message}`); }); }); interaction.editReply({ content: "Setup complete", ephemeral: true }); @@ -799,7 +810,7 @@ discord.on("interactionCreate", async (interaction) => { }); }).catch((err) => { interaction.editReply({ content: "Failed to get outlook", ephemeral: true }); - console.log(`${colors.red("[ERROR]")} Failed to get outlook: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to get outlook: ${err.message}`); console.error(err); }); break; @@ -828,7 +839,7 @@ discord.on("interactionCreate", async (interaction) => { }); }).catch((err) => { interaction.editReply({ content: "Failed to get alert map", ephemeral: true }); - console.log(`${colors.red("[ERROR]")} Failed to get alert map: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to get alert map: ${err.message}`); console.error(err); }); break; @@ -870,7 +881,7 @@ discord.on("interactionCreate", async (interaction) => { }); }).catch((err) => { interaction.editReply({ content: "Failed to get satellite images", ephemeral: true }); - console.log(`${colors.red("[ERROR]")} Failed to get satellite images: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to get satellite images: ${err.message}`); console.error(err); }); }); @@ -880,12 +891,12 @@ discord.on("interactionCreate", async (interaction) => { await interaction.deferReply(); periods = interaction.options.getInteger("periods") || 1; funcs.getWeatherBySearch(interaction.options.getString("location")).then((weather) => { - if (config.debug >= 1) console.log(JSON.stringify(weather, null, 2)) + if (config.debug >= 1) shardLog(JSON.stringify(weather, null, 2)) embeds = funcs.generateDiscordEmbeds(weather, periods); interaction.editReply({ embeds }); }).catch((err) => { interaction.editReply({ content: "Failed to get forecast", ephemeral: true }); - if (config.debug >= 1) console.log(`${colors.red("[ERROR]")} Failed to get forecast: ${err}`); + if (config.debug >= 1) shardLog(`${colors.red("[ERROR]")} Failed to get forecast: ${err}`); }); break; @@ -920,7 +931,7 @@ discord.on("interactionCreate", async (interaction) => { }); }).catch((err) => { interaction.reply({ content: "Failed to get product text", ephemeral: true }); - console.log(`${colors.red("[ERROR]")} Failed to get product text: ${err.message}`); + shardLog(`${colors.red("[ERROR]")} Failed to get product text: ${err.message}`); }); } break; @@ -963,7 +974,7 @@ discord.on("interactionCreate", async (interaction) => { // }) process.on("unhandledRejection", (error, promise) => { - console.log(`${colors.red("[ERROR]")} Unhandled Rejection @ ${promise}: ${error.stack}`); + shardLog(`${colors.red("[ERROR]")} Unhandled Rejection @ ${promise}: ${error.stack}`); // create errors folder if it doesnt exist if (!fs.existsSync("./error")) { fs.mkdirSync("./error"); @@ -986,7 +997,7 @@ process.on("unhandledRejection", (error, promise) => { process.on("uncaughtException", (error) => { - console.log(`${colors.red("[ERROR]")} Uncaught Exception: ${error.message}\n${error.stack}`); + shardLog(`${colors.red("[ERROR]")} Uncaught Exception: ${error.message}\n${error.stack}`); if (!fs.existsSync("./error")) { fs.mkdirSync("./error"); } diff --git a/shard.js b/shard.js index f6b1d80..7a7c309 100644 --- a/shard.js +++ b/shard.js @@ -424,10 +424,12 @@ 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.broadcastEval(client => { - client.users.fetch(row.userid.toString())?.then((user) => { - user.send(thisMsg) - }) + // set channelid var in shard + userid = row.userid; + manager.broadcast({ + type: "sendMsgUser", + user: userid, + msg: thisMsg }) }); }).catch((err) => { @@ -546,15 +548,19 @@ process.on("uncaughtException", (error) => { const { ShardingManager } = require('discord.js'); const { ClusterManager } = require('discord-hybrid-sharding'); const manager = new ClusterManager(`${__dirname}/index.js`, { - totalShards: 'auto', // or numeric shard count + totalShards: 2, // or numeric shard count /// Check below for more options - shardsPerClusters: 2, // 2 shards per process - totalClusters: 4, + shardsPerClusters: 1, // 2 shards per process + totalClusters: 1, mode: 'process', // you can also choose "worker" token: config.discord.token, }); -manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`)); +manager.on('clusterCreate', (cluster) => { + setInterval(() => {cluster.send({ type: "yourId", data: cluster.id})}, 1000); +}) + + manager.spawn({timeout: -1}).then(() => { start();