[英]Discord.js | TypeError: Cannot read property 'voice' of undefined
最近我一直在 discord.js 中开发我的自定义 discord bot。
今天,我修改了我的命令处理程序,并在尝试使用我的 .play 命令通过我的机器人播放音乐时遇到了这个错误:
(node:481) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of undefined
at Object.execute (/home/runner/MaikuBot/commands/play.js:14:46)
at Client.<anonymous> (/home/runner/MaikuBot/index.js:29:34)
at Client.emit (events.js:314:20)
at Client.EventEmitter.emit (domain.js:483:12)
at MessageCreateAction.handle (/home/runner/MaikuBot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31) at WebSocketShard.onPacket (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22) at WebSocketShard.onMessage (/home/runner/MaikuBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10) at WebSocket.onMessage (/home/runner/MaikuBot/node_modules/ws/lib/event-target.js:132:16) (node:481) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
所以这是我的 .play 命令代码:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { MessageEmbed } = require('discord.js');
var volume = 0.5;
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['p', 'skip', 'clear', 'volUp', 'volDown'],
cooldown: 0,
description: "Play music trought bot",
async execute(client, message, args, cmd, Discord) {
const voice_channel = message.member.voice.channel;
if (voice_channel != null) {
if (!voice_channel) {
return message.reply("Devi essere in un canale vocale.");
}
const server_queue = queue.get(message.guild.id);
//If the user has used the play command
if (cmd === 'play' || cmd === 'p'){
if (!args.length) return message.reply('Per favore completa il comando!');
let song = {};
//If the first argument is a link. Set the song object to have two keys. Title and URl.
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 {
//If there was no link, we use keywords to search for a video. Set the song object to have two keys. Title and URl.
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('Non ho trovato il video...');
}
}
//If the server queue does not exist (which doesn't for the first video queued) then create a constructor to be added to our global queue.
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
//Add our key and value pair into the global queue. We then use this to get our server queue.
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
//Establish a connection and play the song with the vide_player function.
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("C'è stato un errore durante la connessione al canale...");
throw err;
}
} else{
server_queue.songs.push(song);
const Embed = new MessageEmbed()
.setTitle(`🎶 Ho aggiunto "**${song.title}**" alla coda`)
.setColor('#36393F')
.setAuthor('maiku', 'https://i.ibb.co/MCkG7wV/M-ROSSA-500.png', 'https://discord.gg/QNhpmbG3Sm')
.setDescription(`[**Brano aggiunto alla coda corretamente**]`);
await server_queue.text_channel.send(Embed);
console.log(`[ll] Ho aggiunto "${song.title}" alla coda`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'clear') clear_song(message, server_queue);
else if(cmd === 'volUp') volUp(message, server_queue);
else if(cmd === 'volDown') volDown(message, server_queue);
}
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
//If no song is left in the server queue. Leave the voice channel and delete the key and value pair from the global queue.
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: volume })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
const Embed = new MessageEmbed()
.setTitle(`🎶 Sto riproducendo "**${song.title}**"`)
.setColor(0xFF0000)
.setAuthor('maiku', 'https://i.ibb.co/MCkG7wV/M-ROSSA-500.png', 'https://discord.gg/QNhpmbG3Sm')
.setDescription(`[**Brano riprodotto correttamente**]`);
await song_queue.text_channel.send(Embed);
console.log(`[>] Sto riproducendo "${song.title}"`);
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
if(!server_queue){
return message.channel.send(`Non ci sono canzoni da skippare`);
}
message.react('👍');
console.log(`[!] Brano skippato con successo`);
server_queue.connection.dispatcher.end();
}
const clear_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
message.react('👍');
server_queue.connection.dispatcher.end();
server_queue.songs = [];
console.log(`[!] Coda azzerata`);
}
const volUp = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
message.react('👍');
volume = volume + 0.5;
console.log(`[?] Volume aumentato di 0.5`);
}
const volDown = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('Devi essere in un canale vocale.');
message.react('👍');
if (volume > 0.5) {
volume = volume - 0.5;
console.log(`[?] Volume diminuito di 0.5`);
}
console.log(`[?] Volume non diminuito [valore minimo raggiunto]`);
}
我尝试查看类似的错误,但使用不同的代码,但这些修复程序都不适用于我。 你能帮我解决这个问题吗? 谢谢
也看看命令处理程序
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args, client, Discord);
} catch (error) {
console.error(error);
message.reply(`Si è verificato un errore durante l'esecuzione del comando...`);
}
})
我不知道 Discord.js 库实际上做了什么,但错误告诉你message
中的 param member
是undefined
。 也许是因为您在执行时发送的第一个参数不是client
,而是message
。
我认为应该是:
client.commands.get(command).execute(client, message, args, command, Discord);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.