Skip to content

Instantly share code, notes, and snippets.

@yshalsager
Last active October 15, 2025 18:08
Show Gist options
  • Select an option

  • Save yshalsager/f10b59827f3dd8b05214a1e5331ddd9e to your computer and use it in GitHub Desktop.

Select an option

Save yshalsager/f10b59827f3dd8b05214a1e5331ddd9e to your computer and use it in GitHub Desktop.
A script to delete all messages in Telegram group topic using Telethon.
# requires-python = ">=3.13"
# dependencies = [
# "telethon",
# ]
# ///
import asyncio
from os import getenv
from telethon import TelegramClient
api_id = int(getenv("TG_API_ID"))
api_hash = getenv("TG_API_HASH")
group_id = int(getenv("TG_CHAT_ID"))
topic_id = int(getenv("TG_TOPIC_ID"))
min_id = int(getenv("TG_MIN_ID")) if getenv("TG_MIN_ID") else None
max_id = int(getenv("TG_MAX_ID")) if getenv("TG_MAX_ID") else None
if not all([api_id, api_hash, group_id, topic_id]):
print("API_ID, API_HASH, GROUP_ID, and TOPIC_ID must be set")
exit(1)
_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_loop)
client = TelegramClient("telethon_session", api_id, api_hash, loop=_loop)
async def main():
await client.start()
print(f"Deleting messages from topic {topic_id} in chat {group_id}...")
deleted_count = 0
message_ids = []
target = await client.get_entity(group_id)
iter_args = {
"reply_to": topic_id,
"reverse": True,
}
if min_id is not None:
iter_args["min_id"] = min_id
if max_id is not None:
iter_args["max_id"] = max_id
async for message in client.iter_messages(target, **iter_args):
message_ids.append(message.id)
# Delete in batches of 100 messages
if len(message_ids) == 100:
try:
await client.delete_messages(group_id, message_ids)
print(f"Deleted batch of {len(message_ids)} messages")
deleted_count += len(message_ids)
message_ids = []
await asyncio.sleep(0.5) # small delay to avoid rate limits
except Exception as e:
print(f"Error deleting batch: {e}")
await asyncio.sleep(2)
if message_ids:
try:
await client.delete_messages(group_id, message_ids)
print(f"Deleted final batch of {len(message_ids)} messages")
deleted_count += len(message_ids)
except Exception as e:
print(f"Error deleting final batch: {e}")
print(f"✅ Done. Total deleted: {deleted_count}")
await client.disconnect()
asyncio.run(main())
[tools]
python = "3.14"
"aqua:astral-sh/uv" = "latest"
[env]
TG_API_ID =
TG_API_HASH =
TG_CHAT_ID =
TG_TOPIC_ID =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment