So im making a mute command which creates a mute role and gives it to the mentioned user, and currently i am getting an error: channel is not defined,
I do not know how to fix this error and i need help with this
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if (!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return message.channel.send("I do not have Permission to mute members.");
let reason = args.slice(1).join(' ');
let roleName = 'Muted';
let muteRole = message.guild.roles.cache.find(x => x.name === roleName);
if (typeof muteRole === undefined) {
guild.roles.create({ data: { name: 'Muted', permissions: ['SEND_MESSAGES', 'ADD_REACTIONS'] } });
} else {
}
muteRole = message.guild.roles.cache.find(x => x.name === roleName);
channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });
const mentionedMember = message.mentions.member.first() || message.guild.members.cache.get(args[0]);
const muteEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setImage(message.mentionedMember.displayAvatarURL());
if (!args[0]) return message.channel.send('You must mention a user to mute.');
if (!mentionedMember) return message.channel.send('The user mentioned is not in the server.');
if (mentionedMember.user.id == message.author.id) return message.channel.send('You cannot mute yourself.');
if (mentionedMember.user.id == client.user.id) return message.channel.send('You cannot mute me smh.');
if (!reason) reason = 'No reason given.';
if (mentionedMember.roles.cache.has(muteRole.id)) return message.channel.send('This user has already been muted.');
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.chanel.send('You cannot mute someone whos role is higher and/or the same as yours');
await mentionedMember.send(muteEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muteRole.id).catch(err => console.log(err).then(message.channel.send('There was an issue while muting the mentioned Member')));
}
}
I beileive that there could be even more errors than i think in this code as I am fairly new to coding.
You have used "channel" without declaring it. Hence, it is undefined.
check your line "channel.updateOverwrite(channel.guild.roles.muteRole, { SEND_MESSAGES: false });"
const { Client, Intents } = require('discord.js')
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.channel.send('pong');
});
});
Please refer the below links
Discord.JS documentation: https://github.com/discordjs/discord.js
Stack-overflow answer: Discord.js sending a message to a specific channel
Related
I've been trying to get my discord bot to work, but it will only become online on discord and say that it's online in the console. What am I doing wrong
here's the code from my index.js
const Discord = require('discord.js')
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ], intents: ["GUILDS", /* Other intents... */]});
const token = '(token here)';
client.login(token);
client.on('ready', () => {
console.log('I ARRIVE FROM THE ASHES OF THE EARTH');
});
client.on('message', message => {
if (message.content === 'Hello') {
message.send('I HAVE A GUN');
}
});
client.on('disconnect', () => {
console.log('ZE POPCORN IS DEAD');
});
const prefix = '-';
client.on('message', message => {
if (message.content === prefix + 'ping') {
message.send('Gun').then(message => message.edit('Pong'));
}
});
client.on('message', message => {
if (message.content === prefix + 'shutdown') {
if (message.author.id === '262707958646901248') {
message.send('Shutting down...').then(message => client.destroy());
}
}
});
client.on('message', message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.send('Gun');
}
}
});
client.on('message', message => {
if (message.content === prefix + 'help') {
message.send('figure it out I guess?');
}
});
client.on('message', message => {
if (message.content === prefix + 'info') {
message.send('I made this bot when popcorn "died". I hope you enjoy it.');
}
});
client.on('message', message => {
if (message.content === 'ping') {
message.send('https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531');
}
});
I tried all the commands that I put in and such, but it didn't do anything.
Code needs a fair bit of work, primarily in organization. Also please take a minute to get familiar with this entire site as all the different elements of this are here and it is a tool you will use often.
discord v13
https://discord.js.org/#/docs/discord.js/v13/general/welcome
discord v12
https://discord.js.org/#/docs/discord.js/v12/general/welcome
const Discord = require('discord.js')
const client = new Discord.Client({
partials: ["MESSAGE", "CHANNEL", "REACTION"],
intents: ["GUILDS", "GUILD_MESSAGES" /* Other intents... */ ] // make sure GUILD_MESSAGES is in there
});
const prefix = '-';
const token = '(token here)';
client.login(token);
client.on('disconnect', () => {
console.log('ZE POPCORN IS DEAD');
});
client.on('ready', () => {
console.log('I ARRIVE FROM THE ASHES OF THE EARTH');
});
client.on('message', async message => { // add async
const content = message.content.toLowerCase() // For readability
// message.send will not work, it needs to be either message.channel.send() or message.reply()
// these will work without prefix
if (content === 'hello') {
message.reply('I HAVE A GUN');
} else if (content === 'ping') {
// Below will just send the link
message.reply('https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531');
// Below will send the attachment
message.reply({
attachments: 'https://tenor.com/view/heavy-tf2-the-rock-rock-the-rock-the-dwayne-johnson-gif-22149531'
})
}
// these will require the prefix
if (content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.reply('Gun');
} else if (command === 'shutdown') {
if (message.author.id === '262707958646901248') {
message.reply('Shutting down...').then(() => client.destroy()); // message not used, so not required
} else {
message.reply('Not allowed') // added else statement
}
} else if (command === 'help') {
message.reply('figure it out I guess?');
} else if (command === 'info') {
message.reply('I made this bot when popcorn "died". I hope you enjoy it.');
}
}
});
I'm making a mute command for my discord bot and currently I'm get an error;
TypeError: Cannot read property 'then' of undefined
I do not know what exactly is causing this issue and would like to know if there are more errors with this code or not
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if(!message.guild.me.hasPermission("MUTE_MEMBERS")) return message.channel.send("I do not have Permissions to mute members.");
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours\nYou cannot mute members that have already been muted'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
let role = 'Muted'
let newrole = message.guild.roles.cache.find(x => x.name === role);
if (typeof newrole === undefined) {
message.guild.roles.create({
data: {
name: 'muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(console.log(err)); {
message.channel.send('Could not create muted role');
}
}
let muterole = message.guild.roles.cache.find(x => x.name === role);
const mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
let reason = args.slice(1).join(" ");
const banEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL());
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.has(muterole)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
await mentionedMember.send(banEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muterole).catch(err => console.log(err).then(message.channel.send('There was an error while muting the member')))
}
}
My guess is that the error has something to do with the last line of code, I'm not sure if this code has more errors is in it but I would very much like to know and am also open to any suggestions with improving the code itself.
You are putting then() in the wrong spot. You would execute then() against add(muterole) (which returns a promise) or you could apply it to catch() or within catch(), but you are applying it to console.log() which doesn't return anything nor is a Promise. Try the following:
await mentionedMember.roles
.add(muterole)
.then()
.catch((err) => {
console.log(err);
// You are trying to send an error message when an error occurs?
return message.channel.send("There was an error while muting the member")
});
or
await mentionedMember.roles
.add(muterole)
.catch((err) => console.log(err))
.then(() =>
message.channel.send("There was an error while muting the member")
);
Hopefully that helps!
I would like to know how to make a ban, kick and clear commands for my bot. I will show you the code but before that I have been doing reasearch and nothing been working. I use node.js and i am a beginner so here's what i need you to tell me.
-The code for the command (No external links)
-How to to get the code to work.
-Where to put the code.
Okay, heres the code.
const Discord = require('discord.js');
const bot = new Discord.Client();
const { MessageEmbed } = require("discord.js");
bot.once('ready', () => {
console.log('Ready!');
});
bot.on('message', message => {
if(message.content === '!help') {
let embed = new MessageEmbed()
.setTitle("Ratchet Commands")
.setDescription("!getpizza, !shutup, !playdead, !server-info, !myname, !banhammer, !yourcreator, !annoy, !youare")
.setColor("RANDOM")
message.channel.send(embed)
}
});
bot.on('message', message => {
if (message.content === '!getpizza') {
message.channel.send('Welcome to Ratchets Pizza!!! Heres your pizza and have a nice day!!! :pizza:');
}
});
bot.on('message', message => {
if (message.content === '!shutup') {
message.channel.send('Okay, I am sorry.');
}
});
bot.on('message', message => {
if (message.content === '!server-info') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
});
bot.on('message', message => {
if (message.content === '!myname') {
message.channel.send(`Your username: ${message.author.username}`);
}
});
bot.on('message', message => {
if (message.content === '!rocket') {
message.channel.send('3..2..1..Blast Off!!! :rocket:');
}
});
bot.on('message', message => {
if (message.content === '!youare') {
message.channel.send(`I am <#!808773656700256318>`);
}
});
bot.on('message', message => {
if(message.content === '!yourcreator') {
let embed = new MessageEmbed()
.setTitle("Ratchets Creator")
.setDescription("My creator is <#!765607070539579402>")
.setColor("RANDOM")
message.channel.send(embed)
}
});
bot.on('message', message => {
if(message.content.startsWith(`!annoy`)) {
const mentionedUser = message.mentions.users.first();
if(!mentionedUser) return message.channel.send("You have to mention someone to continue annoying someone :rofl:");
mentionedUser.send('You have a problem with me?');
message.channel.send("Annoyed " + mentionedUser + "! (Oh wait, I annoyed them 2 times!)");
}
});
module.exports = {
name: '!kick',
description: "this command kicks people",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.member(member);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldnt kick that person');
}
}
}
bot.login('TOKEN');
I know I need a command handler but I don't know how to do that neither.
Thank you!!!
So first you did a very big error, you always recall the message event, optimize your code like this:
const Discord = require('discord.js');
const bot = new Discord.Client();
const { MessageEmbed } = require("discord.js");
bot.once('ready', () => {
console.log('Ready!');
});
bot.on('message', message => {
if(message.content === '!help') {
let embed = new MessageEmbed()
.setTitle("Ratchet Commands")
.setDescription("!getpizza, !shutup, !playdead, !server-info, !myname, !banhammer, !yourcreator, !annoy, !youare")
.setColor("RANDOM")
message.channel.send(embed)
if (message.content === '!getpizza') {
message.channel.send('Welcome to Ratchets Pizza!!! Heres your pizza and have a nice day!!! :pizza:');
}
if (message.content === '!server-info') {
message.channel.send(`Server name: ${message.guild.name}\nTotal members: ${message.guild.memberCount}`);
}
if (message.content === '!myname') {
message.channel.send(`Your username: ${message.author.username}`);
}
if (message.content === '!rocket') {
message.channel.send('3..2..1..Blast Off!!! :rocket:');
}
if (message.content === '!youare') {
message.channel.send(`I am <#!808773656700256318>`);
}
if(message.content === '!yourcreator') {
let embed = new MessageEmbed()
.setTitle("Ratchets Creator")
.setDescription("My creator is <#!765607070539579402>")
.setColor("RANDOM")
message.channel.send(embed)
}
if(message.content.startsWith(`!annoy`)) {
const mentionedUser = message.mentions.users.first();
if(!mentionedUser) return message.channel.send("You have to mention someone to continue annoying someone :rofl:");
mentionedUser.send('You have a problem with me?');
message.channel.send("Annoyed " + mentionedUser + "! (Oh wait, I annoyed them 2 times!)");
}
});
module.exports = {
name: '!kick',
description: "this command kicks people",
execute(message, args){
const member = message.mentions.users.first();
if(member){
const memberTarget = message.guild.member(member);
memberTarget.kick();
message.channel.send("bing bong he is gone!");
}else{
message.channel.send('you couldnt kick that person');
}
}
}
bot.login('TOKEN');
then to do a !ban #mention you can do:
if (message.content.startsWith('!ban ')) {
if (message.mentions.members.first()) {
if (!message.mentions.members.first().bannable) {
message.channel.send('I can\'t ban the specified user')
return
}
try {
message.mentions.members.first().ban()
}finally {
message.channel.send('The member was correctly banned')
}
}
}
and for a !kick
if (message.content.startsWith('!kick ')) {
if (message.mentions.members.first()) {
if (!message.mentions.members.first().kickable) {
message.channel.send('I can\'t kick the specified user')
return
}
try {
message.mentions.members.first().kick
}finally {
message.channel.send('The member was correctly kicked')
}
}
}
and finally for the clear command
if (message.content.startsWith('!clear ')) {
let toClear = args[1]
for (let i = 0; i < toClear; i++) {
m.channel.lastMessage.delete()
}
}
Hope i helped you ^^
I was trying to create a lock command where the user can select what permission gets overwritten. However, this only works if the 3rd and 4th if statements (which check for existing permission overwrites) are removed as the following error is produced: RangeError [BITFIELD_INVALID]: Invalid bitfield flag or number. Would there be a workaround for this?
const channel = bot.channels.cache.get(args[0]);
if(!channel) {
return message.reply('Please provide a channel id!');
}
if(!args[1]) {
return message.reply('Please set the lock type!');
}
if (!channel.permissionsFor(message.guild.roles.everyone).has('VIEW_CHANNEL')) {
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`❌ \`VIEW_CHANNEL\` for \`${channel.name}\` is already disabled.`)
.setColor('RED');
return message.channel.send(errorEmbed);
}
if (!channel.permissionsFor(message.guild.roles.everyone).has('READ_MESSAGES')) {
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`❌ \`READ_MESSAGES\` for \`${channel.name}\` is already disabled.`)
.setColor('RED');
return message.channel.send(errorEmbed);
}
else if (args[1] === 'view' || args[1] === 'read') {
channel.updateOverwrite(message.channel.guild.roles.everyone, { VIEW_CHANNEL: false }).then(() => {
const msgEmbed = new Discord.MessageEmbed()
.setDescription(`✅ The channel\`${message.channel.name}\` has been locked.`)
.setColor('GREEN');
message.channel.send(msgEmbed);
}).catch((error) => {
console.log(error);
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`❌ Unable to lock \`${channel.name}\`.`)
.setColor('RED');
message.channel.send(errorEmbed);
});
}
else if (args[1] === 'send') {
channel.updateOverwrite(message.channel.guild.roles.everyone, { SEND_MESSAGES: false }).then(() => {
const msgEmbed = new Discord.MessageEmbed()
.setDescription(`✅ The channel\`${channel.name}\` has been locked.`)
.setColor('GREEN');
message.channel.send(msgEmbed);
}).catch((error) => {
console.log(error);
const errorEmbed = new Discord.MessageEmbed()
.setDescription(`❌ Unable to lock \`${channel.name}\`.`)
.setColor('RED');
message.channel.send(errorEmbed);
});
}
I think it's because you're using READ_MESSAGES instead of using VIEW_CHANNEL everywhere (it's the same and I think READ_MESSAGES has been removed from Discord.js v12).
So i think i quite forgot some .then's beause the bot sends the B emoji message instanntly without a reaction from the user and even when i would provide a "suggestion" then it wouldnt send it to the specific channel, but idk where i have to put the missing .then's. Can someone help me please? I tried to figure it out myself and tested some but it didn't make anything better.
execute(message, client, args) {
const Discord = require('discord.js');
let Embed = new Discord.MessageEmbed()
.setColor('0x0099ff')
.setDescription(`Suggestion categories`)
.addField(`For what you want to suggest something?`, `\nA: I want to suggest something for the Website/Servers/Discord Server\nB: I want to suggest something for the CloudX Bot \n\nPlease react to this message with A or B`)
message.channel.send(Embed).then(function (message) {
message.react("🇦").then(() => {
message.react("🇧")
const filter = (reaction, user) => {
return ['🇦', '🇧'].includes(reaction.emoji.name) && user.id;
}
message.awaitReactions(filter, { max: 1 })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '🇦') {
const filter = m => m.author.id === message.author.id;
message.channel.send(`Please provide a suggestion for the Website/Servers/Discord Server or cancel this command with "cancel"!`).then(() => {
message.channel.awaitMessages(filter, { max: 1, })
.then(async (collected) => {
if (collected.first().content.toLowerCase() === 'cancel') {
message.reply("Your suggestion has been cancelled.")
}
else {
let embed1 = new Discord.MessageEmbed()
.setColor('0x0099ff')
.setAuthor(message.author.tag)
.addField(`New Suggestion:`, `${collected.first().content}`)
.setFooter(client.user.username, "attachment://CloudX.png")
.setTimestamp();
const channel = await client.channels.fetch("705781201469964308").then(() => {
channel.send({embed: embed1, files: [{
attachment:'CloudX.png',
name:'CloudX.png'
}]})
message.channel.send(`Your suggestion has been filled to the staff team. Thank you!`)
})
}
})
})
}
if (reaction.emoji.name === '🇧') {
const filter = m => m.author.id === message.author.id;
message.channel.send(`Please provide a suggestion for the CloudX Bot or cancel this command with "cancel"!`).then(() => {
message.channel.awaitMessages(filter, { max: 1, })
.then(async (collected) => {
if (collected.first().content.toLowerCase() === 'cancel') {
message.reply("Your suggestion has been cancelled.")
}
else {
let embed2 = new Discord.MessageEmbed()
.setColor('0x0099ff')
.setAuthor(message.author.tag)
.addField(`New Suggestion:`, `${collected.first().content}`)
.setFooter(client.user.username, "attachment://CloudX.png")
.setTimestamp();
const channel = await client.channels.fetch("702825446248808519").then(() => {
channel.send({embed: embed2, files: [{
attachment:'CloudX.png',
name:'CloudX.png'
}]})
message.channel.send(`Your suggestion has been filled to the staff team. Thank you!`)
})
}
})
})
}
})
})
})
},
I would suggest learning await/async functions.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await
This will clean up your code and keep things steady without five thousand .then()
async execute(message, client, args) {
const { MessageEmbed } = require('discord.js');
const embed = new MessageEmbed()
.setColor('#0099ff')
.setDescription(`Suggestion categories`)
.addField(`For what you want to suggest something?`, `\nA: I want to suggest something for the Website/Servers/Discord Server\nB: I want to suggest something for the CloudX Bot \n\nPlease react to this message with A or B`)
const question = message.channel.send(embed)
await question.react("🇦")
await question.react("🇧")
const filter = (reaction, user) => {
return ['🇦', '🇧'].includes(reaction.emoji.name) && user.id;
}
This is just part of it but you should be able to get the gist...