簡體   English   中英

在 Discord.js 中添加一個角色

[英]Add a role in Discord.js

我是 JS 的新手,我正試圖讓我的機器人為特定成員賦予特定角色。

如果你能幫助我,請這樣做。

編碼:

bot.on("message", (msg) => {
    if ((msg.content === "!give", role, member))
        var role = msg.guild.roles.cache.find((r) => {
            return r.name === "convidado astolfofo";
        });
    var member = msg.mentions.members.first();
    member.roles.add(role);
    console.log(member);
    console.log(role);
});

我遇到的錯誤:

(node:2364) UnhandledPromiseRejectionWarning: TypeError [INVALID_TYPE]: Supplied roles is not a Role, Snowflake or Array or Collection of Roles or Snowflakes.
TypeError: Cannot read property 'add' of undefined discord.js

您的代碼有幾個錯誤。 我不確定您嘗試使用if ((msg.content === ",give", role, member))做什么——可能會檢查消息是否以!give開頭以及是否有角色和成員-- 但在 JavaScript 中它不會那樣工作。 一旦定義了這些變量,您需要單獨檢查它們。

如果您檢查msg.content === "!give"但您還希望成員提及成員,則它永遠不會是真的。 如果整個消息只是!give ,則沒有提及用戶。 如果有提到的用戶, msg.content將超過!give 嘗試檢查message.content是否以"!give"開頭。

接下來,如果您在 if 語句后不使用花括號,則只有下一行在該語句內。 因此,您嘗試檢查命令是否為!give ,如果是,則搜索角色,但您檢查添加角色的位置的以下行不在此語句之外。 這意味着,它在每條傳入消息上運行。 嘗試使用花括號。

檢查權限並發送回復以讓用戶知道是否缺少任何權限也是一個好主意。

檢查下面的工作示例,我添加了注釋以使其更易於理解:

bot.on('message', async (msg) => {
  if (msg.content.startsWith('!give')) {
    // check if the message author has the permission to add a role
    if (!msg.member.hasPermission('MANAGE_ROLES')) {
      return msg.reply('You need `MANAGE_ROLES` permission to add a role');
    }

    // check if the bot has the permission to add a role
    if (!msg.guild.me.hasPermission('MANAGE_ROLES')) {
      return msg.reply('I do not have `MANAGE_ROLES` permission to add a role');
    }

    // check if there is a member mentioned
    const member = msg.mentions.members.first();
    // if there is none, send a reply
    if (!member) {
      return msg.reply("Don't forget to mention someone!");
    }

    // search for the role
    // don't forget that it's case-sensitive
    const role = msg.guild.roles.cache.find((r) => r.name === 'convidado astolfofo');

    // check if the role exists
    if (!role) {
      return msg.reply("Oh-oh, I can't find the role `convidado astolfofo`");
    }

    // try to add a role
    try {
      await member.roles.add(role);
      msg.reply(`Role added to ${member}`);
    } catch (error) {
      console.log(error);
      msg.reply('Oops, role not added, there was an error');
    }
  }
});

您似乎使用return不正確。 嘗試這個:

bot.on("message", (msg) => {
    if ((msg.content === "!give", role, member))
        var role = msg.guild.roles.cache.find(r => r.id === "<role id goes here>");
        var member = msg.mentions.members.first();
        member.roles.add(role);
        console.log(member.username);
        console.log(role.name);
});

我還更改了您的console.log語句,因為您的控制台會收到垃圾郵件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM