如果您有一个前缀数组,则无法将其与字符串的第一个字符进行比较。每次都是假的。您应该将字符串与字符串进行比较,因此您应该将数组的元素与消息进行比较。
您可以对数组使用.some() 方法来检查数组中是否至少有一个元素通过了提供的函数实现的测试。在该函数中,您可以检查消息 startsWith() 是否存在数组中的任何字符串。
如果message 以array 中的任何字符串开头,则类似array.some(el => message.startsWith(el)) 的函数会返回true。
检查以下sn-p。您可以查看如何同时使用 .some() 和 .startsWith():
let message = '';
const prefixes = [ '#', 'br', 'bread', '<@767558534074204191>', '<@!767558534074204191>', ];
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = 'lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = '# lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = 'br lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = 'bread lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = '<@767558534074204191> lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
message = '<@!767558534074204191> lorem ipsum'
console.log(prefixes.some(prefix => message.startsWith(prefix)), message)
您的代码将如下所示:
const prefixes = [
'#',
'br',
'bread',
'<@767558534074204191>',
'<@!767558534074204191>',
];
module.exports = async function(msg) {
let tokens = msg.content.split(' ');
let command = tokens.shift();
if (prefixes.some(prefix => command.startsWith(prefix))) {
command = command.substring(1);
commandName[command](msg, tokens);
}
};
更新:我刚刚检查并注意到您尝试使用 command.substring(1) 从命令中删除前缀。硬编码的1 将始终只删除第一个字符,因此您需要将其更改为前缀的长度。
目前,使用.some() 您不知道使用哪个前缀,因此最好使用.find() 方法,该方法返回提供的数组中满足提供的测试功能的第一个元素的值。这样,您可以检查消息是否包含任何前缀,并且您知道前缀及其长度。运行以下sn -p 是如何工作的:
// I changed the order of prefixes as bread starts with br
const prefixes = [ '#', 'bread', 'br', '<@767558534074204191>', '<@!767558534074204191>', ];
let prefix = '';
let command = '';
command = 'lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
command = '# lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
command = 'br lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
command = 'bread lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
command = '<@767558534074204191> lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
command = '<@!767558534074204191> lorem ipsum'
prefix = prefixes.find((prefix) => command.startsWith(prefix));
console.log({command, prefix});
所以您修改后的代码将如下所示:
client.on('message', (msg) => {
let tokens = msg.content.split(' ');
let command = tokens.shift();
let prefix = prefixes.find((prefix) => command.startsWith(prefix));
if (prefix) {
command = command.substring(prefix.length);
commandName[command](msg, tokens);
}
});