Bot automatically removing reaction - javascript

I'm currently working on a music bot. I made a queue command which shows how many songs are currently in the queue. I wanted to make it look like if the songs in the queue are greater than 10 the bot will slice it and show the rest on a next "page". To scroll between pages I wanted to use reactions. My code is working, but the Bot automatically removes its own reaction. Why is that?
const Discord = require("discord.js");
module.exports.run = async (client, message, args, queue, searcher) => {
const serverQueue = queue.get(message.guild.id);
if(!serverQueue)
return message.channel.send("**Jelenleg nincs zene lejátszás alatt!**");
if(message.member.voice.channel != message.guild.me.voice.channel)
return message.channel.send("**Előbb lépj be a hang szobába!**")
let currentPage = 0;
if(serverQueue.songs.length <= 1) return message.channel.send(`**Lejátszás alatt:** [__${serverQueue.songs[0].title}__](${serverQueue.songs[0].url})`);
const embeds = embedGenerator(serverQueue)
//if(serverQueue.songs.length < 12) return message.channel.send(embeds);
const queueEmbed = await message.channel.send(`**Oldal:**: ${currentPage+1}/${embeds.length}`, embeds[currentPage])
await queueEmbed.react('⬅️');
await queueEmbed.react('➡️');
const reactionFilter = (reaction, user) => ['⬅️', '➡️'].includes(reaction.emoji.name) && (message.author.id === user.id)
const collector = queueEmbed.createReactionCollector(reactionFilter);
collector.on('collect', (reaction, user) => {
if(reaction.emoji.name === '➡️'){
if(currentPage < embeds.length-1){
currentPage+=1;
queueEmbed.edit(`**Oldal:**: ${currentPage+1}/${embeds.length}`, embeds[currentPage]);
message.reactions.resolve(reaction).users.remove(user)
}
}else if(reaction.emoji.name === '⬅️'){
if (currentPage !== 0){
currentPage -= 1;
queueEmbed.edit(`**Oldal:** ${currentPage+1}/${embeds.length}`, embeds[currentPage])
message.reactions.resolve(reaction).users.remove(user)
}
}
})
}
function embedGenerator(serverQueue){
const embeds = [];
let songs = 11;
for (let i = 1; i < serverQueue.songs.length; i += 10){
const current = serverQueue.songs.slice(i, songs)
songs += 10;
let j = i-1;
const info = current.map(song => `${++j}. [${song.title}](${song.url})`).join('\n')
const msg = new Discord.MessageEmbed()
.setDescription(`**Lejátszás alatt:** [${serverQueue.songs[0].title}](${serverQueue.songs[0].url}) \n ${info}`)
embeds.push(msg)
}
return embeds;
}
module.exports.config = {
name: "queue",
aliases: ['q']
}

Okay so I found the problem.It turned out that my other bot had a reaction event which removes reactions on messages after like 4 seconds.I didn't add an if(message.author.bot) return; line to that so it removed the reaction all the time.

Related

Unable to find memory leak despite using proper tensor disposal (tfjs)

I've tried all sorts of ways to dispose of tensors (tf.dispose(), start/endscope).
The closest I've got was through this code, where 1 unused tensor remains after each execution. It takes about 2 hours for this program to run enough to use up 64 GB of RAM (big memory leak).
I also suspect that other factors besides TFJS-based operations are contributing to the memory leak, though (in theory) garbage collection should clean this up.
The piece of code below is one event that gets processed by an Event Listener handler. Any help with this issue would be greatly appreciated!
'use strict';
global.fetch = require("node-fetch");
const { MessageActionRow, MessageButton, Permissions } = require('discord.js');
const { mod, eco, m, n } = require(`../../index.js`);
const { Readable } = require('stream');
const PImage = require('pureimage');
const tf = require('#tensorflow/tfjs');
const tfnode = require('#tensorflow/tfjs-node');
const wait = require('util').promisify(setTimeout);
let bufferToStream = (binary) => {
let readableInstanceStream = new Readable({
read() {
this.push(binary);
this.push(null);
}
});
return readableInstanceStream;
}
const predict = async (imageUrl, modelFile) => {
let model = await tf.loadLayersModel(modelFile);
let modelClasses = [ "NSFW", "SFW" ];
let data = await fetch(imageUrl);
let fileType = data.headers.get("Content-Type");
let buffer = await data.buffer();
let stream = bufferToStream(buffer);
let image;
if ((/png/).test(fileType)) {
image = await PImage.decodePNGFromStream(stream);
}
else if ((/jpe?g/).test(fileType)) {
image = await PImage.decodeJPEGFromStream(stream);
}
else {
return;
}
let rawArray;
rawArray = tf.tidy(() => {
let tensorImage;
tensorImage = tf.browser.fromPixels(image).toFloat();
tensorImage = tf.image.resizeNearestNeighbor(tensorImage, [model.inputs[0].shape[1], model.inputs[0].shape[2]]);
tensorImage = tensorImage.reshape([1, model.inputs[0].shape[1], model.inputs[0].shape[2], model.inputs[0].shape[3]]);
return model.predict(tensorImage);
});
rawArray = await rawArray.data();
rawArray = Array.from(rawArray);
tf.disposeVariables();
model.layers.forEach(l => {
l.dispose();
});
if (rawArray[1] > rawArray[0]) {
return [`SFW`, rawArray[1]];
}
else {
return [`NSFW`, rawArray[0]];
}
};
const getResults = async (imageLink, imageNumber) => {
let image = `${imageLink}`;
let prediction = await predict(image, `file://D:/retake7/sfwmodel/model.json`);
let className = `SFW`;
if (prediction[0] == `NSFW`) {
className = `**NSFW**`;
}
return [`[Image ${imageNumber+1}](${imageLink}): ${className} (${(prediction[1]*100).toFixed(2)}% Certainty)`, ((prediction[1]*100).toFixed(2))*1];
}
const main = async (message, client, Discord) => {
if (message.attachments.size == 0 || message.author.bot || message.channel.nsfw) return;
await client.shard.broadcastEval(c => {
console.log(`Scanning...`);
}).catch(e => {
return;
});
let inChannel = await eco.seid.get(`${message.guild.id}.${message.channel.id}.active`);
let sfwImage = await eco.seid.get(`${message.guild.id}.sfwAlerts`);
if (inChannel == `no`) return;
let atmentArr = Array.from(message.attachments);
let msgArr = [];
if (message.attachments.size > 1) {
msgArr.push(`**Images Scanned**`);
} else {
msgArr.push(`**Image Scanned**`);
}
let hasNSFW = false;
let uncertain = false;
for (i = 0; i < message.attachments.size; i++) {
let msg = await getResults(atmentArr[i][1][`proxyURL`], i);
if (msg[1] < 80) {
uncertain = true;
}
if (msg[0].includes(`NSFW`)) {
hasNSFW = true;
}
msgArr.push(msg[0]);
}
if (uncertain == false && hasNSFW == false) {
let cont = `${msgArr.join(`\n`)}`;
msgArr = null;
client.seid.set(`${message.channel.id}.previousScan`, cont);
return;
}
let embed = new Discord.MessageEmbed()
.setColor(`GREEN`)
.setDescription(msgArr.join(`\n`));
let cont2 = `${msgArr.join(`\n`)}`;
client.seid.set(`${message.channel.id}.previousScan`, cont2);
msgArr = null;
if (sfwImage != `no` || hasNSFW || msg[1] <= 80) {
embed.setColor(`RED`);
await message.delete();
let msgSent = await message.channel.send({embeds: [embed], components: [row]});
};
};
module.exports = {
event: 'messageCreate',
run: async (message, client, Discord) => {
await main(message, client, Discord);
},
};
first, separate model loading and inference - in your current code, you'd reload a model each time you need to run prediction on a new image.
and then look at any possible leaks in prediction function - so once model is loaded.
you're loading a model and disposing each layer, but that doesn't mean model itself gets unloaded so there more than a chance that part of model remains in memory.
but leak itself is this line:
rawArray = await rawArray.data();
that variable is already used and its a tensor.
now you're overwriting the same variable with a data array and tensor never gets disposed.

Discord.js Bot giveaway command : embedSent.reactions.get is not a function

