简体   繁体   中英

Discord.js how can I create an invite for every guild my bot is in?

I am trying to make a command, where I can get every guild invite that the bot is currently in. Current code:

client.on('message', async (message) => {
 if (message.content.startsWith(prefix + 'invite')) {
  let invite = client.guilds
   .createInvite({
    maxAge: 0, // 0 = infinite expiration
    maxUses: 0, // 0 = infinite uses
   })
   .catch(console.error);
  message.channel.send(invite);
 }
});

Error:

DiscordAPIError: Cannot send an empty message

Try this:

 var invites = []; // starting array
    message.client.guilds.cache.forEach(async (guild) => { // iterate loop on each guild bot is in

      // get the first channel that appears from that discord, because
      // `.createInvite()` is a method for a channel, not a guild.
      const channel = guild.channels.cache 
        .filter((channel) => channel.type === 'text')
        .first();
      if (!channel || guild.member(client.user).hasPermission('CREATE_INSTANT_INVITE') return;
      await channel
        .createInvite({ maxAge: 0, maxUses: 0 })
        .then(async (invite) => {
          invites.push(`${guild.name} - ${invite.url}`); // push invite link and guild name to array
        })
        .catch((error) => console.log(error));
      console.log(invites);
    });

As an example, this is what I got after running the command:

不和谐的例子


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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