1

I am trying to create an API that gets channels participants Telegram. I am using telethon API in python, I am getting this error

Runtime Error: There is no current event loop in thread

here is my code

import os from threading import Thread from flask import Flask, request from telethon import TelegramClient app = Flask(__name__) api_id = os.environ['API_ID'] api_hash = os.environ['API_HASH'] client = TelegramClient("anon", api_id, api_hash) async def follow(channel_name): # await client.connect() # await client(JoinChannelRequest(channel=channel_name)) me = await client.get_me() print(me.stringify()) channel_users = await client.get_participants(channel_name) return channel_users @app.route('/') def home(): return "I'm alive" @app.route("/follow_channel", methods=["POST"]) def follow_channel(): body = request.get_json() user_id = body["userId"] user_hash = body["userHash"] user_name = body["userName"] channel_name = body["channelName"] client.loop.run_until_complete(client.get_me()) return "helllo" def run(): app.run(host='0.0.0.0',port=8080) t = Thread(target=run) t.start() 
2
  • post the traceback Commented Jan 10, 2022 at 12:14
  • Before attempting to mix threaded and asyncio-based libraries, I recommend you first learn to mix barebones threading and asyncio. An easier route is to use an async alternative to Flask, such as Quart. Commented Jan 12, 2022 at 12:05

1 Answer 1

1

Threads do not have an event loop, you simply need to use the main thread loop.

t = Thread(target=run, args=[client.loop]) 

and simply put the loop in run

def run(loop): asyncio.set_event_loop(loop) ... 

This should solve the problem. If your problem freezes then I dont know how to solve it now.

Sign up to request clarification or add additional context in comments.

2 Comments

I did this but server is not responding now
ok i will update code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.