Create a role with Discord JS - javascript

I am making a Discord JS bot which is supposed to have a mute function that assigns a role to a member so they can't text.
I tried looking all over the web for how to create a role (even the Discord JS documentation) but to no avail.
I've tried the code below but it doesn't work (pulled straight from https://discord.js.org/#/docs/main/stable/class/RoleManager?scrollTo=create).
guild.roles.create({
data: {
name: 'Super Cool People',
color: 'BLUE',
},
reason: 'we needed a role for Super Cool People',
})
.then(console.log)
.catch(console.error);
Thanks in advance!

I'm pretty sure that guild is not defined within your code. roles is a property of Guild, so you need a Guild class to access RoleManager and create a Role.
If your code is executed within a command, you can use message.guild to get the Guild, otherwise, you'll need to get the Guild manually.
Here's a simple example of how to use it:
First Scenario
client.on("message", message => {
if (message.author.bot) return false;
if (message.author.id !== message.guild.ownerID) return false;
message.guild.roles.create({
data: {
name: "Muted",
permissions: [],
color: "RED"
},
reason: "Created the mute role."
}).catch(console.log)
});
Second Scenario
const Guild = client.guilds.cache.get("1234567890123456789");
Guild.roles.create({
data: {
name: "Muted",
permissions: [],
color: "RED"
},
reason: "Created the mute role."
}).catch(console.log)

as long as you have a role manager you should have the create function according to the docs
so my advice to fix this issue is see where it goes wrong. I've done it with the createGuild event in typeScript. this will create the roles when the bot joins a new guild.
client.on('guildCreate', async guild => {
await guild.roles.create({ data: { name: 'roleName' } });
});
also be aware that you need high enough permissions to actually create a role.
ps: providing errors when you have an error would be useful (the full error)

If you will try to do guild.create.roles the console will give you an error with message: guild <= is not defined!
You need to write message.guild.create.roles not the guild.create.roles, after this, you will get the created role.
Example code creating the role, with the "debug messages":
message.channel.send('creating a role')
message.guild.roles.create({
data: {
name: 'Testing Role',
color: 'GREY'
},
reason: 'Stackoverflow.com - created for user14470589'
})
.then((res => {
message.channel.send(`debug result:\n${res}`)
})).catch((err => {
message.channel.send(`error:\n${err}`)
}))

Related

How do I create a text channel discord.js 14

I wanted to ask how to create channels in discord.js 14 (i tried to researched but found nothing) I want to make a simple text channel! :)) Also, with the stuff i found, it worked ( no errors) it just didnt create anything / post errors in debug log
It's literally under Discord.js documentation. Please, next time before asking a question read the docs.
https://discord.js.org/#/docs/discord.js/main/general/welcome
guild.channels.create({
name: "hello",
type: ChannelType.GuildText,
parent: cat[0].ID,
// your permission overwrites or other options here
});
//If the command is slash type
const { Permissions } = require("discord.js")
interaction.guild.channels.create({
name: "new-channel",
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: interaction.guild.id,
accept: [Permissions.FLAGS.VIEW_CHANNEL],
},
],
});
//If the command is message type
const { Permissions } = require("discord.js")
message.guild.channels.create({
name: "new-channel",
type: 'GUILD_TEXT',
permissionOverwrites: [
{
id: message.guild.id,
accept: [Permissions.FLAGS.VIEW_CHANNEL],
},
],
});

Discord /commands 'This command is outdated, please try again in a few minutes'

I have been trying to fix this issue for a while and cant find the right answer this is my code,
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('Get info about a user or a server!')
.addStringOption(option =>
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoices(
{ name: 'Funny', value: 'funny is funny' },
{ name: 'Meme', value: 'Meme is a meme' },
{ name: 'Movie', value: 'Movie is a Movie' },
))
,
async execute(interaction) {
interaction.options.getString('category');
}
}
Heres a pic of whats happening
I've seen this happen time to time. Discord takes some amount of time for slash commands to work their way into the system when you start up your code. If your code hits lots of guilds, it could take an hour. If you only specify one guild, it is usually fairly instant but in some cases it may take 5 min. Let your code run for 5-10 min and check back, it will probably fix this error.

Get channel ID of newly created channel - Discord.js

I am trying to get the channel ID of a channel that gets created when a user reacts to a message with a specific emoji. The creation of the channel works perfectly, the only problem is that I have trouble getting the ID of that created channel.
I use the following code for creating the channel:
await message.guild.channels.create(`🎫│${name}`, {
type: 'text',
parent: 'CATEGORY_ID',
permissionOverwrites: [{
id: reactor,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
}]
});
Now I'd like to get that channels ID so that I can send a message in it after creation. I've been looking for answers but haven't found one that actually works.
channels.create returns a promise with a GuildChannel which has an id property. But you don't even need that ID, you can use the .send method on the newly created channel:
const createdChannel = await message.guild.channels.create(`🎫│${name}`, {
type: 'text',
parent: 'CATEGORY_ID',
permissionOverwrites: [{
id: reactor,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES'],
}],
});
// createdChannel.id is the new channel's id
const { id } = createdChannel;
// but you can simply send a message with .send()
createdChannel.send('This is a message in the new channel');

Adding a custom status on a discord.js bot

I am currently trying to add a custom status to my discord.js bot to request new developers, and it is not working. Here is my code:
client.on('ready', () => {
console.log(`Ready to comply.`);
client.user.setPresence({
status: 'online',
game: {
name:
'need developers, DM Daniel for more info, BTW, you can learn the language at discord.js.org.', //The message shown
type: 'PLAYING',
},
});
});
I have tried searching Stack Overflow, and found an answer that tells me to use the code above, but it's not working.
If you are referring to a custom status, which one of the recent Discord updates have introduced, it is not possible.
If you mean something like 'Playing with 100 commands' you can use:
client.user.setPresence({ activity: { name: 'with discord.js' }, status: 'idle' })
If you use discord.js v12 then try this code, it works perfectly for me:
client.user.setPresence({
status: 'online',
activity: {
type: 'PLAYING',
name: 'need developers, DM Daniel for more info',
},
});

Welcome message with embed is not showing

So I made a bot that will send welcome messages in a channel to new members.
My code is supposed to work because it didn't send any errors in my console, but my bot didn't send the welcome message.
I tried many things:
Made the embed an object (nope)
Made 4 long different codes (all not working)
Searched the web and watched some tuts (no error in the console but not sending)
I'm using discord.js#v12
Code:
client.on('guildMemberAdd', member => {
// Finds the channel name from the array
function channelNamesFilter(channel) {
let channelNames = ['name', 'welcome', 'welcoming', 'greeting', 'general', 'hello'];
if (channelNames.includes(channel.name)) {
return true;
}
return false;
}
const welcome = new Discord.MessageEmbed()
.setColor('#F2CC0D')
.setTitle('Welcome To The Server!')
.addFields({
name: member.nickname
}, {
name: '\n ',
value: 'Make sure to visit the FAQ and Rules channel (if there are)!'
})
.setImage(member.user.avatarURL)
let filteredChannels = member.guild.channels.cache.filter(channelNamesFilter);
filteredChannels.forEach(element => element.send(welcome));
});
Ok I just solved it after like researching for more than 10 hours! I finally got it!
client.on('guildMemberAdd', member =>{
const channel = member.guild.channels.cache.find(channel => channel.name.includes('welcome'));
if (!channel) return;
//send through channel
const welcomegreet = {
color: 0xF2CC0D,
title: `**WELCOME TO THE SERVER, ${member.user.tag} !!**`,
description: `I hope you will enjoy it here! \n A place full of chaos and wonder!`,
thumbnail: {
url: member.user.avatarURL(),
},
fields:[
{
name: 'Need Help?',
value: 'Please read the FAQ and Rules Channels (if there are)! \n Have Fun at the Server! CHEERS 🥂 !',
inline: false
},
{
name: 'Join Me!',
value: 'Do: `h.help` for entertainment and profanities!',
inline: false
}
],
timestamp: new Date(),
};
//send through dm
const welcome = {
color: 0xF2CC0D,
title: `**WELCOME TO THE SERVER, ${member.user.tag} !!**`,
description: `I hope you will enjoy it here! \n A place full of chaos and wonder!`,
thumbnail: {
url: member.user.avatarURL(),
},
timestamp: new Date(),
};
member.send({ embed: welcomegreet });
channel.send({ embed: welcome });
Thanks guys for trying to help me, even though It didn't get too close to the amswer.
I tested this out and it worked splendidly!
note:
This only works if the channel has the word "welcome"

Categories

Resources