Create channels in DiscordJs v14 - discord

So i upgraded to DiscordJs v14 and i want to create a command that creates a channel but i none of the codes i found online are working
Error:
/home/runner/discord-js-v14-1-2/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
name[BASE_TYPE_REQUIRED]: This field is required

https://discord.js.org/#/docs/discord.js/main/typedef/CategoryCreateChannelOptions
Check out discordjs docs first!

Since Discordjs v14 you have to specify the name as a parameter !
Do
interaction.guild.channels.create({
name: "NameOfTheChannel",
type: 'text',
})
Instead of
interaction.guild.channels.create("nameOfTheChannel", {
type: 'text',
})

Related

Discord.js bot assigning roles to users throws permission denied error

I'm trying to make a discord bot (with js) that can assign roles to users.
Discord version: 14.3.0
Nodejs version: 16.17.0
Im using this function to assign role.
const client = new Discord.Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.DirectMessages
]
});
....
var role = message.guild.roles.cache.find(role => role.name == "Role_name")
guildMember.roles.add(role) // this line is causing the error
This is the exact error im getting
/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code :
data.error, status, method, url, requestData);
^
DiscordAPIError[50013]: Missing Permissions
at SequentialHandler.runRequest ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:99:14)
at async REST.request (/media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/#discordjs/rest/dist/lib/REST.cjs:52:22)
at async GuildMemberRoleManager.add ( /media/pranav/Storage/ie/programming/nodejs/project-l isabey/node_modules/discord.js/src/managers/GuildMemberRoleManager.js:129:7) {
rawError: { message: 'Missing Permissions', code: 50013 },
code: 50013,
status: 403,
method: 'PUT',
url: ' https://discord.com/api/v10/guilds/1011546412011507823/members/1021733308457041970/roles/1 021714244846223360',
requestBody: { files: undefined, json: undefined }
}
I tried giving the bot Mod permissions in the server
Invited bot to server with "discord.com/api/oauth2/authorize?client_id=xxxxxxxxxx&permissions=8&scope=bot%20applications.commands"
In developer portal all 3 "privileged gateway intents" are checked.
Still i'm getting the same error. How can I fix this ?
Thanks!
Make sure that the role you're trying to assign is lower to your highest bot role.
In server settings, literally drag the bots role above the roles it will be assigning.

Bot sends a embed when joins a server

Im trying to make my bot send a embed in the server that it joins (E.G a thank you for inviting and what the bot can do).This is the error that I am getting.
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
^
TypeError: Cannot read properties of undefined (reading 'channels')
this is the code that i am using in the index.js file
client.on('guildCreate', message => {
const channel = message.guild.channels.cache.find(channel => channel.type === 'text' && client.user.me.permissions.has("send_messages"))
const embed = new MessageEmbed()
.setColor('GREEN')
.setTitle('Thank You')
.setDescription("Thank you for inviting Rynwin to your server. To get the command list please do /help.\n \n The default Bot prefix is ```<```")
.addFields([
{
name: "Our Support Server",
value: "If you require assistance or would like to get daily bot updates please join our support discord [here] ()"
},
{
name: "Commands",
value: "Try some of these commands; \n\n**/prefix <prefix>** - Sets the server prefix\n\n**/help** - Get the command list or information on a command \n\n**/botinfo** - Shows info on the bot"
},
channel.send({ embeds: [embed] })
])
There are a few things wrong on the first 2 lines. Firstly, guildCreate gives a Guild instance, not a message. Secondly, you aren't checking the correct channel type or permission. Here is the fixed code:
client.on('guildCreate', guild => {
const channel = guild.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && guild.me.permissions.has("SEND_MESSAGES"))
// GUILD_TEXT channel type, guild.me for client guild member, and uppercase permission
// rest of code...
}

Copying and moving message in another channel

My suggestion Script worked totally fine for the last couple of months, but it stopped working a few days ago. I noticed that my .send function was underlined, and it said this:
Property 'send' does not exist on type 'GuildChannel | ThreadChannel'.
Property 'send' does not exist on type 'GuildChannel'
I'm btw. not sure if that's the problem with the script or if they changed anything I didn't notice, and I'm getting no errors. The Script basically just don't work.
My suggestion script:
case "suggestion":
var str = message.content.slice(" .suggestion".length);
const suggestionembed = new Discord.MessageEmbed()
.setThumbnail('png')
.setTitle("Suggestion")
.setColor('#151515')
.addFields(
{ name: "Person, that suggested somenthing:", value: `<#!${message.author.id}>` },
{ name: 'Suggestion:', value: `${str}` },
{ name: 'Channel:', value: `${message.channel}` },
)
.setTimestamp()
await message.guild.channels.cache.find(c => c.name === 'suggestion')
.send({ embeds: [suggestionembed] })
.then(embedMessage => {
embedMessage.react("✅")
embedMessage.react("❌")
});
message.delete();
break;
Just ignore that if you are sure that it's a text channel. That is only there because it can be a VoiceChannel. You won't have autocomplete in Visual Studio Code but it will still work as intended. If you are using TypeScript, you could use as to tell TypeScript it's a TextChannel

Discord.Js options object

I'm actually doing a command to start a "conversation" with a player and take responses he give me. For doing that, I've the plan to use a temporary channel. I don't find a complet way to create a channel. I saw, that we have to create the channel, and after modifie it to adjust as we want. So I have this code :
m.guild.createChannel(`Candidature-${m.author.username}`, 'text', [{
type: 'role',
id: '605021521467146279',
permission: 0x400
}])
with this error :
(node:1904) DeprecationWarning: Guild#createChannel: Create channels with an options object instead of separate parameters
and I don't find real documentation about options object. Can I have some information about how it's work, and some link to learn more ?
Thanks for your help.
I can see the confusion here as the way channels are now created have been altered and here is how to create them: (var name = "blah" isn't needed but cleans it up a bit)
var name = `ticket-${numbers}`;
message.guild.createChannel(name, { type: "text" })
And to do the channel permissions you want to use .then like this:
message.guild.createChannel(name, { type: "text" }).then(
(chan) => {
chan.overwritePermissions(message.guild.roles.find('name', '#everyone'), {
'VIEW_CHANNEL': false
})
You can change the role or change it to other things such as message.author.id or mentioned users etc.
Hope this helps!
Thanks for your answers. I have do this :
m.guild.createChannel(
`Candidature-${m.author.username}`, {
type: 'text',
topic: `Salon de candidature créé par ${m.author.username} | Id du joueur : ${m.author.id}`,
parent: idCategorie,
permissionOverwrites: [{
id: m.guild.id,
deny: ['VIEW_CHANNEL'],
},
{
id: m.author.id,
allow: ['VIEW_CHANNEL'],
}
]
})
.then((chan) => {
console.log("Channel create");
});
With those links :
https://discord.js.org/#/docs/main/stable/typedef/ChannelData
https://discordjs.guide/popular-topics/permissions.html#roles-as-bot-permissions
It's creating a channel with a name, a topic, and a categorie as parent. Only the plyaer itself and administrator can see the channel.

Discord js creating discord category

I'm trying to make a category on discord server using Discord Bot but I couldn't find the method or something on internet. Also I looked the "discord.js.org". Then I thought that isn't there any possibility to do that. So is there any way to make a category on discord servers?
discordjs v13 needs GUILD_CATEGORY instead of just "category"
message.guild.channels.create("Name", { type: "GUILD_CATEGORY" });
You need to use the .createChannel method and then enter „category“ as type of the channel
<guild>.createChannel("NAME OF THE CHANNEL", "category")
I would advice the usage of a promise as it adds a lot of functionality and safety to your code
guild.createChannel('new-category', {
type: 'category',
permissionsOverwrites: [{
id: guild.id,
deny: ['MANAGE_MESSAGES'],
allow: ['SEND_MESSAGES']
}]
})
.then(console.log)
.catch(console.error);
This allows you to create the channel with permissions and actually handle any errors like the channel already existing or your bot not being able to create said channel cause of its permissions assigned.
This is the proper way to do this.
Example to create channel
guild.createChannel('new-general', { type: 'text' })
.then(console.log)
.catch(console.error);
v12:
message.guild.channels.create('Category', { type: 'category' });
I have made a command code for you to use. Modify it and use it.
if(message.content === `${prefix}create-channel`) {
message.guild.createChannel('name', {
//Channel type (text || voice || category)
type: 'text',
permissionsOverwrites: [{
id: guild.id,
deny: [],
allow: ['SEND_MESSAGES']
}]
})
.catch(console.error);
}
discordjs v14 needs ChannelType.GuildCategory and the name in the options
message.guild.channels.create({ name: "Name", type: ChannelType.GuildCategory });

Resources