You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人存款命令Bug求助:输入整数却提示需为整数

Fix for "Deposit amount must be a whole number" Error in Discord Bot Deposit Command

Hey there, let's break down why your deposit command is incorrectly throwing that error message even when you input valid whole numbers like 100.

The Root Cause

The problem is straightforward: when you grab args[0], it’s a string value, not a number. When you try to run amount % 1 != 0 on a string (like "100"), JavaScript can’t handle the modulus operation properly—it returns NaN, which evaluates to true in your condition. That’s why the error pops up every single time, no matter what valid number you input.

The Fix

We need to convert the input string to an actual integer first, plus add a check to make sure the conversion worked (to handle non-numeric inputs). Here’s your updated deposit.js code:

const profileModel = require("../models/profileSchema");
module.exports = {
  name: "deposit",
  aliases: ["dep"],
  permissions: [],
  description: "Deposit gold into your bank!",
  async execute(message, args, cmd, client, discord, profileData) {
    // Convert the input string to an integer
    const amount = parseInt(args[0]);
    
    // Updated validation: catch invalid conversions, non-whole numbers, and negative/zero values
    if (isNaN(amount) || amount % 1 !== 0 || amount <= 0) {
      return message.channel.send("Deposit amount must be a whole number");
    }
    
    try {
      if (amount > profileData.gold) {
        return message.channel.send(`You don't have that amount of gold to deposit`);
      }
      
      await profileModel.findOneAndUpdate(
        { userID: message.author.id },
        {
          $inc: {
            gold: -amount,
            bank: amount,
          },
        }
      );
      
      return message.channel.send(`You deposited ${amount} of gold into your bank`);
    } catch (err) {
      console.log(err);
    }
  },
};

Key Changes Explained

  • parseInt(args[0]): Turns the string input into an integer. If someone inputs something non-numeric (like -deposit abc), this returns NaN.
  • isNaN(amount): Adds a check to catch those non-numeric inputs before proceeding.
  • Now that amount is a proper number, the amount % 1 !== 0 check will correctly flag any non-whole numbers (though parseInt already truncates decimals, this is a good safeguard for inputs like 100.5).

Don’t Forget the Withdraw Command

Since you mentioned the withdraw command has the same structure, you’ll need to apply the exact same fix there too—convert args[0] to an integer with parseInt() and update the validation condition to include isNaN(amount). That’ll prevent the same error from popping up when users try to withdraw funds.

内容的提问来源于stack exchange,提问作者KazTeko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:47:32