【发布时间】: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