Discord机器人存款命令Bug求助:输入整数却提示需为整数
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 returnsNaN.isNaN(amount): Adds a check to catch those non-numeric inputs before proceeding.- Now that
amountis a proper number, theamount % 1 !== 0check will correctly flag any non-whole numbers (thoughparseIntalready truncates decimals, this is a good safeguard for inputs like100.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

