Skip to content

Instantly share code, notes, and snippets.

@mahdizojaji
Last active April 15, 2021 23:12
Show Gist options
  • Save mahdizojaji/41311b37e6f690187b21189eeba7a1f8 to your computer and use it in GitHub Desktop.
Save mahdizojaji/41311b37e6f690187b21189eeba7a1f8 to your computer and use it in GitHub Desktop.
delete self messages

Delete all self messages (when user not admin of telegram group) [with pyrogram]

  • Requirements:

    1. pip3 install pyrogram
    2. pip3 install -U pyrogram[fast]
  • Usag:

    1. Get your api-id & api-hash then Insert these on Client parameters.
    2. Enter command python3 delete_self_msg.py (if your region has limited: torsocks python3 delete_self_msg.py)
  • Community: @PyrogramIR

from pyrogram import Client, Message, Filters, MessageHandler
from pyrogram.api import functions, types
app = Client(
session_name='app',
api_id=12345,
api_hash='your api-hash'
# You can get your api-id and api-hash in: https://my.telegram.org
)
def search_msg(bot: Client, chat_id):
offset_id = 0
current = 0
total = (1 << 31) - 1
limit = min(100, total)
while True:
search = bot.send(
functions.messages.Search(
peer=bot.resolve_peer(chat_id),
q='',
filter=types.InputMessagesFilterEmpty(),
min_date=0,
max_date=0,
offset_id=offset_id,
add_offset=0,
limit=limit,
max_id=0,
min_id=0,
hash=0,
from_id=bot.resolve_peer(bot.get_me().id)
)
)
if not search.messages:
return
offset_id = search.messages[-1].id
for message in search.messages:
if not isinstance(message, types.MessageService):
yield message
current += 1
if current >= total:
return
def on_message(bot: Client, msg: Message):
msg_ids = []
for message in search_msg(bot, msg.chat.id):
msg_ids.append(message.id)
try:
bot.delete_messages(msg.chat.id, msg_ids)
print(f'{len(msg_ids)} messages from {msg.chat.id} has been deleted.')
except Exception as error:
print(f'{error}')
def main():
with app:
app.add_handler(
MessageHandler(
callback=on_message,
filters=Filters.user(app.get_me().id) & Filters.regex('^[!?#]?[Cc][Ll][Ee][Aa][Nn]$')
)
)
app.idle()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment