Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

Telethon python3 example using string session get all my messages in a group given group…

  1. User

    Telethon python3 example using string session get all my messages in a group given group chat id and delete all those messages in a loop with 5 sec sleep each between each 10 messages and ensure all messages got deleted.

  2. Assistant

    Here is an example of a Python script using Telethon with the provided instructions. Please install Telethon first if you haven't already (pip install telethon).

    WARNING: The script will delete messages, which is irreversible. Please use it with caution.

    import asyncio
    from telethon.sync import TelegramClient
    from telethon.sessions import StringSession
    from telethon.errors import FloodWaitError
    
    # Use your own values from my.telegram.org
    api_id = 'your_api_id'
    api_hash = 'your_api_hash'
    string_session = 'your_string_session'
    
    # Group chat ID (you can get this with client.get_entity(group_link))
    group_chat_id = 'group_chat_id'
    
    async def delete_messages(client, chat_id):
        total_deleted = 0
        async for message in client.iter_messages(chat_id, from_user='me'):
            try:
                await client.delete_messages(chat_id, [message.id], revoke=True)
                total_deleted += 1
                print(f"Deleted message {message.id}")
                
                if total_deleted % 10 == 0:
                    print("Sleeping for 5 seconds...")
                    await asyncio.sleep(5)
            
            except FloodWaitError as e:
                print(f"Got a flood wait error. Sleeping for {e.seconds} seconds.")
                await asyncio.sleep(e.seconds)
            except Exception as e:
                print(f"An error occurred: {e}")
        print(f"Total deleted messages: {total_deleted}")
    
    async def main():
        async with TelegramClient(StringSession(string_session), api_id, api_hash) as client:
            await client.connect()
            await delete_messages(client, group_chat_id)
            messages_left = await client.get_messages(group_chat_id, from_user='me')
            if not messages_left:
                print("All messages have been deleted.")
            else:
                print(f"Some messages could not be deleted.")
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    

    Here's how the script works:

    1. Import necessary modules from Telethon.
    2. Set up your API ID, API hash, and StringSession, all of which can be obtained through https://my.telegram.org/auth.
    3. The delete_messages asynchronous function will go through all of your messages in the specified group and will delete them in a batch. It pauses for 5 seconds after every 10 messages.
    4. The main function is the entry point that establishes the connection with the TelegramClient and calls the delete_messages function with the group chat ID.
    5. We get the event loop and run the main function, which will connect and perform the deletion process.

    Please replace 'your_api_id', 'your_api_hash', 'your_string_session', and 'group_chat_id' with your actual API credentials, StringSession, and group chat ID.

    Run this script with caution, as it cannot be undone. Ensure that you really want to remove your messages from the group before running this script.

  3. User

    Add a progress as well that shows as inplace buffer about total messages deleted out of total messages

  4. Assistant

    You can include progress information by modifying the deletion loop to fetch the total message count first, and then display the deletion progress while deleting each message. The following script includes these changes:

    import asyncio
    from telethon.sync import TelegramClient
    from telethon.sessions import StringSession
    from telethon.errors import rpcerrorlist
    
    # Use your own values from my.telegram.org
    api_id = 'your_api_id'
    api_hash = 'your_api_hash'
    string_session = 'your_string_session'
    
    # Group chat ID (you can get this with client.get_entity(group_link))
    group_chat_id = 'group_chat_id'
    
    async def delete_messages(client, chat_id):
        total_deleted = 0
        count = await client.get_messages(chat_id, from_user='me', limit=0).total
        print(f"Total messages to delete: {count}")
    
        async for message in client.iter_messages(chat_id, from_user='me'):
            try:
                # Delete the message
                await client.delete_messages(chat_id, [message.id], revoke=True)
                total_deleted += 1
                
                # Print progress
                print(f"\rDeleted {total_deleted} out of {count} messages.", end="")
    
                # Sleep after every 10 messages
                if total_deleted % 10 == 0:
                    print("\nSleeping for 5 seconds...")
                    await asyncio.sleep(5)
            
            except rpcerrorlist.FloodWaitError as e:
                print(f"Got a flood wait error. Sleeping for {e.seconds} seconds.")
                await asyncio.sleep(e.seconds)
            except Exception as e:
                print(f"An error occurred: {e}")
        
        if total_deleted == count:
            print("\nAll messages have been deleted.")
        else:
            print(f"\nSome messages could not be deleted. Deleted {total_deleted} out of {count} messages.")
    
    async def main():
        async with TelegramClient(StringSession(string_session), api_id, api_hash) as client:
            await delete_messages(client, group_chat_id)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    

    Here's what the updated script does:

    1. Queries the total number of messages to delete initially, to establish the total count.
    2. Shows progress information directly in the terminal by printing the current status with carriage return (\r) after each delete operation to overwrite the previous progress output.
    3. Reports completion status, whether all messages were deleted or if some could not be deleted.

    Replace 'your_api_id', 'your_api_hash', 'your_string_session', and 'group_chat_id' with your actual API credentials, StringSession, and group chat ID. Please note that I have used the print function with \r at the beginning, which allows the script to show the progress on the same line, creating the effect of an updating progress bar in a command-line environment.

    IMPORTANT: This script will irreversibly delete messages. Use it with caution and verify that you want the messages to be deleted before running the script.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.