【问题标题】:Coroutine error when using threading with python, RuntimeWarning: coroutine 'time_messege' was never awaited使用 python 线程时出现协程错误,RuntimeWarning: coroutine 'time_messege' 从未等待
【发布时间】:2021-08-01 23:43:34
【问题描述】:

他们知道如何在 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

我从主脚本中的这个函数组装线程

    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()

导入这个...:

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

但还是不行:

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)

事实是我不再明白为什么会出现这个错误,希望你能帮助我解决这两个错误。

【问题讨论】:

    标签: python python-3.x multithreading discord artificial-intelligence


    【解决方案1】:

    time_message 是一个异步函数,但是当你启动它时,你并没有等待它。 但是我不建议在你的机器人中使用线程。 time.sleep 将导致您的机器人中的blocking

    discord.py 有自己的原生扩展来制作task loops。您应该检查一下,因为它适用于异步环境。

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2020-10-10
      • 2018-10-26
      • 1970-01-01
      • 2021-10-22
      • 2019-12-15
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多