【问题标题】:discord bot custom command JSdiscord bot自定义命令JS
【发布时间】:2017-08-31 01:39:54
【问题描述】:

我正在尝试使用 Discord,js-commando 库编写一个简单的 Discord 机器人,到目前为止,我已经完成了大部分工作,但我现在遇到了一个问题,所以我得到了这个命令,你可以这样做!滚动,它会随机选择一个从 1 到 6 的数字,但我想让它更加自定义,所以它看起来像这样

!roll(从 1 滚动到 6)

!roll 25(从 1 滚动到 25)

!roll 100 200(从 100 滚动到 200)

问题是当我尝试执行 !roll 25 时,我的验证一直说它不是一个有效的数字,但所有其他命令都可以正常工作,只有当我执行 !roll 然后一些我无法弄清楚的数字时才会发生为什么它不起作用它可能是一个简单的修复提前谢谢

const commando = require('discord.js-commando')
const _ = require('lodash')

 class DiceRollCommand extends commando.Command {

    constructor(bot) {
        super(bot, {
            name: 'roll',
            group: 'random',
            memberName: 'roll',
            description: 'Rolls a dice.'
        })
    }

    async run(message, args) {
        let roll = args.split(' ')
        let hasNumber = /^[0-9]$/

        if (roll[0] || roll[1]) {
            if (!hasNumber.test(roll[0]) || !hasNumber.test(roll[1])) {
                console.log('roll[1] -> '+ !hasNumber.test(roll[0])) // returns true
                console.log('roll[2] -> '+ !hasNumber.test(roll[1])) // returns true

                message.reply('[DEBUG] Syntax Error input must be a number')
                return
            }
        }
        if (roll.length >= 3) {
            message.reply('[DEBUG] Syntax Error cannot use more than 2 parameters')
            return
        }
        if (roll[0] > 1000000 || roll[1] > 1000000) {
            message.reply('Unfortunately for you, computers have a limited amount of memory, so unless you want me to run out, stop sending ludicrous numbers. Thanks.')
            return
        }
       if (message.content.match(/^!roll$/)) {
           message.reply('rolled ' + _.random(1, 6))
       }
       if (message.content.match(/^!roll [0-9]+\b/)) {
           message.reply('rolled ' + _.random(1, roll[0]))
       }
       if (message.content.match(/^!roll ([0-9]*) ([0-9]*)+\b/)) {
           message.reply('rolled ' + _.random(roll[0], roll[1]))
       }

    }

}

module.exports = DiceRollCommand

【问题讨论】:

    标签: javascript node.js discord


    【解决方案1】:
    let hasNumber = /^[0-9]$/
    

    您的正则表达式仅测试 1 位数字。试试:

    let hasNumber = /^[0-9]+$/
    

    【讨论】:

      【解决方案2】:

      尝试改变

      if (!hasNumber.test(roll[0]) || !hasNumber.test(roll[1])) {
      

      if (!hasNumber.test(roll[0]) && !hasNumber.test(roll[1])) {
      

      并尝试将您的hasNumber 正则表达式更改为/^[0-9]+$/,否则它可能会在任何多于一位的数字上失败。

      【讨论】:

      • 谢谢你这样做;)
      • 这仍然是错误的,因为 ["b", "3"] 将通过数字验证
      • ["b", "3"] 是什么意思?据我所知,现在一切正常
      猜你喜欢
      • 2021-12-20
      • 2021-08-07
      • 2020-10-31
      • 2022-01-20
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2020-10-25
      相关资源
      最近更新 更多