Hrozone
Hrozone

Reputation: 1

how to listen updates from telegram and send the msg to a group on fulfilled conditions with telethon library

i want to listen updates from telegram and send the msg to a group on fulfilled conditions simultaneously but i am not able to do both together i am facing issue with client connection

I am using this code but if i call client.send_message method without checking the client is connected or not and reconnect if it is disconnected i receive this error can't send message when client is not connected and if i connect it in send update function i receive the account is likely misusing the session: database is locked error i am starting the client in main method with client.start() and receiving the update accurately but not able to send message to the group with the client i am using global client variable

client = TelegramClient('sess', api_id, api_hash)

async def send_update_filter(html_content, group_id):
    try:
        if not client.is_connected():
            print("connecting client again")
            await client.connect()
        await client.send_message(entity=group_id,  # Group ID or username
                                  message=html_content,  # HTML message content
                                  parse_mode='html')  # Specify HTML parsing
    except Exception as e:
        print(f"Failed to send message: {e}")


async def main():
    try:
        await client.start()

        await asyncio.gather(
            get_edit_update(),
            get_updates()
        )
    except Exception as e:
        print(f"Error occurred: {e}")

    finally:
        # Ensure disconnection in all scenarios
        await client.disconnect()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(f"Main execution error: {e}")

Upvotes: 0

Views: 56

Answers (1)

Nafis
Nafis

Reputation: 11

Don't run asyncio.run(), its a common issue, use asyncio.get_event_loop().run_until_complete() and then use client.run_until_disconnected()

Caution: Do not use asyncio.run() in Telethon!

Edit: Also, first connect the client and then use the connected client in all gathering functions directly, Do not again and again connect in those gathering client for database locked issue!

Upvotes: 0

Related Questions