I’m developing a Telegram bot using the Telethon library. I’ve defined an event handler function to handle specific events in a Telegram channel. However, when a relevant event occurs, the event handler function doesn’t seem to execute as expected.
Here all code:
import asyncio
from telethon import TelegramClient, events
from telethon.tl.functions.channels import GetFullChannelRequest
from config import api_id, api_hash, phone_number, welcome_message
session_name = 'new_session'
async def main():
client = TelegramClient(session_name, api_id, api_hash)
await client.start(phone_number)
try:
channel = await client(GetFullChannelRequest('yaebav1010'))
channel_id = channel.full_chat.id
@client.on(events.ChatAction(chats=channel_id))
async def handler(event):
print(f"Event received: {event}")
if event.user_added or event.user_joined:
try:
new_user = await event.get_user()
user_id = new_user.id
print(f"New user joined: {new_user.username or new_user.id}")
await client.send_message(user_id, welcome_message)
print(f"Message sent to {new_user.username or new_user.id}")
except Exception as e:
print(f"Failed to send message to {new_user.username or new_user.id}: {e}")
print('Bot started...')
while True:
try:
await client.run_until_disconnected()
except Exception as e:
if "Disconnect" in str(e):
print("Disconnected. Reconnecting...")
await asyncio.sleep(5) # pause for 5 seconds before attempting to reconnect
await client.connect()
await client.start(phone_number)
except Exception as e:
print(f"Error occurred: {e}")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I verified that the event handler function is correctly defined and registered.
I ensured that the necessary event is triggered in the Telegram channel.
I checked for any errors or exceptions thrown during the execution of the event handler function, but there are no apparent issues.
I expect the event handler function to execute whenever the specified event occurs in the Telegram channel, allowing me to perform the desired actions in response to the event.
ap1aryy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1