'Telegram Message Listener - RuntimeError: Event Loop is closed
I want to receive new messages from Telegram via a python script. I filter the message and then put out the result. But there is something wrong with the loop so I can't use this script in another because it always ends with this error. This is my Code:
import asyncio
import configparser
from telethon import TelegramClient, events
#Reading Config
config = configparser.ConfigParser()
config.read("config.ini")
#Setting configuration values
api_id = config["Telegram"]["api_id"]
api_hash = config["Telegram"]["api_hash"]
api_id = int(api_id)
api_hash = str(api_hash)
phone = config["Telegram"]["phone"]
username = config["Telegram"]["username"]
async def get_msg_async():
client = TelegramClient("session_read", api_id, api_hash)
user_input_channel = "https://t.me/+boLhJxP8JDU1NmVi"
message_filter = "Coin is:"
found = asyncio.get_event_loop().create_future()
@client.on(events.NewMessage())
async def new_message_listener(event):
new_message = event.message.message
channel = event.message.peer_id.channel_id
if new_message.find(message_filter) != -1 and channel == 1717661228:
search_index_coin = new_message.find("Coin is: ")
coin = new_message[search_index_coin + 9 : search_index_coin + 14]
if coin.find("\n") != -1:
blank_index = coin.find("\n")
coin = coin[:blank_index]
if new_message.find("Projected Gain: ") != -1:
search_index_gain = new_message.find("Projected Gain: ")
gain = new_message[search_index_gain + 16 : search_index_gain + 20]
if gain.find("-") != -1:
dash_index = gain.find("-")
gain = gain[:dash_index]
elif gain.find("%") != -1:
percent_index = gain.find("%")
gain = gain[:percent_index]
found.set_result({"coin": coin, "gain": gain})
else:
found.set_result({"coin": coin})
else:
print("Not found!")
# start the client
await client.start()
# allow the client to run in the background and wait for
# newMessageListener to provide the message
return await found
def get_msg():
asyncio.run(get_msg_async())
if __name__ == "__main__":
msg = get_msg()
print(msg)
When I get a new message I get a output with the right result but also the Error. How to fix this?
{'coin': 'BTC', 'gain': '600'}
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000002640CC73E20>
Traceback (most recent call last):
File "C:\Users\xamre\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\xamre\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\xamre\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\xamre\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Solution 1:[1]
This is actually a bug in asyncio on windows.
You can read about the details here if interested.
This was the code I was using at the top of all my projects:
# Windows Development Fix
# Big thanks to https://github.com/paaksing for this snippet!
# https://github.com/aio-libs/aiohttp/issues/4324
# http://www.apache.org/licenses/LICENSE-2.0
import platform
from functools import wraps
# Protected member is being patched as a bug fix.
# noinspection PyProtectedMember
from asyncio.proactor_events import _ProactorBasePipeTransport
def silence_event_loop_closed(func):
""" This code serves to fix a crash that specifically happens on windows due to the aiohttp
library using a different underlying mechanism on windows. See issue 4324 for more information."""
@wraps(func)
def wrapper(self, *args, **kwargs):
"""Wraps the incoming function with an exception handler"""
try:
return func(self, *args, **kwargs)
except RuntimeError as e:
if str(e) != 'Event loop is closed':
raise
return wrapper
if platform.system() == 'Windows':
# Silence the exception here.
_ProactorBasePipeTransport.__del__ = silence_event_loop_closed(_ProactorBasePipeTransport.__del__)
# End Windows Development Fix
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |