简体   繁体   English

需要帮助为用户添加角色。 (discord.js)

[英]Need help adding a role to a user. (discord.js)

When I'm online the bot gives me a role, as soon as I go offline the bot removes that role from me.当我在线时,机器人会给我一个角色,一旦我 go 离线,机器人就会从我身上删除该角色。

When it removes the role, I want the bot to give the role to a specific user.当它删除角色时,我希望机器人将角色赋予特定用户。 How can I do that?我怎样才能做到这一点?

I have my current code below:我在下面有我当前的代码:

client.on('presenceUpdate', (oldPresence, newPresence) => {
  const member = newPresence.member;
  if (member.id === 'user.id') {
    if (oldPresence.status !== newPresence.status) {
      var gen = client.channels.cache.get('channel.id');
      if (
        newPresence.status == 'idle' ||
        newPresence.status == 'online' ||
        newPresence.status == 'dnd'
      ) {
        gen.send('online');
        member.roles.add('role.id');
      } else if (newPresence.status === 'offline') {
        gen.send('offline');
        member.roles.remove('role.id');
      }
    }
  }
});

You could get the other member by its ID.您可以通过其 ID 获取其他成员。 newPresence has a guild property that has a members property; newPresence有一个guild属性,该属性有一个members属性; by using its .fetch() method, you can get the member you want to assign the role to.通过使用它的.fetch()方法,你可以获得你想要分配角色的成员。 Once you have this member, you can use .toles.add() again.拥有此成员后,您可以再次使用.toles.add() Check the code below:检查下面的代码:

// use an async function so we don't have to deal with then() methods
client.on('presenceUpdate', async (oldPresence, newPresence) => {
  // move all the variables to the top, it's just easier to maintain
  const channelID = '81023493....0437';
  const roleID = '85193451....5834';
  const mainMemberID = '80412945....3019';
  const secondaryMemberID = '82019504....8541';
  const onlineStatuses = ['idle', 'online', 'dnd'];
  const offlineStatus = 'offline';
  const { member } = newPresence;

  if (member.id !== mainMemberID || oldPresence.status === newPresence.status)
    return;

  try {
    const channel = await client.channels.fetch(channelID);

    if (!channel) return console.log('Channel not found');

    // grab the other member
    const secondaryMember = await newPresence.guild.members.fetch(secondaryMemberID);

    if (onlineStatuses.includes(newPresence.status)) {
      member.roles.add(roleID);
      secondaryMember.roles.remove(roleID);
      channel.send('online');
    }

    if (newPresence.status === offlineStatus) {
      member.roles.remove(roleID);
      secondaryMember.roles.add(roleID);
      channel.send('offline');
    }
  } catch (error) {
    console.log(error);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM