需要发送消息两次才能得到回复

Need to send message twice in order to get a response

当我这里有这段代码时:

    client.on("message", msg => {
    const args = msg.content.trim().split(/ +/g);
    let second = args[1];
    let x = Math.floor((Math.random() * second) + 1);
    if(msg.content === "random") {
    msg.channel.send(`${x}`)
    console.log(x)
    console.log(second)
    }
    })

我需要发送“随机 10(示例)”两次,但它仍然不起作用,因为它使用“随机”作为“第二个”的输入——我如何使它起作用?

由于“msg”是一个字符串,在对其进行操作之前,您需要将其解析为一个整数。我建议用以下内容替换“let x”行:

let x = Math.floor((Math.random() * parseInt(second)) + 1);

parseInt 是一个内部函数,它将带有数字内容的字符串转换为整数。

const triggerWords = ['random', 'Random'];

client.on("message", msg => {
  if (msg.author.bot) return false;
  const args = msg.content.trim().split(/ +/g);
    let second = args[1];
    let x = Math.floor((Math.random() * parseInt(second)) + 1);

  triggerWords.forEach((word) => {
    if (msg.content.includes(word)) {
      msg.reply(`${x}`);
    }
  });
});

为了补充 quandale dingle 的回答,您可以使用您的机器人创建一个命令处理程序,这将使开发过程更加容易并且看起来不错。如果你真的不想创建一个命令处理程序,你也可以使用下面的代码:

 if (message.content.startsWith(prefix)){
        //set a prefix before, and include this if statement in the on message
          const args = message.content.slice(prefix.length).trim().split(/ +/g)
          const commandName = args.shift().toLowerCase()
        //use if statements for each command, make sure they are nested inside the startsWith statement
        }

如果您想创建一个命令处理程序,下面有一些示例代码。它适用于 discord.js v13,但我不知道它是否适用于 v12。这是一个更高级的命令处理程序。

 /*looks for commands in messages & according dependencies
 or command handler in more simple terms*/
 const fs = require("fs");
 const prefix = "+"; //or anything that's to your liking
 client.commands = new Discord.Collection();
 fs.readdirSync("./commands/").forEach((dir) => {
 const commandFiles = fs.readdirSync(`./commands/${dir}/`).filter((file) =>
       file.endsWith(".js")
 ); //subfolders, like ./commands/helpful/help.js

 //alternatively... for a simpler command handler
 fs.readdirSync("./commands/").filter((file) =>
    file.endsWith(".js")
 );
 for (const file of commandFiles) {
    const commandName = file.split(".")[0]
    const command = require(`./commands/${file}`);
    client.commands.set(commandName, command);
 }
 });
    
    
    
 //looks for commands in messages
 client.on("messageCreate", message => {
 if (message.author == client.user) return;
 if (message.content.startsWith(prefix)){
    const args = message.content.slice(prefix.length).trim().split(/ +/g)
    const commandName = args.shift().toLowerCase()
    const command = client.commands.get(commandName)
    if (!command) return;
    command.run(client, message, args)
 }
 });