how do i use permission overwrites discord.js - javascript

it worked on my last bot but now the permission overwrites wont work on the new bot i looked at documentation on discord.js was just wandering if someone could help me out as im at a dead end
code:
module.exports = {
name: 'ticket',
description: "creates ticket",
async execute(message, args, Discord){
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`);
channel.setParent('967965866035642408');
channel.permissionOverwrites.edit(message.guild.id, {
SEND_MESSAGES: false,
VIEW_CHANNEL: false,
});
channel.permissionOverwrites.edit(message.author, {
SEND_MESSAGES: true,
VIEW_CHANNEL: true,
});
const reactionMessage = await channel.send('Thank you for contacting support!');
try{
await reactionMessage.react("πŸ”’");
await reactionMessage.react("β›”");
}catch(err){
channel.send('Error sending emojis!');
throw err;
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"),
{dispose: true }
);
collector.on("collect", (reaction, user) => {
switch (reaction.emoji.name) {
case "πŸ”’":
channel.permissionOverwrites.edit(message.author, { SEND_MESSAGES: false });
break;
case "β›”":
channel.send('deleting this channel in 5 seconds');
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel.send(`we will be right with you! ${channel}`).then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
}).catch((err) => {
throw err;
});
}
}

So the first part of this would be the command, and I seperated the command from the reaction, just in case the bot reboots or there was ever an error with the collector, this code will survive a reboot. I also tested this on my bot and it works without issue.
Command.js file
module.exports = {
name: 'ticket',
description: "creates ticket",
async execute(message, args, Discord) {
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`, {
parent: '967965866035642408',
permissionOverwrites: [{
id: message.guild.id,
deny: [
'VIEW_CHANNEL',
],
}, {
id: message.author,
allow: [
'VIEW_CHANNEL',
'SEND_MESSAGES',
],
}],
});
const reactionMessage = await channel.send(`Thank you for contacting support! ${message.author}`);
// message.author is important for later so make sure it stays in the message somehow.
try {
await reactionMessage.react("πŸ”’");
await reactionMessage.react("β›”");
} catch (err) {
channel.send('Error sending emojis!');
throw err;
}
message.channel.send(`we will be right with you! ${channel}`).then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
}).catch((err) => {
throw err;
});
},
};
This section would go into your main bot.js file to catch the reaction add and it will auto remove reactions that are placed by members who are not admins
client.on('messageReactionAdd', async (messageReaction, user) => {
if (user.bot) return;
const message = await messageReaction.message.fetch(true);
const channel = message.channel;
const guild = client.guilds.cache.get(message.guildId);
const member = guild.members.cache.get(user.id);
if (channel.parent.id === '967965866035642408') {
const regex = /\d+/g;
const authorID = message.content.match(regex);
const originalAuthor = client.users.cache.get(authorID[0]);
if (!member.permissions.has("ADMINISTRATOR")) {
message.reactions.cache.find(reaction => reaction.emoji.name == messageReaction.emoji.name).users.remove(member.user);
return;
} else {
switch (messageReaction.emoji.name) {
case "πŸ”’":
channel.permissionOverwrites.edit(originalAuthor, { SEND_MESSAGES: false });
break;
case "β›”":
channel.send('deleting this channel in 5 seconds');
setTimeout(() => channel.delete(), 5000);
break;
}
}
} else {
return;
}
});

Related

messageReactionAdd isn't firing despite proper setup Discord.js

Entire file below. I've been trying for an ungodly amount of time to get a reaction roles command working. Currently using MongoDB and everything is setup properly no errors my schema has worked properly as well there are no issues. Despite everything working I cannot get my event to fire at all with multiple revisions. Any help would be phenomenal on this one as I am too new to all of this to figure it out for myself...
const Schema = require('../reactions');
const Discord = require('discord.js');
const { client, intents } = require('..')
module.exports = {
name: 'messageReactionAdd',
run: async (reaction, message, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
const { guild } = reaction.message;
if (!guild) return;
if (!guild.me.permissions.has("MANAGE_ROLES")) return;
isEmoji = function(emoji) {
const e = Discord.Util.parseEmoji(emoji);
if (e.id === null) {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: false
}
} else {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: true
}
}
}
const member = guild.members.cache.get(user.id);
await Schema.findOne({
guild_id: guild.id,
msg_id: reaction.message.id
}, async (err, db) => {
if (!db) return;
if (reaction.message.id != db.msg_id) return;
const data = db.rcs;
for (let i in data) {
if (reaction.emoji.id === null) {
if (reaction.emoji.name === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
} else {
if (reaction.emoji.id === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
}
}
});
},
};```
Intents
You need the GUILD_MESSAGE_REACTIONS in your client

MessageEmbed is not defined (discord.js v13)

I have this problem where it always says MessageEmbed is not defined! I don't know why it says that please help me! I have tried to solve this problem but nothing solved the problem!
const wait = require('util').promisify(setTimeout);
const OWNER_ID = require("../../config.json").OWNER_ID;
const { MessageEmbed }= require('discord.js');
require('dotenv').config();
var token = process.env.BOT_TOKEN;
module.exports = {
name: "restart",
description: "restarts the bot",
async execute(interaction, client) {
const logMsg = `Command Used: \`RESTART\` \nUser: \`${interaction.user.id}\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\``;
client.channels.cache.get(client.config.errorLog).send(logMsg);
try {
if (interaction.user.id != OWNER_ID || ID) {
await interaction.reply({content: "RESTARRR...",ephemeral: true});
await wait(1000);
await interaction.editReply({content:"Wait ... What?!",ephemeral: true});
await wait(2000);
return await interaction.editReply({content:"Bruh! You are not a developer, this command is not for you : )",ephemeral: true});
}
await interaction.reply("RESTARTING FAST AS F BOIIIIII ...").then((m) => {
client.destroy(BOT_TOKEN);
});
await wait(2000).then((m) => {
client.login(BOT_TOKEN);
});
await interaction.editReply("Damn! I'm Back πŸ”₯");
} catch(err) {
const errTag = client.config.errTag;
client.channels.cache.get(client.config.ERROR_LOGS_CHANNEL).send(`**ERROR!** ${errTag} \n${err}\nCommand: \`RESTART\` \nChannel: \`${interaction.channel.id} (${interaction.channel.name})\` \n User: \`${interaction.user.id}\`\n`);
}
},
};
I have tried to solve this problem but nothing happened!
here the code in the command.js file
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.run(client, message, args, p, cooldowns);
} catch (error) {
console.error(error);
let embed2000 = new MessageEmbed()
.setDescription("There was an error executing that command.")
.setColor("BLUE");
message.channel.send({ embeds: [embed2000] }).catch(console.error);
}
};

Discord.js: how can I make paticular permissons for each reaction?

I am coding a !ticket command and cannot handle allowing members without any permissions to react β›”.
Code
module.exports = {
name: "ticket",
slash: true,
aliases: [],
permissions: [],
description: "open a ticket!",
async execute(client, message, args) {
let chanel = message.guild.channels.cache.find(c => c.name === `ticket-${(message.author.username).toLowerCase()}`);
if (chanel) return message.channel.send('You already have a ticket open.');
const channel = await message.guild.channels.create(`ticket-${message.author.username}`)
channel.setParent("837065612546539531");
channel.updateOverwrite(message.guild.id, {
SEND_MESSAGE: false,
VIEW_CHANNEL: false,
});
channel.updateOverwrite(message.author, {
SEND_MESSAGE: true,
VIEW_CHANNEL: true,
});
const reactionMessage = await channel.send(`${message.author}, welcome to your ticket!\nHere you can:\n:one: Report an issue or bug of the server.\n:two: Suggest any idea for the server.\n:three: Report a staff member of the server.\n\nMake sure to be patient, support will be with you shortly.\n<#&837064899322052628>`)
try {
await reactionMessage.react("πŸ”’");
await reactionMessage.react("β›”");
} catch (err) {
channel.send("Error sending emojis!");
throw err;
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"),
{ dispose: true }
);
collector.on("collect", (reaction, user) => {
switch (reaction.emoji.name) {
case "πŸ”’":
channel.updateOverwrite(message.author, { SEND_MESSAGES: false });
break;
case "β›”":
channel.send("Deleting this ticket in 5 seconds...");
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel
.send(`We will be right with you! ${channel}`)
.then((msg) => {
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
})
.catch((err) => {
throw err;
});
},
};
It is related to the following part of the code.
const collector = reactionMessage.createReactionCollector(
(reaction, user) => message.guild.members.cache.find((member) => member.id === user.id).hasPermission("ADMINISTRATOR"),
{ dispose: true }
);
I want it to allow lock the ticket for administrators, and allow to close for everyone.
Not sure if I understand you correctly, but it seems you have two reactions and only want admins to use the πŸ”’, and both admins and the original author to use the β›”.
Your current code only collects reactions from members who have ADMINISTRATOR permissions. You should change the filter to also collect reactions from the member who created the ticket.
The following filter does exactly that.
const filter = (reaction, user) => {
const isOriginalAuthor = message.author.id === user.id;
const isAdmin = message.guild.members.cache
.find((member) => member.id === user.id)
.hasPermission('ADMINISTRATOR');
return isOriginalAuthor || isAdmin;
}
There are other errors in your code, like there is no SEND_MESSAGE flag, only SEND_MESSAGES. You should also use more try-catch blocks to catch any errors.
It's also a good idea to explicitly allow the bot to send messages in the newly created channel. I use overwritePermissions instead of updateOverwrite. It allows you to use an array of overwrites, so you can update it with a single method.
To solve the issue with the lock emoji... I check the permissions of the member who reacted with a πŸ”’, and if it has no ADMINISTRATOR, I simply delete their reaction using reaction.users.remove(user).
Check out the working code below:
module.exports = {
name: 'ticket',
slash: true,
aliases: [],
permissions: [],
description: 'open a ticket!',
async execute(client, message, args) {
const username = message.author.username.toLowerCase();
const parentChannel = '837065612546539531';
const ticketChannel = message.guild.channels.cache.find((ch) => ch.name === `ticket-${username}`);
if (ticketChannel)
return message.channel.send(`You already have a ticket open: ${ticketChannel}`);
let channel = null;
try {
channel = await message.guild.channels.create(`ticket-${username}`);
await channel.setParent(parentChannel);
await channel.overwritePermissions([
// disable access to everyone
{
id: message.guild.id,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
// allow access for the one opening the ticket
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
// make sure the bot can also send messages
{
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
]);
} catch (error) {
console.log(error);
return message.channel.send('⚠️ Error creating ticket channel!');
}
let reactionMessage = null;
try {
reactionMessage = await channel.send(
`${message.author}, welcome to your ticket!\nHere you can:\n:one: Report an issue or bug of the server.\n:two: Suggest any idea for the server.\n:three: Report a staff member of the server.\n\nMake sure to be patient, support will be with you shortly.\n<#&837064899322052628>`,
);
} catch (error) {
console.log(error);
return message.channel.send(
'⚠️ Error sending message in ticket channel!',
);
}
try {
await reactionMessage.react('πŸ”’');
await reactionMessage.react('β›”');
} catch (err) {
console.log(err);
return channel.send('⚠️ Error sending emojis!');
}
const collector = reactionMessage.createReactionCollector(
(reaction, user) => {
// collect only reactions from the original
// author and users w/ admin permissions
const isOriginalAuthor = message.author.id === user.id;
const isAdmin = message.guild.members.cache
.find((member) => member.id === user.id)
.hasPermission('ADMINISTRATOR');
return isOriginalAuthor || isAdmin;
},
{ dispose: true },
);
collector.on('collect', (reaction, user) => {
switch (reaction.emoji.name) {
// lock: admins only
case 'πŸ”’':
const isAdmin = message.guild.members.cache
.find((member) => member.id === user.id)
.hasPermission('ADMINISTRATOR');
if (isAdmin) {
channel.updateOverwrite(message.author, {
SEND_MESSAGES: false,
});
} else {
// if not an admin, just remove the reaction
// like nothing's happened
reaction.users.remove(user);
}
break;
// close: anyone i.e. any admin and the member
// created the ticket
case 'β›”':
channel.send('Deleting this ticket in 5 seconds...');
setTimeout(() => channel.delete(), 5000);
break;
}
});
try {
const msg = await message.channel.send(`We will be right with you! ${channel}`);
setTimeout(() => msg.delete(), 7000);
setTimeout(() => message.delete(), 3000);
} catch (error) {
console.log(error);
}
},
};

How can i count the reactions in discord.js and after that display it (slappey version)

I'm trying to display who win the poll but i run into a problem. While I want to get the number of the reactions with
.addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
My console says that the count is undefined. I've tried to search it but I didn't find anything and I tried so many ways but nothing.
The code:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require("discord.js")
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('vote', 'moderation', []);
}
async run(client, message, args) {
const filter = m => m.author.id == message.author.id;
let embed = new Discord.MessageEmbed()
.setFooter(`${message.author.tag} started the poll`)
.setTimestamp();
message.channel.send('what the question is?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.setTitle(msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('first option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[πŸ”΄] the first option:`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
message.channel.send('second option?');
try {
let msg = await message.channel.awaitMessages(filter, { max: 1, time: 15000, errors: ['time'] });
console.log(msg.first().content);
embed.addField(`[πŸ”΅] the second option`, msg.first().content);
} catch (err) {
console.log(err);
message.channel.send('You run out of time! Pls type again the command \`~prefix~ vote\`');
}
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed).then(sentMessage => sentMessage.react('πŸ”΄')).then(reaction => reaction.message.react('πŸ”΅')));
} catch (err) {
console.log(err);
}
const filters = (reaction) => reaction.emoji.name === "πŸ”΄" || reaction.emoji.name === "πŸ”΅";
const results = await message.awaitReactions(filters, { time: 15000 })
let resultsEmbed = new Discord.MessageEmbed()
.setTitle(`the poll result`)
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
.addField("πŸ”΅:", `${results.get("πŸ”΅").count //if i dont type here the .count then i've got this embed but after the "πŸ”΅": says'undefined' }`)
.setColor("#84daf8")
.setTimestamp()
message.channel.send(resultsEmbed);
}
}
A szavazΓ‘s eredmΓ©nye = The poll result in my language. I see this when i dont write the .count there: .addField("πŸ”΄:", `${results.get("πŸ”΄").count}`)
and i see this when i write .count
The problem was that the bot was trying to retrieve the reactions of a deleted message I believe. In order to fix this, you'll have to put your resultsEmbed code inside of your chained then methods.
Code:
try {
await message.channel.bulkDelete(7)
.then(message.channel.send(embed)
.then(sentMessage => sentMessage.react('πŸ”΄'))
.then(reaction => reaction.message.react('πŸ”΅'))
.then(reaction => {
const filters = (reaction) => reaction.emoji.name === "πŸ”΄" || reaction.emoji.name === "πŸ”΅";
reaction.message.awaitReactions(filters, { time: 15000 }).then(collected => {
console.log(collected);
if (collected.get("πŸ”΄") !== undefined && collected.get("πŸ”΅") !== undefined) {
let optionOne = collected.get("πŸ”΄").count;
let optionTwo = collected.get("πŸ”΅").count;
let resultsEmbed = new Discord.MessageEmbed()
.setTitle("the poll result")
.setDescription(`the result of the poll: ${args.join(" ")}`)
.addField("πŸ”΄:", `${optionOne}`)
.addField("πŸ”΅:", `${optionTwo}`)
.setColor('#')
.setTimestamp()
message.channel.send(resultsEmbed);
} else {
//there were no votes for one of the options, thus it will not be able to get property
message.channel.send("There were no votes for one of the options.");
}
})
})
);
} catch (err) {
console.log(err);
}

Discord.js 'awaitReactions is not a function' error

I'm trying to have a bot react when users click the emojis on the bot's embeds.
I'm receiving in the console:
UnhandledPromiseRejectionWarning: TypeError: chestEmbed.awaitReactions
is not a function
The code:
module.exports = {
name: 'enterhouse',
aliases: 'eh',
permissions: ["ADMINISTRATOR", "MANAGE_MESSAGES", "CONNECT"],
description: "Pick a number",
async execute(client, message, args, Discord){
const chestEmbed = new MessageEmbed()
.setColor('#FFA500')
.setImage('https://imageURL.jpg');
message.channel.send(chestEmbed).then(chestEmbed => {chestEmbed.react('1️⃣').then(() => chestEmbed.react('2️⃣').then(() => chestEmbed.react('3️⃣')))}
)
.catch(() => console.error('One of the emojis failed to react.'));
const filter = (reaction, user) => {
return (['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === message.author.id);
};
chestEmbed.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '1️⃣') {
chestEmbed.delete();
message.reply('you reacted with 1');
} else if (reaction.emoji.name === '2️⃣') {
message.reply('you reacted with 2');
} else {
message.reply('you reacted with 3');
}
})
.catch(collected => {
message.reply('Time is up, you did not react.');
});
}
}
It worked fine when it was message.awaitReactions instead.
Any help is really appreciated!
You are awaiting messages from the embed it's self not the message the embed is in.
Simple fix:
...
chestEmbed = await message.channel.send(chestEmbed)
...
Full Code:
module.exports = {
name: 'enterhouse',
aliases: 'eh',
permissions: ["ADMINISTRATOR", "MANAGE_MESSAGES", "CONNECT"],
description: "Pick a number",
async execute(client, message, args, Discord) {
const chestEmbed = new MessageEmbed()
.setColor('#FFA500')
.setImage('https://imageURL.jpg');
chestEmbed = await message.channel.send(chestEmbed)
chestEmbed.react('1️⃣').then(() => chestEmbed.react('2️⃣')).then(() => chestEmbed.react('3️⃣'))
const filter = (reaction, user) => {
return (['1️⃣', '2️⃣', '3️⃣'].includes(reaction.emoji.name) && user.id === message.author.id);
};
chestEmbed.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '1️⃣') {
chestEmbed.delete();
message.reply('you reacted with 1');
} else if (reaction.emoji.name === '2️⃣') {
message.reply('you reacted with 2');
} else {
message.reply('you reacted with 3');
}
})
.catch(collected => {
message.reply('Time is up, you did not react.');
});
}
}

Categories

Resources