Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # pip install 'telethon==0.19.1.6'
- from os import listdir
- from time import sleep
- from telethon import TelegramClient
- from telethon.errors import SessionPasswordNeededError
- from telethon.tl.functions.channels import DeleteMessagesRequest
- from telethon.tl.functions.messages import \
- DeleteMessagesRequest as DeleteMessagesRequestFromUser
- from telethon.tl.functions.messages import GetHistoryRequest, SearchRequest
- from telethon.tl.types import (Channel, Chat, InputMessagesFilterEmpty,
- InputUserEmpty, InputUserSelf, MessageEmpty)
- # Secondary functions
- def chunks(l, n):
- """Splits list l into chunks of size n. Returns generator"""
- for i in range(0, len(l), n):
- yield l[i:i + n]
- def print_header(text):
- """Just for nice output"""
- print('====================')
- print('= {} ='.format(text))
- print('====================')
- ###########################################
- API_ID = 111111
- API_HASH = '111111111111111111111'
- PHONE = '+11111111111'
- class DeleterClient(TelegramClient):
- def __init__(self, session_user_id, user_phone, api_id, api_hash):
- super().__init__(session_user_id, api_id, api_hash)
- self.messages_to_delete = set()
- # Check connection to the server
- print('Connecting to Telegram servers...')
- if not self.connect():
- print('Initial connection failed. Retrying...')
- if not self.connect():
- print('Could not connect to Telegram servers.')
- return
- # Check authorization
- if not self.is_user_authorized():
- print('First run. Sending code request...')
- self.send_code_request(user_phone)
- self_user = None
- while self_user is None:
- code = input('Enter the code you just received: ')
- try:
- self_user = self.sign_in(user_phone, code)
- # Two-step verification may be enabled
- except SessionPasswordNeededError:
- pw = input('Two step verification is enabled. Please enter your password: ')
- self_user = self.sign_in(password=pw)
- limit = input('Enter number of chats to show them (empty for all): ')
- # To show specified number of chats
- if limit:
- self.limit = int(limit)
- else:
- self.limit = None
- def run(self):
- peer = self.choose_peer()
- self.messages_to_delete.update(msg.id for msg in self.get_messages(peer))
- r = self.delete_messages_from_peer(peer)
- return r
- def choose_peer(self):
- entities = [d.entity for d in self.get_dialogs(limit=self.limit)]
- s = ''
- entities = [entity for entity in entities if isinstance(entity, Channel)]
- entities = [entity for entity in entities if entity.megagroup]
- for i, entity in enumerate(entities):
- name = entity.title
- s += '{}. {}\t | {}\n'.format(i, name, entity.id)
- print(s)
- num = input('Choose group: ')
- print('Chosen: ' + entities[int(num)].title)
- return entities[int(num)]
- def delete_messages_from_peer(self, peer):
- messages_to_delete = list(self.messages_to_delete)
- print_header('Delete {0} my messages in chat {1}'.format(len(messages_to_delete), peer.title))
- for chunk_data in chunks(messages_to_delete, 100): # Because we can delete only 100 messages (Telegram API restrictions)
- r = self(DeleteMessagesRequest(peer, chunk_data))
- if r.pts_count:
- print('Number of deleted messages: {0}'.format(r.pts_count))
- sleep(1)
- return True
- def get_messages(self, peer, limit=100, offset_id=0, max_id=0, min_id=0):
- print_header('Getting messages...')
- add_offset = 0
- messages = []
- while True:
- sleep(1)
- result = self(SearchRequest(
- peer=peer,
- q='',
- filter=InputMessagesFilterEmpty(),
- min_date=None,
- max_date=None,
- offset_id=offset_id,
- add_offset=add_offset,
- limit=limit,
- max_id=max_id,
- min_id=min_id,
- from_id=InputUserSelf(),
- hash=0
- ))
- if result.messages:
- print('Received: {0} messages. Offset: {1}.'.format(len(result.messages), add_offset))
- messages.extend(result.messages)
- add_offset += len(result.messages)
- else:
- print_header("It's stopped because it met end of chat.")
- return messages
- client = DeleterClient('Deleter', PHONE, API_ID, API_HASH)
- client.run()
Add Comment
Please, Sign In to add comment