So basically, I am trying to fetch embed from 1 channel and then send it to another channel but it's giving an error saying something about empty message.
Full Error:
Received 1 messages
/home/bot/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/bot/node_modules/discord.js/src/rest/RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/bot/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async TextChannel.send (/home/bot/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:171:15) {
method: 'post',
path: '/channels/874619472902774845/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: []
}
}
Here is my bot script:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });;
client.on('ready', () => {
const channel1 = client.channels.cache.get("791100523246911499");
const logchannel1 = client.channels.cache.get("874619472902774845");
channel1.messages.fetch({ limit: 1 }).then(messages => {
console.log(`Received ${messages.size} messages`);
//Iterate through the messages here with the variable "messages".
messages.forEach(message => {
logchannel1.send(message.embeds);
})
})
I hope someone knowledgeable in discord.js can help me out with this dilemma.
Thanks for reading
Regards, Infamous.
This part is incorrect
messages.forEach(message => {
logchannel1.send(message.embeds);
})
You have to specify they are embeds
messages.forEach(message => {
logchannel1.send('optional content', {embeds: [...message.embeds]});
})
Related
I'm building a bot with Discord.js.
I wrote below code, and persists same error.
How can I fix or avoid that error?
require("dotenv").config();
const fs = require("fs");
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const commands = [];
const commandfiles = fs.readdirSync("./src/Commands").filter(file => file.endsWith(".js"));
commandfiles.forEach(commandfile => {
const command = require(`./Commands/${commandfile}`);
commands.push(command.data.toJSON());
});
const restClient = new REST({version: "9"}).setToken(process.env.TOKEN);
restClient.put(Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.DISCORD_GUILD_ID),
{body: commands})
.then(()=> console.log("Successfully registered commands"))
.catch(console.error);
Error message and stacktrace:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:708:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\kitel\vscode workspace\DiscordBot\node_modules\#discordjs\rest\dist\index.js:511:14) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/932218396219674624/guilds/932240564102000710/commands',
requestBody: { files: undefined, json: [ [Object] ] }
{ rawError: { message: 'Missing Access', code: 50001 }
As you mentioned, it's missing access i think. Enable your intents on web and grant your bot application commands privilege.
When I try to execute a slash command it crashes with an 404 error.
I already tried to delete all commands but it didn't work.
Here's the code I'm using
const commands = [
{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Reloading slash commands');
await rest.put(
Routes.applicationGuildCommands("client_id", "server_id"),
{ body: commands },
);
console.log("Reloaded slash commands");
} catch (error) {
console.error(error);
}
})();
Here's the error
node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown application command
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.fetch (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:93:23)
at async Client.<anonymous> (/home/container/index.js:101:17) {
method: 'get',
path: '/applications/client_id/guilds/guild_id/commands/command_id',
code: 10063,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
if you want to register your Slash Commands with the moderately recent Discord.js Rest library you have to use the builder library as well. You are also not passing JSON to the body you are passing an Array of Objects.
From Discord.js Guide on Making Slash Commands
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
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: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
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 recently started working on discord ban bot with 3 main features:
Export IDs of all banned users in current Server/Guild.
Import IDs of banned users into current guild
Transfer ban list from current server to target server. (Under development)
None of the slash commands are working even though the logic is seemingly correct.
I'm following the discordjs guide & managed to make a Time Tag generator bot & this is my 2nd bot project. I admit I'm not familier with Javascript but the guide is very helpful nonetheless
Here is the export-ban-list code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
function new_paste(serverName, results) {
const outputFile = `${serverName}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return data;
}
else {
return 'There was some unexpected error.';
}
});
}
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
const fe = new_paste(interaction.serverName, results);
return interaction.editReply(fe);
},
};
This command basically calculates the number of users banned, makes an array & exports it to pastebin.
The issue is, the bot code reaches till calculation part, but when it comes to making the list, console throws me errors:
Found 13 bans. Exporting...
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async InteractionWebhook.editMessage (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\Webhook.js:311:15)
at async CommandInteraction.editReply (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:137:21)
at async Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:41:3) {
method: 'patch',
path: '/webhooks/897454611370213436/aW50ZXJhY3Rpb246ODk4ODkyNzI0NTcxMzczNjA5OmtPeGtqelQ5eUFhMnNqVzc1Q3BpMWtQZUZRdVhveGQxaHFheFJCdVFoUWNxNUk5TVpGbThEQjdWcDdyaHZyaUJPeUpsRWFlbUp0WnVLYjB5V0RtYmJCSmlNU2wwUVlka1hYMHg0bHRJbzlHelVwRmJ6VUpRaXF2YktaVDN1ZlVp/messages/#original',
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: []
}
}
D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89
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 (D:\Github\Discord-Ban-Utils-Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:89:46)
at Client.<anonymous> (D:\Github\Discord-Ban-Utils-Bot\index.js:45:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
Thanks to Jim I used the console.log() to check what was going on.
And indeed the data from function inside new_paste() wasn't being returned to fe.
(I had messed up the return scopes basically)
Here is the final code after fixes & scope resolutions
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { token, pasteUser, pastePass, pasteKey } = require('../config.json');
const paste = require('better-pastebin');
const rest = new REST({ version: '9' }).setToken(token);
const date = new Date();
paste.setDevKey(pasteKey);
paste.login(pasteUser, pastePass);
module.exports = {
data: new SlashCommandBuilder()
.setName('export-ban-list')
.setDescription('Exports ban list of current server'),
async execute(interaction) {
const bans = await rest.get(
Routes.guildBans(interaction.guildId),
);
await interaction.deferReply(`Found ${bans.length} bans. Exporting...`);
console.log(`Found ${bans.length} bans. Exporting...`);
let results = [];
bans.forEach((v) => {
results.push(v.user.id);
});
results = JSON.stringify(results);
console.log(results);
const outputFile = `${interaction.guild.name}-${date}.txt`;
paste.create({
contents: results,
name: outputFile,
expires: '1D',
anonymous: 'true',
},
function(success, data) {
if (success) {
return interaction.editReply(data);
}
else {
return interaction.editReply('There was some unexpected error.');
}
});
},
};
And finally I get the proper pastebin url as output.
Code hosted here
I think your npm package better-pastebin has an error. I am not familiar with that npm package, so I can’t determine whether it has an error for you, but I think if you change the npm package, the error will not appear.
I'm getting a missing access error when trying to add slash commands to my guild. I already kicked the bot, deleted the bot and changed the intents.
My intent number is 32265
This is my code for adding it the commands:
const commandFiles = await globPromise(`${process.cwd()}/commands/**/*.js`);
const arrayOfSlashCommands = [];
commandFiles.map((value) => {
const file = require(value);
const splitted = value.split("/");
const directory = splitted[splitted.length - 2];
if (file.name) {
const properties = { directory, ...file };
client.commands.set(file.name, properties);
arrayOfSlashCommands.push(file);
}
});
client.on("ready", () => {
client.guilds.cache.get("783606158669381663").commands.set(arrayOfSlashCommands);
});
But I'm getting this error:
E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async GuildApplicationCommandManager.set (E:\Development\DiscordBot\Dc_v1_13_FeatureTest\node_modules\discord.js\src\managers\ApplicationCommandManager.js:146:18) {
method: 'put',
path: '/applications/893555323200237599/guilds/783606158669381663/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: [
{
name: 'search',
description: 'Search',
type: undefined,
options: undefined,
default_permission: undefined
}
],
files: []
}
}
The solution was to invite the bot using: