【问题标题】:RuntimeWarning: coroutine 'function' was never awaitedRuntimeWarning:从未等待协程“功能”
【发布时间】:2022-03-22 13:34:18
【问题描述】:

我有一个 PersonalMessage 类,它的函数 sendPersonalMessage 可以通过电报向用户发送消息。

class PersonalMessage:
def __init__(self):
    self.api_id = api_id,
    self.api_hash = api_hash,
    self.token = token,
    self.user_id_1 = user_id_1,
    self.phone = phone

async def sendPersonalMessage(self, message, user_id):
    client = TelegramClient('session', api_id, api_hash)
    await client.connect()
    if not client.is_user_authorized():
        await client.send_code_request(phone)
        await client.sign_in(phone, input('Enter the code: '))
    try:
        receiver = InputPeerUser(user_id, 0)
        await client.send_message(receiver, message, parse_mode='html')
    except Exception as e:
        print(e)
    client.disconnect()

当我尝试像这样调用主 .py 文件中的函数时:

elif there_exists(['send', 'send']):
    speak("What should I send?")
    response = takeCommand()
    PersonalMessage().sendPersonalMessage(response, user_id_1)

它给了我这个错误:RuntimeWarning: coroutine 'PersonalMessage().sendPersonalMessage(response, user_id_1)' was never awaited

【问题讨论】:

  • 嗯,错误信息告诉你问题出在哪里:sendPersonalMessage 是一个协程(它是用await def 声明的)但你没有等待它。所以它永远不会运行。您需要在方法调用前加上await
  • 是的,但是我在哪里添加异步,if 语句被包装在一个 while 循环中
  • 包含await的函数必须声明为async def
  • 在 sendPersonalMessage() 函数中?

标签: python asynchronous python-asyncio python-telegram-bot py-telegram-bot-api


【解决方案1】:

你可能应该使用await PersonalMessage().sendPersonalMessage(response, user_id_1) 而不是使用asyncio.run 来执行这个单独的协程,除非你想失去使用 asyncio 的好处(同时运行其他协程的能力)。

asyncio.run 应该是整个程序的入口点,所有处理 I/O 的函数都应该声明为 async def。答案herehere 更详细一点。

【讨论】:

    【解决方案2】:

    我明白了,我只需要导入 asyncio 并像这样包装函数:

    elif there_exists(['send', 'send']):
        speak("What should I send?")
        response = takeCommand()
        asyncio.run(PersonalMessage().sendPersonalMessage(response, user_id_1))
        speak("Message sent successfully")
    

    【讨论】:

    • 不,你应该改用await PersonalMessage().sendPersonalMessage(response, user_id_1),除非你想失去使用 asyncio 的好处(同时运行其他协程的能力)。 asyncio.run 应该是整个程序的入口点,所有处理 I/O 的函数都应该声明为 async def。答案herehere 更详细一点。
    • 你能添加这个作为答案吗?
    猜你喜欢
    • 2018-10-26
    • 2021-10-22
    • 2019-12-15
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2020-10-10
    相关资源
    最近更新 更多