Reputation: 569
I am trying to use Quart with Hypercorn and Telethon. I have a message listener, but since I integrated Quart and Telethon, the listener does not fire any more (please see the minimal reproducible example below). Has anybody an idea why this code does not work?
I used this code as template, but it is not exactly the same usecase, as there is no update listener.
When I start the code with python3 main.py
everything works correctly, but when I start with python3 -m hypercorn main:api
(Windows 10) the listener doesn't work.
import os
from dotenv import load_dotenv
from telethon import TelegramClient, events, sync
import hypercorn.asyncio
from quart import Quart, request, json
# Load environment variables
load_dotenv()
# Global variables
allMessages = []
# Enable connection
api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")
phone_number = os.getenv("PHONE_NUMBER")
channel_username=os.getenv("CHANNEL")
client = TelegramClient('abc', api_id, api_hash)
client.start(phone_number)
# Get chat entity
chat = client.get_entity(channel_username)
# Listen for new messages
@client.on(events.NewMessage(incoming=True, chats=chat))
async def handler(event):
message = event.message
allMessages.insert(0, message)
print(message.stringify())
# Web Server
api = Quart(__name__)
@api.route('/messages/json', methods=['GET'])
def route_get_messages_json():
return "test"
async def main():
await hypercorn.asyncio.serve(api, hypercorn.Config())
if __name__ == '__main__':
client.loop.run_until_complete(main())
Moreover, I have tried to replace the bottom few lines with the snipped from this question, but unfortunately, that didn't work either.
async def main():
await serve(api, hypercorn.config.Config())
if __name__ == '__main__':
loop = client.loop
asyncio.set_event_loop(loop)
client.loop.run_until_complete(main())
Upvotes: 1
Views: 513
Reputation: 7039
Using python3 -m hypercorn
will create a new event loop, which will stop the one setup and used by the Telethon client. Whereas your python3 main.py
usage will run Hypercorn in the client event loop (client.loop.run_until_complete(main())
). Using python3 main.py
is therefore the best option for you.
Upvotes: 1