Automating Telegram Channel and Chat Cleanup with Telethon

now a days every one is really busy with their lives. and keep track of social accounts are really tough like many Telegram channels, groups and chats. If your telegram is really mess up with many chats and telegrams channels and do you want to clean up this mess at once, using automation can make the job much easier. This article will delve into how you can use the Telethon library to automate leaving channels and groups, as well as deleting chat histories in just few minutes by using Python.

Introduction to Telethon

Telethon is a strong and very famous Python library that makes it really easy to work with the Telegram API. It offers both asynchronous and synchronous options for different Telegram functions, making it a great tool for developers who want to automate tasks on Telegram.

Setting Up the Environment

Before we dive into the code, ensure you have the following prerequisites:

  1. Python 3.6+: Telethon requires Python 3.6 or newer.
  2. Telethon Library: You can install it via pip by using your terminal.
pip install telethon

Code Explanation

Here is the Python script that automates the process of leaving channels, groups, and deleting chat histories in a minute.

from telethon.sync import TelegramClient
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.messages import DeleteHistoryRequest
from telethon.tl.types import InputPeerChannel, InputPeerChat, InputPeerUser

# Replace with your own values from my.telegram.org
api_id = 'YOUR_API_ID'  #paste your api_id here
api_hash = 'YOUR_API_HASH'  #paste your api_hash here
phone_number = 'YOUR_PHONE_NUMBER' #your phone no which is connected with your telegram account

client = TelegramClient('session_name', api_id, api_hash, connection_retries=5, timeout=30)

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

    dialogs = await client.get_dialogs()

    for dialog in dialogs:
        entity = dialog.entity
        if dialog.is_channel:
            if getattr(entity, 'left', False):
                print(f'Already left channel: {entity.title}')
            else:
                print(f'Leaving channel: {entity.title}')
                try:
                    await client(LeaveChannelRequest(channel=InputPeerChannel(entity.id, entity.access_hash)))
                except Exception as e:
                    print(f'Error leaving channel: {e}')

            print(f'Deleting chat history in channel: {entity.title}')
            try:
                await client(DeleteHistoryRequest(peer=InputPeerChannel(entity.id, entity.access_hash), max_id=0, just_clear=False, revoke=True))
            except Exception as e:
                print(f'Error deleting chat history: {e}')

        elif dialog.is_group:
            if getattr(entity, 'left', False):
                print(f'Already left group: {entity.title}')
            else:
                print(f'Leaving group: {entity.title}')
                try:
                    await client(LeaveChannelRequest(channel=InputPeerChat(entity.id)))
                except Exception as e:
                    print(f'Error leaving group: {e}')

            print(f'Deleting chat history in group: {entity.title}')
            try:
                await client(DeleteHistoryRequest(peer=InputPeerChat(entity.id), max_id=0, just_clear=False, revoke=True))
            except Exception as e:
                print(f'Error deleting chat history: {e}')

        elif dialog.is_user:
            print(f'Deleting chat history with user: {entity.username or entity.phone}')
            try:
                await client(DeleteHistoryRequest(peer=InputPeerUser(entity.id, entity.access_hash), max_id=0, just_clear=False, revoke=True))
            except Exception as e:
                print(f'Error deleting chat history: {e}')

with client:
    client.loop.run_until_complete(main())

Explanation of the Code

  • Importing Necessary Modules:
from telethon.sync import TelegramClient
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.messages import DeleteHistoryRequest
from telethon.tl.types import InputPeerChannel, InputPeerChat, InputPeerUser
  • Setting Up API Credentials: Replace the placeholders (YOUR_API_ID, YOUR_API_HASH, and YOUR_PHONE_NUMBER) with your actual credentials obtained from my.telegram.org.
  • Initializing the Telegram Client:
client = TelegramClient('session_name', api_id, api_hash, connection_retries=5, timeout=30)
  • Main Function: The main function is where the automation happens. It starts the client, fetches all dialogs (conversations), and processes each dialog to leave channels/groups and delete chat histories.
  • Processing Each Dialog: The script checks if the dialog is a channel, group, or user chat, and performs the necessary actions (leaving the channel/group and deleting chat history).
  • Running the Script: The script is executed within the client’s event loop using client.loop.run_until_complete(main()).

Conclusion

This script demonstrates how to automate Telegram channel and chat management using Telethon. By modifying and extending this script, you can tailor it to your specific needs, making Telegram account maintenance more efficient and less time-consuming. if any problem you can comment in the comment box bellow.

Leave a Comment