bot's username is not defined - javascript

I am getting this error UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined which is caused by client.user.username in embed's .setFooter().
module.exports = {
name: 'suggest',
aliases: ['sug', 'suggestion'],
description: 'Suggest something for the Bot',
execute(message, client, args) {
const Discord = require('discord.js');
const filter = m => m.author.id === message.author.id;
message.channel.send(`Please provide a suggestion for the Bot or cancel this command with "cancel"!`)
message.channel.awaitMessages(filter, { max: 1, })
.then(async (collected) => {
if (collected.first().content.toLowerCase() === 'cancel') {
message.reply("Your suggestion has been cancelled.")
}
else {
let embed = new Discord.MessageEmbed()
.setFooter(client.user.username, client.user.displayAvatarURL)
.setTimestamp()
.addField(`New Suggestion from:`, `**${message.author.tag}**`)
.addField(`New Suggestion:`, `${collected.first().content}`)
.setColor('0x0099ff');
client.channels.fetch("702825446248808519").send(embed)
message.channel.send(`Your suggestion has been filled to the staff team. Thank you!`)
}
})
},
catch(err) {
console.log(err)
}
};

According to your comment here
try { command.execute(message, args); } catch (error) { console.error(error); message.reply('There was an error trying to execute that command!'); } });
You are not passing client into execute(), you need to do that.
You also need to use await on channels.fetch() since it returns a promise so replace client.channels.fetch("702825446248808519").send(embed) with:
const channel = await client.channels.fetch("702825446248808519")
channel.send(embed)

Related

Discord.js 'await is only valid in an async function' even though it is an async function?

I am coding a bot to make a ticketing system, and I am trying to get the bot to react to the message, but it isn't as I am getting the error await is only valid in an async function. I know what that means, and the part where I am confused is that it is an async function: I know this because earlier in the function/event, there is an await statement. Here is the code:
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then((collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for
your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try{
let claimChannel = client.channels.cache.find(channel => channel.name === 'general');
claimChannel.send(claimEmbed);
await claimMessage.react("✅");
} catch (err) {
throw (err);
}
})
.catch((err) => console.log(err));
}
})
When you collect the messages, there is an arrow function that has a missing async keyword:
client.on('message', async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === '-ticket') {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket');
embed.setDescription(
'Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.',
);
embed.setColor('AQUA');
message.author.send(embed);
channel
.awaitMessages(filter, { max: 1, time: 1000 * 300, errors: ['time'] })
// it should be async
.then(async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for
your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket');
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`);
claimEmbed.setColor('AQUA');
claimEmbed.setTimestamp();
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
claimChannel.send(claimEmbed);
await claimMessage.react('✅');
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
});

Discord.js Error: Cannot read property 'then' of undefined

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!

discord.js error "channel is not defined"

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

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.

missing .then's but idk where to put

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...

Categories