discord.py: How to get the user who invited/added the bot to his server? [solution]

Question:

I want to send a DM to the user, who invited/added the bot to his server.
I noticed that it’s displayed in the audit log. Can I fetch that and get the user or is there a easier way to achieve that?

Example:
bot = commands.Bot()

@bot.event
async def on_guild(guild, inviter):
    await inviter.send("Thanks for adding the bot to your server!")
Asked By: puncher

||

Answers:

Discord.py doesn’t support Bot Integrations yet. Please check this Pull Request. Once it is merged, you can do integration.user to get the user who invited the bot.

Answered By: Sairam

In discord.py 1.7.3 and lower does not have any actual method. However you can instead fetch the Audit Log Entry (documentation) and find out who invited the Bot from there.

Answered By: Syntaxツ

With discord.py 2.0 you can get the BotIntegration of a server and with that the user who invited the bot.

Example

from discord.ext import commands

bot = commands.Bot()

@bot.event
async def on_guild_join(guild):
    # get all server integrations
    integrations = await guild.integrations()

    for integration in integrations:
        if isinstance(integration, discord.BotIntegration):
            if integration.application.user.name == bot.user.name:
                bot_inviter = integration.user # returns a discord.User object
                
                # send message to the inviter to say thank you
                await bot_inviter.send("Thank you for inviting my bot!!")
                break

Note: guild.integrations() requires the Manage Server (manage_guild) permission.


References:

Answered By: puncher
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.