1

If I create a new express invitation to the server when the bot is turned on, an error occurs. In other cases, it works

const invites = {};
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
  wait(1000);
    g.fetchInvites().then(guildInvites => {
      invites[g.id] = guildInvites;
    });
  });
});
client.on('guildMemberAdd', member => {
   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);
     const inviter = client.users.get(invite.inviter.id);
     const logChannel = member.guild.channels.find(channel => channel.name === "join-logs");
     logChannel.send(`${member.user.tag} joined using invite code ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
   });
 });

Errors:

2019-07-07T09:49:20.363359+00:00 app[worker.1]: Unhandled Rejection: 
2019-07-07T09:49:20.363377+00:00 app[worker.1]:  TypeError: Cannot read property 'uses' of undefined
2019-07-07T09:49:20.363378+00:00 app[worker.1]:     at guildInvites.find.i (./bot.js:398:57)
2019-07-07T09:49:20.363380+00:00 app[worker.1]:     at Map.find (./node_modules/discord.js/src/util/Collection.js:160:13)
2019-07-07T09:49:20.363381+00:00 app[worker.1]:     at member.guild.fetchInvites.then.guildInvites (./bot.js:398:33)
2019-07-07T09:49:20.363382+00:00 app[worker.1]:     at process._tickCallback (internal/process/next_tick.js:68:7)

398 deadline

const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
LousyFox
  • 13
  • 3
  • I think you should console log `i.uses` maybe it is missing something? you cannot always assume the object contain all the fields if better you should console log guild invites – Hamuel Jul 07 '19 at 16:52
  • How to do it? Can you write the code? – LousyFox Jul 07 '19 at 17:03

1 Answers1

1

The invite used is new, and isn't yet in the cache. However, ei.get(i.code).uses assumes it is, and tries to use a property of it when it doesn't exist.

This revised predicate function will return the invite that isn't cached, or the invite that increased in uses.

const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);
slothiful
  • 5,548
  • 3
  • 12
  • 36
  • Thank you so much, everything works fine!! But sometimes there is a error: TypeError: Cannot read property 'inviter' of null . – LousyFox Jul 08 '19 at 04:25
  • Quoted from the docs... "The only guaranteed properties are `code`, `url`, `guild`, and `channel`. Other properties can be missing." Change the declaration of `inviter` to `invite.user || 'an unknown user'`. If defined, `invite.user` would already return a User, and if it isn't defined, this code would declare the variable as the string "an unknown user." – slothiful Jul 08 '19 at 13:36