How to delete all messages in a telegram conversation except the pinned pyrogram?

263 views Asked by At

I'm writing a userbot and I need functionality for clearing messages. Only in the group there is a pinned message that does not need to be deleted. I searched online, but couldn't figure out how to parse the messages and delete all of them except the top one.

async def handleCommands(client: Client, message: Message):
    if message.chat.id == manage_channel_id and message.text == '/clear':
        for mesID in range(message.id - 50, message.id + 1):
            print(mesID)
            await client.delete_messages(manage_channel_id, mesID)

Now everything works for me manually, that is, the current message '/clear' and the 50 messages after it (by id) are deleted. How can I delete only those messages that are in the conversation except for one pinned one

1

There are 1 answers

1
Akshay Saambram On BEST ANSWER

To delete all messages in a Telegram group conversation except the pinned one using Pyrogram, you'll need to use Pyrogram's iter_history method to iterate through the messages and check if a message is pinned before deleting it. Here's a modified version of your code:

from pyrogram import Client
from pyrogram.types import Message

async def handleCommands(client: Client, message: Message):
    if message.chat.id == manage_channel_id and message.text == '/clear':
        async for msg in client.iter_history(manage_channel_id, limit=50):
            if not msg.pinned:
                await client.delete_messages(manage_channel_id, msg.message_id)

In this code:

We use the iter_history method to iterate through the last 50 messages in the specified chat (manage_channel_id).

For each message, we check if it's pinned using msg.pinned. If it's not pinned, we delete the message using client.delete_messages.

This code will delete all messages in the chat except the pinned one. Make sure you have the necessary permissions to delete messages in the group.