missing .then's but idk where to put - javascript

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

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));
}
});

How to detect more than one reaction to a message in discord.js?

I'm trying to create a dynamic help command, in the sense that the users can decide what "page" they would like to go to simply by reacting to the message. I have tried doing this, however, with my code it only detects the first reaction. I have tried setting the max for the awaitReactions method to more than 1, however once I do that it doesn't detect any reaction. Here is my code:
const Discord = require('discord.js');
const fs = require('fs');
module.exports = {
name: 'help',
aliases: ('cmds'),
description: 'Shows you the list of commands.',
usage: 'help',
example: 'help',
async execute(client, message, args, prefix, footer, color, invite, dev, devID, successEmbed, errorEmbed, usageEmbed) {
const helpEmbed = new Discord.MessageEmbed()
.setColor(color)
.setAuthor(`${client.user.username} Discord Bot\n`)
.setDescription('ā€¢ šŸ“ Prefix: ``' + prefix + '``\n' +
`ā€¢ šŸ”§ Developer: ${dev}\n\nāš™ļø - **Panel**\nšŸ‘® - **Moderation**\nā” - **Other**`);
const moderationEmbed = new Discord.MessageEmbed()
.setColor(color)
.setAuthor(`Config\n`)
.setDescription('To get more information about a certain command, use ``' + prefix +
'help [command]``.\n\nā€¢``test``, ``test2``, ``test3``.');
try {
const filter = (reaction, user) => {
return (reaction.emoji.name === 'āš™ļø' || 'šŸ‘®' || 'ā”') && user.id === message.author.id;
};
message.delete();
message.channel.send(helpEmbed).then(embedMsg => {
embedMsg.react("āš™ļø")
.then(embedMsg.react("šŸ‘®"))
.then(embedMsg.react("ā”"))
embedMsg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === 'āš™ļø') {
embedMsg.edit(helpEmbed);
} else if (reaction.emoji.name === 'šŸ‘®') {
embedMsg.edit(moderationEmbed);
} else if (reaction.emoji.name === 'ā”') {
message.reply('test.');
}
})
.catch(collected => {
message.reply('didnt work.');
});
});
} catch (e) {
console.log(e.stack);
}
}
}
Used a collector.
const collector = embedMsg.createReactionCollector(filter);
collector.on('collect', (reaction, user) => {
reaction.users.remove(user.id); // remove the reaction
if (reaction.emoji.name === 'āš™ļø') {
embedMsg.edit(helpEmbed);
} else if (reaction.emoji.name === 'šŸ› ļø') {
embedMsg.edit(utilityEmbed);
} else if (reaction.emoji.name === 'šŸ‘®') {
embedMsg.edit(moderationEmbed);
}
});

How to get old message reactions

What I'm trying to do is to get username for users who reacts on that message. It's working good but when the bot restarts only new reactions work.
how to make it send all users reactions
client.on('ready', () => {
client.guilds.get('guild_id').channels.get('chnl_id').fetchMessage('msg_id');
});
client.on('messageReactionAdd', (reaction, user) => {
const { message} = reaction;
if(message.channel.id == 'chnl_id'){
if(reaction.emoji.name === "āœ…") {
message.guild.fetchMember(user.id).then(member => {
if(user.bot) return;
else {
message.channel.send(reaction.users.map(u => u.username.toString()))
}
})
}}});
If you have the message, then you can filter the reaction of that message by emojis:
const reaction = await message.reactions.cache.filter(r=> r.emoji.name === 'āœ…').first().fetch();
Then you can fetch all reactions with that specific emoji:
await reaction.users.fetch();
Then you can filter from that if you want to (for example your own bot), with:
const filteredReactions = reaction.users.cache.filter(r=> !r.bot);
And don't forget to put these in an async function.

How to make bot send message to another channel after reaction | Discord.js

How do I make it so that when someone reacts with the first emoji in this command, the bot deletes the message and sends it to another channel?
Current Code:
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES"))
return message.channel.send("You are not allowed to run this command.");
let botmessage = args.join(" ");
let pollchannel = bot.channels.cache.get("716348362219323443");
let avatar = message.author.avatarURL({ size: 2048 });
let helpembed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, avatar)
.setColor("#8c52ff")
.setDescription(botmessage);
pollchannel.send(helpembed).then(async msg => {
await msg.react("715383579059945512");
await msg.react("715383579059683349");
});
};
module.exports.help = {
name: "poll"
};
You can use awaitReactions, createReactionCollector or messageReactionAdd event, I think awaitReactions is the best option here since the other two are for more global purposes,
const emojis = ["715383579059945512", "715383579059683349"];
pollchannel.send(helpembed).then(async msg => {
await msg.react(emojis[0]);
await msg.react(emojis[1]);
//generic filter customize to your own wants
const filter = (reaction, user) => emojis.includes(reaction.emoji.id) && user.id === message.author.id;
const options = { errors: ["time"], time: 5000, max: 1 };
msg.awaitReactions(filter, options)
.then(collected => {
const first = collected.first();
if(emojis.indexOf(first.emoji.id) === 0) {
msg.delete();
// certainChannel = <TextChannel>
certainChannel.send(helpembed);
} else {
//case you wanted to do something if they reacted with the second one
}
})
.catch(err => {
//time up, no reactions
});
});

bot's username is not defined

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)

Categories