Discord.js permissionOverwrites not working but no error at all - javascript

I've been working on a ticket bot for our company and ended up not being able to update a user's permissions per channel.
I cannot find any problems and the code is working apart of the permissions perfectly. I'm using DiscordJS 12.5.1.
Here's my code:
module.exports = {
name: 'ticket',
category: 'Ticket',
description: 'Creates a new ticket.',
aliases: ['new'],
usage: 'new',
userperms: [],
botperms: [],
run: async (client, message, args, prefix) => {
const discord = require('discord.js');
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
// parent: 'category id',
},
)
.then(async (channel) => {
let category = client.channels.cache.find(
(c) => c.name == '➣ Online Tickets' && c.type == 'category',
);
if (!category) throw new Error('Category channel does not exist');
channel.setParent(category.id);
// channel.permissionOverwrites.create(message.author.id, {VIEW_CHANNEL: true, SEND_MESSAGES: false});
// channel.permissionOverwrites.create(message.guild.roles.everyone, {VIEW_CHANNEL: false});
var embedParent = new discord.MessageEmbed()
.setTitle(`Beste, ${message.author.username}`)
.setDescription(
'Een van onze medewerkers helpt je z.s.m! Laat alvast een bericht achter zodat wij je zo goed mogelijk kunnen helpen. Om U zo goed mogelijk te kunnen helpen komen nu enkele vragen, gelieve deze te beantwoorden.\nReageer met 1️⃣ voor een technische vraag \nReageer met 2️⃣ voor boekhouding en juridische vragen.\nReageer met 3️⃣ voor een samenwerking.\nReageer met 4️⃣ voor overige vragen. \n\n ***LET OP: Als U errors krijgt op uw server, kunt U het beste een ticket aanmaken op de website: snip ***',
)
.setColor('007BFF')
.setFooter(
'© OnlineNode.nl 2021 - Ticket Systeem',
'https://media.discordapp.net/attachments/735827815521452133/830082858470604870/logo_400x400.png',
)
.setTimestamp();
channel.send(embedParent).then(function (embedParent) {
embedParent.react('1️⃣');
embedParent.react('2️⃣');
embedParent.react('3️⃣');
embedParent.react('4️⃣');
//embedParent.react("5️⃣")
});
message.guild.channels.cache
.find((c) => c.name == '🗃┃-discord-logs')
.send('New ticket has been submitted!');
});
},
};

Your permissionOverwrites array has an object where you repeat the allow key several times:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
As an object can't have two keys with the same name, it's basically the same as this:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
allow is an array of the permissions that are allowed for the user or role:
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
}
Another error is that when you set the parent of the channel with the setParent method, it overwrites the permissions you just added and sets them to the same as the parent channel.
The setParent method accepts an options object as its second parameter. One of its properties is lockPermissions. It tells whether to lock the permissions to what the parent's permissions are and its default value is true. To prevent synchronising permissions, you can set it to false instead, like this:
channel.setParent(category.id, { lockPermissions: false });

As Zsolt Meszaros mentioned, your permissions will need to be in an array.
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
// parent: 'category id',
},
)
Another thing, it is possible that your bot is setting the permissions, but then soon after inside your code, you changed the category the channel belongs in:
channel.setParent(category.id);
Also, I'm not sure, but there might be a chance that after you change the category, the permissions are being removed and then copied from what the category's permissions are, so you'll have to set the category before setting the permissions.

Related

Discord.js channel manage channel permissions

I'm having a little issue creating a new channel. I want to create a new channel using the following code:
message.guild.channels.create('channel name', {
type: 'voice',
permissionOverwrites: [
{
id: some_id,
deny: ['VIEW_CHANNEL'],
},
{
id: bot_id,
deny: ['MANAGE_CHANNEL'],
},
],
})
However, I'm getting an error saying the bitfield of manage channel is invalid. I have tried to lookup a list of channel permissions but I couldn't find any.
Error : [Symbol(code)]: 'BITFIELD_INVALID'
Can anyone help me ?
const { ChannelType, PermissionsBitField } = require('discord.js');
guild.channels.create({
name: 'new-channel',
type: ChannelType.GuildText,
permissionOverwrites: [
{
id: interaction.guild.id,
deny: [PermissionsBitField.Flags.ViewChannel],
},
{
id: interaction.user.id,
allow: [PermissionsBitField.Flags.ViewChannel],
},
],
});
Discord.js#v14 has change all BitField check it out this link: https://discordjs.guide/popular-topics/permissions.html#adding-overwrites

Sending Messages to members on join

