[英]Discord.JS UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined
I'm currently trying to implement speech recognition into a discord bot, but I keep running into errors.我目前正在尝试将语音识别实现到一个不和谐的机器人中,但我一直遇到错误。 I'm also new to Discord.JS and programming as a whole.
我也是 Discord.JS 和整个编程的新手。
I copied some of the following code from an event file that interprets normal messages instead of speech, and it works fine there.我从解释正常消息而不是语音的事件文件中复制了以下一些代码,并且在那里工作正常。
The following line throws an "UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined": if (!msg.content.startsWith(prefix) || msg.author.bot) return;
下面这行抛出一个“UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'startsWith' of undefined”:
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
My entire file:我的整个文件:
const fs = require('fs');
module.exports = {
name: "join",
description: "Joins the VC that user is in",
async execute(client, message, args, Discord) {
const voiceChannel = message.member.voice.channel;
const connection = await voiceChannel.join();
if (!voiceChannel) return message.channel.send('Join a VC retard');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send("You don't have the correct permissions");
if (!permissions.has('SPEAK')) return message.channel.send("You don't have the correct permissions");
connection.client.on('speech', msg => {
console.log(msg.content);
const prefix = 'yo bot ' || 'Aries ' || 'Ares ' || 'yobot ';
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd);
if (command) command.execute(client, msg, args, Discord);
})
}
}
If message content is not a string then you cannot use that function.如果消息内容不是字符串,则不能使用该函数。
You need to check if message content exists first:您需要先检查消息内容是否存在:
if (!msg.content
|| !msg.content.startsWith(prefix)
|| msg.author.bot
) {...}
You need to make sure that the message content is defined, before reading it's startsWith
property.在阅读它的
startsWith
属性之前,您需要确保已定义消息内容。 You can do this with optional chaining .您可以使用可选链接来做到这一点。
if (!msg?.content?.startsWith(prefix) || msg.author.bot) return;
msg?.content?.startWith(prefix)
will return undefined if either: msg?.content?.startWith(prefix)
将返回 undefined ,如果:
msg
does not have a content
propery msg
没有content
属性content
does not have a startWith
property content
没有startWith
属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.