Discord Bot Maker - MySQL 调平系统或 Discord.js - MySQL 调平系统

Posted

技术标签:

【中文标题】Discord Bot Maker - MySQL 调平系统或 Discord.js - MySQL 调平系统【英文标题】:Discord Bot Maker - MySQL Leveling System or Discord.js - MySQL Leveling System 【发布时间】:2021-03-25 17:57:10 【问题描述】:

所以让我来布置背景:

不和谐机器人制造商: 我有一个调平系统,可以根据帖子添加 xp 并将其存储到 JSON 文件中,并且可以正常工作。一旦成员达到一定的经验等级,机器人就会在不和谐中为他们分配一个新角色。如果我必须重新启动机器人,所有拥有 xp 的成员都会从 0 xp 的级别 1 重新开始。

Discord.js 我有一个 xp 机器人,它根据帖子添加 xp 并将信息存储在在线 mysql 数据库中。此机器人在达到特定 xp 级别时不会自动分配角色,但如果我需要重新启动机器人,则会保存信息。

我需要帮助(指向正确的方向)让 DBM 机器人将数据存储在 MySQL 中(我已经搜索了几个小时,但找不到教程或任何东西)。这是 DBM 原始数据(减去 ID 和其他不相关的信息)

指挥级

    
      "name": "level",
      "permissions": "NONE",
      "restriction": "1",
      "actions": [
        
          "member": "1",
          "varName": "",
          "dataName": "exp",
          "defaultVal": "0",
          "storage": "1",
          "varName2": "memberexp",
          "name": "Store Member Data"
        ,
        
          "member": "1",
          "varName": "",
          "dataName": "level",
          "defaultVal": "1",
          "storage": "1",
          "varName2": "myLevel",
          "name": "Store Member Data"
        ,
        
          "channel": "0",
          "varName": "",
          "message": "```You are level $tempVars(\"myLevel\") with $tempVars(\"memberexp\")!```",
          "storage": "0",
          "varName2": "",
          "name": "Send Message"
        
      ],
      "_id": "Tucww",
      "comType": "0"
    

指挥级系统

    
      "name": "LevelingSystem",
      "temp": "msg",
      "event-type": "2",
      "actions": [
        
          "info": "0",
          "find": "channelid goes here",
          "storage": "2",
          "varName": "channel name goes here",
          "name": "Find Channel"
        ,
        
          "storage": "2",
          "varName": "myLevel",
          "comparison": "1",
          "value": "7",
          "iftrue": "2",
          "iftrueVal": "7",
          "iffalse": "0",
          "iffalseVal": "",
          "name": "Check Variable"
        ,
        
          "storage": "2",
          "varName": "myLevel",
          "comparison": "1",
          "value": "13",
          "iftrue": "2",
          "iftrueVal": "10",
          "iffalse": "0",
          "iffalseVal": "",
          "name": "Check Variable"
        ,
        
          "storage": "2",
          "varName": "myLevel",
          "comparison": "1",
          "value": "25",
          "iftrue": "2",
          "iftrueVal": "13",
          "iffalse": "0",
          "iffalseVal": "",
          "name": "Check Variable"
        ,
        
          "storage": "2",
          "varName": "myLevel",
          "comparison": "1",
          "value": "50",
          "iftrue": "2",
          "iftrueVal": "16",
          "iffalse": "0",
          "iffalseVal": "",
          "name": "Check Variable"
        ,
        
          "storage": "2",
          "varName": "myLevel",
          "comparison": "1",
          "value": "100",
          "iftrue": "2",
          "iftrueVal": "19",
          "iffalse": "1",
          "iffalseVal": "",
          "name": "Check Variable"
        ,
        
          "info": "0",
          "find": "roleid number goes here",
          "storage": "2",
          "varName": "role name goes here",
          "name": "Find Role"
        ,
        
          "member": "3",
          "varName2": "member",
          "role": "4",
          "varName": "role name goes here",
          "reason": "",
          "name": "Add Member Role"
        ,
        
          "name": "End Action Sequence"
        ,
        
          "info": "0",
          "find": "roleid number goes here",
          "storage": "2",
          "varName": "role name goes here",
          "name": "Find Role"
        ,
        
          "member": "3",
          "varName2": "member",
          "role": "4",
          "varName": "role name goes here",
          "reason": "",
          "name": "Add Member Role"
        ,
        
          "name": "End Action Sequence"
        ,
        
          "info": "0",
          "find": "roleid number goes here",
          "storage": "2",
          "varName": "role name goes here",
          "name": "Find Role"
        ,
        
          "member": "3",
          "varName2": "member",
          "role": "4",
          "varName": "role name goes here",
          "reason": "",
          "name": "Add Member Role"
        ,
        
          "name": "End Action Sequence"
        ,
        
          "info": "0",
          "find": "roleid number goes here",
          "storage": "2",
          "varName": "role name goes here",
          "name": "Find Role"
        ,
        
          "member": "3",
          "varName2": "member",
          "role": "4",
          "varName": "role name goes here",
          "reason": "",
          "name": "Add Member Role"
        ,
        
          "name": "End Action Sequence"
        ,
        
          "info": "0",
          "find": "roleid number goes here",
          "storage": "2",
          "varName": "role name goes here",
          "name": "Find Role"
        ,
        
          "member": "3",
          "varName2": "member",
          "role": "4",
          "varName": "role name goes here",
          "reason": "",
          "name": "Add Member Role"
        ,
        
          "name": "End Action Sequence"
        
      ],
      "_id": "gUxAU",
      "restriction": "1",
      "comType": "3",
      "permissions": "NONE"
    

事件级别系统

    
      "name": "LevelingSystem",
      "temp": "msg",
      "event-type": "2",
      "actions": [
        
          "message": "1",
          "varName": "msg",
          "info": "3",
          "storage": "2",
          "varName2": "member",
          "name": "Store Message Info"
        ,
        
          "member": "3",
          "varName": "member",
          "dataName": "exp",
          "changeType": "1",
          "value": "1",
          "name": "Control Member Data"
        ,
        
          "member": "3",
          "varName": "member",
          "dataName": "level",
          "defaultVal": "1",
          "storage": "2",
          "varName2": "myLevel",
          "name": "Store Member Data"
        ,
        
          "member": "3",
          "varName": "member",
          "dataName": "exp",
          "comparison": "4",
          "value": "serverVars(\"myLevel\")*48",
          "iftrue": "0",
          "iftrueVal": "",
          "iffalse": "1",
          "iffalseVal": "",
          "name": "Check Member Data"
        ,
        
          "member": "3",
          "varName": "member",
          "dataName": "level",
          "changeType": "1",
          "value": "1",
          "name": "Control Member Data"
        
      ],
      "_id": "Mtoid"
    

我需要弄清楚当存储在 MySQL 中的 xp 达到一定级别时,如何让 discord.js 机器人向成员添加角色。这是 discord.js 机器人代码(同样删除了登录信息):

./bot.js

    const Discord = require('discord.js');
    const bot = new Discord.Client();
    const mysql = require("mysql");
    const prefix = '.';
    const fs = require('fs');
    
    bot.commands = new Discord.Collection();
    
    
    fs.readdir("./cmds/", (err, files) => 
      if(err) console.error(err);
    
      let jsfiles = files.filter(f => f.split(".").pop() === "js");
      if(jsfiles.length <= 0) 
        console.log("No commands to load!");
        return;
      
    
      console.log(`Loading $jsfiles.length commands!`);
    
      jsfiles.forEach((f, i) => 
        let props = require(`./cmds/$f`);
        console.log(`$i + 1: $f loaded!`);
        bot.commands.set(props.help.name, props);
      );
    );
    
    bot.login(process.env.BOT_TOKEN);
    
    bot.once('ready', () => 
        console.log('Bot is online!')
    );
    
    var con =mysql.createConnection(
        host: "host name goes here",
        user: "username goes here",
        password: "password goes here",
        database: "database name goes here"
    );
    
    con.connect(err => 
      if(err) throw err;
      console.log("Connected to database.");
      
    );
    
    function generateXp() 
      let min = 1
      let max = 1
    //the above numbers are both one's because I only want each message to count as 1xp
      return Math.floor(Math.random() * (max - min + 1)) + min;
    ;
    
    bot.on('message', async message => 
      if(message.author.bot) return;
      if(message.channel.type === "dm") return;
    
      con.query(`SELECT * FROM xp WHERE id = '$message.author.id'`, (err, rows) => 
        if (err) throw err;
        
        let sql;
    
        if(rows.length < 1) 
          sql = `INSERT INTO xp (id, xp) VALUES ('$message.author.id', $generateXp())`
         else 
            let xp = rows[0].xp;
            sql = `UPDATE xp SET xp = $xp +generateXp() WHERE id = '$message.author.id'`;
        
    
        con.query(sql);
    
      );
    
      if(/(?:https?:\/)?discord(?:app.com\/invite|.gg)/gi.test(message.content)) 
        message.delete();
        return;
      
    
      let messageArray = message.content.split(/\s+/g);
      let command = messageArray[0];
      let args = messageArray.slice(1);
    
      if(!command.startsWith(prefix)) return;
    
      let cmd = bot.commands.get(command.slice(prefix.length));
      if(cmd) cmd.run(bot, message, args, con);
    
    );

