javascript - 如何跨服务器为用户存储数据不和谐
问题描述
我在任何地方都找不到任何对我有帮助的答案,所以我想我会自己问。
您如何跨服务器存储一个用户的数据?示例:如果服务器 A 有一个机器人,并且用户输入了他们喜欢的号码或其他内容,那么服务器 B 上的同一个机器人如何打印该号码?(假设用户在两台服务器上)。DM 与机器人的工作方式是否相同?多用户怎么办?
我真的不知道您为此使用了什么类或变量,所以我自己没有尝试过任何东西。
解决方案
我已经编写了一些代码来接受命令!favNum
和!favColor
. 如果没有传递参数,机器人将尝试检索保存的值;如果传递了一个参数,机器人将保存该值。
消息事件处理程序侦听所有服务器上的消息,如Jakye 在评论中所述:
客户端的事件,
message
正在侦听来自您的机器人所在的所有服务器的消息。您可以使用message.guild
来获取Guild
.
警告:如果机器人重新启动,以下代码将丢失所有数据。
// Set a prefix for commands
const prefix = '!';
// Create a collection for all data
const data = new Discord.Collection();
// Create individual collections for different pieces of data
data.set('favNum', new Discord.Collection());
data.set('favColor', new Discord.Collection());
client.on('message', message => {
// Exit if the message was sent by a bot or doesn't start with the command prefix
if (message.author.bot || !message.content.startsWith(prefix)) return;
// Split the message into a command and arguments
const args = message.content.slice(prefix.length).trim().split(/\s+/g);
const command = args.shift().toLowerCase();
// Execute a section of code depending on what the command was
switch (command) {
// Favourite number command
case 'favNum':
// If no arguments were passed, try to get the saved value
if (!args[0]) {
if (!data.get('favNum').has(message.author.id)) return message.reply(`you haven't set a favorite number.`);
const favNum = data.get('favNum').get(message.author.id);
message.reply(`your favorite number is ${favNum}.`);
}
// If arguments were passed, set the value
data.get('favNum').set(message.author.id, args[0]);
break;
// Favourite color command
case 'favColor':
// If no arguments were passed, try to get the saved value
if (!data.get('favColor').has(message.author.id)) return message.reply(`you haven't set a favorite color.`);
const favColor = data.get('favColor').get(message.author.id);
message.reply(`your favorite color is ${favColor}.`);
}
// If arguments were passed, set the value
data.get('favColor').set(message.author.id, args[0]);
break;
// Default reply if the command was not recognized
default:
message.reply(`could not recognize the command \`command\`.`);
});
推荐阅读
- javascript - JavaScript屏幕记录正在视频标签中播放,但下载后没有
- django - 向所有模板发送特定的查询集
- mysql - 这两个mySql的下载大小有什么区别
- javascript - 未处理的运行时错误:无法加载脚本:/_next/static/chunks/pages/api/twitter/generate-auth-link.js
- c++ - Qt在同一个QGraphicsScene中插入两个不同的QGraphicsWidget,setZValue无效
- sql - 如何在不使用 NOT IN 的情况下优化 SQL 查询
- r - R中基因强度值的热图
- python-appium - Pytest + Appium 测试框架
- api - 有哪些现成的解决方案可以安排、执行和监控每天对外部 API 的 1000 个请求?
- android - 我想要全屏图像,但图像在屏幕中与其他布局共享