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.
Related
I wrote a new command when my bot ran on my pc and not a server.
While the bot ran on my pc the command worked very well, but after I put my bot into a server
the command stopped working and I always get an error message:
DiscordAPIError: Cannot send an empty message
The code:
const Discord = require("discord.js");
const recon = require('reconlx');
const rpages = recon.ReactionPages
const moment = require('moment');
const fs = require('fs');
module.exports = class HelpCommand extends BaseCommand {
constructor() {
super('help', 'moderation', []);
}
async run(client, message, args) {
const y = moment().format('YYYY-MM-DD HH:mm:ss')
const sayEmbed1 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed2 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed3 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed5 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed4 = new Discord.MessageEmbed()
.setTitle(`example`)
const sayEmbed6 = new Discord.MessageEmbed()
.setTitle(`example`)
.setDescription("[A készítőm Weboldala](https://istvannemeth1245.wixsite.com/inde/)\n\n")
try {
await
message.delete();
const pages = [{ embed: sayEmbed1 }, { embed: sayEmbed2 }, { embed: sayEmbed3 }, { embed: sayEmbed4 }, { embed: sayEmbed5 }, { embed: sayEmbed6 }];
const emojis = ['◀️', '▶️'];
const textPageChange = true;
rpages(message, pages, textPageChange, emojis);
} catch (err) {
console.log(err);
message.channel.send('Nem tudom ki írni az üzenetet');
}
const contetn = `\n[${y}] - ${message.author.username} használta a help parancsot. `;
fs.appendFile('log.txt', contetn, err => {
if (err) {
console.err;
return;
}
})
}
}
Full error message:
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/home/container/Lee-Goldway/node_modules/discord.js/src/rest/RequestHandler.js:39:14) {
method: 'post',
path: '/channels/833629858210250813/messages',
code: 50006,
httpStatus: 400
}
A couple of things. Are you sure that this reconlx package is compatible with your discord.js version? It's always a good idea to post your discord.js version when you have a problem with libraries.
If you're using reconlx v1, you can see in their old documentation that in ReactionPages the second parameter takes an array of embeds. If you check the source code, you can see that it tries to send the first item of pages as an embed, like this: message.channel.send({ embeds: [pages[0]] }).
It means that with your code embeds is an array where the first item is an object that has an embed key with the sayEmbed1 embed, while discord.js accepts an array of MessageEmbeds.
I would try to pass down an array of embeds like this:
const pages = [
sayEmbed1,
sayEmbed2,
sayEmbed3,
sayEmbed4,
sayEmbed5,
sayEmbed6,
];
PS: ki írni is incorrect. When the verb particle precedes the verb, they are written as one word. So, it should be kiírni. :)
In the code provided, there appears to be no code that references "{embeds:[embed]}".
However, assuming the error is coming from this line:
message.channel.send('Nem tudom ki írni az üzenetet');
Referring to the official documentation, you can provide an object.
For example:
message.channel.send({ content: 'Nem tudom ki írni az üzenetet' });
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);
Objective: Making a simon says command
Problem:
I am receiving a strange error while sending an non-empty message in discord.js v13.
For some reason the discord api sends the message:
const startMessage = await channel.send({ content: `Quest: **${start.string} ${currentGame.startMessage.toLowerCase()}** *(You have ${Math.floor(actualTime / 1000)} seconds)*`})`
and then returns an error:
DiscordAPIError: Cannot send an empty message
|--NOTE: ------------------------------------------------------------------|
This seems to only happend when I put an await before the
channel.send(message) command
-------------------------------------------------------------------------------|
And it doesn't make sense why it sends the message and after that returns an error about that specific message.
module.exports.runGame = async function (channel, players_, client) {
let players = players_
let time = 1
let winners
let gameOn = true
let rounds = 1
let lastGame = null
//example of how to start a game
let config = JSON.parse(fs.readFileSync(`./guilds/${channel.guild.id}.json`)); //for this game only
while (gameOn) {
//chooses a random minigame
let enabledGames = []
for(let game of minigames){
if(config.minigames[game.name]){
if(game.name == 'oppositeDay' && rounds < 4) continue
enabledGames.push(game)
}
}
if(enabledGames.length == 0){
channel.send('You need to have at least one game enabled to play. Enable/disable with the config command.')
return
}
let currentGame = enabledGames[getRandomInt(enabledGames.length)]
while(currentGame == lastGame){
currentGame = enabledGames[getRandomInt(enabledGames.length)]
}
//picks a random start of startmessage (67% chance of getting "Simon says")
let start
if (currentGame.name == 'oppositeDay') {
start = {
string: config.opposite_day ? 'Good morning,' : 'Simon says',
real: true
}
} else if(rounds < 3){
start = {
string: 'Simon says',
real: true
}
} else {
start = randomStart(channel.guild.id, config)
}
let actualTime = (time * currentGame.defTime).clamp(5000, 15000)
//sends startmessage
console.log("\n\n\n\n\n\n\n\n\nSTART\n\n\n\n\n");
try {
const startMessage = await channel.send({ content: `Quest: **${start.string} ${currentGame.startMessage.toLowerCase()}** *(You have ${Math.floor(actualTime / 1000)} seconds)*`})
} catch (err) {
console.log(`Known Error in line 59 on game.js ${err}`)
}
//runs the game
console.log("\n\n\n\n\n\n\n\n\nEND\n\n\n\n\n");
console.log(currentGame.name)
let {
playersOut,
playersLeft,
configOut
} = await currentGame.run(channel, players, actualTime, client, {
simonSaid: start.real,
startMessage: startMessage,
config: config
})
config = configOut
}
}
Here is the full error output including my debug console.log(); instructions
START
/home/lixt/Desktop/The Lixt Bot/LIXTON/node_modules/discord.js/src/rest/RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/lixt/Desktop/The Lixt Bot/LIXTON/node_modules/discord.js/src/rest/RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/lixt/Desktop/The Lixt Bot/LIXTON/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async TextChannel.send (/home/lixt/Desktop/The Lixt Bot/LIXTON/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:171:15) {
method: 'post',
path: '/channels/997996030572384288/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: []
}
}
How do I know the error is in that specific message?
I debug it to there. I made a console.log() before the message and other console.log after that message.
Edit
Using vsc debugger I got this image
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})
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.