Discord Bot消息统计功能报错:TypeError: db.add(...).then is not a function
解决Discord Bot中
TypeError: db.add(...).then is not a function报错 这个报错我之前也碰到过,根源是你使用的quick.db版本(v7及以上)已经切换为同步API,不再返回Promise对象,而你的代码还在沿用旧版本的异步.then()链式调用写法,所以触发了类型错误。下面是具体的修复步骤和修改后的代码:
一、修复主文件的消息跟踪逻辑
把原来的异步.then()调用改成同步写法,直接获取db.add的返回值,同时调整错误处理方式:
const client = new Discord.Client(); const prefix = "!"; const fs = require('fs'); const db = require('quick.db'); client.on('ready', () => { console.log('Logged in and ready to socially distance!'); }); client.on('message', message => { // 先过滤机器人自身消息和非指令前缀的消息,减少无效执行 if (message.author.bot || !message.content.startsWith(prefix)) return; let args = message.content.slice(prefix.length).trim().split(" "); let cmd = args.shift().toLowerCase(); try { let commandFile = require(`./commands/${cmd}.js`); commandFile.run(client, message, args); } catch(e) { console.log(e.message); } finally { console.log(`${message.author.username} ran the command: ${cmd}`); } // 消息跟踪/等级系统(同步写法) try { // 用下划线拼接ID,避免纯数字ID拼接后出现歧义 const messageCount = db.add(`${message.author.id}_${message.guild.id}`, 1); let targetCount; if (messageCount === 25) targetCount = 25; else if (messageCount === 50) targetCount = 50; else if (messageCount === 100) targetCount = 100; if (targetCount) { const newLevel = db.add(`userLevel_${message.author.id}_${message.guild.id}`, 1); message.channel.send(`You sent ${targetCount} messages, so you leveled up! You are now level ${newLevel}`); } } catch(ex) { message.channel.send("Sorry, can't do that."); console.error(ex); // 控制台打印错误详情,方便排查 } }); client.login('TOKEN-ID');
二、修复指令文件的查询逻辑
同样改为同步写法,去掉.then(),同时处理用户无数据时的默认值:
const db = require('quick.db'); // 别忘了引入db模块! exports.run = (bot, message, args) => { try { // 用户无数据时返回0,避免undefined显示 const messageCount = db.get(`${message.author.id}_${message.guild.id}`) || 0; const userLevel = db.get(`userLevel_${message.author.id}_${message.guild.id}`) || 0; message.channel.send(`Messages sent: \`${messageCount}\`\nLevel: \`${userLevel}\``); } catch(ex) { message.channel.send("Sorry, can't do that."); console.error(ex); } }
额外优化说明
- 把ID拼接从
message.author.id + message.guild.id改成${message.author.id}_${message.guild.id},避免两个纯数字ID拼接后出现歧义(比如用户ID123+服务器ID456=123456,和用户ID1234+服务器ID56结果一致)。 - 新增了用户无数据时的默认值处理(
|| 0),避免返回undefined影响展示。 - 调整了消息过滤逻辑的位置,减少不必要的代码执行。
内容的提问来源于stack exchange,提问作者CrazyDiamond99
相关产品推荐
相关产品推荐

