试图让Spotify命令工作Discord JS



我的bot运行spotify命令时遇到问题。上面写着Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'type')

这是基于我朋友发给我的代码和discord.js网站。

main.js:在discordjs.guide的帮助下从头开始构建。这需要一段时间才能实现,但我怀疑这里的某些东西可能也是罪魁祸首。

const fs = require('fs');
const Discord = require('discord.js');
const config = require('./handlers/config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
require('dotenv').config();
//Client Login
client.on("ready", ()=>{
client.user.setActivity("JS: v.0.1.ch1r.canary", {type: "PLAYING"});
console.log('Chikyoko Haruka>> System is now loaded and is ready to have fun!');
const logch = client.channels.cache.get(process.env.chid);
const online = {
color: 0x0099ff,
title: 'Beep Boop...',
description: `Chiyoko Haruka is now active!`,
thumbnail: {
url: 'https://64.media.tumblr.com/02dabf2a7299753f442feee1512e326c/tumblr_o2qhk8IoJs1tydz8to1_500.gif',
},
timestamp: new Date(),
footer: {
text: config.BOT_NAME +': ' + config.BOT_VERSION ,
},
};
logch.send({ embed: online });
});
//Client Start
client.login(process.env.TOKEN);
//command handler
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);
}
//Command Starter
client.on('message', message => {
if (!message.content.startsWith(config.PREFIX) || message.author.bot) return;
const args = message.content.slice(config.PREFIX.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).run(client, message, args);
} catch (error) {
console.error(error);
const err = {
color: 0x0099ff,
title: 'Beep Boop...',
description: 'Error! Failed to execute command (╯°□°)╯︵ ┻━┻ ' + `${error}`,
thumbnail:{
url:'https://c.tenor.com/_3mSq0fET5oAAAAC/tenor.gif',
},
timestamp: new Date(),
footer: {
text: config.BOT_NAME +': ' + config.BOT_VERSION ,
},
};
message.channel.send({ embed: err });
}
});

spotify.js:基于我朋友发给我的代码,但添加了我自己的错误代码,从35:39开始这就是if (status !== null && status.type === "LISTENING" && status.name === "Spotify" && status.assets !== null) {。我不明白为什么我朋友发给我的机器人能工作,但它对正在构建的机器人不起作用。我甚至无法确定这个问题,所以我在这一点上非常不清楚。

const Discord = require('discord.js');
const convert = require('parse-ms');
const config = require('../handlers/config.json');

module.exports = {
name: "spotify",
category: "Utility",
description: 'Gives the info of the song in which the mentioned user is litening to spotify',
run: async (client, message, args) => {

const user = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member;
let status;
if (user.presence.activities.length === 1) status = user.presence.activities[0];
else if (user.presence.activities.length > 1) status = user.presence.activities[1];
if (user.presence.activities.length === 0 || status.name !== "Spotify" && status.type !== "LISTENING") {
const spotifyerr = {
color: 0x0099ff,
title: 'Beep Boop...',
description: user.displayName + ' is not listening to spotify!',
thumbnail:{
url:'https://c.tenor.com/_3mSq0fET5oAAAAC/tenor.gif',
},
timestamp: new Date(),
footer: {
text: config.BOT_NAME +': ' + config.BOT_VERSION ,
},
};
message.channel.send({ embed: spotifyerr });
}
if (status !== null && status.type === "LISTENING" && status.name === "Spotify" && status.assets !== null) {
let image = `https://i.scdn.co/image/${status.assets.largeImage.slice(8)}`,
url = `https:/open.spotify.com/track/${status.syncID}`,
name = status.details,
artist = status.state,
album = status.assets.largeText,
timeStart = status.timestamps.start,
timeEnd = status.timestamps.end,
timeConvert = convert(timeEnd - timeStart);
let minutes = timeConvert.minutes < 10 ? `0${timeConvert.minutes}` : timeConvert.minutes;
let seconds = timeConvert.seconds < 10 ? `0${timeConvert.seconds}` : timeConvert.seconds;
let time = `${minutes}:${seconds}`;
const embed = new Discord.MessageEmbed()
.setAuthor(user.user.tag, user.user.displayAvatarURL({ dynamic: true }))
.setTitle("Listening to Spotify !!")
.setColor('RANDOM')
.setThumbnail(image)
.addField("Song Name:", ````${name}````, true)
.addField("Album:", ````${album}````, true)
.addField("Artist:", ````${artist}````, true)
.addField("Duration:", ````${time}````, false)
.addField("Listening Now!", `[`${artist} - ${name}`](${url})`)
.setFooter(`Requested by ${message.author.username}`,  message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
return message.channel.send(embed)
}

}
}

根据请求,以下是完整的错误日志:

Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'type')
at run (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarycommandsspotify.js:35:39)
at <anonymous> (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarymain.js:47:32)
at emit (events:527:28)
at handle (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_modulesdiscord.jssrcclientactionsMessageCreate.js:31:14)
at module.exports (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_modulesdiscord.jssrcclientwebsockethandlersMESSAGE_CREATE.js:4:32)
at handlePacket (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:384:31)
at onPacket (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:444:22)
at onMessage (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:301:10)
at onMessage (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibevent-target.js:132:16)
at emit (events:527:28)
at receiverOnMessage (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibwebsocket.js:1068:20)
at emit (events:527:28)
at dataMessage (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibreceiver.js:517:14)
at getData (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibreceiver.js:435:17)
at startLoop (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibreceiver.js:143:22)
at _write (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibreceiver.js:78:10)
at writeOrBuffer (internal/streams/writable:389:12)
at _write (internal/streams/writable:330:10)
at Writable.write (internal/streams/writable:334:10)
at socketOnData (c:UsersftautDesktopChiyoko Haruka-v0.1.ch1r.canarynode_moduleswslibwebsocket.js:1162:35)
at emit (events:527:28)
at addChunk (internal/streams/readable:315:12)
at readableAddChunk (internal/streams/readable:289:9)
at Readable.push (internal/streams/readable:228:10)
at onStreamRead (internal/stream_base_commons:190:23)
at callbackTrampoline (internal/async_hooks:130:17)

错误在spotify.js:39是这个代码:

if (status !== null && status.type === "LISTENING" && status.name === "Spotify" && status.assets !== null) {

错误在main.js:47:32是这个代码:

client.commands.get(command).run(client, message, args);

ps:请向我详细解释(如果可以的话(这个问题,这样我就可以了解为什么会发生这种情况。

这是因为您正在检查status !== null,但statusundefined,而undefinednull不同。

只需检查status是否属实:

if (status && status.type === "LISTENING" ...