首页 > 解决方案 > Discord.js XP 系统,添加角色作为成员升级

问题描述

所以我找到了一些易于理解的 XP 系统,我只想编辑它并添加一个功能,例如在升级时添加角色。目前,没有任何反应。我尝试在这里和那里移动一些东西,结果要么最终通过升级嵌入向频道发送垃圾邮件,要么根本没有。我没有错误。

提前致谢!

下面的代码:

// Further up are the level roles defined, etc but that's not relevant.
  if (message.author.bot) return;

  let xpAdd = Math.floor(Math.random() * 7) + 8;

  if (!xp[message.author.id]) {
    xp[message.author.id] = {
      xp: 0,
      level: 1
    };
  }

  let curxp = xp[message.author.id].xp;
  let curlvl = xp[message.author.id].level;
  let nxtLvl = xp[message.author.id].level * 500;
  xp[message.author.id].xp = curxp + xpAdd;

  let lvlupRoles = new Discord.RichEmbed()
  .setAuthor("Level Up!", message.author.displayAvatarURL)
  .setThumbnail("https://cdn.discordapp.com/attachments/682717976771821646/705125856455950496/Levelup.png")
  .setColor("RANDOM")
  .setDescription(`Level: ${curlvl + 1}\nXP: ${curxp}`);

  if (nxtLvl <= xp[message.author.id].xp) {
    xp[message.author.id].level = curlvl + 1;

    let lvlup = new Discord.RichEmbed()
      .setAuthor("Level Up!", message.author.displayAvatarURL) .setThumbnail("https://cdn.discordapp.com/attachments/682717976771821646/705125856455950496/Levelup.png")
      .setColor("#00703C")
      .setDescription(`Level: ${curlvl + 1}\nXP: ${curxp}`);

      message.channel.send(lvlup).then(message => {message.delete(10000)});

    if (curlvl === "10") {
      lvlupRoles.addField("Roles gained", `${Level10Role.toString()}`, true)
      let addrankup = message.member;
      addrankup.addRole(Level10Role.id).catch(console.error);
      message.channel.send(lvlupRoles).catch(e => console.log(e))
    }

    if (curlvl === "20") {
      lvlupRoles.addField("Roles gained", `${Level20Role.toString()}`, true)
      let addrankup = message.member;
      addrankup.addRole(Level20Role.id).catch(console.error);
      message.channel.send(lvlupRoles).catch(e => console.log(e))
    }
   // ETC . . .
  }

  fs.writeFile("./storage/xp.json", JSON.stringify(xp), (err) => {
    if (err) console.log(err)
  });

标签: discorddiscord.js

解决方案


我认为这可能是由于您存储xp[message.author.id].levelcurlvl修改xp[message.author.id].level和仍在使用curlvl. 在 JS 中,只有对象({}、数组、函数等)通过引用传递,因此curlvl不会更新,xp[message.author.id].level因为它是一个数字。

在下面添加xp[message.author.id].level = curlvl + 1;

curlvl = xp[message.author.id].level;

推荐阅读