Discord: I need a filter to make a select menu with author id but its keeps saying is "properties of undefined (reading 'author')" - discord

//I need only 1 use of select menu
const { MessageEmbed, MessageAttachment, Message } = require('discord.js');
module.exports = {
name: 'interactionCreate',
async execute(interaction, client, message) {
if (interaction.isCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
}
} else if (interaction.isSelectMenu()) {
const i = `${interaction.user.id}`
console.log(i)
const g = `${message.author.id}`
console.log(g)
if (interaction.customId == "color-select") {
let colores = "";
await interaction.values.forEach(async value =>{
colores += `${value} `
});
const filter = (interaction) => {
i === g;
};
const collector = interaction.channel.createMessageCollector({ filter, time: 15000 });
await interaction.reply({ content: `Wow tu color favorito es: ${colores} `});
}
}
},
};
//error
TypeError: Cannot read properties of undefined (reading 'author')

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.

Chaining async/await calls in react

I have an application that can add NYT bestseller items to a database. Currently, users can add a bestseller to the db even if it already exists in the db. I want to be able to chain API calls such that if a user tries to save an item, the application first checks if that item is in the db, and only if it isn't proceed to save the item.
Here is my existing code:
const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => {
setCurrentInDb(false);
let targetObj = {
title: book.title,
author: book.author,
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
axios.get(url).then((res) => {
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true);
}
}
});
} catch (error) {
console.log(error);
}
}
const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db');
return;
}
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
axios.post(postURL, newObj).then((response) => {
console.log('new item added');
});
} catch (error) {
console.log("error: ", error);
}
};
const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
.then(res => handleSaveBook(book))
}
Oddly, upon page reload, the first time I try to add an item to the db that is already there, I CAN add a duplicate. Then if I try to add it again, it correctly does not allow me to add it. Ideas?
There is no need to use .then in the async function. you can simply use await & chain your asynchornous requests.
const [currentInDb, setCurrentInDb] = useState(false);
interface bookInt {
title: string;
author: string;
}
const handleDbCheck = async(book: bookInt) => {
setCurrentInDb(false);
let targetObj = {
title: book.title,
author: book.author,
list: selectedCategory
}
try {
let url = baseURL + "/read-all";
const res = await axios.get(url)
for (let i = 0; i < res.data.length; i++){
let current = res.data[i]
if (current.title === targetObj.title && current.list === targetObj.list){
setCurrentInDb(true);
}
}
} catch (error) {
console.log(error);
}
}
const handleSaveBook = async (book: bookInt) => {
if (currentInDb){
console.log('handleSaveBook stopped early because item in db');
return;
}
try {
let newObj = {
title: book.title,
author: book.author,
list: selectedCategory,
};
let postURL = baseURL + "/create";
const response = await axios.post(postURL, newObj)
console.log(response)
} catch (error) {
console.log("error: ", error);
}
};
const handleCheckAndSave = async(book: bookInt): Promise<any> => {
await handleDbCheck(book)
await handleSaveBook(book)
}

message.member.voice.channel; not working

Basically, i'm coding a discord bot and i'm trying to code a music bot / command. On line 14 whenever ?play is run (the command) i get TypeError: Cannot read property 'voice' of undefined (NOTE: i AM in a voice channel when i run this command) Im using discord js v.12.4 not sure how to check :/ I've gone over some stack overflow questions and they're all saying to update message.member.voiceChannel to message.member.voice.channel. btw i have tried message.member.voiceChannel it returns the same error.
code:
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 10,
description: 'Advanced music bot',
async execute(message, args, cmd, client, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}```

Discord.js voice, player on finish event

I'm trying to learn discord.js so I wanted to learn how music bots work. The code below is my shot and everything works but I'm having an issue with my queue.
I cannot get the player.on "finish" or "end" events. So when the song ends I want to call the recursive method that plays a song but I don't know how to get the correct event.
I have tried using player.on(AudioPlayerStatus.Idle) events and making something out of that but that didn't work out so well.
If anyone has any advice to what am I doing wrong or how to improve the code below, I'd be grateful.
const queue = new Map();
module.exports = {
name: "play",
aliases: ["skip", "stop", "leave"],
async execute(message, args, cmd, client, Discord) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) {
return message.channel.send({
content: "You need to be in a channel to execute this command!",
});
}
const permissions = voiceChannel.permissionsFor(message.member);
if (!(permissions.has('CONNECT')) || !(permissions.has('SPEAK'))) {
return message.channel.send({
content: "You don't have the correct permissions!",
});
}
const serverQueue = queue.get(message.guild.id);
if (cmd == "play") {
if (!(args.length)) {
return message.channel.send({
content: "Invalid song link!",
});
}
let song = {};
if (ytdl.validateURL(args[0])) {
const songInfo = await ytdl.getInfo(args[0]);
song = { title: songInfo.videoDetails.title, url: songInfo.videoDetails.video_url }
} else {
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(" "));
if (video) {
song = { title: video.title, url: video.url }
} else {
message.channel.send({
content: `No video results found!`
})
}
}
if (!(serverQueue)) {
const queueConstructor = {
voiceChannel: voiceChannel,
textChannel: message.channel,
connection: null,
player: null,
songs: [],
}
queue.set(message.guild.id, queueConstructor);
queueConstructor.songs.push(song);
try {
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.member.voice.channel.guild.id,
adapterCreator: message.member.voice.channel.guild.voiceAdapterCreator,
});
queueConstructor.connection = connection;
const player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause
}
});
queueConstructor.player = player;
videoPlayer(message.guild, queueConstructor.songs[0]);
} catch (error) {
queue.delete(message.guild.id);
message.channel.send({
content: `There was an error connecting!`
})
throw error;
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
return message.channel.send({
content: `${song.title} added to the queue!`
})
}
} else if (cmd == "skip") {
// TODO
} else if (cmd == "leave") {
// TODO
}
}
}
const videoPlayer = async (guild, song) => {
const songQueue = queue.get(guild.id);
if (!(song)) {
songQueue.player.stop();
songQueue.connection.destroy();
queue.delete(guild.id);
return;
}
const stream = await ytdl(song.url, { filter: "audioonly" });
const songStream = await (createAudioResource(stream));
const subscription = songQueue.connection.subscribe(songQueue.player);
const dispatcher = songQueue.player.play(createAudioResource(stream)).on("finish", () => {
songQueue.songs.shift();
songQueue.playing = false;
videoPlayer(guild, songQueue.songs[0]);
songQueue.textChannel.send({
content: `Now playing: ${song.title}`
});
});
}
player.addListener("stateChange", (oldOne, newOne) => {
if (newOne.status == "idle") {
console.log("The song finished");
}
});
Use event stateChange. It called when voice state change from oldOne to newOne. (ex: playing -> idle)
newOne { status: "playing | idle | buffering | ..." }

My music play command isn't working or sending any error, how can I fix this?

I am trying to make a my bot play music, and so when I run my command, it doesn't show any error or joining the vc. however when I'm not in the vc it does send me a message telling me to execute this command after joining the vc. I do have Ytdl and YtSearch installed ofcourse, but I can't figure out how to fix this. I'm using repl btw. I'm using Aliases for the skip and stop command.
The code is below.
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
description: 'Plays music',
async execute(message, args, cmd, client, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}

Resources