I am making a discord bot which needs to track which user joined the server using which invite link. For that it needs to track discord invite link code generated by the user. Here is my code. I am able to get user id who invited the user, how many users have he already added and the id of the member who joined. What I am not able to get correctly is the invite code. Here is my code
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
}
}
})
To get invite used you'd need to store the invites and then see which one is incremented, aka the one being used. One way would be to store the invites when you first start the client, in the ready event.
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
Then you'd need to use the guildMemberAdd event and see which invite incremented. If you use multiple files for events, you'll need to import invites from the ready event.
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);
you now have the used invite stored in the variable usedInvite where you can access its properties such as invite.code and invite.inviter