Cannot set permissions on newly created channel - javascript

I want to make my bot able to create private tickets. It can create the channel just fine, but when I try to set the permissions on that channel, it says that #everyone is the only role (therefore having default permissions). Also, the console doesn't report any error messages.
To clarify, I can't get the bot to apply permissions to a channel.
const client = new discord.Client();
const config = require("./config.json");
var userTickets = new Map();
client.login(config.token);
client.on("ready", () => {
console.log(client.user.username + "has logged in.")
});
client.on("message", message => {
if(message.author.bot) return;
if(message.content.toLowerCase() === "?crearticket" && message.channel.id === "729851516667691058") {
if(userTickets.has(message.author.id) || message.guild.channels.cache.some(channel =>
channel.name.toLowerCase() === message.author.username + "-ticket")) {
message.author.send("ยกYa tienes un ticket!");
}
else {
let guild = message.guild;
message.guild.channels.create(`${message.author.username}-ticket`, {
type: "text",
permissionsOverwrites: [
{
id: message.author.id,
allow: ["VIEW_CHANNEL"]
},
{
id: message.guild.id,
deny: ["VIEW_CHANNEL"] //This is the part I mentioned.
},
{
id: "729481759955222538",
allow: ["VIEW_CHANNEL"]
},
],
}).then(ch => {
console.log("Creado el canal" + ch.name)
userTickets.set(message.author.id, ch.id);
console.log(userTickets);
}).catch(err => console.log(err));
}
}
else if(message.content.toLowerCase() == "?closeticket"){
if(userTickets.has(message.author.id)) {
if(message.channel.id === userTickets.get(message.author.id)) {
message.channel.delete("Cerrando Ticket")
.then(channel => {
console.log("Eliminado el canal " + channel.name);
userTickets.delete(message.author.id);
})
.catch(err => console.log(err));
}
}
}
});

Change permissionsOverwrites to permissionOverwrites (you had an extra s).
Happy coding!

Related

Ticket bot only saying the id's

