Search code examples
pythondiscorddiscord.py

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


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!")

Solution

  • 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: