关于quick.db实现货币余额增减及抢劫功能Bug的技术求助
问题修复方案
问题1:抢劫后余额无变化的原因及修复
你的代码存在变量混淆和操作对象错误:
author2错误使用了目标用户的ID,应该获取**发起抢劫的用户(message.author)**的余额- 扣款和加款操作都针对了同一个用户(目标用户),导致数值抵消,正确逻辑是:从目标用户余额扣除随机金额,加到发起抢劫的用户余额中
问题2:允许用户抢劫自己的修复
在代码开头增加判断,如果被@的用户是发起者本人,直接阻止操作并提示。
完整修正代码
const Discord = require("discord.js"); const db = require("quick.db"); const ms = require("parse-ms"); module.exports.run = async (bot, message, args) => { if(!message.content.startsWith('db!'))return; let user = message.mentions.members.first() // 新增:阻止抢劫自己 if (!user || user.id === message.author.id) { return message.channel.send(new Discord.RichEmbed().setColor("#FFFFFF").setDescription("❌ 你不能抢劫自己!")); } // 修正变量:明确区分发起者和目标用户的数据 let targetBalance = await db.fetch(`money_${message.guild.id}_${user.id}`) || 0; let authorRobCooldown = await db.fetch(`rob_${message.guild.id}_${message.author.id}`); let authorBalance = await db.fetch(`money_${message.guild.id}_${message.author.id}`) || 0; let timeout = 600000; if (authorRobCooldown !== null && timeout - (Date.now() - authorRobCooldown) > 0) { let time = ms(timeout - (Date.now() - authorRobCooldown)); let timeEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ 你已经抢劫过了\n\n请等待 ${time.minutes}m ${time.seconds}s 后再试`); message.channel.send(timeEmbed) } else { let moneyEmbed = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ 你的钱包里至少需要200个金币才能抢劫别人`); if (authorBalance < 200) { return message.channel.send(moneyEmbed) } let moneyEmbed2 = new Discord.RichEmbed() .setColor("#FFFFFF") .setDescription(`❌ ${user.user.username} 身上没有可以抢劫的金币`); // 修正:判断目标余额是否<=0,避免余额为0时仍可抢劫 if (targetBalance <= 0) { return message.channel.send(moneyEmbed2) } // 修正:判断发起者的VIP状态,而非目标用户 let authorVip = await db.fetch(`bronze_${message.author.id}`); let random = authorVip === true ? Math.floor(Math.random() * 200) + 1 : Math.floor(Math.random() * 100) + 1; // 新增:避免抢劫金额超过目标余额,防止出现负数 if (random > targetBalance) { random = targetBalance; } let embed = new Discord.RichEmbed() .setDescription(`✔️ 你抢劫了 ${user},成功抢到 ${random} 个金币!`) .setColor("#FFFFFF") message.channel.send(embed) // 修正:目标用户扣款,发起者加款 db.subtract(`money_${message.guild.id}_${user.id}`, random) db.add(`money_${message.guild.id}_${message.author.id}`, random) // 修正:给发起者设置冷却,而非目标用户 db.set(`rob_${message.guild.id}_${message.author.id}`, Date.now()) }; } module.exports.help = { name:"rob", aliases: [""] }
额外优化说明
- 给余额变量设置默认值
|| 0,避免null导致的数值判断错误 - 增加抢劫金额不超过目标余额的判断,防止出现负数余额
- 修正VIP状态的判断对象(应判断发起抢劫的用户是否为VIP)
- 修正冷却时间的存储对象(应给发起者设置冷却)
内容的提问来源于stack exchange,提问作者ren
相关产品推荐
相关产品推荐