Hi I want to get the bot to send a direct/private message to new users that join the server. It is able to post a welcome message on a channel but it doesnt work when i does in in private messages.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const prefix = '*';
bot.on('ready', () => {
console.log('Bot Démarré');
bot.user.setActivity('Chill \'N Code (*help)', { type: 'WATCHING' });
bot.user.setStatus('online');
})
bot.on('guildMemberAdd', member => {
console.log(member.user.username + " a rejoint le serveur");
const embed = new Discord.MessageEmbed()
.setTitle("<EARLY_SUPPORTER:840512953928515595> Bienvenue " + member.user.username + " !")
.setImage('https://i.imgur.com/Kbl451j.gif')
.setDescription("__**Voici quelques informations utiles :**__")
.addFields(
{ name: '\u200B', value: '\u200B' },
{ name: '<:channel:840513546416554045> **Règlement**', value: 'Nous T\'invitions à lire le [règlement](https://discord.com/channels/836947422122344448/836947422173200410/836962049484390449]', inline: false },
{ name: '<:add_reaction:840512848266657792> **Rôles**', value: 'Tu peux prendre tes rôles [ici](https://discord.com/channels/836947422122344448/836947422617141290/837022973830496286)', inline: false },
{ name: '<:moderation:840528469317517333> **Devenir Staff**', value: 'Tu peux devenir staff [ici](https://forms.gle/rGV26bZytcx5atG28)', inline: false },
{ name: '\u200B', value: '\u200B' },
{ name: 'Github', value: '[Github](https://github.com/chillncode)', inline: false },
{ name: 'Twitter', value: '[Twitter](https://twitter.com/ChillNCode1)', inline: false }
)
.setFooter('Chill \'N Code', 'https://cdn.discordapp.com/icons/836947422122344448/d27317d317a5b260d0365f6ca0da5455.png');
member.send(embed);
console.log("message envoyé");
})
Make sure you have the SERVER MEMBERS INTENT enabled in the Discord Developer Portal

How to edit an Embed Author?

I want to edit the author of an embed sent by my bot.
The message is sent by this code :
task_chan.send('', {
embed: {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
})
To edit the message I've tried :
taken.embeds[0].author.icon_url = util.avatarURL
taken.embeds[0].author.name = util.username
taken.edit(new Discord.RichEmbed(taken.embeds[0]));
taken contain the message to edit and util an user.
And it only change the name…
I don't understand why but author.icon_url is undefined between these two code samples.
I hope you can help me :)
method channel.send return a promise, so you can use .then(msg=> to get a message object.
let testEmbed = {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
}
task_chan.send({embed:testEmbed}).then(msg => {
testEmbed.name = 'LOL'
testEmbed.iconURL = 'SOMEURL'
msg.edit({embed:testEmbed})
})
I would recommend that you use the built-in methods for creating embeds, in my opinion it is more convenient.

How to update an object inside an array inside an object with mongoose?

Let's say I want to update "numberOfUpVotes" where the title is "Een centrale plek voor alle ideeen". I want the new value of "numberOfUpVotes" to be stored in the database. How do I do that?
Right now my code doesn't give an error, but it also doesn't work. This is what I've tried:
Board.findOneAndUpdate(
{"ideas.numberOfUpVotes": 23},
{$set: {"numberOfUpVotes": 2}}, // $set
{new: true},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("hallo");
});
This is my data:
{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: ida1,
userId: id1,
title: 'Een centrale plek voor alle ideeen',
text: 'Een plek waar alle ideeen getoond worden op een scherm ofzo. Waar mensen dan op kunnnen stemmen via hun telefoon',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: ida2,
userId: id1,
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
}
You can do this without mongoose, something like.
const board = {
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: 'ida1 (demo)',
userId: 'id1 (demo)',
title: 'Een centrale plek voor alle ideeen',
text: 'Verkort voor demonstratie',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: 'ida2 (demo)',
userId: 'id1 (demo)',
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
};
// find the filtered record and update its value
// the found record is a reference, so the value
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;
// QED
console.log(JSON.stringify(board, null, " "));
This is my final answer:
Board.update(
{"ideas._id": mongoose.Types.ObjectId("abc123")},
{$inc:{"ideas.$.numberOfUpVotes": 1}},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("succes! (:");
})

Not able to access object property with dashes

i'm confused about accessing a property from a javascript object.
In this scenario, i'm working with Node.js and Mongoose from find() method
My object:
{
_id: 52f541c7d2750f2d2cbf6d4a,
descriptions: {
'en-us': 'Lorem ipsum',
'pt-br': 'Os acessórios já não são mais meros coadjuvantes na harmonia de uma combinação, mas sim a sua assinatura de estilo, dando um caprichoso arremate ao que você escolheu ser pro dia de hoje.'
},
id: '1',
ids: { 'en-us': 'accessories', 'pt-br': 'acessorios' },
name: 'accessories',
names: { 'en-us': 'Accessories', 'pt-br': 'Acessórios' },
images: {
header: '/images/categories/86e3451ca755d31234e5fcad4af055f1',
unset: []
},
position: { x: 650, y: 735 },
active: true
}
Here's the thing:
I'm able to access any property except object.names, object.descriptions and object.ids, it returns 'undefined'.
But when i access the properties with Object.get('property'), i got the expected return.
Object.ids = undefined
Object['ids'] = undefined
Object.get('ids') = { 'en-us': 'accessories', 'pt-br': 'acessorios' }
Am i missing something here ? Maybe the issue occurs with special chars (In this case, dashes..?)
Hope you guys can help me. Best regards!

Categories

Resources