I am back again with a question :). I am building my own ticket function, and I just started but if I create a channel for a ticket, its only saying ticket-(Discord account ID) And thats also the case by the embed. Anyone who can look at it?
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions} = require('discord.js');
const { execute } = require("./ticket");
module.exports = {
name: 'create',
description: 'create your own ticket.',
execute(message, client, args){
if(message.guild.channels.cache.find(channel => channel.name === "Ticket from <#" + message.author + ">")) {
message.reply(`${message.member.user.toString()} **You have successfully created a ticket, Please click on ${channel} to view your ticket**`).then(m => m.delete({ timeout: 14000 }).catch(e => {}));
if(message.guild.channels.cache.find(channel => channel.name === `ticket-${message.author.id}`)) {
return message.reply('<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**');
}
message.delete();
message.guild.channels.create(`Ticket ${message.author}`, {
permissionOverwrites: [
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: message.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
}).then(async channel => {
const embed = new MessageEmbed()
.setTitle("<#" + message.author + "> Ticket")
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
.setColor("BLUE")
channel.send({ embeds: [embed] })
});
}
}
}
I cleaned up the code a fair bit, less is more. Text channels do not have spaces in them so I replaced them with what Discord uses, hypens. The below code will check if a channel already exists and create one if it doesn't.
const {
MessageEmbed,
} = require('discord.js');
module.exports = {
name: 'create',
description: 'create your own ticket.',
async execute(message, client, args) {
const channelName = `ticket-${message.author.username}`
const existing = message.guild.channels.cache.find(channel => channel.name === channelName.toLowerCase());
if (existing) {
return message.reply({
content: `<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**\n${existing}.`,
}).then((m) => {
setTimeout(() => {
m.delete();
}, 14000);
})
}
message.delete();
message.guild.channels.create(channelName, {
type: 'GUILD_TEXT',
permissionOverwrites: [{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
}).then(async channel => {
const embed = new MessageEmbed()
.setColor("BLUE")
.setTitle(`${message.author.username} Ticket`)
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
channel.send({
embeds: [embed]
})
});
}
}

Discord.js: Cannot read property "roles" of undefined

Ive been working on a bot, and I am trying to get it to create a role and add it, it was working before, but now it is no longer working.
Here is the code:
exports.run = (client, message, args) => {
var member = message.mentions.members.first();
var sender = message.author;
var guild = message.guild;
var name = (message.author.username + "'s party")
var role = sender.guild.roles.cache.find(role => role.name === message.author.username + "'s party");
// sender.roles.add(role);
if (typeof role === undefined) {
let newRole = guild.roles.create({
data: {
name: name,
color: 'BLUE',
},
reason: 'Partee',
})
.then(console.log)
.catch(console.error);
member.roles.add(newRole);
message.channel.send("Your party has been created!")
} else {
member.roles.add(newRole);
message.channel.send("You have been added to your party!")
}
}
I dont know why it is going wrong. here is the error:
TypeError: Cannot read property 'roles' of undefined
I believe the problem is that message.author returns the user that sent the message. You would need the member. The member object returns more details about the user, by giving information on the user's position in a server/guild.
Just change the value of sender to message.member.
Example:
exports.run = (client, message, args) => {
var member = message.mentions.members.first();
var sender = message.member;
var guild = message.guild;
var name = (message.author.username + "'s party")
var role = sender.guild.roles.cache.find(role => role.name === message.author.username + "'s party");
// sender.roles.add(role);
if (typeof role === undefined) {
let newRole = guild.roles.create({
data: {
name: name,
color: 'BLUE',
},
reason: 'Partee',
})
.then(console.log)
.catch(console.error);
member.roles.add(newRole);
message.channel.send("Your party has been created!")
} else {
member.roles.add(newRole);
message.channel.send("You have been added to your party!")
}
}
Hopefully that works!
The message.author doesn't have a guild method, so calling this will return undefined. To make a role and give it to both author and mentioned user, I would do something like this for example:
if(message.author.bot === true) return;
if(message.channel.type === "dm") return;
const name = (message.author.username + "'s party");
const member = message.mentions.members.first();
if(member) {
const authorUser = message.guild.members.cache.get(message.author.id);
// Find the role first
const role = message.guild.roles.cache.find(role => role.name === name);
if(!role) {
// The role has not be found, create a new one.
// Create the new role and give it to the person
// Discord v12: { data: { name: "name", reason: "new role", ...properties } }
// Discord v13: { name: "name", reason: "new role", ...properties }
message.guild.roles.create({
data: {
name: name,
color: "BLUE",
},
reason: "The party has been started ๐ŸŽ‰"
}).then(RoleCreated => {
authorUser.roles.add(RoleCreated)
.then(() => member.roles.add(RoleCreated))
.then(() => message.channel.send("PARTY HAS BEEN CREATED! LET'S GET THIS PARTY STARTED! ๐ŸŽ‰"))
.catch((error) => {
console.log(error.message);
});
});
}else{
// Role exists, give it to the mentioned user
member.roles.add(role).then(() => message.channel.send("WELCOME TO MY PARTY! LET'S GET THIS PARTY STARTED! ๐ŸŽ‰")).catch((error) => {
console.error(error.message);
});
}
}
! You might need to adjust the code to fit with your framework. I have tested this on Discord V13. Should work on V12 as well. Also note that if a user changes it's username, a new role will be created, so your server might get some ghost roles.

Discord.js: Embed not sending

I'm trying to make a help embed command with reactions, but I keep getting this error
I'm trying to make a help embed with reactions, but when I do !help, it doesnt send the embed???
I'm trying to make a help embed command with reactions, but I keep getting this error I'm trying to make a help embed with reactions, but when I do !help, it doesnt send the embed???
This is my code:
const Discord = require('discord.js')
module.exports = {
name: 'help',
description: "Help command",
execute(message, args){
async function helpEmbed(message, args) {
const helpEmbed = new Discord.MessageEmbed()
.setTitle('Help!')
.setDescription(`**React with one of the circles to get help with a category!**`)
.addFields(
{ name: 'Moderation', value: ':blue_circle:'},
{ name: 'Fun', value: ':green_circle:'},
{ name: 'Misc', value: ':purple_circle:'},
)
.setColor(4627199)
message.channel.send({embed: helpEmbed}).then(embedMessage => {
embedMessage.react('๐Ÿ”ต')
embedMessage.react('๐ŸŸข')
embedMessage.react('๐ŸŸฃ')
})
const msg = await sendReact()
const userReactions = message.reactions.cache.filter(reaction => reaction.users.cache.has(userId));
const filter = (reaction, user) =>{
return ['๐Ÿ”ต', '๐ŸŸข', '๐ŸŸฃ'].includes(reaction.emoji.name) && user.id === message.author.id;
}
msg.awaitReactions(filter, { max: 1, time: 10000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '๐Ÿ”ต') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Moderation');
} else if (reaction.emoji.name === '๐ŸŸข') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Fun');
} else if (reaction.emoji.name === '๐ŸŸฃ') {
try {
for (const reaction of userReactions.values()) {
reaction.users.remove(userId)
}
} catch (error) {
console.error('Failed to remove reactions.')
}
message.channel.send('Misc')
}
})
.catch(collected => {
message.reply('you reacted with neither a thumbs up, nor a thumbs down.');
});
}
}
}
You defined helpEmbed funcion but not called it.
try writing "helpEmbed()" after "execute(message, args){"
if still doesn't work:
Check bot's permission
Bot needs SEND_EMBED_LINKS Permission in that channel.

Permission overwrite isn't setting permissions

I don't know why is permissionOverwrites not working for me. No error here. No permissions will change for anyone. I think the problem is here: {allow: 'VIEW_CHANNEL', id: userId,}. I think the problem will be in the id. I hope someone finds out where I made a mistake.
module.exports = (client, Discord, chalk, message, args) => {
const channelId = '799339037306912808'
const getEmoji = (emojiName) =>
client.emojis.cache.find((emoji) => emoji.name === emojiName)
const emojis = {
golden_ticket: 'rules',
}
const handleReaction = (reaction, user, add) => {
if (user.id === '799652033509457940') {
return
}
const emoji = reaction._emoji.name
const { guild } = reaction.message
const userName = user.username
const userId = guild.members.cache.find((member) => member.id === user.id)
const categoryId = '802172599836213258';
if (add) {
reaction.users.remove(userId)
reaction.message.guild.channels
.create(`${userName}`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: userId,
}
],
})
.then((channel) => {
channel.setParent(categoryId)
channel => ticketChannelId = channel.id;
message.ticketChannelId.send('cs');
})
} else {
return;
}
}
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelId) {
handleReaction(reaction, user, true)
}
})
}
Here, it is better to specify the type of the overwrite. Plus, "allow" should be an array.
permissionOverwrites: [
{
allow: [ 'VIEW_CHANNEL' ],
id: userId,
type: 'member'
}
],
it should resolve your issue. Note that by default, your channel will be readable by everyone, use:
permissionOverwrites: [
{
deny: ['VIEW_CHANNEL'],
id: reaction.message.guild.id,
type: 'role'
},
{
allow: ['VIEW_CHANNEL'],
id: userId,
type: 'member'
}
],
so everyone can't see the channel except admins and the user

Discord.js Get user from reactions **Updated**

Update
I have updated the code that is currently working for me, It will now create the channel and then check to see if the channel is create. It will only allow 1 user to create a channel you will not be able to create a T5 channel and a T4 channel as the same user.
Thank you and I hope you all have a great Christmas.
Client.on("message", async (message) => {
if (message.author.Client || message.channel.type === "dm") return;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = message.content.substring(message.content.indexOf(" ") + 1);
if (cmd === `${prefix}battle`) {
let embed = new Discord.MessageEmbed()
.setTitle("โš”๏ธ 1657 Battles! โš”๏ธ")
.setDescription("React to this message to join the battle.")
.addFields(
{ name: "๐Ÿฅ‡", value: "T5" },
{ name: "๐Ÿฅˆ", value: "T4" },
{ name: "๐Ÿฅ‰", value: "T3" },
{ name: "๐Ÿ…", value: "T2" },
{ name: "๐ŸŽ–", value: "T1" }
)
.setColor("#0099ff")
.setTimestamp()
.setFooter("Please pick the troop type you want to battle with!");
let msgEmbed = await message.channel.send(embed);
msgEmbed.react("๐Ÿฅ‡"); // T5
msgEmbed.react("๐Ÿฅˆ"); // T4
msgEmbed.react("๐Ÿฅ‰"); // T3
msgEmbed.react("๐Ÿ…"); // T2
msgEmbed.react("๐ŸŽ–"); // T1
}
});
Client.on("messageReactionAdd", async (reaction, user, message) => {
//Add an event listener
if (reaction.message.partial) await reaction.message.fetch();
if (user.id === Client.user.id) return; //If the reaction was from the bot, return
if (!reaction.message.guild) return; //If the reaction was not in a guild
const guild = Client.guilds.cache.get("644295524404428832");
if (
guild.channels.cache.find((channel) => channel.name === "t5-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅ‡") {
let guild = reaction.message.guild;
guild.channels.create("T5 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400016736780338",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t4-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅˆ") {
let guild = reaction.message.guild;
guild.channels.create("T4 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400619114463275",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t3-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿฅ‰") {
let guild = reaction.message.guild;
guild.channels.create("T3 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400701130670110",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t2-battle-channel")
)
return;
if (reaction.emoji.name === "๐Ÿ…") {
let guild = reaction.message.guild;
guild.channels.create("T2 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400738727624704",
allow: ["VIEW_CHANNEL"],
},
],
});
}
if (
guild.channels.cache.find((channel) => channel.name === "t1-battle-channel")
)
return;
if (reaction.emoji.name === "๐ŸŽ–") {
let guild = reaction.message.guild;
guild.channels.create("T1 Battle Channel", {
//Creating the channel
type: "text", //Make sure the channel type is text
permissionOverwrites: [
//Set overwrites
{
id: guild.id,
deny: "VIEW_CHANNEL",
},
{
id: "788400784420372490",
allow: ["VIEW_CHANNEL"],
},
],
});
}
});
If you want to get all of the reactions on a message, you can use the reactions property on a message, if you already have the message object. This will return a ReactionManager which you can use.
You should use a reaction collector.
These work quite similarly to message collectors, except that you
apply them on a message rather than a channel. The following is an
example taken from the documentation, with slightly better variable
names for clarification. The filter will check for the ๐Ÿ‘ emoji - in
the default skin tone specifically, so be wary of that. It will also
check that the person who reacted shares the same id as the author of
the original message that the collector was assigned to.
const filter = (reaction, user) => {
return reaction.emoji.name === '๐Ÿ‘' && user.id === message.author.id;
};
const collector = message.createReactionCollector(filter, { time: 15000 });
collector.on('collect', (reaction, user) => {
console.log(`Collected ${reaction.emoji.name} from ${user.tag}`);
});
collector.on('end', collected => {
console.log(`Collected ${collected.size} items`);
});
Read it's documentation here.
I would like to also know if it is possible to the randomly pair each users that have reacted to a specific role.
The collected property should be handy for this task.
As for adding a role/roles to a GuildMember, use the add method. Read about how you can add a role to a member here.

Categories