代码之家  ›  专栏  ›  技术社区  ›  THOMAS Corentin

不一致js |拆分消息

  •  0
  • THOMAS Corentin  · 技术社区  · 7 年前

    我对开发领域还很陌生,我想练习做JS,我了解到Discord机器人可以用这种语言完成,我觉得练习很酷。

    我的问题是:我想将命令与消息的其余部分分开。我设法将命令与单词分开,但当我输入几个单词时,它就不起作用了。这就是它所做的:

    (!Command HELLO”将发送“Command+HELLO”,但“!Command HELLO HI”将不起作用)

    const PREFIX = "!";
    bot.on('message', function(message) {
    	if(message.content[0] === PREFIX) {
    		let splitMessage = message.content.split(" ");
    		if(splitMessage[0] === '!command') {
    			if(splitMessage.length === 2) {
    				message.channel.send('Command + ' + splitMessage[1]);
    			}
    		}
    	}
    });

    谢谢

    2 回复  |  直到 5 年前
        1
  •  0
  •   Ryan Wilson    7 年前

    正如我在评论中所说:

        const PREFIX = "!";
        bot.on('message', function(message) {
            if(message.content[0] === PREFIX) {
                let command = message.content.substring(message.content.indexOf(" ") + 1, message.content.length);
                message.channel.send('Command + ' + command);
            }
        });
    
        2
  •  0
  •   Jonas Wilms    7 年前
     splitMessage[1]
    

    这将从拆分的数组中提取第二个单词。因此 Command! Hello world 会的 Hello . 您可能希望从拆分消息中提取第一个元素之后的所有内容,如下所示:

    splitMessage.slice(1)
    

    返回 ["Hello", "World"] ,所以只需将其连接回字符串

     .join(" ")
    

    我将如何做到这一点:

      const [command, ...args] = message.content.split(" ");
    
      switch(command){
        case "!Command":
           message.channel.send('Command + ' + args.join(" "));
        break;
        //....
      }