Why im getting this error tho the cmd is fine? Cannot read properties of undefined (reading 'get') - discord

DiscordJS context menu problem, like it says the cmd is running fine but when it does it shows the error of Cannot read properties of undefined (reading 'get') don't know why
Im getting this error on my events folder in discordjs v14 my content.js event
the error kept showing up though the context is still executed/working
I know i should be ignoring this error as long as the command is running good but it just annoying to my console and it doesn't look clean haha...
my context events:
module.exports = {
name: 'interactionCreate',
execute: async (interaction, client) => {
if (interaction.isContextMenuCommand()) {
const { command } = client;
const { commandName } = interaction;
const contextCommand = command.get(commandName);
if (!contextCommand) return;
try {
await contextCommand.execute(client, interaction)
} catch (e) {
console.log(e)
}
}
}
}
simple wave context
const { ApplicationCommandType, EmbedBuilder } = require("discord.js"); // packages
const superagent = require('superagent');
const ee = require('../../Config/embed.json');
module.exports = {
name: 'wave', // name of the command
// description: '', description of the command
developer: false, // false if the command is for public
type: ApplicationCommandType.User, // chatinput
cooldown: 3000, // cooldown of the commands
default_member_permissions: 'SendMessages', // discord perms
// options: [], options string
execute: async (client, interaction) => {
try {
let { body } = await superagent.get(`https://api.waifu.pics/sfw/wave`);
const embed = new EmbedBuilder()
.setColor(ee.color)
.setDescription(`Hey <#${interaction.targetUser.id}>!, <#${interaction.user.id}> just wave at you!`)
.setImage(body.url)
.setTimestamp()
.setFooter({ text: `${client.user.username} | waifumusic.ml` })
interaction.reply({ embeds: [embed] })
} catch (e) {
console.log(e)
}
}
}

Related

TypeError: command.execute is not a function

I am aware that this problem has been discussed already, but I don't seem to fit the solutions found into my code. I've created some commands to this bot and they seem to work, although they are only basic slash commands (e.g. /ping). This problem came in when I try to run a moderation command or a play command.
This is the code with the error
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.execute(interaction, client);
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
None of the fixes that I found seem to fit, at least to my rather unexperienced eye.
The command I try to run is this:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const { QueryType } = require("discord-player")
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Asculta muzica")
.addSubcommand((subcommand)=>
subcommand
.setName("song")
.setDescription("Incarca o singura melodie printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul melodiei").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("playlist")
.setDescription("Incarca un playlist printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul playlist-ului").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("search")
.setDescription("Cauta o melodie pe baza cuvintelor-cheie")
.addStringOption((option) =>
option.setName("searchterms").setDescription("the search keywords").setRequired(true))),
run: async ({ client, interaction }) => {
if (interaction.member.voice.channel)
return interaction.editReply("Trebuie sa fii pe un voice channel pentru a folosi aceasta comanda!")
const queue = await client.player.createQueue(interaction.guild)
if (!queue.connection) await queue.connect(interaction.member.voice.channel)
let embed = new MessageEmbed()
if (interaction.options.getSubcommand() === "song"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_VIDEO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
} else if (interaction.options.getSubcommand() === "playlist"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_PLAYLIST
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const playlist = result.tracks
await queue.addTrack(result.tracks)
embed
.setDescription(`**${result.tracks.length} melodii din [${playlist.title}](${playlist.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${playlist.duration}`})
} else if (interaction.options.getSubcommand() === "search"){
let url = interaction.options.getString("seatchterms")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
}
if (!queue.playing) await queue.play()
await interaction.editReply({
embeds: [embed]
})
}
}
and the corresponding error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\shelby\Bot\src\events\interactionCreate.js:15:27)
at Client.<anonymous> (C:\Users\shelby\Bot\src\functions\handelEvents.js:8:58)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\shelby\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
at module.exports [as INTERACTION_CREATE] (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:489:22)
at WebSocketShard.onMessage (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:328:10)
at callListener (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:290:14)
at WebSocket.onMessage (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:209:9)
You should be using command.run() instead of command.execute(), as your exported Slash Command uses this property name to store the core function.
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.run({ interaction, client });
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
Additionally, you have to use an object that contains your interaction and client to run the function instead of using two arguments.

DiscordJS 403 Error Missing Access Error when trying to add Slash Commands

I am following the docs at DiscrodJS step by step and have been able to invite my bot just fine to my test server. My problem comes in when I try to add the slash commands.
Here is my index.js file.
const { Client, GatewayIntentBits } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.GuildMessages,
],
})
client.once('ready', () => {
console.log('Ready!')
})
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return
const { commandName } = interaction
const command = interaction.client.commands.get(commandName)
if (!command) {
console.error(`No command matching ${commandName} was found.`)
return
}
try {
await command.execute(interaction)
}
catch (error) {
console.error(error)
await interaction.reply({ ontent: 'There was an error while executing this command', ephemeral: true })
}
})
client.login(process.env.DISCORD_PRIVATE_TOKEN)
Here is my deploy-commands.js file.
const fs = require('node:fs')
const { Routes } = require('discord.js')
const { REST } = require('#discordjs/rest')
require('dotenv').config()
const {
DISCORD_PRIVATE_TOKEN,
DISCORD_CLIENT_ID,
DISCORD_GUILD_ID,
} = process.env
const commands = []
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
commands.push(command.data.toJSON())
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(DISCORD_PRIVATE_TOKEN)
// and deploy your commands!
const deployCommand = async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`)
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID),
{ body: commands },
)
console.log(`Successfully reloaded ${data.length} application (/) commands.`)
}
catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error)
}
}
deployCommand()
There error that I get back from this is the following:
requestBody: { files: undefined, json: [ [Object] ] },
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/[client_id]/guilds/[guild_id]/commands'
}
In the bot settings
I've set auth method to In-app Authorization.
I've set the scope to bot and applications.commands then included Use Slash Commands (also tried this with ALL including Administrator bot permissions.
I've also done this through the URL Generator path.
In my discord server
I've put my Discord server into Developer mode to test my bot.
I've invited my bot to my test server.
In my code
I've ran the one time script for deploy-commands.js.

Discord js v14 i am trying to get the value of the option input to export and use in the index file, the value is always undefined and an error occurs

When I put the command through, the "ign" option seems to not be read after specifying to get the string value of the option. It returns error:
{ message: 'Unknown interaction', code: 10062 },
code: 10062,
status: 404,
method: 'POST',
Command file:
const { SlashCommandBuilder, GatewayIntentBits } = require("discord.js");
const { Client } = require("discord.js");
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
module.exports = {
data: new SlashCommandBuilder()
.setName('stats')
.setDescription('Flex your tournament stats')
.addStringOption(option =>
option.setName('ign')
.setDescription("Your minecraft name")
.setRequired(true)),
};
client.on("interactionCreate", async (interaction)=> {
if (!interaction.isCommand()) {
return
}
const{ commandName, options } = interaction
if (commandName === 'stats') {
const ign = options.getString('ign');
module.exports = { ign };
}
});

DiscordAPIError: Unknown application command

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);

Discord.js: Export Ban list command not working

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.

Resources