首页 > 解决方案 > 如何跨服务器为用户存储数据不和谐

问题描述

我在任何地方都找不到任何对我有帮助的答案,所以我想我会自己问。

您如何跨服务器存储一个用户的数据?示例:如果服务器 A 有一个机器人,并且用户输入了他们喜欢的号码或其他内容,那么服务器 B 上的同一个机器人如何打印该号码?(假设用户在两台服务器上)。DM 与机器人的工作方式是否相同?多用户怎么办?

我真的不知道您为此使用了什么类或变量,所以我自己没有尝试过任何东西。

标签: javascriptdiscorddiscord.js

解决方案


我已经编写了一些代码来接受命令!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\`.`);
});

推荐阅读