N
N
neuro4live2021-12-01 18:07:27
Python
neuro4live, 2021-12-01 18:07:27

How to use Telethon in streams?

Hello! I need to write an application using flask that will send a message to the user in a telegram. To work with the telegram, I decided to use the Telethon library. When calling the send message function, the program throws an error There is no current event loop in thread 'Thread-1'
The official documentation has an example of teleson working with threads

import asyncio
import threading

async def actual_work():
    client = TelegramClient(..., loop=loop)
    ...  # can use `await` here

def go():
    asyncio.run(actual_work())

threading.Thread(target=go).start()


In my case, the program gives the same error... I know that it's better not to use asynchronous code in threads, but still, please tell me how to solve this problem. Here is my code which I tried to use to run asynchronous code in threads. Thanks in advance

from telethon import TelegramClient
import asyncio
import threading

loop=asyncio.new_event_loop()
api_id = 11111111
api_hash = '911111111111'
client = TelegramClient('puat_notification.session', api_id, api_hash, loop=loop)





async def send_message():

    await client.send_message('+7901111', '123')





def go():
    with client:
        asyncio.run(send_message())


threading.Thread(target=go).start()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
neuro4live, 2021-12-01
@neuro4live

Thanks to all. Figured it out myself.
Might be useful to someone:

from telethon import TelegramClient
import asyncio
import threading







async def send_message():
    loop = asyncio.new_event_loop()
    api_id = 555
    api_hash = '555555555'
    client = TelegramClient('55555555.session', api_id, api_hash, loop=loop)
    async with client:
        await client.send_message('+55555555', '123')





def go():
    asyncio.run(send_message())


threading.Thread(target=go).start()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question