Doing things

This commit is contained in:
Christopher Cookman 2024-07-06 12:03:54 -06:00
parent 661fd36905
commit eadd7118f7
Signed by: ChrisChrome
GPG key ID: A023A26E42C33A42
2 changed files with 68 additions and 51 deletions

View file

@ -23,17 +23,21 @@ const discord = new Discord.Client({
"DirectMessages" "DirectMessages"
], ],
shards: getInfo().SHARD_LIST, // An array of shards that will get spawned 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() 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 // Setup SQlite DB
const db = new sqlite3.Database("channels.db", (err) => { const db = new sqlite3.Database("channels.db", (err) => {
if (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; iem = message.rooms;
break; break;
case "sendMsgChannel": case "sendMsgChannel":
console.log(`Trying to send message to ${message.channel}`);
channel = discord.channels.cache.get(message.channel); channel = discord.channels.cache.get(message.channel);
if (!channel) return; if (!channel) return;
channel.send(message.msg).then(msg => { channel.send(message.msg).then(msg => {
if (msg.channel.type === Discord.ChannelType.GuildAnnouncement) msg.crosspost(); 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; break;
} }
}); });
discord.on('ready', async () => { 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 // 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})`); shardLog(`${colors.cyan("[INFO]")} In guild: ${guild.name} (${guild.id})`);
}); });
@ -284,30 +295,30 @@ discord.on('ready', async () => {
// setTimeout(() => { // setTimeout(() => {
// // Wait 10 seconds, if startup is still true, something went wrong // // Wait 10 seconds, if startup is still true, something went wrong
// if (startup) { // if (startup) {
// console.log(`${colors.red("[ERROR]")} Startup failed, exiting...`); // shardLog(`${colors.red("[ERROR]")} Startup failed, exiting...`);
// process.exit(1); // process.exit(1);
// } // }
// }, 10000) // }, 10000)
// Check all channels in DB, fetch them, if they dont exist, delete all subscriptions // Check all channels in DB, fetch them, if they dont exist, delete all subscriptions
db.all(`SELECT channelid FROM channels`, (err, rows) => { // db.all(`SELECT channelid FROM channels`, (err, rows) => {
if (err) { // if (err) {
console.error(err.message); // console.error(err.message);
} // }
rows.forEach((row) => { // rows.forEach((row) => {
const channel = discord.channels.cache.get(row.channelid); // const channel = discord.channels.cache.get(row.channelid);
if (!channel) { // if (!channel) {
// Delete the channel from the database and return // // Delete the channel from the database and return
return db.run(`DELETE FROM channels WHERE channelid = ?`, [row.channelid], (err) => { // return db.run(`DELETE FROM channels WHERE channelid = ?`, [row.channelid], (err) => {
if (err) { // if (err) {
console.error(err.message); // console.error(err.message);
} // }
console.log(`${colors.cyan("[INFO]")} Deleted channel ${row.channelid} from database`); // 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 // Get all users in userAlerts and fetch them
db.all(`SELECT userid FROM userAlerts`, (err, rows) => { db.all(`SELECT userid FROM userAlerts`, (err, rows) => {
if (err) { if (err) {
@ -523,10 +534,10 @@ discord.on("interactionCreate", async (interaction) => {
embeds: [ embeds: [
{ {
title: "Temp About Me", 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; break;
case "rooms": case "rooms":
@ -534,7 +545,7 @@ discord.on("interactionCreate", async (interaction) => {
// let roomList = ""; // let roomList = "";
// iem.forEach((channel) => { // iem.forEach((channel) => {
// room = channel.jid.split("@")[0] // room = channel.jid.split("@")[0]
// console.log(getWFOByRoom(room)) // shardLog(getWFOByRoom(room))
// roomList += `\`${room}\`: ${getWFOByRoom(room).location}\n`; // roomList += `\`${room}\`: ${getWFOByRoom(room).location}\n`;
// }); // });
// const roomEmbed = { // const roomEmbed = {
@ -573,7 +584,7 @@ discord.on("interactionCreate", async (interaction) => {
// wfos is object "wfo": {"location": "Text Name", "room": "roomname"} // wfos is object "wfo": {"location": "Text Name", "room": "roomname"}
for (let i = 0; i < total; i += chunkSize) { for (let i = 0; i < total; i += chunkSize) {
chunks.push(iem.slice(i, 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, name: categoryName,
type: Discord.ChannelType.GuildCategory type: Discord.ChannelType.GuildCategory
}).then((newCategory) => { }).then((newCategory) => {
console.log(`${colors.cyan("[INFO]")} Created category ${newCategory.name}`); shardLog(`${colors.cyan("[INFO]")} Created category ${newCategory.name}`);
chunk.forEach((channel) => { chunk.forEach((channel) => {
channelName = `${channel.jid.split("@")[0]}_${getWFOByRoom(channel.jid.split("@")[0]).location}` channelName = `${channel.jid.split("@")[0]}_${getWFOByRoom(channel.jid.split("@")[0]).location}`
if (channelName == "Unknown") channelName = channel.jid.split("@")[0] if (channelName == "Unknown") channelName = channel.jid.split("@")[0]
@ -594,19 +605,19 @@ discord.on("interactionCreate", async (interaction) => {
parent: newCategory, parent: newCategory,
topic: `Weather.im room for ${getWFOByRoom(channel.jid.split("@")[0]).location} - ${channel.jid.split("@")[0]}` topic: `Weather.im room for ${getWFOByRoom(channel.jid.split("@")[0]).location} - ${channel.jid.split("@")[0]}`
}).then((newChannel) => { }).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) => { db.run(`INSERT INTO channels (channelid, iemchannel, custommessage) VALUES (?, ?, ?)`, [newChannel.id, channel.jid.split("@")[0], null], (err) => {
if (err) { if (err) {
console.error(err.message); 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) => { }).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) => { }).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 }); interaction.editReply({ content: "Setup complete", ephemeral: true });
@ -799,7 +810,7 @@ discord.on("interactionCreate", async (interaction) => {
}); });
}).catch((err) => { }).catch((err) => {
interaction.editReply({ content: "Failed to get outlook", ephemeral: true }); 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); console.error(err);
}); });
break; break;
@ -828,7 +839,7 @@ discord.on("interactionCreate", async (interaction) => {
}); });
}).catch((err) => { }).catch((err) => {
interaction.editReply({ content: "Failed to get alert map", ephemeral: true }); 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); console.error(err);
}); });
break; break;
@ -870,7 +881,7 @@ discord.on("interactionCreate", async (interaction) => {
}); });
}).catch((err) => { }).catch((err) => {
interaction.editReply({ content: "Failed to get satellite images", ephemeral: true }); 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); console.error(err);
}); });
}); });
@ -880,12 +891,12 @@ discord.on("interactionCreate", async (interaction) => {
await interaction.deferReply(); await interaction.deferReply();
periods = interaction.options.getInteger("periods") || 1; periods = interaction.options.getInteger("periods") || 1;
funcs.getWeatherBySearch(interaction.options.getString("location")).then((weather) => { 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); embeds = funcs.generateDiscordEmbeds(weather, periods);
interaction.editReply({ embeds }); interaction.editReply({ embeds });
}).catch((err) => { }).catch((err) => {
interaction.editReply({ content: "Failed to get forecast", ephemeral: true }); 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; break;
@ -920,7 +931,7 @@ discord.on("interactionCreate", async (interaction) => {
}); });
}).catch((err) => { }).catch((err) => {
interaction.reply({ content: "Failed to get product text", ephemeral: true }); 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; break;
@ -963,7 +974,7 @@ discord.on("interactionCreate", async (interaction) => {
// }) // })
process.on("unhandledRejection", (error, promise) => { 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 // create errors folder if it doesnt exist
if (!fs.existsSync("./error")) { if (!fs.existsSync("./error")) {
fs.mkdirSync("./error"); fs.mkdirSync("./error");
@ -986,7 +997,7 @@ process.on("unhandledRejection", (error, promise) => {
process.on("uncaughtException", (error) => { 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")) { if (!fs.existsSync("./error")) {
fs.mkdirSync("./error"); fs.mkdirSync("./error");
} }

View file

@ -424,10 +424,12 @@ xmpp.on("stanza", (stanza) => {
if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return; if (!filters.some((filter) => body.toLowerCase().includes(filter)) && !filters.some((filter) => text.toLowerCase().includes(filter))) return;
thisMsg = JSON.parse(JSON.stringify(discordMsg)); thisMsg = JSON.parse(JSON.stringify(discordMsg));
thisMsg.content = row.custommessage || null; thisMsg.content = row.custommessage || null;
manager.broadcastEval(client => { // set channelid var in shard
client.users.fetch(row.userid.toString())?.then((user) => { userid = row.userid;
user.send(thisMsg) manager.broadcast({
}) type: "sendMsgUser",
user: userid,
msg: thisMsg
}) })
}); });
}).catch((err) => { }).catch((err) => {
@ -546,15 +548,19 @@ process.on("uncaughtException", (error) => {
const { ShardingManager } = require('discord.js'); const { ShardingManager } = require('discord.js');
const { ClusterManager } = require('discord-hybrid-sharding'); const { ClusterManager } = require('discord-hybrid-sharding');
const manager = new ClusterManager(`${__dirname}/index.js`, { const manager = new ClusterManager(`${__dirname}/index.js`, {
totalShards: 'auto', // or numeric shard count totalShards: 2, // or numeric shard count
/// Check below for more options /// Check below for more options
shardsPerClusters: 2, // 2 shards per process shardsPerClusters: 1, // 2 shards per process
totalClusters: 4, totalClusters: 1,
mode: 'process', // you can also choose "worker" mode: 'process', // you can also choose "worker"
token: config.discord.token, 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(() => { manager.spawn({timeout: -1}).then(() => {
start(); start();