简体   繁体   English

Discord.js | 拆分一条消息

[英]Discord.js | split a message

I'm pretty new to the development world, I wanted to practice doing JS, and I learned that Discord bots could be done in this language, I found it cool to practice. 我对开发世界还很陌生,我想练习使用JS,并且了解到Discord机器人可以用这种语言完成,我发现练习起来很酷。

My problem: I want to separate the command from the rest of the message. 我的问题:我想将命令与其余消息分开。 I managed to separate the command from a word, but when I enter several words, it does not work. 我设法将命令与单词分开,但是当我输入多个单词时,它不起作用。 This is what it does: 这是它的作用:

(!Command HELLO" will send "Command + Hello", but "!command HELLO HI" will not work) (!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]); } } } }); 

Thanks 谢谢

 splitMessage[1]

that takes the second word from the splitted array. 从拆分数组中获取第二个单词。 So with Command! Hello world 因此,使用Command! Hello world Command! Hello world it will be Hello . Command! Hello world Hello You might want to take everything after the first element from the split Message like so: 您可能希望将所有内容都放在拆分后的消息的第一个元素之后,如下所示:

splitMessage.slice(1)

that returns ["Hello", "World"] , so you just need to join it back to a string 返回["Hello", "World"] ,因此您只需要将其连接回字符串即可

 .join(" ")

How i would do that: 我该怎么做:

  const [command, ...args] = message.content.split(" ");

  switch(command){
    case "!Command":
       message.channel.send('Command + ' + args.join(" "));
    break;
    //....
  }

As I stated in the comment: 正如我在评论中所述:

    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);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM