I want to make a poll command, where the bot send an embed with the poll and afterwards reacts to it with some emojis. I added the reaction Intent to my index.js but still get an error everytime I call the command. This is my code:
const { SlashCommandBuilder } = require('#discordjs/builders')
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("poll")
.setDescription("Create a quick poll.")
.addStringOption(option => option.setName("question").setDescription("The question").setRequired(true)),
async execute(interaction) {
const question = interaction.options.getString("question")
const message = await interaction.reply({embeds: [
new MessageEmbed()
.setColor('GREEN')
.setTitle(`Discord Poll`)
.setAuthor(`Requested by ${interaction.member.user.tag}`, interaction.member.user.avatarURL())
.setDescription(question)
.setThumbnail('https://pngimg.com/uploads/question_mark/question_mark_PNG126.png')
.setTimestamp()
.setFooter('Bot by Iuke#4681', 'https://cdn.discordapp.com/emojis/912052946592739408.png?size=96')
]})
message.react(':check:')
.then(() => message.react(':neutral:')
.then(() => message.react(':xmark:')))
}
}
And get this error:
TypeError: Cannot read properties of undefined (reading 'react')
You will need to fetch the reply. You can use the fetchReply option and set it to true.
module.exports = {
data: new SlashCommandBuilder()
.setName('poll')
.setDescription('Create a quick poll.')
.addStringOption((option) =>
option
.setName('question')
.setDescription('The question')
.setRequired(true),
),
async execute(interaction) {
const question = interaction.options.getString('question');
const message = await interaction.reply({
embeds: [
new MessageEmbed()
.setColor('GREEN')
.setTitle(`Discord Poll`)
.setAuthor(
`Requested by ${interaction.member.user.tag}`,
interaction.member.user.avatarURL(),
)
.setDescription(question)
.setThumbnail(
'https://pngimg.com/uploads/question_mark/question_mark_PNG126.png',
)
.setTimestamp()
.setFooter(
'Bot by Iuke#4681',
'https://cdn.discordapp.com/emojis/912052946592739408.png?size=96',
),
],
fetchReply: true,
});
// you could use await to react in sequence instead of then()s
await message.react(':check:');
await message.react(':neutral:');
await message.react(':xmark:');
},
};
According to the docs you need to add the fetchReply option on interaction.reply like this:
const message = await interaction.reply({ content: 'Pong!', fetchReply: true });
Related
So im making a ban slash command using .addUserOption but when i try to get the permissions from the .addUserOption so that the bot doesnt crash when trying to ban an admin i get an error. I already know why, you cant get permissions from a user, only a GuildMember, so how would i go from user to GuildMember?
CODE: (if needed)
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("ban")
.setDescription("Bans the specified user!")
.addUserOption((option) =>
option
.setName("user")
.setDescription('Who do you want to ban?')
.setRequired(true)
)
.addStringOption((option) =>
option
.setName('reason')
.setDescription("Whats the reason youre banning this user?")
),
async execute(client, interaction) {
if (client.cooldowns.has(interaction.user.id)) {
let cooldownEmbed = new MessageEmbed()
.setTitle("Please wait for the cooldown to end.")
.setDescription("This is so that the bot doesnt overload")
.setColor("RED")
.setFooter("The cooldown is 5 sec")
.setTimestamp()
interaction.reply({ embeds: [cooldownEmbed], ephemeral: true });
} else {
const user = interaction.member
const permission = user.permissions.has('BAN_MEMBERS');
let embed = new MessageEmbed()
.setTitle("❌️ | You dont have the permissions to use this command.")
if(!permission)
return interaction.reply({embeds: [embed]})
const tgt = interaction.options.getUser('user')
let permsEmbed = new MessageEmbed()
.setTitle("The user you are trying to ban is an Administrator!")
.setColor("RED")
if (tgt.permissions.has('BAN_MEMBERS')) return interaction.reply({ embeds: [permsEmbed]})
const reason = interaction.options.getString('reason') || "No reason specified"
client.cooldowns.set(interaction.user.id, true);
setTimeout(() => {
client.cooldowns.delete(interaction.user.id);
}, client.COOLDOWN_SECONDS * 1000);
}
}
}
I checked CollinD's suggestion and i managed to fix the problem. Heres the code if anyone else runs into this problem and needs an answer.
CODE:
const tgt = interaction.options.getUser('user');
let permsEmbed = new MessageEmbed()
.setTitle('The user you are trying to ban is an Administrator!')
.setColor('RED');
const guildMember = interaction.guild.members.cache.get(tgt.id);
if (guildMember.permissions.has('BAN_MEMBERS'))
return interaction.reply({ embeds: [permsEmbed] });
Code:
const config = require('../../config.json');
const Discord = require('discord.js');
module.exports = async(guild, bannerURL, client) => {
const logChannel = await client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({ name: guild.name, iconURL: guild.iconURL() })
.setDescription(`**${guild.name} has banner now!**`)
.setImage(bannerURL)
.setColor(config.colour)
.setTimestamp()
return logChannel.send({ embeds: [embed] })
}
When adding a banner to the server it gives the error Unhandled Rejection: TypeError: Cannot read properties of undefined (reading 'channels')
The other logging files have the exact same line of code const logChannel = await client.channels.cache.get(config.log_channel_id); and it works fine
Adding console.log(client) before const logChannel returns undefined
This code below works after we troubleshot the issue.
banner.js
module.exports = {
name: 'banner',
description: 'emit update',
devs: true,
run: async (guild, message) => {
guild.emit('guildBannerAdd', message.member);
message.channel.send('Done ...');
},
};
guildBannerAdd.js
const config = require('../../config.json')
const Discord = require('discord.js')
module.exports = async (client, member) => {
const guild = client.guilds.cache.get(config.serverID)
const logChannel = client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({
name: guild.name,
iconURL: guild.iconURL()
})
.setDescription(`**${guild.name} has banner now!**`)
.setImage(guild.bannerURL())
.setColor(config.colour)
.setTimestamp();
return logChannel.send({
embeds: [embed]
});
}
i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})
I am making a ban command with confirmation thingy. I use buttons and
MessageComponentCollector for it. However it fails and outputs the error. Here's my code:
var bu1tton = new Discord.MessageButton()
.setStyle(`SUCCESS`)
.setEmoji(`872905464797605938`)
.setLabel(`Proceed`)
.setCustomId("proceed")
var bt1 = new Discord.MessageButton()
.setStyle("DANGER")
.setEmoji(`872905464747286598`)
.setLabel(`Cancel`)
.setCustomId("back")
var row = new Discord.MessageActionRow()
.addComponents([bu1tton, bt1])
const confirmation = interaction.followUp({
embeds: [new Discord.MessageEmbed().setTitle(`Are you sure?`).setColor("RED").setDescription(`Are you sure you want to ban **${target.user.tag}** for ${reason}?\nThis action will be automatically canceled in 10 seconds if you do not select any option.`).setFooter(interaction.guild.name)],
components: [row]
})
const filter = ( inter ) => inter.user.id === interaction.user.id
const collector = confirmation.createMessageComponentCollector({ filter, time: 10000 })
collector.on('collect', async interaction => {
if(interaction.customId === "proceed") {
interaction.deferReply()
await interaction.followUp({
content: `**${interaction.user.tag}** banned **${target.user.tag}**.\nReason: *${reason}*.`
})
const reportChannel = interaction.guild.channels.cache.get(log_channel)
const messageLink = `https://discord.com/channels/${interaction.guild.id}/${interaction.channel.id}/${interaction.id}`;
let logchat = new Discord.MessageEmbed()
.setAuthor(`${interaction.user.tag} (${interaction.user.id})`, interaction.user.displayAvatarURL())
.setDescription(`**<:target:890913045126213633> Member:** ${target.user} (${target.user.id})\n**<:law:913487126576914502> Action:** Ban\n**<:decision:890913045537235005> Reason:** ${reason}\n**<:link:907511618097803284> Link:** [Click here](${messageLink})`)
.setColor('RED')
.setFooter(`ID: ${uuidv4()}`)
.setTimestamp();
const log = await reportChannel.send({
embeds: [logchat]
})
const data = log.embeds[0]
let dmembed = new Discord.MessageEmbed()
.setTitle("You have been banned from Rice Farm #11")
.setDescription(`If you find this ban abusive or wrong, please proceed to [Ban Appeal page](https://ricesupport.brizy.site/).`)
.addField("Moderator", `${interaction.user}`)
.addField("Reason", `${reason}`)
.setColor("RED")
.setFooter(`${data.footer.text}`)
.setTimestamp();
await target.send({
embeds: [dmembed]
}).catch((err) => console.log(err));
await target.ban({
reason: `Banned by ${interaction.user.tag} | Reason: ${reason}`,
days: num
}).catch((err) => console.log(err));
}
if(interaction.customId === "back") {
interaction.deferReply()
interaction.message.delete()
}
})
collector.on('end', async interaction => {
})
It sends the embed with components, but the collector obviously won't create.
Here's the full error:
[Error Handling System] Unhandled Rejection/Catch
TypeError: confirmation.createMessageComponentCollector is not a function
at Object.run (/PC/184395345943/slash/Moderation/ban.js:114:36) Promise {
<rejected> TypeError: confirmation.createMessageComponentCollector is not a function
at Object.run (/PC/184395345943/slash/Moderation/ban.js:114:36)
}
I tried changing confirmation.createMessageComponentCollector(...) line to confirmation.message.createMessageComponentCollector(...), but it output almost the same error:
confirmation.message.createMessageComponentCollector() - undefined
This made me confusing. Thank you in advance! <3
followUp returns a Promise <(Message|APIMessage )>, see for example this doc. So you need to await on it:
const confirmation = await interaction.followUp({
...
Title might be a little confusing so here's a screenshot of what's happening when I type a command:
It works, but then it fails at the same time. I get no errors from this interaction. Here's my code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("suggest")
.setDescription("Send your suggestion to the specified channel")
.addStringOption((option) =>
option
.setName("suggestion")
.setDescription("Your suggestion")
.setRequired(true)
),
async execute(interaction) {
let suggestion = interaction.options.getString("suggestion");
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${suggestion}`);
await interaction.channel
.send({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
Try deferring the reply. More info on it here
For example,
const wait = require('util').promisify(setTimeout);
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.deferReply();
await wait(4000);
await interaction.editReply('Pong!');
}
});