import random
from telethon import TelegramClient, events
def main():
api_id = 9123640
api_hash = '8as6fgvs8t9ar76fse89rgearz'
chat = '@username'
message = 'hi'
client = TelegramClient('afewfe', api_id, api_hash)
@client.on(events.NewMessage(chats=chat))
async def normal_handler(event):
if event.message.button_count == 4:
await event.message.click(random.randint(0, 3))
await client.disconnect()
client.start()
client.send_message(chat, message)
client.run_until_disconnected()
if __name__ == '__main__':
main()
I want to send message to user then get back from user message with 4 buttons, click random button and stop script. Problem with sending message. If I comment line client.send_message(chat, message)
and send message by myself, code will continue working fine but but line client.send_message(chat, message)
an error appears:
RuntimeWarning: coroutine 'MessageMethods.send_message' was never awaited
client.send_message('@username', 'hi')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
How to solve this problem?
3
Answers
Full error:
It looks like you are running asynchronous code in a normal function. The error is complaining that the
client.send_message(chat, message)
code doesn’t have theawait
keyword before it. In order to be able to run any async function the way you want to (as just a normal function call), you must have theawait
keyword before the function call’s code. To be able to use the await keyword without throwing an error, the outer function holding the code (main
) needs to be asynchronous and can be run withasyncio.run
.Just import:
That should work.