I'm making a discord bot using discord.js and node.js.
Essentially, the bot needs to a message every predefined amount of time.
To not send a message to every channel of every server the bot is in, I made an enable-disable system:
when you type !enable, the bot saves in an array the channel and when it needs to send a message, for each channel in the array, it sends a message to that channel.
The problem is that when I update/restart the bot, that array is gone, so I have to re-type !enable in every channel I need.
This is the code that handles the !enable and !disable
enabled_channels = [];
client.on("message", message => {
if(message.content.startsWith("!")) {
if(message.content === "!enable") {
if(!enabled_channels.includes(message.channel)) {
enabled_channels.push(message.channel);
message.channel.send("Bot enabled in this channel");
} else {
message.channel.send("Bot already enabled in this channel");
}
} else if(message.content === "!disable") {
if(enabled_channels.includes(message.channel)) {
enabled_channels.splice(enabled_channels.indexOf(message.channel), 1)
}
message.channel.send("Bot disabled in this channel");
}
}
});
And this is the code that sends the message to all the channels
function sendToAll(message) {
for(let c of enabled_channels) {
c.send(message);
}
}
setInterval(() => {
var message = functionThatGenerateTheMessageContent(); //really simplified here
sendToAll(message);
}, 5 * 60 * 1000); //5 minutes
Is there a way to save the enabled_channels
array? I tried with node-localstorage
but I found that saving an object, just saves [Object object]
and saving the stringified object saves only the attributes and not the type so I cannot call functions associated with that object.
client.channels.fetch(id)
to fetch each channel and send a message. – ignis