Prohibition of the use of emojireact-role in third-party channels - javascript

how to make sure that the role when pressing the bell is give only in a certain channel? The code is below. Can also make that only administrators have the right to issue reactions with a bell that will issue a role. Help, pls.
var emojiname = ["🔔"];
var rolename=["🔔 Notifications"];
client.on('message', msg => {
if(msg.content.startsWith("reaction" && message.channel.name.toLowerCase() === 'information')){
if(!msg.channel.guild) return;
for(let n in emojiname){
var emoji =[msg.guild.emojis.find(r => r.name == emojiname[n])];
for(let i in emoji){
msg.react(emoji[i]);
}
}
}
});
client.on("messageReactionAdd",(reaction,user)=>{
if(!user) return;
if(user.bot)return;
if(!reaction.message.channel.guild) return;
for(let n in emojiname){
if(reaction.emoji.name == emojiname[n]){
let role = reaction.message.guild.roles.find(r => r.name == rolename[n]);
reaction.message.guild.member(user).addRole(role).catch(console.error);
}
}
});
client.on("messageReactionRemove",(reaction,user)=>{
if(!user) return;
if(user.bot)return;
if(!reaction.message.channel.guild) return;
for(let n in emojiname){
if(reaction.emoji.name == emojiname[n]){
let role = reaction.message.guild.roles.find(r => r.name == rolename[n]);
reaction.message.guild.member(user).removeRole(role).catch(console.error);
}
}
});

Here it is.
First, be aware that there is 2 types of discord emojis. The unicode one, common emoji, like ➡. And the guild emoji, that you add to a server.
The first one are represented only by the unicode name, while the second have an id and others difference (see Emoji and Message Reaction)
That being said, I used the name of the emoji in the emojiname array. I then changed a little bit the code to accept both unicode and guild emojis.
The rest of the code was good. Just be sure to use === instead of == except if you realy want to accept "falsy" term.
demo gif
// ➡ is an ascii emoji
// lina is a guild emoji
var emojiname = ['➡', 'lina'];
var rolename=["➡ Notifications", "lina supporter"];
client.on('message', msg => {
if(msg.content.startsWith('reaction') && (msg.channel.name.toLowerCase() === 'information')) {
for (let n in emojiname){
let emoji = msg.guild.emojis.find(r => r.name === emojiname[n]);
if (emoji === null) {
emoji = emojiname[n];
}
msg.react(emoji);
}
}
});
client.on("messageReactionAdd",(reaction,user)=>{
if (!user) { return; }
if (user.bot) { return; }
if (reaction.message.channel.name.toLowerCase() !== 'information') { return; }
for(let n in emojiname){
if(reaction.emoji.name === emojiname[n]){
let role = reaction.message.guild.roles.find(r => r.name === rolename[n]);
reaction.message.guild.member(user).addRole(role).catch(console.error);
}
}
});
client.on("messageReactionRemove",(reaction,user)=>{
if(!user) { return; }
if(user.bot) { return; }
if (reaction.message.channel.name.toLowerCase() !== 'information') { return; }
for(let n in emojiname){
if(reaction.emoji.name === emojiname[n]){
let role = reaction.message.guild.roles.find(r => r.name == rolename[n]);
reaction.message.guild.member(user).removeRole(role).catch(console.error);
}
}
});

Related

how to get a users roles discord.js

I want to check if a user has a role but when I try to get the user it always returns the bot user, not the wanted user. How can I go about fixing this?
Here's my code:
const member = client.guilds.cache.get(localVars.ServerID).members.cache.find((member) => {
console.log(member.username);
return member.username == localVars.username;
});
const role = client.guilds.cache.get(localVars.ServerID).roles.cache.find((role) => {
return role.name === localVars.RoleName;
});
console.log(member);
if (member.roles.cache.get(role.id)) {
localVars.ReturnValue = 1;
} else {
localVars.ReturnValue = 0;
}
Your code is a little bit overcomplicated and some things are just unneccessary / wrong, e.g. that you call return in the find() and get() functions :D
You could simplify it like this:
const { guilds } = client;
const targetGuild = guilds.cache.get(localVars.ServerID);
const member = targetGuild.members.cache.find(user => user.username === localVars.username);
const role = targetGuild.roles.cache.find(role => role.name === localVars.RoleName);
if(member.roles.cache.has(role.id)) {
localVars.ReturnValue = 1
} else {
localVars.ReturnValue = 0
}

TypeError: mention.send is not a function - discord.js

I have been trying to code this discord bot to send a message to a certain person through DMs. The way it is supposed to work is:
tb!send #usernamehere Hi
Then this should send a DM message to #usernamehere saying, "Hi". But instead, I get an error saying TypeError: mention.send is not a function. Here is my code:
client.on('message', (message) => {
var msg = message.content.toLowerCase();
if (message.author.bot) return;
let mention = message.mentions.users.first().id;
if (msg.startsWith(prefix + 'send')) {
console.log('ok');
if (mention == null) return;
message.delete();
var mentionMessage = message.content.slice(8);
mention.send(mentionMessage);
message.channel.send('done!');
}
});
Change
let mention = message.mentions.users.first().id;
to
let mention = message.mentions.users.first();
You can choose between using the id or mention
ID
let mention = message.mentions.users.first().id;
if (msg.startsWith(prefix + 'send')) {
console.log('ok');
if (mention == null) {
return;
}
message.delete();
mentionMessage = message.content.split(' ').slice(1);
client.users.cache.get(mention).send(mentionMessage);
message.channel.send('done!');
}
Or mention
let mention = message.mentions.users.first();
if (msg.startsWith(prefix + 'send')) {
console.log('ok');
if (mention == null) {
return;
}
message.delete();
mentionMessage = message.content.split(' ').slice(1);
mention.send(mentionMessage);
message.channel.send('done!');
}
Also I changed message.content.slice(8) to message.content.split(' ').slice(1) so it will work with all prefix that doesn't have a space.

Creating a BulkDelete command | Discord.JS

As you read by the title I'm trying to make a clear command for my Discord bot, but I can't get it to work.
Here's a snippet:
client.on('message', message => {
if (message.content = "clear") {
let args = message.content.substring(prefix.length).split(" ");
var deleteCount = message.guild.members.cache.get(args[1]);
if (message.member.hasPermission("MANAGE_MESSAGES")) {
const deleteCount = args[2];
const fetched = ({
limit: deleteCount
});
message.delete(fetched)
try {
} catch (error) {
}(error => message.reply(`Couldn't delete messages because of: ${error}`));
if (!deleteCount || deleteCount < 2 || deleteCount > 100)
return message.reply("Please provide a number between 2 and 100 for the number of messages to delete");
message.channel.send('Successfully deleted ' + `${deleteCount}` + 'messages!');
}
}
});
Also, don't ask me what I'm doing and why I copied some stuff from other people trying to make it but the code was outdated.
Can someone help me?
client.on("message", message => {
if (message.content.indexOf(prefix) !== 0) {return false};
const arguments = message.content.slice(prefix.length).trim().split(/ +/g);
const command = arguments.shift().toLowerCase();
if (command == "clear") {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send("You are not allowed to use this command.");
if (!arguments[0]) return message.channel.send("Please provide a number between 2 and 100.")
if (arguments[0] < 2 || arguments[0] > 100) return message.channel.send("Please provide a number between 2 and 100.")
message.channel.bulkDelete(arguments[0]).then(messages => {
message.channel.send(`Deleted ${messages.size} messages.`);
}).catch(e => console.log(e));
};
});

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