Home > Mobile >  RuntimeWarning: coroutine 'function' was never awaited
RuntimeWarning: coroutine 'function' was never awaited

Time:02-11

I have a class PersonalMessage with a function sendPersonalMessage that sends a message to a user in telegram.

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

when I try to call the function in the main .py file like this:

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

it gives me this error: RuntimeWarning: coroutine 'PersonalMessage().sendPersonalMessage(response, user_id_1)' was never awaited

CodePudding user response:

You should probably do await PersonalMessage().sendPersonalMessage(response, user_id_1) instead of using asyncio.run to execute this individual coroutine, unless you want to lose the benefits of using asyncio (ability to run other coroutines concurrently).

asyncio.run should be the entry point of your whole program, and all your functions dealing with I/O should be declared as async def. The answers here and here elaborate a bit further.

CodePudding user response:

I got it I just had to import asyncio and wrap the function like this:

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