My Problem is that I'm getting the following error Message:
(node:12160) DeprecationWarning: The message event is deprecated. Use messageCreate instead(Use `node --trace-deprecation ...` to show where the warning was created)
I know that there's a solution for this on this Site but my problem is that my await function is not working when I try to change the .send({ embeds: [embed] }) to message.channel.send({ embeds: [embed] }); and i don't know how to change the embed so my await function is working and the error resolves.
if (message.content.startsWith("!Suggestion")) {
var str = message.content.slice(" !Suggestion".length);
const embed = new Discord.MessageEmbed()
.setThumbnail('Png')
.setTitle("Suggestion")
.setColor('#151515')
.addFields(
{ name: "Person, with a suggestion:", value: `<#!${message.author.id}>` },
{ name: 'Suggestion:', value: `${str}` },
{ name: 'Channel:', value: `${message.channel}` },
)
.setTimestamp()
.setFooter("You can vote for the suggestion with the emojis on the bottom")
await message.guild.channels.cache.find(c => c.name === 'Suggestion')
.send({ embeds: [embed] })
.then(embedMessage => {
embedMessage.react("✅")
embedMessage.react("❌")
});
message.delete();
}
});
It looks like you updated to Discord.js V13 and there are a lot of changes.
The warning you get is about the on message event.
On v12 it was:
client.on("message", ...);
and now on v13 it is:
client.on("messageCreate", ...);
Check https://discordjs.guide/additional-info/changes-in-v13.html for all the changes in the newest version.
You will have to update your code according to the changes.
Related
on my say command it's not embedded so it lets members #everyone I want to embed the bot's reply to prevent that.
i tried other embeds but they did not work out due to them being
outdated i tried my own but it did not work
command I use:
client.on('message',
function(msg){
if(msg.content === "v!say"){
I don't lnow what to put after
There are several things you could do on this
FYI message is deprecrated and you should use the event listener below:
client.on(`messageCreate`, async (msg) => {
// code here
};
Prevent #everyone and #here
if(msg.content === `v!say` && !msg.content.includes(`#everyone`) && !msg.content.includes(`#here`){
let message2send = //however you already do this
await msg.channel.send({
content: message2send,
});
}
Embed Message
const { MessageEmbed } = require(`discord.js`);
//put at top of file
if(msg.content === `v!say`){
let message2send = //however you already do this
let embed = new MessageEmbed()
.setDescription(message2send)
await msg.channel.send({
embeds: [embed],
});
}
Do Both
const { MessageEmbed } = require(`discord.js`);
//put at top of file
if(msg.content === `v!say` && !msg.content.includes(`#everyone`) && !msg.content.includes(`#here`){
let message2send = //however you already do this
let embed = new MessageEmbed()
.setDescription(message2send)
await msg.channel.send({
embeds: [embed],
});
}
UPDATE: this answer is not for Discord.js v14+ as MessageEmbed is now EmbedBuilder
const { SlashCommandBuilder } = require("#discordjs/builders");
const {
MessageEmbed,
MessageActionRow,
MessageSelectMenu,
} = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup the bot to your server!"),
async execute(interaction) {
let array = [];
await interaction.guild.members.cache.forEach(async (user) => {
if (user.user.bot === false || user.user.id === "925077132865052702")
return;
array.push({
label: user.user.username,
description: user.id,
value: user.id,
emoji: "<a:right:926857658500251668>",
});
});
let row;
if (array < 5) {
row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId("select")
.setMinValues(1)
.setMaxValues(parseInt(array.length))
.setPlaceholder("Nothing selected.")
.addOptions(array)
);
} else {
row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId("select")
.setMinValues(1)
.setMaxValues(5)
.setPlaceholder("Nothing selected.")
.addOptions(array)
);
}
let welcome = new MessageEmbed()
.setTitle("UChecker | Setup")
.setDescription(
"Please select from the dropdown below all the bots you would like to be notified for."
)
.setColor("FUCHSIA");
let message = await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
});
const filter = i => {
return i.user.id === interaction.user.id;
};
await message.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 })
.then(async interaction => await interaction.editReply(`You selected ${interaction.values.join(', ')}!`))
.catch(err => console.log(`No interactions were collected.`));
},
};
Here is my code. As you can see at the bottom I am using awaitMessageComponent and it says an error:
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
at Object.execute (C:\Users\Owner\Desktop\UChecker\src\setup.js:55:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (C:\Users\Owner\Desktop\UChecker\index.js:38:3)
C:\Users\Owner\Desktop\UChecker\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (C:\Users\Owner\Desktop\UChecker\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90:46)
at Client.<anonymous> (C:\Users\Owner\Desktop\UChecker\index.js:41:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
I am confused as I thought you could edit a reply? Could someone please help me out because I am really confused. I have created a reply so then it can be edited by the interaction collector and it says it has already replied.
You have to use CommandInteraction#fetchReply() to retrieve the reply message.
await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
});
const message = await interaction.fetchReply();
Interaction replies are not returned unless you specify fetchReply: true in the options
let message = await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
fetchReply: true
})
I want to get message id from interaction message, but i can't get it :|
discord.js verson : ^13.1.0
client.on('interactionCreate',async interaction => {
if(interaction.commandName==='test') {
let message = await interaction.reply({content:'testing...',ephemeral:true});
console.log(message); //undefined
}
});
You can use the CommandInteraction#fetchReply() method to fetch the Message instance of an initial response.
Example:
client.on('interactionCreate', async (interaction) => {
if (interaction.commandName === 'test') {
interaction.reply({
content: 'testing...',
ephemeral: true,
})
const message = await interaction.fetchReply()
console.log(message)
}
})
For latest version of Discord.js:
You can use the fetchReply property of InteractionReplyOptions to fetch the Message object after send it.
let message = await interaction.reply({content:'testing...',ephemeral:true, fetchReply: true});
console.log(message); //Message Object
In a hypothetical situation like below, the bot can send an embed then delete the message in 3 seconds.
message.reply({ embeds: [embed] })
.then((msg) => {
setTimeout(() => msg.delete(), 3000)
})
When a user deletes the message before the bot, the bot crashes and I get this error:
C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async MessageManager.delete (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\managers\MessageManager.js:205:5)
at async Message.delete (C:\Users\\Documents\GitHub\\node_modules\discord.js\src\structures\Message.js:709:5) {
method: 'delete',
path: '/channels/877943546932494377/messages/888575942379847681',
code: 10008,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
So is there a way to detect if a message is deleted before attempting to delete it?
".deleted" returns a boolean with which you could check.
https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=deleted
Or if you don't care about the error, you could also just use ".catch" after ".then". Tho, it's probably better to avoid the error in the first place with the above.
Building off this answer by TayDex you should check Message#deleted after the timeout has ended. The reason being is that once the timer starts, it's possible that the message gets deleted within the 3 seconds it's counting down.
Additionally you can add a catch() callback to Message#delete() for error handling and preventing crashes.
message.reply({ embeds: [embed] })
.then(msg => {
setTimeout(() => {
if (!msg.deleted) {
msg.delete()
.catch(err => {
console.log('An error occurred but the bot is still running')
console.error(err)
})
}
}, 3000)
})
So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs