Discord.js如何使用机器人提及和一组前缀作为前缀



我想这样做,如果我执行[prefix] [command],它将产生与[mention bot] [command]相同的效果,但我创建命令和参数的方式使这变得困难:

前缀存储为var prefix = '!3';

这就是我创建命令的方式:

bot.on('message', msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot)
return;
//the first message after '!13 '
//!
let args = msg.content.toLowerCase().substring(prefix.length).split(" ");
//^
//any capitalisation is allowed (ping,Ping,pIng etc.)
switch(args[1]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}//switch (command) ends here
};//event listener ends here

您可以有一个预定义前缀的列表,并在其上循环以确定msg是否有该列表中的前缀。

let prefixList = ['!31 ', '!asdf ', `<@${bot.user.id}> `, `<@!${bot.user.id}> `]
function hasPrefix(str) {
for(let pre of prefixList)
if(str.startsWith(pre))
return true;
return false;
}

<@${bot.user.id}><@!${bot.user.id}>将设置机器人提及作为前缀。

我假设您运行的是旧版本的Discord.js,因为如果您使用的是v13message,那么它是不复杂的,应该是messageCreate,但这是我在不使用斜杠命令时使用的。

const escapeRegex = str => str.replace(/[.*+?^${}()|[]\]/g, '\$&')
const prefix = '!'
bot.on('message', async msg => {
const prefixRegex = new RegExp(`^(<@!?${bot.user.id}>|${escapeRegex(prefix)})\s*`)
if (!prefixRegex.test(message.content)) return
// checks for bot mention or prefix
const [, matchedPrefix] = message.content.match(prefixRegex)
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/)
// removes prefix or bot mention
const command = args.shift().toLowerCase()
// gets command from next arg
if (command === 'ping') {
msg.channel.send('Pong!')
}
})

以下是secretlyrice's答案的较短版本:

const startsWithPrefix = (command) => 
['!prefix1 ', '!prefix2', <@botId>, <@!botId>].some(p => command.startsWith(p))

代码不错,但将其1更改为0

switch(args[0]) {
case 'ping': //if user inputs '!3 ping'
msg.channel.send('Pong!') //send a message to the channel 'Pong!'
}

最新更新