I am trying to make a Discord.js giveaway command that send an embed, save it to the variable embedSent then collect the reactions after the TimeOut with the reactions.get() method, but I keep getting the error TypeError: embedSent.reactions.get is not a function Here is the part of my code :
var embed = new Discord.MessageEmbed();
embed.setColor(0x3333ff);
embed.setTitle("Nouveau Giveaway !");
embed.setDescription("**" + item + "**");
embed.addField(`Durée : `, ms(ms(time), {
long: true
}), true);
embed.setFooter("Réagissez à ce message avec 🎉 pour participer !");
var embedSent = await message.channel.send(embed);
embedSent.react("🎉");
setTimeout(function () {
var peopleReacted = embedSent.reactions.get("🎉").users.filter(user => user.id !== client.user.id).array()
}, time);
Ok, after almost 2 months, I finally figured it out. The full, working command (DiscordJS v12) :
if (command == "giveaway") {
// !giveaway {time s/m/d} {item}
const messageArray = message.content.split(" ");
if (!message.member.hasPermission(["ADMINISTRATOR"])) return message.channel.send("You don't have enough permissions to start a giveaway !")
var item = "";
var time;
var winnerCount;
for (var i = 1; i < args.length; i++) {
item += (args[i] + " ");
}
time = args[0];
if (!time) {
return message.channel.send(`Invalid duration provided`);
}
if (!item) {
item = "No title"
}
var embed = new Discord.MessageEmbed();
embed.setColor(0x3333ff);
embed.setTitle("New Giveaway !");
embed.setDescription("**" + item + "**");
embed.addField(`Duration : `, ms(ms(time), {
long: true
}), true);
embed.setFooter("React to this message with 🎉 to participate !");
var embedSent = await message.channel.send(embed);
embedSent.react("🎉");
setTimeout(async () => {
try{
const peopleReactedBot = await embedSent.reactions.cache.get("🎉").users.fetch();
var peopleReacted = peopleReactedBot.array().filter(u => u.id !== client.user.id);
}catch(e){
return message.channel.send(`An unknown error happened during the draw of the giveaway **${item}** : `+"`"+e+"`")
}
var winner;
if (peopleReacted.length <= 0) {
return message.channel.send(`Not enough participants to execute the draw of the giveaway **${item}** :(`);
} else {
var index = Math.floor(Math.random() * peopleReacted.length);
winner = peopleReacted[index];
}
if (!winner) {
message.channel.send(`An unknown error happened during the draw of the giveaway **${item}**`);
} else {
console.log(`Giveaway ${item} won by ${winner.toString()}`)
message.channel.send(`🎉 **${winner.toString()}** has won the giveaway **${item}** ! Congratulations ! 🎉`);
}
}, ms(time));
}
Hope it helped some !
I guess this giveaway command works for me - Discord.js V13
don't forget to have npm i ms installed if you haven't already
const { Client, Intents, CommandInteraction, ReactionUserManager } = require('discord.js');
const INTENTS = new Intents(32767); // 32767 == full intents, calculated from intent calculator
const client = new Client({
intents: INTENTS
});
const Discord = require('discord.js');
const ms = require('ms') // make sure package ms is downloaded in console, to do this, simply type: npm i ms in your terminal
// https://www.npmjs.com/package/ms
client.once("ready" , () => {
console.log("I am online!")
});
client.on('messageCreate', async message => {
const prefix = "!" // this can be any prefix you want
let args = message.content.substring(prefix.length).split(" ")
// COMMAND FORMAT: !startgiveaway {duration} {winners} {#channel} {prize}
// E.g. !startgiveaway 24h 3w #giveaways Free Discord Nitro
if ((message.content.startsWith(`${prefix}startgiveaway`))) { // this condition can be changed to any command you'd like, e.g. `${prefix}gstart`
if (message.member.roles.cache.some(role => (role.name === 'Giveaway') )) { // user must have a role named Giveaway to start giveaway
let duration = args[1];
let winnerCount = args[2];
if (!duration)
return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
if (
!args[1].endsWith("d") &&
!args[1].endsWith("h") &&
!args[1].endsWith("m") &&
!args[1].endsWith("s")
)
return message.channel.send('Please provide a duration for the giveaway!\nThe abbreviations for units of time are: `d (days), h (hours), m (minutes), s (seconds)`');
if (!winnerCount) return message.channel.send('Please provide the number of winners for the giveaway! E.g. `1w`')
if (isNaN(args[2].toString().slice(0, -1)) || !args[2].endsWith("w")) // if args[2]/winnerCount is not a number (even after removing end 'w') or args[2] does not end with 'w', condition returns:
return message.channel.send('Please provide the number of winners for the giveaway! E.g. `3w`');
if ((args[2].toString().slice(0, -1)) <= 0)
return message.channel.send('The number of winners cannot be less than 1!');
let giveawayChannel = message.mentions.channels.first();
if (!giveawayChannel || !args[3]) return message.channel.send("Please provide a valid channel to start the giveaway!")
let prize = args.slice(4).join(" ");
if (!prize) return message.channel.send('Please provide a prize to start the giveaway!');
let startGiveawayEmbed = new Discord.MessageEmbed()
.setTitle("🎉 GIVEAWAY 🎉")
.setDescription(`${prize}\n\nReact with 🎉 to participate in the giveaway!\nWinners: **${winnerCount.toString().slice(0, -1)}**\nTime Remaining: **${duration}**\nHosted By: **${message.author}**`)
.setColor('#FFFFFF')
.setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway will end
.setFooter("Giveaway ends");
let embedGiveawayHandle = await giveawayChannel.send({embeds: [startGiveawayEmbed]})
embedGiveawayHandle.react("🎉").catch(console.error);
setTimeout(() => {
if (embedGiveawayHandle.reactions.cache.get("🎉").count <= 1) {
return giveawayChannel.send("Nobody joined the giveaway :(")
}
if (embedGiveawayHandle.reactions.cache.get("🎉").count <= winnerCount.toString().slice(0, -1)) { // this if-statement can be removed
return giveawayChannel.send("There's not enough people in the giveaway to satisfy the number of winners!")
}
let winner = embedGiveawayHandle.reactions.cache.get("🎉").users.cache.filter((users) => !users.bot).random(winnerCount.toString().slice(0, -1));
const endedEmbedGiveaway = new Discord.MessageEmbed()
.setTitle("🎉 GIVEAWAY 🎉")
.setDescription(`${prize}\n\nWinner(s): ${winner}\nHosted By: **${message.author}**\nWinners: **${winnerCount.toString().slice(0, -1)}**\nParticipants: **${embedGiveawayHandle.reactions.cache.get("🎉").count - 1}**\nDuration: **${duration}**`)
.setColor('#FFFFFF')
.setTimestamp(Date.now() + ms(args[1])) // Displays time at which the giveaway ended
.setFooter("Giveaway ended");
embedGiveawayHandle.edit({embeds:[endedEmbedGiveaway]}); // edits original giveaway message to show that the giveaway ended successfully
const congratsEmbedGiveaway = new Discord.MessageEmbed()
.setDescription(`🥳 Congratulations ${winner}! You just won **${prize}**!`)
.setColor('#FFFFFF')
giveawayChannel.send({embeds: [congratsEmbedGiveaway]}).catch(console.error);
}, ms(args[1]));
} // end "Giveaway" role condition
}
})
client.login('INSERT YOUR BOT TOKEN HERE');

