Search code examples
pythonpython-3.xasynchronousdiscord.pyapscheduler

Discord Python Bot - Send Message in Aux Function Using APScheduler


I think I'm doing something wrong.

What I'm trying to accomplish is having a function that whenever a user stays more than a specific amount of time deafen, it sends a message to a text channel.

It doesn't crash when compiling. It runs. It only gives:

RuntimeWarning: coroutine 'check_pomada_state' was never awaited

The timers work fine so it should not be a problem with them. Every method is async.

I do believe the problem is something to do with the call of scheduler.add_job(...). I might be missing some argument or something but in the documentation there is nothing that mentions it.

import ...

client = commands.Bot(command_prefix = ids.prefix)
times_check_pomada = [5, 3600, 10800, 18000]
timers_da_pomada = {...}

scheduler = BackgroundScheduler()
scheduler.start()

@client.event
async def on_ready():
    print('Bot is ready.')

@client.event
async def on_voice_state_update(member, before, after):
    if before.self_mute != after.self_mute and before.self_deaf != after.self_deaf:
        if after.self_mute and after.self_deaf:
            t = Timer()
            t.start()
            timers_da_pomada[member] = t
            scheduler.add_job(check_pomada_state, 'interval', seconds = 1, id=f'{member}_sched', args=[member])
        else:
            if member in timers_da_pomada and timers_da_pomada[member].isRunning():
                timers_da_pomada[member].stop()
                scheduler.remove_job(f'{member}_sched')

async def check_pomada_state(member):
    if not timers_da_pomada[member].isRunning():
        scheduler.remove_job(f'{member}_sched')

    else:
        curr = timers_da_pomada[member].current()
        if curr in times_check_pomada:
            channel = client.get_channel(<channel_id>)
            await channel.send(f'{member}... {curr // 60} minutes deafened')

client.run(ids.TOKEN)

Solution

  • You must use AsyncIOScheduler instead of BackgroundScheduler. Its accompanying AsyncIOExecutor is the only executor capable of running scheduled coroutine functions.