Message content must be a non-empty string when editing message - javascript

I wanted to make a command to make the bot return its connection status to the database, but I got an error and I am a little confused now.
RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string.
const { MessageEmbed } = require('discord.js');
const quick = require('quick.db');
module.exports = {
name: 'ping',
aliases: [],
description: 'Get bot ping.',
permissions: [],
async execute(message, client) {
const ping = await getDBPingData();
const messagePing = Date.now();
const msg = await message.channel.send('Loading...');
const endMessagePing = Date.now() - messagePing;
const embed = new MessageEmbed()
.setDescription(
`
Database ping data:
- Fetch ping: \`${ping.endGet}ms\`
- Wright ping: \`${ping.endWright}ms\`
- Avrage ping: \`${ping.avarage}ms\`
Message ping: \`${endMessagePing}ms\`
`
)
.setColor('GREEN')
.setTimestamp();
msg.edit({
content: '',
embed,
});
},
};
async function getDBPingData() {
// get the fetch data ping
const startGet = Date.now();
await quick.get('QR=.');
const endGet = Date.now() - startGet;
// get the wright data ping
const startWright = Date.now();
await quick.set('QR=.', Buffer.from(startWright.toString()).toString('base64'));
const endWright = Date.now() - startWright;
// avrage ping time
const avarage = (endGet + endWright) / 2;
try {
quick.delete('QR=.');
} catch (error) {}
return { endGet, endWright, avarage };
}
I am using discord.js v13, and the packages in use for this command are: discord.js and quick.db.

In v13, messages sent by bots now support up to 10 embeds. As a result, the embed option was removed and replaced with an embeds array, which must be in the options object, so your message edit should be msg.edit({ embeds: [embed] }).
If you also want to remove the previous text (Loading...), you need to add content: null as providing an empty string ('') as the content will throw a RangeError.
msg.edit({
content: null,
embeds: [embed],
});

Try this:
// only need to edit embed in an embeds array
msg.edit({ embeds: [embed] })

Related

How can i get my discord.js v14 bot to stop saying "The application did not respond" if the slash command works?

i have multiple commands that work perfectly fine but i always get this message in return.
here is the code for that command. it works perfectly fine i guess it just doesn't respond to the interaction even though i feel like it should be?
how can i get it to ignore this message or reply properly?
const Discord = require('discord.js');
const { EmbedBuilder, SlashCommandBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('totalfrozencheckouts')
// command description
.setDescription('Add up every message in the frozen checkouts channel after a specific message ID')
.addStringOption(option =>
option.setName('messageid')
.setDescription('The message ID')
.setRequired(true)),
async execute(interaction) {
const channel = '<#' + process.env.FROZENCHECKOUTS + '>';
const messageId = interaction.options.getString("messageid");
// Check if the channel mention is valid
if (!channel.startsWith('<#') || !channel.endsWith('>')) {
return interaction.channel.send(`Invalid channel mention. Please use the format: ${this.usage}`);
}
// Extract the channel ID from the channel mention
const channelId = channel.slice(2, -1);
// Try to fetch the messages from the requested channel and message ID
interaction.guild.channels.cache.get(channelId).messages.fetch({ after: messageId })
.then(messages => {
// Create an array of the message contents that are numbers
const numbers = messages.map(message => message.content).filter(content => !isNaN(content));
// Check if there are any messages
if (numbers.length === 0) {
return interaction.channel.send(`No messages were found in ${channel} after message ID https://discord.com/channels/1059607354678726666/1060019655663689770/${messageId}`);
}
// Adds up the messages
const sum = numbers.reduce((accumulator) => accumulator + 1, 1);
// Create an embed object
const embed = new EmbedBuilder()
.setColor(0x4bd8c1)
.setTitle(`Total Checkouts in #frozen-checkouts for today is:`)
.addFields(
{name: 'Total Checkouts', value: sum.toString() , inline: true},
)
.setThumbnail('https://i.imgur.com/7cmn8uY.png')
.setTimestamp()
.setFooter({ text: 'Frozen ACO', iconURL: 'https://i.imgur.com/7cmn8uY.png' });
// Send the embed object
interaction.channel.send({embeds: [embed]});
})
.catch(error => {
console.error(error);
interaction.channel.send('An error occurred while trying to fetch the messages. Please try again later.');
});
}
}
I don't really know what to try because it literally works I just don't know how to get it to either ignore that message or respond with nothing. It doesn't break the bot its just annoying to look at.
Use interaction.reply instead of interaction.channel.send to reply.

Getting back a empty string Discord JS in json array

im trying to get back all the license that exist in the json file the code below works fine
in the Console.Log. There im getting exactly what i need. but when i want to use it as a
.SetDescription i get nothing just empty space.
client.on('messageCreate', async (message) => {
if (message.content === '!acglobalbans') {
const res = await fetch('website');
const data = await res.json();
const licenses = data.globalbans.map(ban => ban.license);
console.log(licenses);
const embed = new MessageEmbed()
.setAuthor({ name: client.user.username, iconURL: client.user.displayAvatarURL() })
.setDescription("test: ", licenses)
.setColor("BLACK");
message.reply({ embeds: [embed] });
}
});

How to .deferReply to specified channel?

How can I have it so that the bot sends a message to a specific channel, while using .deferReply and .editReply? Currently, I'm getting an error saying that suggestionChannel.deferReply is not a function. 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, client) {
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
await suggestionChannel.deferReply();
await suggestionChannel
.editReply({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
How can I have it so that the bot sends a message to a specific
channel, while using .deferReply and .editReply?
Well, the short answer is; you can't. But you can do this:
As the error already says, deferReply() is not a method of the TextBasedChannels class, defined by your suggestionChannel.
Instead, try sending a message to the channel instead of replying. Replies can only be executed in the interaction's channel:
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
// use this instead
await suggestionChannel.send({
embeds: [embed],
});
P.S side note, deferReply() starts a 15-minute timer before the interaction expires and triggers that 'x is thinking...' text to appear when the client is calculating stuff, so try to call it as soon as possible. By default, interactions expire after 3 seconds, so if your bot fails to finish whatever it needs to accomplish within that timeframe, that interaction will fail.

I'm coding a discord bot, but when I'm using the ping command its shows me 0 ms. what should i do?

I'm trying to do a ping command but when I'm using it the ping is 0.
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "ping",
description: "this is the ping command",
execute(message, args, Discord) {
const msg = message.channel.send("**Pinging...**").then((m) => m.delete({ timeout: 0 }));
const embed = new MessageEmbed().setColor("#42d242").setDescription(`**:hourglass_flowing_sand: ${message.createdTimestamp - message.createdTimestamp}**`);
message.channel.send(embed);
},
};
The reason why your code is always returning 0 is that you are deducting message.createdTimestamp from itself, which will always result in 0 because it is the same number.
The solution is to create a new Date() and use getTime() to get the UNIX Timestamp and deduct it from message.createdTimestamp.
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "ping",
description: "this is the ping command",
execute(message, args, Discord) {
const msg = message.channel.send("**Pinging...**").then((m) => m.delete({ timeout: 0 }));
const embed = new MessageEmbed().setColor("#42d242").setDescription(`**:hourglass_flowing_sand: ${new Date().getTime() - message.createdTimestamp}**`);
message.channel.send(embed);
},
};
For starters, you're using message.createdTimestamp - message.createdTimestamp. If we replace those with a random number to represent the time, we get 573 - 573. Obviously that equals zero. You're subtracting the number from itself. Try something like
var ping = await msg.channel.send("Fetching ping...");
const pingEmb = new MessageEmbed()
.setColor("#42d242")
.setDescription(`:hourglass_flowing_sand: Heartbeat is ${client.ws.ping}ms,\nMessage Roundtrip took ${ping.createdTimestamp - message.createdTimestamp}ms.`);
return ping.edit("", {
embed: pingEmb
});

Discord js giveaway command

I am currently trying to make a Discord.js command where the first person who reacts wins the prize. There are 2 issues that I am encountering right now. First, the bot is picking up the last prize that was entered through with the command rather than the current one. Secondly, the giveaway sent before a bot restart won't work after the bot restarts.
Here is the code:
const DropModel = require('../modules/DropModel');
const { MessageEmbed, ReactionCollector } = require("discord.js")
const { COLOR, MONGO } = require("../util/BotUtil");
module.exports = {
name: "drop",
description: "First to react wins the giveaway!",
async execute(message, args) {
let prizes = args.slice(0).join(' ').toString()
if (!prizes) return message.channel.send("You didn't provide a prize.");
const newDrop = new DropModel({
guildId: message.guild.id,
prize: prizes,
channelId: message.channel.id,
createdBy: message.author,
timeCreated: new Date(),
});
newDrop.save();
let Drops = await DropModel.findOne({ guildId: message.guild.id, channelId: message.channel.id });
if (!Drops) return;
const { prize, createdBy } = Drops;
const DropEmbed = new MessageEmbed()
.setTitle(`${prize}`)
.setDescription(`First to React with 🎁 wins the giveaway
Hosted by: ${createdBy}`)
.setColor(COLOR)
.setTimestamp();
const dropMsg = await message.channel.send(`🎁 **giveaway** 🎁`, DropEmbed);
await Drops.remove();
await dropMsg.react('🎁');
const filter = (reaction, user) => !user.bot;
const reaction = new ReactionCollector(dropMsg, filter, { max: 1 });
reaction.on('collect', async (reaction, user) => {
const { embeds } = dropMsg;
const embed = embeds[0];
embed.setTitle(`Someone called giveaway!`);
embed.setDescription(`Winner: ${user.toString()}
Please contact ${createdBy} to claim your giveaway!`);
await dropMsg.edit(embed);
dropMsg.channel.send(`${user.toString()} won **${prize}**!`);
});
}
}
Any help regarding the issues mentioned above would be appreciated! Thanks!
You can save the giveaway end timestamp in JSON file or whatever database and then delete it when it's finished.

Categories

Resources