Invite Channel Notification Discord.js

Viewed 437

So i am coding a bot , in Node.js with Visual Studio Code. I want to have a channel, that when a user joins the guild , will send 'Welcome user and invited by thisuser(Total Invites: 5)

The code is :

module.exports = (client) => {
  const invites = {} // { guildId: { memberId: count } }

  const getInviteCounts = async (guild) => {
    return await new Promise((resolve) => {
      guild.fetchInvites().then((invites) => {
        const inviteCounter = {} // { memberId: count }

        invites.forEach((invite) => {
          const { uses, inviter } = invite
          const { username, discriminator } = inviter

          const name = `${username}#${discriminator}`

          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 = '731801004462571602'
        const channel = guild.channels.cache.get(channelId)
        const count = invitesAfter[inviter]
        channel.send(
          `Please welcome <@${id}> to the Discord! Invited by ${inviter} (${count} invites)`
        )

        invites[guild.id] = invitesAfter
        return
      }
    }
  })
}

This code works perfectly with console but i am facing a problem,never post the message in the channel!

1 Answers

The message might not be being sent because of the channel ID double check you are using the right channel ID and you might want to try changing
const channel = guild.channels.cache.get(channelId) to this const channel = client.channels.cache.get(channelId)

Related