java
java

Reputation: 252

Trying to get guild from channel id

I've tried this code:

module.exports = async (client, channel) => {
  if (channel.type === "dm" || channel.type === "group") return;

  var guild;
  client.guilds.forEach(e => {
    e.fetchAuditLogs({type: 'CHANNEL_DELETE'})
      .then(audit => {
        if (audit.entries.first().id === channel.id) guild = e;
      });
  });
  if (!guild) return;
};

I am wanting to get the guild of the channel id that is passed on through the event parameters.
This is in channelDelete event, so I can't do client.channels.get(channel.id) since the ID does not exist in that collection. I need to get the information from the audit logs.

The problem is that I feel like this is overdoing the API, or there is probably a better method instead of having to loop through every single guild this bot is in.

Also, the actual code does not work as intended. It seems as though it reaches if (!guild) return; before the actual loops have finished, which means it will always return.

So, how do I make it so the code flows step by step, so that it does not return all the time, or a way to improve the code where it is not as intensive (if this method is intensive on the API/host).

Upvotes: 2

Views: 3350

Answers (1)

slothiful
slothiful

Reputation: 5623

You can simply reference channel.guild instead of trying to acquire the guild from the client's cache.

For future reference, to skip a value in a loop, you should use continue rather than return.

Upvotes: 4

Related Questions