无法获得 discord api 的邀请码

Not able to get a invite code of discord api

我正在制作一个 discord 机器人,它需要跟踪哪个用户使用哪个邀请加入服务器 link。为此,它需要跟踪用户生成的不和谐邀请 link 代码。这是我的代码。我能够获得邀请用户的用户 ID,他已经添加了多少用户以及加入的成员的 ID。我无法正确获取的是邀请码。这是我的代码

const invites = {} // { guildId: { memberId: count } }
    let Array = [];
    const getInviteCounts = async (guild) => {
      return await new Promise((resolve) => {
        guild.fetchInvites().then((invites) => {
          const inviteCounter = {} // { memberId: count }
  
          invites.forEach((invite) => {
            const { uses, inviter,id } = invite
            const { username, discriminator } = inviter
            console.log("ID is ",invite.code);
            
            const name = `${username}#${discriminator}`
            Array[name] = [inviter,[invite.code]];
            inviteCounter[name] = (inviteCounter[name] || 0) + uses
          })
  
          resolve(inviteCounter)
        })
      })
    }
  
    client.guilds.cache.forEach(async (guild) => {
      invites[guild.id] = await getInviteCounts(guild)
    })
  
    client.on('guildMemberAdd', async (member) => {
      const { guild, id } = member
  
      const invitesBefore = invites[guild.id]
      const invitesAfter = await getInviteCounts(guild)
  
      console.log('BEFORE:', invitesBefore)
      console.log('AFTER:', invitesAfter)
  
      for (const inviter in invitesAfter) {
        if (invitesBefore[inviter] === invitesAfter[inviter] - 1) {
          const channelId = '937987923205304390'
          const channel = guild.channels.cache.get(channelId)
          const count = invitesAfter[inviter]
         let userID =  client.users.cache.find(u => u.tag === inviter).id;
         console.log("USERID",inviter.code); 
         channel.send(
            `Please welcome <@${id}> to the Discord! Invited by ${inviter} (${count} invites)`
          )
            
          invites[guild.id] = invitesAfter
          return
        }
      }
    }) 

要使用邀请,您需要存储邀请,然后查看增加的邀请,也就是正在使用的邀请。一种方法是在您第一次启动客户端时在 ready 事件中存储邀请。

const invites = new Map();
const firstInvites = await <yourGuild>.invites.fetch();
    
invites.set(<yourGuild>.id, new Map(firstInvites.map((invite) => [invite.code, invite.uses])));

module.exports = { invites }; //Export if you use multiple files for events

然后您需要使用 guildMemberAdd 事件并查看哪个邀请增加了。如果您为活动使用多个文件,则需要从 ready 活动中导入邀请。

const { invites } = require('PATH/TO/YOUR/ready.js');

const newInvites = await <member>.guild.invites.fetch();
const oldInvites = invites.get(member.guild.id);

const usedInvite = newInvites.find(inv => oldInvites.get(inv.code) < inv.uses);

您现在已将使用过的邀请存储在变量 usedInvite 中,您可以在其中访问其属性,例如 invite.codeinvite.inviter