Coroutine error when using threading with python, RuntimeWarning: coroutine 'time_messege' was never awaited

Viewed 269

They know how to fix these 2 ** coroutine errors when using threading with python ** :

C:\Users\PC0\Anaconda3\lib\threading.py:870: RuntimeWarning: coroutine 'time_messege' was never awaited
  self._target(*self._args, **self._kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

From this function in a main script I assemble the thread

    async def on_ready(self) -> None:

        print("Logged on as {0}!".format(self.user))

        x = threading.Thread(target=time_messege) #Creo un thread independiente del main_thread
        x.start()

Import this... :

from core.modules.greetings import time_messege
import threading
import asyncio

But it still doesn't work:

import time, random, discord
from datetime import datetime
import asyncio


async def time_messege():

    alarmtime = "09:59"
    channel = bot.get_channel("814238156396298310")

    while True:
      
        lcltime = datetime.now().strftime('%H:%M')

        if lcltime == alarmtime:

            #aca pondria el code de detectar canal y enviar
            print("is time!")

            random_num = random.randint(1, 4)

            if answer_num == 1:
                await greeting_channel.send(f"""AA""")
            if answer_num == 2:
                await greeting_channel.send(f"""A""")
            if answer_num == 3:
                await greeting_channel.send(f"""B""")
            elif answer_num == 4:
                await greeting_channel.send(f"""c""")

            time.sleep(90)

        else:
            print("not yet")
            time.sleep(10)

The truth is that I no longer understand why that error appears, I hope you can help me with these 2 errors.

1 Answers

time_message is an async function but when you start it, you aren't awaiting it. However I do not recommend using threading in your bot. time.sleep will lead to blocking in your bot.

discord.py has its own native extension for making task loops. You should check this out, as it is made to work with an asynchronous environment.

Related