【问题标题】:Discord.js On message command not workingDiscord.js 关于消息命令不起作用
【发布时间】:2023-03-03 03:31:02
【问题描述】:

Discord.js 问题 我应该指出我在 discord.js 方面没有经验。 我有以下代码应该将用户请求的总和或表达式更改为实际的答案和消息。我的另一个命令正在工作,但另一个不是这里的代码:

client.once("message", msg => {
    if(msg.content.includes("!simple")){
       math = Number(msg.content.slice(msg.content.search("e")))
msg.reply(guild.username + "The answer is " + math )


    }
})

我基本上是通过 slice 方法删除命令部分,然后使用 Number 函数计算它的值并随后返回它,但我没有得到机器人的响应。任何帮助表示赞赏

【问题讨论】:

  • once 只会监听第一个事件,也许使用on 代替
  • 而且我不认为msg.content 是一个数组,所以msg.content.splice 会抛出一个错误。
  • 没有拼接方法吗?我用过切片?
  • 我认为使用message.content 的最佳方式是if (message.content == "!simple") {
  • 通常我会同意,但在这种情况下,我需要用户在 !simple 命令之后包含输入

标签: javascript node.js api discord.js


【解决方案1】:

我会这样处理

client.on("message",message=>{

  if(!message.content.startsWith("!simple") return ;//if the message does not start with simple return
  const args=message.content.slice(6).trim().split(/ +/);//splits the command into an array separated by spaces
  const command=args.shift().toLowerCase();//removes the command (!simple in this case)
//now you can acces your arguments args[0]..args[1]..args[n]
  });

【讨论】:

    【解决方案2】:

    我不确定你所说的“请求的总和或表达式”是什么意思?

    client.on('message', msg => {
      if (msg.content.startsWith('!simple')) {
        var tocalc = msg.content.substr(8);
        if (!tocalc.match(/^[\d\(\)\+\-\/\*e\.%=!\s]+$/)) { // allowed = ['number', '(', ')', '+', '-', '*', '/', 'e', '.', '%', '=', '!', ' ']
            msg.reply('no valid expression or calculation');
            return;
        }
        var result;
        try {
            result = Function('return ' + tocalc)();
        } catch(e) {
            console.error(`tried to exploit! ban user ${msg.author.id}!`);
            return;
        }
        if (isNaN(result)) {
            console.error(`tried to exploit! ban user ${msg.author.id}!`);
            return;
        }
        msg.reply(result);
      }
    });
    
    !simple 1 + 8 - (4 * .25) // 8
    !simple 1 == 1 // true
    !simple 9 % 2 != 8 % 2 // true
    

    【讨论】:

      【解决方案3】:

      与此同时,Discord 更改了他们的 API。 client.on("message") 现已弃用。 2021 年的工作示例如下所示:

      const { Client, Intents } = require('discord.js');
      const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
      
      client.on("messageCreate", (message) => {
        if (message.author.bot) return false; 
        
        console.log(`Message from ${message.author.username}: ${message.content}`);
      });
      
      client.login(process.env.BOT_TOKEN);
      

      启动需要明确的权限才能读取消息。如果机器人没有该权限,则不会触发 onmessageCreate 事件。

      【讨论】:

      • 你救了我!这甚至没有记录在任何地方。可悲的是,互联网上到处都是过时的方法。非常感谢!
      猜你喜欢
      • 2021-07-24
      • 2018-08-26
      • 2021-07-25
      • 2021-09-04
      • 2021-11-19
      • 2018-07-28
      • 1970-01-01
      • 2017-12-30
      • 2020-11-26
      相关资源
      最近更新 更多