Skip to content
Advertisement

get only information of a specific guild

Hey so this code works completely fine but my problem is that it gets info of all the servers that the bot is in.

@commands.Cog.listener()
async def on_user_update(self, before, after):
        logs = self.bot.get_channel(810977833823240262)
        embed = discord.Embed(colour=0x7289da)
        embed.description = f"{after.name} has changed his avatar"
        if before.avatar_url != after.avatar_url:
            embed.add_field(name="New avatar")
            embed.set_image(url=after.avatar_url)
        if before.name != after.name:
            embed.add_field(name="Previous name",value=before.name,inline=False)
            embed.add_field(name="New name ",value=after.name,inline=False)
        if before.status != after.status:
            embed.add_field(name="Previous Status",value=before.status,inline=False)
            embed.add_field(name="New Status ",value=after.status,inline=False)
        await logs.send(embed=embed)  

This code is for logs so I want it to have different logs for each server. For example, I don’t want to show a server that I’m not in if I changed avatar or anything. Any help is appreciated

Advertisement

Answer

You can simply check if you have any mutual guilds with the user that updated it’s info

@commands.Cog.listener()
async def on_user_update(self, before, after):
    my_id = YOUR_ID_HERE # Obviously put your ID here
    mutual_guilds = [g for g in self.bot.guilds if g.get_member(my_id) and g.get_member(after.id)]
    
    if mutual_guilds: # Checking if the list is not empty
        # The user is in one of your guilds
        logs = self.bot.get_channel(810977833823240262)
        embed = discord.Embed(colour=0x7289da)
        embed.description = f"{after.name} has changed his avatar"

        if before.avatar_url != after.avatar_url:
            embed.add_field(name="New avatar")
            embed.set_image(url=after.avatar_url)

        if before.name != after.name:
            embed.add_field(name="Previous name",value=before.name,inline=False)
            embed.add_field(name="New name ",value=after.name,inline=False)

        if before.status != after.status:
            embed.add_field(name="Previous Status",value=before.status,inline=False)
            embed.add_field(name="New Status ",value=after.status,inline=False)

        await logs.send(embed=embed)  

To explain a bit more the list comprehension:

mutual_guilds = []

for g in self.bot.guilds: # Looping though every guild
    if g.get_member(my_id) and g.get_member(after.id): # Checking if both you and the user are in the guild
        mutual_guilds.append(g)
Advertisement