./cmds/xp.js

    module.exports.run = async (bot, message, args, con) => 
        let target = message.mentions.users.first() || message.author;
    
        con.query(`SELECT * FROM xp WHERE id = '$target.id'`, (err, rows) => 
            if(err) throw err;
    
            if(!rows[0]) return message.channel.send("This member has no XP on record.")
            let xp = rows[0].xp;
            message.channel.send(xp);
        );
    ;
    
    module.exports.help = 
        name: "xp"
    

【问题讨论】:

这是一个小细节,但在您的代码 sn-ps 中突出显示的语法似乎有点不对劲。您可以像这样在初始反引号之后添加语言:```javascript 【参考方案1】:

我在 Discord Bot Maker 方面没有太多经验,但我可以为 discord.js 提供一个潜在的解决方案。 Its documentation 可能需要一些时间来适应,但它做得很好,对于找到你需要的东西很有用。

在您的主消息事件处理程序中,运行更新他们的经验值 (con.query(sql)) 的 SQL 查询后,您应该检查他们的经验值是否超过了该角色的阈值。

// inside the callback for your SELECT query
if (err) throw err;

let sql;
let originalXp;
let updatedXp;

if (rows.length < 1) 
  originalXp = 0;
  updatedXp = generateXp();
  sql = `INSERT INTO xp (id, xp) VALUES ('$message.author.id', $updatedXp)`;
 else 
  originalXp = rows[0].xp;
  updatedXp = originalXp + generateXp();
  sql = `UPDATE xp SET xp = $updatedXp WHERE id = '$message.author.id'`;


con.query(sql);

// if you want different roles at certain thresholds, replace this with the snippet later in the answer
if (originalXp < SOME_XP_THRESHOLD && updatedXp >= SOME_XP_THRESHOLD) 
  // this example gets a role based on name
  // you could also get the role you want using some other criteria
  const role = message.member.guild.roles.cache.find(role => role.name === ROLE_TO_ADD);
  message.member.roles.add(role);

如果你想包含多个角色来达到不同的阈值,你可以将它们设置在一个数组中:

const roles = [
  
    name: 'foo',
    threshold: 5,
  ,
  
    name: 'bar',
    threshold: 10,
  ,
];

然后循环遍历它们:

// insert this snippet instead at the point indicated above
for (const xpRole of roles) 
  if (originalXp < xpRole.threshold && updatedXp >= xpRole.threshold) 
    const role = message.member.guild.roles.cache.find(role => role.name === xpRole.name);
    // you could potentially remove the previous role here as well
    message.member.roles.add(role);
  

【讨论】:

以上是关于Discord Bot Maker - MySQL 调平系统或 Discord.js - MySQL 调平系统的主要内容,如果未能解决你的问题,请参考以下文章

在 Discord Bot MAker 中从 JSON 解析数据

在 Discord.js 和 MySQL 中注册命令

bot.js 中的 Discord BOT 错误(SyntaxError:无效或意外令牌)

Discord Bot 回复自己,无法识别 message.author.bot

如何使用 discord.js 从 discord bot 向特定用户发送消息

Discord - BOT 发送私信