1

I am using discord.py async version and I need to assign a role 10.5 minutes after a user joins a server. I was considering using threading.Timer(..) but member.add_roles(...) is a coroutine and therefore Timer will not await it.

I tried an alternate method using loop.call_later(...) but in my testing I get a RuntimeWarning that my coroutine to add roles, add_roles, was never waiting. Here's what I tried so far:

import discord, asyncio
from discord.utils import get

client = discord.Client()

async def on_member_join(member):
    ...
    newuser, noparty = get(member.guild.roles, name="New Member"), get(member.guild.roles, name="No Party")
    async def add_roles(member, newuser, noparty):
        await member.add_roles(newuser, noparty, reason="Auto-role new users.")
    loop = asyncio.get_event_loop()
    loop.call_later(630, add_roles, member, newuser, noparty)

The expected outcome is that after 10.5 minutes the member will be assigned the New User and No Party roles, but instead I get the RuntimeWarning described above. My questions are: is this the proper approach? Or can I simply use asyncio.sleep(630) since the rest of my program is async functions? Any help is appreciated.

1 Answer 1

3

await asyncio.sleep(630)

Should work just fine.

If you have other things that you want to do inside on_member_join that you don't want to wait 10 minutes for, you could set it up to run it as an asyncio task

async def give_permission_later(member, newuser, noparty):
    await asyncio.sleep(630)
    await member.add_roles(newuser, noparty, reason="Auto-role new users.")

async def on_member_join(member):
    ...
    newuser, noparty = get(member.guild.roles, name="New Member"), get(member.guild.roles, name="No Party")
    client.loop.create_task(give_permission_later(member, newuser, noparty))
    # More code that should execute now
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, since that's my last task I'll try that. Thanks!
To expand on that, calling asyncio.sleep is basically saying to the interpreter "come back to me in x amount of time", instead of normal time.sleep, which is basically "don't do anything else until x amount of time has passed"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.