Search code examples
pythondiscord.pyroles

Discord.py get_member with on_ready


We have a bot command on a server !verifyme1

Which adds a member to a role.

async def verfiyme1(ctx):
    user=ctx.message.author
    #user=ctx.guild.get_member(536147700115308545)
    print(user)
    channel = bot.get_channel(858993936932274196)
    print(client)
    await user.send('Welcome to the Member Club!')
    role= discord.utils.get(user.guild.roles, name="Holder Club")
    if role in user.roles:
        await channel.send(f"You are already a member of the holder club!")
        #exit()

    else:
        await user.add_roles(role)
        await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
        #exit()

We need to change the command so it isn't triggered by a user but by us triggering the script (so we can do some extra verification checks) ie loading members.py triggers it to add the role to the chosen member then exits.

Looking at the docs i need to use on_ready()

async def on_ready():
    #user=ctx.message.author
    print("this is a test")
   
    channel = bot.get_channel(858993936932274196)
    print(channel)
    user=ctx.guild.get_member([we will pass this ID in])
    print(user)
    await user.send('Welcome to the Member Club!')
    role= discord.utils.get(user.guild.roles, name="Holder Club")
    if role in user.roles:
        await channel.send(f"You are already a member of the  holder club!")
        #exit()

    else:
        await user.add_roles(role)
        await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
        #exit()

bot.run(DISCORD_TOKEN)

But the issue with this is you can't use ctx with on_ready thus ctx.guild.get_member returns an error. Is there any alternative to guild.get.member that would work?


Solution

  • You can get the guild, just like you get the channel

    guild = bot.get_guild(guild_id)

    Found in the docs.


    @bot.event
    async def on_ready():
        guild = bot.get_guild(guild_id)
        if guild == None:
            guild = await bot.fetch_guild(guild_id) # if guild not in cache
    
        user = guild.get_member(536147700115308545)
        channel = guild.get_channel(858993936932274196)
    
        await user.send('Welcome to the Member Club!')
        role = discord.utils.get(guild.roles, name="Holder Club")
        if role in user.roles:
            await channel.send(f"You are already a member of the holder club!")
            #exit()
    
        else:
            await user.add_roles(role)
            await channel.send(f"Congrats {user.mention} You are now a member of the Holder Club!")
            #exit()