Guest User

Untitled

a guest
Aug 22nd, 2018
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.69 KB | None | 0 0
  1. # pip install 'telethon==0.19.1.6'
  2.  
  3. from os import listdir
  4. from time import sleep
  5.  
  6. from telethon import TelegramClient
  7. from telethon.errors import SessionPasswordNeededError
  8. from telethon.tl.functions.channels import DeleteMessagesRequest
  9. from telethon.tl.functions.messages import \
  10. DeleteMessagesRequest as DeleteMessagesRequestFromUser
  11. from telethon.tl.functions.messages import GetHistoryRequest, SearchRequest
  12. from telethon.tl.types import (Channel, Chat, InputMessagesFilterEmpty,
  13. InputUserEmpty, InputUserSelf, MessageEmpty)
  14.  
  15. # Secondary functions
  16.  
  17. def chunks(l, n):
  18. """Splits list l into chunks of size n. Returns generator"""
  19. for i in range(0, len(l), n):
  20. yield l[i:i + n]
  21.  
  22.  
  23. def print_header(text):
  24. """Just for nice output"""
  25. print('====================')
  26. print('= {} ='.format(text))
  27. print('====================')
  28.  
  29. ###########################################
  30.  
  31. API_ID = 111111
  32. API_HASH = '111111111111111111111'
  33. PHONE = '+11111111111'
  34.  
  35. class DeleterClient(TelegramClient):
  36. def __init__(self, session_user_id, user_phone, api_id, api_hash):
  37. super().__init__(session_user_id, api_id, api_hash)
  38.  
  39. self.messages_to_delete = set()
  40.  
  41. # Check connection to the server
  42. print('Connecting to Telegram servers...')
  43. if not self.connect():
  44. print('Initial connection failed. Retrying...')
  45. if not self.connect():
  46. print('Could not connect to Telegram servers.')
  47. return
  48.  
  49. # Check authorization
  50. if not self.is_user_authorized():
  51. print('First run. Sending code request...')
  52. self.send_code_request(user_phone)
  53.  
  54. self_user = None
  55. while self_user is None:
  56. code = input('Enter the code you just received: ')
  57. try:
  58. self_user = self.sign_in(user_phone, code)
  59.  
  60. # Two-step verification may be enabled
  61. except SessionPasswordNeededError:
  62. pw = input('Two step verification is enabled. Please enter your password: ')
  63. self_user = self.sign_in(password=pw)
  64.  
  65. limit = input('Enter number of chats to show them (empty for all): ')
  66. # To show specified number of chats
  67. if limit:
  68. self.limit = int(limit)
  69. else:
  70. self.limit = None
  71.  
  72. def run(self):
  73. peer = self.choose_peer()
  74. self.messages_to_delete.update(msg.id for msg in self.get_messages(peer))
  75. r = self.delete_messages_from_peer(peer)
  76. return r
  77.  
  78. def choose_peer(self):
  79. entities = [d.entity for d in self.get_dialogs(limit=self.limit)]
  80. s = ''
  81.  
  82. entities = [entity for entity in entities if isinstance(entity, Channel)]
  83. entities = [entity for entity in entities if entity.megagroup]
  84.  
  85. for i, entity in enumerate(entities):
  86. name = entity.title
  87. s += '{}. {}\t | {}\n'.format(i, name, entity.id)
  88.  
  89. print(s)
  90. num = input('Choose group: ')
  91. print('Chosen: ' + entities[int(num)].title)
  92.  
  93. return entities[int(num)]
  94.  
  95. def delete_messages_from_peer(self, peer):
  96. messages_to_delete = list(self.messages_to_delete)
  97. print_header('Delete {0} my messages in chat {1}'.format(len(messages_to_delete), peer.title))
  98. for chunk_data in chunks(messages_to_delete, 100): # Because we can delete only 100 messages (Telegram API restrictions)
  99. r = self(DeleteMessagesRequest(peer, chunk_data))
  100. if r.pts_count:
  101. print('Number of deleted messages: {0}'.format(r.pts_count))
  102. sleep(1)
  103. return True
  104.  
  105. def get_messages(self, peer, limit=100, offset_id=0, max_id=0, min_id=0):
  106. print_header('Getting messages...')
  107. add_offset = 0
  108. messages = []
  109.  
  110. while True:
  111. sleep(1)
  112. result = self(SearchRequest(
  113. peer=peer,
  114. q='',
  115. filter=InputMessagesFilterEmpty(),
  116. min_date=None,
  117. max_date=None,
  118. offset_id=offset_id,
  119. add_offset=add_offset,
  120. limit=limit,
  121. max_id=max_id,
  122. min_id=min_id,
  123. from_id=InputUserSelf(),
  124. hash=0
  125. ))
  126.  
  127. if result.messages:
  128. print('Received: {0} messages. Offset: {1}.'.format(len(result.messages), add_offset))
  129. messages.extend(result.messages)
  130. add_offset += len(result.messages)
  131. else:
  132. print_header("It's stopped because it met end of chat.")
  133. return messages
  134.  
  135.  
  136. client = DeleterClient('Deleter', PHONE, API_ID, API_HASH)
  137. client.run()
Add Comment
Please, Sign In to add comment