I am trying to program a discord chat bot, that when the command '!help' is directed to a certain text channel, the bot writes a direct message to the person who wrote the command in order to answer a series of questions, this is the code that I try:
const {Client, RichEmbed, Intents, MessageEmbed} = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.DIRECT_MESSAGES] });
const token = 'TOKEN';
const PREFIX = '!';
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
})
bot.on('messageCreate', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'help':
const Embed = new MessageEmbed()
.setTitle("Helper Embed")
.setColor(0xFF0000)
.setDescription("Make sure to use the !help to get access to the commands");
message.author.send(Embed);
break;
}
});
bot.login(token);
However, it throws me a DiscordAPIError error. Which is the following:
node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/Users/mybot/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/Users/mybot/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async DMChannel.send (/Users/mybot/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:176:15) {
method: 'post',
path: '/channels/98595393932745/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
If I'm correct and you are using discord.js v13, you have to use message.author.send({embeds: [Embed]}) to send embeds!
In discord.js v13, you no longer send messages directly, you need to specify if its an embed, components etc. here's an example
message.author.send({content: 'you need help'}) // Normal message
message.author.send({embeds: [Embed]}) // embedded message
message.author.send({content: 'you need help', embeds: [Embed], components: [buttonRow]}) // To send message, embed and components
To make an interaction reply ephemeral, you use the same method, but boolean:
interaction.reply({embeds: [Embed], components: [row], ephemeral: true})
Related
So I'm trying to send an embed to a specific channel (1068005047373414481) and I'd like to send an embed with the sort of new buttons using the ActionRow components. Keep in mind that the channel is not the same channel where the interaction will be ran. Anyways I've tried using the interaction.guild.channels.cache.get(id).send(embed); method but it seems to not work. I always end up getting a DiscordAPIError[50006]: Cannot send an empty message error. Either way I don't think you can add components to that message like you can do with interaction.reply({ embeds: embed, components: [row] });
Here is my current code:
client.once('ready', () => {
console.log('Ready!')
client.user.setActivity("all you rascals", {
type: ActivityType.Watching,
});
var testing = new EmbedBuilder()
.setTitle('test')
client.guilds.cache.get(guild).channels.cache.get(channel).send(testing)
})
(This is for testing as I will implement the correct way into my bot once I find an answer)
When I run that I get this error:
C:\Users\User\OneDrive\Documents\a\c\fbot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50006]: Cannot send an empty message
at SequentialHandler.runRequest (C:\Users\User\OneDrive\Documents\a\c\fbot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\User\OneDrive\Documents\a\c\fbot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (C:\Users\User\OneDrive\Documents\a\c\fbot\node_modules\#discordjs\rest\dist\lib\REST.cjs:52:22)
at async TextChannel.send (C:\Users\User\OneDrive\Documents\a\c\fbot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15) {
rawError: { message: 'Cannot send an empty message', code: 50006 },
code: 50006,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1068005047373414481/messages',
requestBody: {
files: [],
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
}
}
interaction.reply({ embeds: embed, components: [row] });
Is very close to what you need, remember that the embeds property must be an array of embeds, even if you only have one.
The correct code would be
interaction.reply({ embeds: [embed], components: [row] });
So been following a guide to get started on a discord bot, but keep getting this error message when running node deploy-commands.js
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
at async REST.request (C:\Users\voidy\.vscode\python\test-codes\DiscordBot\node_modules\#discordjs\rest\dist\lib\REST.cjs:52:22) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/1018530446092554290/guilds/1018530446092554290/commands',
requestBody: { files: undefined, json: [ [Object], [Object], [Object] ] }
}
I have already added both the bot and applications.commands scope for my bot, and kicked it and re-added it quite a few times with no luck.
The guildId, clientId and Token are all correct, even reset and used the new token instead.
Here's the code if needed
const { SlashCommandBuilder, Routes } = require('discord.js');
const { REST } = require('#discordjs/rest');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '10' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
As one of the first bigger js/node projects I decided to make a discord bot using discord.js. Every user is able to add new messages to the repl.it (the website I host the bot on) database and read random ones. The bot is working fine so I wanted to make it reply with embeds because it looks better and that is where the problem is.
I don't get any errors when making the embed but when I try to send it to the chat it says that it can't send an empty message at the RequestHandler.execute. Here is the full error message:
/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/runner/anonymous-message/node_modules/discord.js/src/rest/RequestHandler.js:51:14) {
method: 'post',
path: '/channels/880447741283692609/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: 0,
message_reference: { message_id: '970404904537567322', fail_if_not_exists: true },
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
And here is the full code:
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const keepAlive = require("./server.js") //just a webserver that I combine with uptimerobot.com so the bot doesn't go offline
const Database = require("#replit/database")
const db = new Database()
client.login(process.env.TOKEN) //since all replits are public (unless you buy the premium) you can use the environment variables to keep somestuff private
let prefix = "msg "
let channel
let starterMessages = ["a random test message!", "Hello World!", "why is this not working"]
db.get("msgs", messages => {
if (!messages || messages.length < 1) {
db.set("msgs", starterMessages)
}
})
client.on("ready", () => {
console.log("bot is working")
})
client.on("messageCreate", (msg) => {
channel = msg.channel.guild.channels.cache.get(msg.channel.id)
switch (true) {
case msg.content.toLowerCase().startsWith(prefix + "ping"):
channel.send("the bot is working")
break
case msg.content.toLowerCase().startsWith(prefix + "send"):
let exists = false
let tempMsg = msg.content.slice(prefix.length + 5, msg.length)
if (tempMsg.length > 0) {
db.get("msgs").then(messages => {
for (i = 0; i < messages.length; i++) {
if (tempMsg.toLowerCase() === messages[i].toLowerCase()) { exists = true }
}
if (exists === false) {
console.log(tempMsg)
messages.push(tempMsg)
db.set("msgs", messages)
msg.delete() //deletes the message so no one knows who added it
} else {
console.log("message already exists") //all console logs are for debugging purposes
}
});
}
break
case msg.content.toLowerCase().startsWith(prefix + "read"):
db.get("msgs").then(messages => {
let rndMsg = messages[Math.floor(Math.random() * messages.length)] //gets the random message from the database
//Here I make the embed, it doesn't give any errors
let newEmbed = new Discord.MessageEmbed()
.setColor("#" + Math.floor(Math.random() * 16777215).toString(16))
.setTitle("a message from a random stranger:")
.setURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley")
.addFields({ name: rndMsg, value: `if you want to send one of these for other people to read? Type "${prefix}send [MESSAGE]"` })
.setFooter({ text: `type "${prefix}help" in the chat for more info!` })
msg.channel.send(newEmbed) //and here is the problem. Without this line it runs with no errors
});
break
}
})
keepAlive() //function from the webserver
I couldn't find any answers to this problem on the internet so I'm hoping you can answer it. Thanks in advance!
Since you're using (I assume) discord.js v13, the way to send embeds is this:
msg.channel.send({embeds: [newEmbed]});
That should solve your problem.
I am trying to make a profanity discord bot. Whenever I run it, it is fine but when I type a word that it's supposed to filter out, it stops. This is the error I get when typing in a blocked word.
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\loser\Desktop\word filter bot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\loser\Desktop\word filter bot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.send (C:\Users\loser\Desktop\word filter bot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15)
at async Client.<anonymous> (C:\Users\loser\Desktop\word filter bot\index.js:33:19) {
method: 'post',
path: '/channels/954840804466257921/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
and here is my code
const Discord = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const prefix = '-'
client.once('ready', () => {
console.log('woohoo, Im ready to get online and block some words!')
client.user.setActivity('-help', {type: 'LISTENING'})
})
client.on('message', async message => {
if(message.channel.type === 'dm' || message.author.bot) return;
const logChannel = client.channels.cache.find(channel => channel.id === '954845946326450206')
let words = ["banana", "orange"]
let foundInText = false;
for (var i in words) {
if (message.content.toLowerCase().includes(words[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
let logEmbed = new Discord.MessageEmbed()
.setDescription(`<#${message.author.id}> Said a bad word`)
.addField('The Message', message.content)
.setColor('RANDOM')
.setTimestamp()
logChannel.send(logEmbed)
let embed = new Discord.MessageEmbed()
.setDescription(`That word is not allowed here`)
.setColor('RANDOM')
.setTimestamp()
let msg = await message.channel.send(embed);
message.delete()
msg.delete({timeout: '3500'})
}
})
is there anyway you guys can help me out? I would really like to get this up and running.
I assume you're using discord.js v13.
The send method only take one parameter since v13. You can to use send({ embeds: [your, cool, embeds] }); to send embeds or any message that contain not only contents.
Also the Message.prototype.delete() does not take any parameter now. You have to use setTimeout if you want to delete messages after a certain amount of time.
This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 1 year ago.
I am having issues with sending discord embeds. This is my code:
module.exports = {
name: 'tiktok',
description: "sends tiktok link",
execute(message, args, Discord) {
const newEmbed = new Discord.MessageEmbed()
.setColor('#228B22')
.setTitle('Tiktok')
.setURL('https://www.tiktok.com/#elcattuccino?lang=en')
.setDescription('tiktok link for the discord server')
.addFields(
{name: 'Tiktok', value:'heres the tiktok link'},
)
.setImage('https://cdn.discordapp.com/avatars/752212130870329384/6a16609eafc28f95ad8f64e80ffcc24e.png?size=80')
.setFooter('check out the tiktok');
message.channel.send(newEmbed);
}
}
But I get this error:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\willm\OneDrive\Desktop\Discord Bot\node_modules\discord.js\src\rest\RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\willm\OneDrive\Desktop\Discord
Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async TextChannel.send (C:\Users\willm\OneDrive\Desktop\Discord Bot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:172:15)
{ method: 'post', path: '/channels/910099863180550144/messages',
code: 50006, httpStatus: 400, requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: [] } }
If you're using discord.js v13, you should send an embed like this as you can send up to 10 embeds now:
message.channel.send({ embeds: [newEmbed] });
The embed option was removed and replaced with an embeds array, which must be in the options object. More info
Use message.channel.send({ embeds: [newEmbed] });
Also field has changed
.addField('LINK', '[LINK](TIKTOK LINK)', true)
like this