Tmi.js 如何让 bot 命令带参数

问题描述

我不知道如何让我的聊天机器人在命令后接受 args。

示例:!poll weights [50,60,75]

代码

client.on('message',(target,context,msg,self) => {
  if (self) { return; }
  const msgcon = msg.trim();
  if (msgcon.startsWith('!')) {
    if (msgcon === '!poll') {
        client.say(target,'')
        console.log(`* Executed ${msgcon} command at ${target}`);
    } else {
        console.log(`* UnkNown command ${msgcon} attempted at ${target}`);
    }
  }
});

我如何让它接受 args?

解决方法

因为 message 的参数类型只是一个字符串,您可以使用 .split 方法将其拆分。

const PREFIX = "!";
let [command,...args] = message.slice(PREFIX.length).split(/ +/g); 

if (command == "!test") {
 console.log({ command,args })
}

如果用户在聊天中说什么写!test one two three,它会输出:

{
  command: "!test",args: ["one","two","three"]
}

意味着您可以通过键入 args[x] 来访问每个参数(请记住,javascript 从 0 开始计数)


解释:本质上我正在做的是获取类型为字符串的消息并使用 .slice 方法删除前缀(更清洁的命令值),然后为每个空格拆分消息将其放入数组的字符串。数组中的第一项将设置为命令,其余为参数。


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice