RuntimeWarning:从未等待协程 'function'
RuntimeWarning: coroutine 'function' was never awaited
我有一个 class 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
我明白了,我只需要导入 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.run
来执行这个单独的协程,除非你想失去使用 asyncio 的好处(能够同时 运行 其他协程) .
asyncio.run
应该是整个程序的入口点,所有处理 I/O 的函数都应该声明为 async def
。答案 and 进一步详细说明。
我有一个 class 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
我明白了,我只需要导入 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.run
来执行这个单独的协程,除非你想失去使用 asyncio 的好处(能够同时 运行 其他协程) .
asyncio.run
应该是整个程序的入口点,所有处理 I/O 的函数都应该声明为 async def
。答案