AnIdiotsGuide/discordjs-bot-guide

Can not read property of uses

Mxdi opened this issue · 6 comments

Mxdi commented

In this line

const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);

if the invite was not used or had a count of 0 uses, It throws an error saying that it can not read the property of uses. Maybe update the guide?

I will investigate the guide, but just to clarify this doesn't work with single use invites if that is what you're using it for.

Is there a solution to this problem?

zfbx commented

Well there's a few solutions.
First is to just check if invite is undefined and set invite.code and invite.uses to "n/a" and skip the inviter section
Second (technically additionally): the invites object is created on ready... so anyone that creates an invite from the time your bot is loaded will cause that error unless you regularly update the invites list. for a small server it's not bad, just do a repeating event every 60 or so seconds where you wipe the invites object and recreate it again like in ready and then you'll always have as many invites caught as you can.

I tried to find a way to catch onInviteCreated to add it but I can't seem to find a hook for that in the discord.js documents unless it's in guildUpdate or something. Honestly what SHOULD happen is discord should include the invite code and inviter id in the guildMemberAdd call..

If you want here's my code but it's quite different from the source and you'll need to replace a few functions and it's built for a single server so it's dumbed down a bit

client.on('guildMemberAdd', async member => {
    var logServer = member.guild.channels.get('584388004026777630');

    member.guild.fetchInvites().then(guildInvites => {
        const ei = invites[member.guild.id];
        invites[member.guild.id] = guildInvites;
        const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
        
        if (logServer) {
            const embed = new Discord.MessageEmbed()
                .setAuthor("User joined")
                .setColor(5697854)
                .setImage(member.user.avatarURL({format: 'png', size: 2048}))
                .addField("Id", `<@${member.user.id}> (${member.user.id})`);
            if(invite) {
                embed.addField("Inviter", `<@${invite.inviter.id}> - ${invite.code} (${invite.uses} Uses)`); 
            } else {
                embed.addField("Inviter", `Unknown (Temp Invite)`);
            }
            embed.addField("Joined Discord", client.time.stamp(new Date(member.user.createdTimestamp)), true);
            embed.setFooter(client.time.stamp());

            logServer.send({embed});
        }
    });
});

Isn't it easier?
const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);

Please join https://discord.gg/4NE4bk7 for any further help with this issue.

Isn't it easier?
const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);

Worked!