Discord机器人开发:如何在多个文件中共享调用numberofp变量?
跨文件共享变量解决方案
方法1:将变量挂载到client对象(最适配Discord机器人场景)
直接把计数变量绑定到全局client实例上,所有能获取到client的位置都可以直接调用:
修改index.js代码:
// variables // 把变量挂载到client实例而非单独声明 client.numberofp = 0; // 注意:原代码判断条件用了赋值符号=,要改成严格相等===避免逻辑错误 // discord.js v13及以上版本已废弃message事件,请使用messageCreate client.on('messageCreate', (message) => { if(message.author.id === 714544589305806868){ if(message.content.includes(':p')){ client.numberofp += 1; console.log('Porsha_boy said :p, so far it has been sent this many times:', client.numberofp); } } })
修改命令文件代码,注册命令时记得把client传入execute参数:
const db = require("quick.db") const Discord = require('discord.js') module.exports = { name: 'rub', description: '查询:p的发送次数', // 把client加入参数列表 execute(message, args, Discord, client){ var embed = new Discord.MessageEmbed() .setAuthor(client.numberofp) .setColor("#34BDE1") message.channel.send({embeds: [embed]}) console.log('working') } }
方法2:用已安装的quick.db持久化存储(重启机器人数据不会丢失)
该方案更实用,原生内存存储的变量会在机器人重启后清零,用数据库存储数据更稳定:
修改index.js代码:
client.on('messageCreate', async (message) => { if(message.author.id === 714544589305806868){ if(message.content.includes(':p')){ // 计数累加,无数据时默认从0开始 await db.add('numberofp', 1) const currentCount = await db.get('numberofp') console.log('Porsha_boy said :p, so far it has been sent this many times:', currentCount); } } })
命令文件直接调用数据库取数即可:
const db = require("quick.db") const Discord = require('discord.js') module.exports = { name: 'rub', description: '查询:p的发送次数', async execute(message, args, Discord){ const numberofp = await db.get('numberofp') || 0 var embed = new Discord.MessageEmbed() .setAuthor(numberofp) .setColor("#34BDE1") message.channel.send({embeds: [embed]}) console.log('working') } }
方法3:单独导出共享变量
新建counter.js文件专门存储共享变量:
// counter.js module.exports = { numberofp: 0 }
index.js引入后修改逻辑:
const counter = require('./counter.js') client.on('messageCreate', (message) => { if(message.author.id === 714544589305806868){ if(message.content.includes(':p')){ counter.numberofp += 1; console.log('Porsha_boy said :p, so far it has been sent this many times:', counter.numberofp); } } })
命令文件直接引入文件即可调用变量:
const counter = require('./counter.js') // 后续直接使用counter.numberofp即可
内容的提问来源于stack exchange,提问作者Quistty
相关产品推荐
相关产品推荐