How can I go about handling an error, ignoring it and continuing with the function? discord.js

I'm trying to dm all users in my private server with all my friends however some of them don't want to be dmed so they turn off their dms. Because of this, I get an error which stops the bot from continuing on to the other users. How can I skip over that user when the error is found and tell my bot to continue to dm the next user after.
heres my code
const commando = require('discord.js-commando');
const app = require('../../app.js');
const config = require('../../config.json');
const Discord = require('discord.js');
class DMallCommand extends commando.Command {
constructor(client){
super(client, {
name: `dmall`,
group: 'dms',
memberName: 'dmall',
description: 'Sends message provided to all members of the guild.',
examples: [ `${config.prefix}dmall Hey everyone! This might reach more people than a mass ping...` ]
});
}
async run(message, args){
let dmGuild = message.guild;
let role = message.mentions.roles.first();
var msg = message.content;
try {
msg = msg.substring(msg.indexOf("dmall") + 5);
} catch(error) {
console.log(error);
return;
}
if(!msg || msg.length <= 1) {
const embed = new Discord.RichEmbed()
.addField(":x: Failed to send", "Message not specified")
.addField(":eyes: Listen up!", "Every character past the command will be sent,\nand apparently there was nothing to send.");
message.channel.send({ embed: embed });
return;
}
let memberarray = dmGuild.members.array();
let membercount = memberarray.length;
let botcount = 0;
let successcount = 0;
console.log(`Responding to ${message.author.username} : Sending message to all ${membercount} members of ${dmGuild.name}.`)
for (var i = 0; i < membercount; i++) {
let member = memberarray[i];
if (member.user.bot) {
console.log(`Skipping bot with name ${member.user.username}`)
botcount++;
continue
}
let timeout = Math.floor((Math.random() * (config.wait - 0.01)) * 1000) + 10;
await sleep(timeout);
if(i == (membercount-1)) {
console.log(`Waited ${timeout}ms.\t\\/\tDMing ${member.user.username}`);
} else {
console.log(`Waited ${timeout}ms.\t|${i + 1}|\tDMing ${member.user.username}`);
}
try {
member.send(`${msg} \n #${timeout}`);
successcount++;
} catch (error) {
console.log(`Failed to send DM! ` + error)
}
}
console.log(`Sent ${successcount} ${(successcount != 1 ? `messages` : `message`)} successfully, ` +
`${botcount} ${(botcount != 1 ? `bots were` : `bot was`)} skipped.`);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = DMallCommand;
I understand I am not handling any errors but I am not sure how to go about this and could really use some help
Also here is my bot.js code
const Discord = require('discord.js');
const figlet = require('figlet');
const colors = require('colors');
const readline = require('readline');
const commando = require(`discord.js-commando`);
const config = require('./config.json');
const bot = new commando.Client({
commandPrefix:'£',
owner: config.id
});
const cmdsArray = [
"dmall <message>",
"dmrole <role> <message>"
];
bot.on("ready", () => {
clear();
console.log('______')
bot.user.setActivity('PRDX');
});
bot.on("error", (error) => {
bot.login(config.token);
});
bot.registry.registerGroup('dms', 'help');
bot.registry.registerDefaults();
bot.registry.registerCommandsIn(__dirname + "/commands");
if (process.env.BOT_TOKEN) bot.login(process.env.BOT_TOKEN);
else bot.login(config.token);
}
Anywhere in your code use an error event listener
client.on("error", () => { client.login(token) });
You'll want to catch the error, basically, if that error happens, you want it to just pass by and ignore the error. In Javascript this is known as try and catch. Read about it below then apply it to wherever the error is being identified.
https://www.w3schools.com/js/js_errors.asp
You can use .catch() block, member.send('Message') return a promise with succes sended message or error. So you can use
member.send('message').catch(console.error)

Loop for display help command

Actually, i try to create a bot with discord.js and i try to do a help command.
i don't understand why my loop do this (i know it's not a good way for this)
let i = 0;
const embed = new RichEmbed();
if (args.length < 1) {
embed.setColor('#5B4DCA');
while (i < list_groups.length) {
let x = 0;
embed.setTitle(`${list_groups[i]}`)
while (x < groups.length) {
if (groups[x] === list_groups[i]) {
embed.addField('test1', 'test2')
}
x++;
}
message.channel.send(embed)
i++;
}
}
"Modérations" is supposed to display one command, "level & rank" too, "Outils" 4 command and "Sondage" too
enter image description here
I think you solutuion its not right way. If you will have more then 10 groups bot will spam commands list. The 1 way to do it its display all categories list if args.length===0, if args !==0 you try to find all commands in this category. To discord embed you can add only 18 fields, so if you have more then 18 command in categroy you will get api error. So you need spliced commands to pages.
This code will display all categories if args.length === 0, or command groups not fined.
If group fined bot send embed message with command in group (max 10), and react message if pages more then 1, so user can change page with reaction.
const {Discord,RichEmbed} = require('discord.js');
const {prefix,token,classic_roles} = require('../config.json');
const logs = require('../logs/logs');
module.exports.run = async (bot, message, args) => {
if(args.length === 0) {
//Show user all allowed groups commands
let commandCategories = bot.commands.map(command => `!help ${command.help.groups}`).filter(onlyUnique).join('\n') //find all categories and get onlyUnique
let helpMessage = `**The list of command groups:**\n\n ${commandCategories}`
let Embed = new Discord.RichEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarUrl)
.setDescription(helpMessage)
.setColor('#e0c40b')
message.channel.send(Embed)
} else {
//try find required group
let commandsInCategory = bot.commands.filter(command => command.help.groups === args.join(' ').toLowerCase())
if(commandsInCategory.size === 0) {
// if no group find, then display user list of groups
let commandCategories = bot.commands.map(command => `!help ${command.help.groups}`).filter(onlyUnique).join('\n')
let helpMessage = `**For get command list use**\n\n ${commandCategories}`
let Embed = new Discord.RichEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarUrl)
.setDescription(helpMessage)
.setColor('#e0c40b')
message.channel.send(Embed)
return
}
let counter = 0
let allCommands = []
commandsInCategory.map(command => {
allCommands.push({
name: command.help.name,
description: command.help.description
})
})
allCommands = generateHelpArray(allCommands)
//for better display, we will display only 10 in page
let Embed = new Discord.RichEmbed()
Embed.setAuthor(message.author.tag, message.author.displayAvatarUrl)
Embed.setDescription(`The list command of group : **${args.join(' ')}**`)
allCommands[counter].map(command => {
Embed.addField(`**${command.name}**`,`${command.description}`,false)
})
Embed.setColor('#E8DB0E')
Embed.setFooter(`Page ${counter+1} of ${allCommands.length}`)
message.channel.send(Embed).then(msg => {
if(allCommands.length < 2) return
// To change page we will use react emoji
msg.react(`◀️`).then(() => msg.react('▶️'))
const filter = (reaction, user) => {
return [`◀️`, '▶️'].includes(reaction.emoji.name) && user.id === message.author.id;
};
const collector = msg.createReactionCollector(filter, { max:50, time: 60000 });
collector.on('collect', (reaction, reactionCollector) => {
if (reaction.emoji.name === `◀️`) {
//Change counter, remove user reaction and call change embed function
reaction.remove(message.author.id)
counter-=1
if(counter < 0) counter = 0
editEmbed(message, msg, counter, args.join(' '), allCommands)
} else if (reaction.emoji.name === `▶️`) {
//Change counter, remove user reaction and call change embed function
reaction.remove(message.author.id)
counter+=1
if(counter >= allCommands.length) counter = allCommands.length -1
editEmbed(message, msg, counter, args.join(' '), allCommands)
}
});
collector.on('end', (reaction, reactionCollector) => {
msg.clearReactions()
})
})
}
}
module.exports.help = {
name: "help",
description: "Vous permet d'obtenir toutes les commandes accessibles pour vos rôles.",
access: "Public",
groups: "Outils"
}
const onlyUnique = (value, index, self) => {
return self.indexOf(value) === index;
}
const editEmbed = (message, msg, counter, category, allCommands) => {
let Embed = new Discord.RichEmbed()
Embed.setAuthor(message.author.tag, message.author.displayAvatarURL)
Embed.setDescription(`The list command of group : **${category}**`)
Embed.setColor('#E8DB0E')
allCommands[counter].map(command => {
Embed.addField(`**${command.name}**`,`${command.description}`,false)
})
Embed.setFooter(`Page ${counter+1} of ${allCommands.length}`)
msg.edit(Embed)
}
const generateHelpArray = (arr) => {
let newArray = [];
for (let i = 0; i < arr.length; i+=10) {
newArray.push(arr.slice(i,i+10))
}
return newArray
}

I cant get code to detect the beginning of a link (www or https)

currently trying to get my code to notice the beginning of a message if its "www" or "https" and then checking if they're associated with either reddit or youtube, I've tried multiple different posts (there arent very many on the discord API for javascript) so Im kinda stumpted at this point
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const bot = new Discord.Client();
var protect = false;
const forbidenWords = ['reddit', 'youtube']
const Message = ''
bot.login(botconfig.token);
let prefix = "!";
bot.on("message", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (message.content.startsWith(prefix + "protect")) {
message.channel.send("PROTECT THE KING!!!!");
protect = true;
console.log('protecc is true')
} else
if (message.content.startsWith(prefix + "stop")) {
message.channel.send("I will now stop :(");
protect = false;
}
if(protect == true && message.content.startsWith("www" || "https")){
console.log('isWebsite true')
for (var i = 0; i < forbidenWords.length; i++) {
if (message.content.includes(forbidenWords[i])) {
break;
}
}
}
});
any help on this is greatly appreciated.
Move the additional logic into a helper function.
function startsWithWebsiteToken(message) {
const tokens = ['https', 'www'];
const length = tokens.length;
for (let i = 0; i < length; i++) {
if ( message.startsWith(tokens[i]) )
return true;
}
return false;
}
if (protect === true && startsWithWebsiteToken(message.content)) {
console.log('isWebsite true');
}
You can define a custom function for this
START_TOKENS = ['https','https','www'];
function doesUrlStartWithToken(url) {
return START_TOKENS.reduce((accumulator, currentValue) => {
if (accumulator) {
return true;
}
return currentValue.startsWith(url);
}, false);
}
Alternatively, if you only need to support browser which support new URL(), it becomes easier to detect certain domains
const SPECIAL_DOMAINS = ['youtube.com', 'reddit.com']
function isSpecialDomain(url) {
const deconstructedUrl = new URL(url)
const domain = deconstructedUrl.hostname.replace('www.','');
return SPECIAL_DOMAINS.reduce((e, val) => e || domain === val, false);
}

Categories