From 51ef4eeea9039da204577191351ce880a003710e Mon Sep 17 00:00:00 2001 From: Abhi <85984486+AbhiTheModder@users.noreply.github.com> Date: Sat, 15 Jun 2024 18:08:22 +0000 Subject: [PATCH 1/3] Fixes #18 --- helpers/TeleViewer.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/helpers/TeleViewer.py b/helpers/TeleViewer.py index 81bb314..84f6fab 100644 --- a/helpers/TeleViewer.py +++ b/helpers/TeleViewer.py @@ -13,24 +13,28 @@ def get_file_info(data): media_type = "" random_numbers = [random.randint(1, 100) for _ in range(6)] + # print("data.media value:", data.media) if data.media is not None: try: - for key in ['document', 'photo', 'video', 'location', 'voice', 'audio']: + for key in ['MessageMediaType.DOCUMENT', 'MessageMediaType.PHOTO', 'MessageMediaType.VIDEO', 'MessageMediaType.LOCATION', 'MessageMediaType.VOICE', 'MessageMediaType.AUDIO', 'MessageMediaType.STICKER']: if key in str(data): media_type = key + # print("Media_type found:", media_type) break - if media_type == "document": + if media_type == "MessageMediaType.DOCUMENT": return (data.document.file_id, data.document.file_name) - elif media_type == "photo": + elif media_type == "MessageMediaType.PHOTO": return (data.photo.file_id, f"{random_numbers}.png") - elif media_type == "video": + elif media_type == "MessageMediaType.VIDEO": return (data.video.file_id, data.video.file_name) - elif media_type == "location": + elif media_type == "MessageMediaType.LOCATION": return (data.location.file_id, data.location.file_name) - elif media_type == "voice": + elif media_type == "MessageMediaType.VOICE": return (data.voice.file_id, data.voice.file_name) - elif media_type == "audio": + elif media_type == "MessageMediaType.AUDIO": return (data.audio.file_id, data.audio.file_name) + elif media_type == "MessageMediaType.STICKER": + return (data.sticker.file_id, data.sticker.file_name) else: return (None, None) except Exception as e: @@ -113,6 +117,8 @@ async def progress(current, total): file.write(str(messages)) else: directory = f'Downloads/{chat_id}/logs' + if not os.path.exists(directory): + os.makedirs(directory) with open(f'{directory}/{chat_id}_bot.txt', 'a') as file: file.write(f"Message ID: {messages.id}\n") file.write(f"Date: {messages.date}\n") From 6ef9ca2f0754c26d04c58c25b99e5c244f403e53 Mon Sep 17 00:00:00 2001 From: Abhi <85984486+AbhiTheModder@users.noreply.github.com> Date: Sat, 15 Jun 2024 18:11:51 +0000 Subject: [PATCH 2/3] black --- TeleGatherer.py | 517 ++++++++++++++++++++++-------------------- helpers/TeleTexter.py | 53 +++-- helpers/TeleViewer.py | 254 +++++++++++---------- 3 files changed, 433 insertions(+), 391 deletions(-) diff --git a/TeleGatherer.py b/TeleGatherer.py index a52eac4..57fd96d 100644 --- a/TeleGatherer.py +++ b/TeleGatherer.py @@ -9,292 +9,321 @@ def parse_dict(title, dictionary): - result = f"{title}:\n" - for key, value in dictionary.items(): - if isinstance(value, dict): - result += '\n'.join(f"- {k}: {v}" for k, v in value.items()) - else: - result += f"- {key}: {value}\n" - return result + "\n" + result = f"{title}:\n" + for key, value in dictionary.items(): + if isinstance(value, dict): + result += "\n".join(f"- {k}: {v}" for k, v in value.items()) + else: + result += f"- {key}: {value}\n" + return result + "\n" + def delete_messages(bot_token, chat_id, message_id): - try: - response = deleteMessage(bot_token, chat_id, message_id) - if response.get("ok") == True: - print(f"Deleted message {message_id}") - message_id -= 1 - elif response.get("ok") == False and response.get("description") == "Bad Request: message can't be deleted for everyone": - print(f"Message {message_id} is an old message. You can only delete messages that are within 24 hours.") - elif response.get("ok") == False: - print(f"Message {message_id} not found.") - except Exception as e: - print(f"Error: {message_id}") + try: + response = deleteMessage(bot_token, chat_id, message_id) + if response.get("ok") == True: + print(f"Deleted message {message_id}") + message_id -= 1 + elif ( + response.get("ok") == False + and response.get("description") + == "Bad Request: message can't be deleted for everyone" + ): + print( + f"Message {message_id} is an old message. You can only delete messages that are within 24 hours." + ) + elif response.get("ok") == False: + print(f"Message {message_id} not found.") + except Exception as e: + print(f"Error: {message_id}") + def deleteMessage(bot_token, chat_id, message_id): - url = f"https://api.telegram.org/bot{bot_token}/deleteMessage" - data = {"chat_id": chat_id, "message_id": message_id} - response = requests.post(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/deleteMessage" + data = {"chat_id": chat_id, "message_id": message_id} + response = requests.post(url, data=data) + return response.json() + def send_file_to_telegram_channel(bot_token, chat_id, file_path): - try: - mime_type = mimetypes.guess_type(file_path)[0] - file_type = 'document' # default to document - - if mime_type: - if 'audio' in mime_type: - file_type = 'audio' - elif 'video' in mime_type: - file_type = 'video' - elif 'image' in mime_type: - file_type = 'photo' - - file_type_methods = { - 'document': 'sendDocument', - 'photo': 'sendPhoto', - 'audio': 'sendAudio', - 'video': 'sendVideo', - 'animation': 'sendAnimation', - 'voice': 'sendVoice', - 'video_note': 'sendVideoNote' - } - - url = f"https://api.telegram.org/bot{bot_token}/{file_type_methods[file_type]}" - with open(file_path, 'rb') as file: - files = { - file_type: file - } - message = input("Enter the message to send with the file (press enter to skip): ") - data = { - 'chat_id': chat_id, - 'caption': message - } - response = requests.post(url, files=files, data=data) - return response.json() - except Exception as e: - print(f"An error occurred while trying to send the file: {e}") + try: + mime_type = mimetypes.guess_type(file_path)[0] + file_type = "document" # default to document + + if mime_type: + if "audio" in mime_type: + file_type = "audio" + elif "video" in mime_type: + file_type = "video" + elif "image" in mime_type: + file_type = "photo" + + file_type_methods = { + "document": "sendDocument", + "photo": "sendPhoto", + "audio": "sendAudio", + "video": "sendVideo", + "animation": "sendAnimation", + "voice": "sendVoice", + "video_note": "sendVideoNote", + } + + url = f"https://api.telegram.org/bot{bot_token}/{file_type_methods[file_type]}" + with open(file_path, "rb") as file: + files = {file_type: file} + message = input( + "Enter the message to send with the file (press enter to skip): " + ) + data = {"chat_id": chat_id, "caption": message} + response = requests.post(url, files=files, data=data) + return response.json() + except Exception as e: + print(f"An error occurred while trying to send the file: {e}") + def get_my_commands(chat_id, bot_token): - url = f"https://api.telegram.org/bot{bot_token}/getMyCommands" - data = {"chat_id": chat_id} - response = requests.get(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getMyCommands" + data = {"chat_id": chat_id} + response = requests.get(url, data=data) + return response.json() def get_updates(bot_token, offset=None, timeout=30): - url = f"https://api.telegram.org/bot{bot_token}/getUpdates?timeout={timeout}" - if offset: - url += f"&offset={offset}" - response = requests.get(url) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getUpdates?timeout={timeout}" + if offset: + url += f"&offset={offset}" + response = requests.get(url) + return response.json() def get_bot_info(bot_token): - url = f"https://api.telegram.org/bot{bot_token}/getMe" - response = requests.get(url) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getMe" + response = requests.get(url) + return response.json() def get_My_Default_AdministratorRights(bot_token, chat_id): - url = f"https://api.telegram.org/bot{bot_token}/getMyDefaultAdministratorRights" - data = {"chat_id": chat_id} - response = requests.get(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getMyDefaultAdministratorRights" + data = {"chat_id": chat_id} + response = requests.get(url, data=data) + return response.json() def get_chat_info(bot_token, chat_id): - url = f"https://api.telegram.org/bot{bot_token}/getChat" - data = {"chat_id": chat_id} - response = requests.post(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getChat" + data = {"chat_id": chat_id} + response = requests.post(url, data=data) + return response.json() def get_chat_administrators(bot_token, chat_id): - url = f"https://api.telegram.org/bot{bot_token}/getChatAdministrators" - data = {"chat_id": chat_id} - response = requests.post(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getChatAdministrators" + data = {"chat_id": chat_id} + response = requests.post(url, data=data) + return response.json() def get_chat_member_count(bot_token, chat_id): - url = f"https://api.telegram.org/bot{bot_token}/getChatMembersCount" - data = {"chat_id": chat_id} - response = requests.post(url, data=data) - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/getChatMembersCount" + data = {"chat_id": chat_id} + response = requests.post(url, data=data) + return response.json() def get_latest_messageid(bot_token, chat_id): - response = send_telegram_message(bot_token, chat_id, ".") - if response.get("ok") == True: - message_id = response.get('result').get('message_id') - deleteMessage(bot_token, chat_id, message_id) - return message_id - else: - print("Error: Unable to retrieve latest message id: ", - response.get("description")) - return None + response = send_telegram_message(bot_token, chat_id, ".") + if response.get("ok") == True: + message_id = response.get("result").get("message_id") + deleteMessage(bot_token, chat_id, message_id) + return message_id + else: + print( + "Error: Unable to retrieve latest message id: ", response.get("description") + ) + return None def main(bot_token, chat_id): - # Retrieve information and print in a pretty format - can_read = get_bot_info(bot_token).get('result', - {}).get('can_read_all_group_messages', - False) - if not args.silent: - print(parse_dict("Bot Information", get_bot_info(bot_token))) - print(parse_dict("Chat Information", get_chat_info(bot_token, chat_id))) - print( - parse_dict("Chat Administrators", - get_chat_administrators(bot_token, chat_id))) - print( - parse_dict("My Default Administrator Rights", - get_My_Default_AdministratorRights(bot_token, chat_id))) - print( - parse_dict("Available Bot Commands", get_my_commands(chat_id, - bot_token))) - print( - parse_dict("Chat Member Count", - get_chat_member_count(bot_token, chat_id))) - if args.info: - exit() - while True: - print("\nOptions:") - print("1. Monitor for new messages from a different bot") - print("2. Send a message to the malicious telegram channel") - print("3. Spam the malicious telegram channel with a specific message") - print("4. Delete all messages from the malicious telegram channel that are sent within 24 hours\n") - print("5. Get approximate number of messages on the malicious telegram channel") - print("6. Download ALL messages from the malicious telegram channel") - print("7. Send a file to the malicious telegram channel\n") - print("8. EXIT") - choice = input("\nEnter your choice: ") - if choice == '1': - offset = None # Variable to keep track of the last update ID - if can_read: + # Retrieve information and print in a pretty format + can_read = ( + get_bot_info(bot_token) + .get("result", {}) + .get("can_read_all_group_messages", False) + ) + if not args.silent: + print(parse_dict("Bot Information", get_bot_info(bot_token))) + print(parse_dict("Chat Information", get_chat_info(bot_token, chat_id))) print( - "\t [*] Administrator persmission granted. Monitoring for new messages...." + parse_dict( + "Chat Administrators", get_chat_administrators(bot_token, chat_id) + ) ) - while True: - try: - updates = get_updates(bot_token, offset) - for update in updates.get("result", []): - print("Received Update:") - pprint.pprint(update, indent=4, width=50) - - # Update the offset to only receive new updates - offset = update["update_id"] + 1 - except KeyboardInterrupt: - print("Monitoring interrupted. Going back to options.") - break - time.sleep(1) - else: - print("Bot does not have permission to read messages.") - - elif choice == '2': - message = input("Enter the message you want to send: ") - response = send_telegram_message(bot_token, chat_id, message) - if response.get("ok") == True: - print("Message sent. Response:") - pprint.pprint(response) - - elif choice == '3': - message = input("Enter the message you want to spam: ") - processes = [] - for _ in range(1000000000): # Adjust the number of processes as needed - p = multiprocessing.Process(target=send_telegram_message, - args=(bot_token, chat_id, message)) - p.start() - processes.append(p) - - for p in processes: - p.join() - - elif choice == '4': - message_id = get_latest_messageid(bot_token, chat_id) - processes = [] - for _ in range(1000000000): # Adjust the number of processes as needed - p = multiprocessing.Process(target=delete_messages, - args=(bot_token, chat_id, message_id)) - p.start() - processes.append(p) - message_id -= 1 - - for p in processes: - p.join() - - elif choice == '5': - message_id = get_latest_messageid(bot_token, chat_id) - if message_id is not None: print( - f"Approximate number of messages on the malicious channel: {message_id}" + parse_dict( + "My Default Administrator Rights", + get_My_Default_AdministratorRights(bot_token, chat_id), + ) ) - else: - print(message_id) - - elif choice == '6': - try: - message_id = get_latest_messageid(bot_token, chat_id) - print(f"\t\n TOTAL NUMBER OF MESSAGES: ~{message_id}\n") - num_messages = input( - "Press ENTER to retreive all messages or enter a number (Downloading from Newest to Oldest): " + print(parse_dict("Available Bot Commands", get_my_commands(chat_id, bot_token))) + print( + parse_dict("Chat Member Count", get_chat_member_count(bot_token, chat_id)) ) - if num_messages == "": - num_messages = message_id - else: - num_messages = int(num_messages) - question = input( - "Would you like to start from a specific message_id? (y/n): ") - if question.lower() == 'y': - message_id = int( - input(f"Enter the message_id offset to start from: ")) - if message_id is not None: - process_messages(bot_token, chat_id, num_messages, message_id) + if args.info: + exit() + while True: + print("\nOptions:") + print("1. Monitor for new messages from a different bot") + print("2. Send a message to the malicious telegram channel") + print("3. Spam the malicious telegram channel with a specific message") + print( + "4. Delete all messages from the malicious telegram channel that are sent within 24 hours\n" + ) + print("5. Get approximate number of messages on the malicious telegram channel") + print("6. Download ALL messages from the malicious telegram channel") + print("7. Send a file to the malicious telegram channel\n") + print("8. EXIT") + choice = input("\nEnter your choice: ") + if choice == "1": + offset = None # Variable to keep track of the last update ID + if can_read: + print( + "\t [*] Administrator persmission granted. Monitoring for new messages...." + ) + while True: + try: + updates = get_updates(bot_token, offset) + for update in updates.get("result", []): + print("Received Update:") + pprint.pprint(update, indent=4, width=50) + + # Update the offset to only receive new updates + offset = update["update_id"] + 1 + except KeyboardInterrupt: + print("Monitoring interrupted. Going back to options.") + break + time.sleep(1) + else: + print("Bot does not have permission to read messages.") + + elif choice == "2": + message = input("Enter the message you want to send: ") + response = send_telegram_message(bot_token, chat_id, message) + if response.get("ok") == True: + print("Message sent. Response:") + pprint.pprint(response) + + elif choice == "3": + message = input("Enter the message you want to spam: ") + processes = [] + for _ in range(1000000000): # Adjust the number of processes as needed + p = multiprocessing.Process( + target=send_telegram_message, args=(bot_token, chat_id, message) + ) + p.start() + processes.append(p) + + for p in processes: + p.join() + + elif choice == "4": + message_id = get_latest_messageid(bot_token, chat_id) + processes = [] + for _ in range(1000000000): # Adjust the number of processes as needed + p = multiprocessing.Process( + target=delete_messages, args=(bot_token, chat_id, message_id) + ) + p.start() + processes.append(p) + message_id -= 1 + + for p in processes: + p.join() + + elif choice == "5": + message_id = get_latest_messageid(bot_token, chat_id) + if message_id is not None: + print( + f"Approximate number of messages on the malicious channel: {message_id}" + ) + else: + print(message_id) + + elif choice == "6": + try: + message_id = get_latest_messageid(bot_token, chat_id) + print(f"\t\n TOTAL NUMBER OF MESSAGES: ~{message_id}\n") + num_messages = input( + "Press ENTER to retreive all messages or enter a number (Downloading from Newest to Oldest): " + ) + if num_messages == "": + num_messages = message_id + else: + num_messages = int(num_messages) + question = input( + "Would you like to start from a specific message_id? (y/n): " + ) + if question.lower() == "y": + message_id = int( + input(f"Enter the message_id offset to start from: ") + ) + if message_id is not None: + process_messages(bot_token, chat_id, num_messages, message_id) + else: + print(message_id) + except Exception as e: + print(f"Error: {e}") + elif choice == "7": + file_path = input("Enter the absolute file path: ") + response = send_file_to_telegram_channel(bot_token, chat_id, file_path) + if response.get("ok") == True: + print("File sent. Response:") + pprint.pprint(response) + else: + print("Error: Unable to send file: ", response.get("description")) + elif choice == "8": + print("Exiting...") + break else: - print(message_id) - except Exception as e: - print(f"Error: {e}") - elif choice == '7': - file_path = input("Enter the absolute file path: ") - response = send_file_to_telegram_channel(bot_token, chat_id, file_path) - if response.get("ok") == True: - print("File sent. Response:") - pprint.pprint(response) - else: - print("Error: Unable to send file: ", response.get("description")) - elif choice == '8': - print("Exiting...") - break - else: - print("Invalid choice. Please try again.") + print("Invalid choice. Please try again.") + # Check a file for the bot token and chat id pair it is stored in the file in the form of bot_token:chat_id, then print a message asking if you are sure you want to continue. Otherwise continue and add the bot token and chat id to the file in the form of bot_token:chat_id and continue. def check_file_for_token_and_chat_id(file_path, bot_token, chat_id): - with open(file_path, 'r') as file: - for line in file: - if line.strip() == f"{bot_token}:{chat_id}": - return True - return False + with open(file_path, "r") as file: + for line in file: + if line.strip() == f"{bot_token}:{chat_id}": + return True + return False + def add_token_and_chat_id_to_file(file_path, bot_token, chat_id): - with open(file_path, 'a') as file: - file.write(f"{bot_token}:{chat_id}\n") + with open(file_path, "a") as file: + file.write(f"{bot_token}:{chat_id}\n") + if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Telegram Bot Script") - parser.add_argument("-t", "--bot_token", help="Telegram Bot Token") - parser.add_argument("-i", "--info", help="Get Bot Information and exit", action="store_true") - parser.add_argument("-c", "--chat_id", help="Telegram Chat ID", type=int) - parser.add_argument("-s", "--silent", help="Silent mode, no prompts, just show the information and exit", action="store_true") - args = parser.parse_args() - - file_path = ".bot-history" # Replace with the actual file path - - if check_file_for_token_and_chat_id(file_path, args.bot_token, args.chat_id): - print("Bot token and chat ID pair already exists in the file.") - response = input("Are you sure you want to continue? (y/n): ") - if response.lower() != "y": - exit() - else: - add_token_and_chat_id_to_file(file_path, args.bot_token, args.chat_id) - - main(args.bot_token, args.chat_id) \ No newline at end of file + parser = argparse.ArgumentParser(description="Telegram Bot Script") + parser.add_argument("-t", "--bot_token", help="Telegram Bot Token") + parser.add_argument( + "-i", "--info", help="Get Bot Information and exit", action="store_true" + ) + parser.add_argument("-c", "--chat_id", help="Telegram Chat ID", type=int) + parser.add_argument( + "-s", + "--silent", + help="Silent mode, no prompts, just show the information and exit", + action="store_true", + ) + args = parser.parse_args() + + file_path = ".bot-history" # Replace with the actual file path + + if check_file_for_token_and_chat_id(file_path, args.bot_token, args.chat_id): + print("Bot token and chat ID pair already exists in the file.") + response = input("Are you sure you want to continue? (y/n): ") + if response.lower() != "y": + exit() + else: + add_token_and_chat_id_to_file(file_path, args.bot_token, args.chat_id) + + main(args.bot_token, args.chat_id) diff --git a/helpers/TeleTexter.py b/helpers/TeleTexter.py index b25e2d5..e7e2d98 100644 --- a/helpers/TeleTexter.py +++ b/helpers/TeleTexter.py @@ -5,38 +5,41 @@ def send_telegram_message(bot_token, chat_id, message): - """ + """ Sends a message to a specified Telegram channel. """ - url = f"https://api.telegram.org/bot{bot_token}/sendMessage" - data = {"chat_id": chat_id, "text": message} - response = requests.post(url, data=data) - if response.json().get("ok") == True: - print(f"Message sent successfully! -> message_id: {response.json().get('result').get('message_id')}") - return response.json() + url = f"https://api.telegram.org/bot{bot_token}/sendMessage" + data = {"chat_id": chat_id, "text": message} + response = requests.post(url, data=data) + if response.json().get("ok") == True: + print( + f"Message sent successfully! -> message_id: {response.json().get('result').get('message_id')}" + ) + return response.json() def main(bot_token, chat_id, message, spam): - if spam: - while True: - response = send_telegram_message(bot_token, chat_id, message) - print("Message sent. Response:") - pprint.pprint(response) - time.sleep(0.04) # Delay to respect rate limits, adjust as needed - else: - response = send_telegram_message(bot_token, chat_id, message) - print("Message sent. Response:") - pprint.pprint(response) + if spam: + while True: + response = send_telegram_message(bot_token, chat_id, message) + print("Message sent. Response:") + pprint.pprint(response) + time.sleep(0.04) # Delay to respect rate limits, adjust as needed + else: + response = send_telegram_message(bot_token, chat_id, message) + print("Message sent. Response:") + pprint.pprint(response) if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Send a message to a Telegram channel") - parser.add_argument("-t", "--bot_token", help="Telegram Bot Token") - parser.add_argument("-c", "--chat_id", help="Telegram Chat ID") - parser.add_argument("-m", "--message", help="Message to send") - parser.add_argument("--spam", help="Send messages continuously", action="store_true") + parser = argparse.ArgumentParser(description="Send a message to a Telegram channel") + parser.add_argument("-t", "--bot_token", help="Telegram Bot Token") + parser.add_argument("-c", "--chat_id", help="Telegram Chat ID") + parser.add_argument("-m", "--message", help="Message to send") + parser.add_argument( + "--spam", help="Send messages continuously", action="store_true" + ) - args = parser.parse_args() + args = parser.parse_args() - main(args.bot_token, args.chat_id, args.message, args.spam) + main(args.bot_token, args.chat_id, args.message, args.spam) diff --git a/helpers/TeleViewer.py b/helpers/TeleViewer.py index 84f6fab..c39760c 100644 --- a/helpers/TeleViewer.py +++ b/helpers/TeleViewer.py @@ -6,137 +6,147 @@ load_dotenv() -api_id = os.getenv('API_ID') -api_hash = os.getenv('API_HASH') +api_id = os.getenv("API_ID") +api_hash = os.getenv("API_HASH") def get_file_info(data): - media_type = "" - random_numbers = [random.randint(1, 100) for _ in range(6)] - # print("data.media value:", data.media) - if data.media is not None: - try: - for key in ['MessageMediaType.DOCUMENT', 'MessageMediaType.PHOTO', 'MessageMediaType.VIDEO', 'MessageMediaType.LOCATION', 'MessageMediaType.VOICE', 'MessageMediaType.AUDIO', 'MessageMediaType.STICKER']: - if key in str(data): - media_type = key - # print("Media_type found:", media_type) - break - if media_type == "MessageMediaType.DOCUMENT": - return (data.document.file_id, data.document.file_name) - elif media_type == "MessageMediaType.PHOTO": - return (data.photo.file_id, f"{random_numbers}.png") - elif media_type == "MessageMediaType.VIDEO": - return (data.video.file_id, data.video.file_name) - elif media_type == "MessageMediaType.LOCATION": - return (data.location.file_id, data.location.file_name) - elif media_type == "MessageMediaType.VOICE": - return (data.voice.file_id, data.voice.file_name) - elif media_type == "MessageMediaType.AUDIO": - return (data.audio.file_id, data.audio.file_name) - elif media_type == "MessageMediaType.STICKER": - return (data.sticker.file_id, data.sticker.file_name) - else: - return (None, None) - except Exception as e: - print(f"Error: {e}") - return (None, None) + media_type = "" + random_numbers = [random.randint(1, 100) for _ in range(6)] + # print("data.media value:", data.media) + if data.media is not None: + try: + for key in [ + "MessageMediaType.DOCUMENT", + "MessageMediaType.PHOTO", + "MessageMediaType.VIDEO", + "MessageMediaType.LOCATION", + "MessageMediaType.VOICE", + "MessageMediaType.AUDIO", + "MessageMediaType.STICKER", + ]: + if key in str(data): + media_type = key + # print("Media_type found:", media_type) + break + if media_type == "MessageMediaType.DOCUMENT": + return (data.document.file_id, data.document.file_name) + elif media_type == "MessageMediaType.PHOTO": + return (data.photo.file_id, f"{random_numbers}.png") + elif media_type == "MessageMediaType.VIDEO": + return (data.video.file_id, data.video.file_name) + elif media_type == "MessageMediaType.LOCATION": + return (data.location.file_id, data.location.file_name) + elif media_type == "MessageMediaType.VOICE": + return (data.voice.file_id, data.voice.file_name) + elif media_type == "MessageMediaType.AUDIO": + return (data.audio.file_id, data.audio.file_name) + elif media_type == "MessageMediaType.STICKER": + return (data.sticker.file_id, data.sticker.file_name) + else: + return (None, None) + except Exception as e: + print(f"Error: {e}") + return (None, None) def parse_and_print_message(message): - print("=" * 20 + "\n") - message_dict = message.__dict__ - for key, value in message_dict.items(): - if value not in [None, False]: - print(f"{key}: {value}") - print("\n") - print("=" * 20 + "\n") + print("=" * 20 + "\n") + message_dict = message.__dict__ + for key, value in message_dict.items(): + if value not in [None, False]: + print(f"{key}: {value}") + print("\n") + print("=" * 20 + "\n") def process_messages(bot_token, chat_id, num_messages, message_id): - directory = f'sessions/{chat_id}' - if not os.path.exists(directory): - os.makedirs(directory) - bot_token_filename = bot_token.replace(":", "_").replace("/", "_") - bot_token_filename = f"{directory}/{bot_token_filename}.session" - app = pyrogram.Client(bot_token_filename, api_id, api_hash) + directory = f"sessions/{chat_id}" + if not os.path.exists(directory): + os.makedirs(directory) + bot_token_filename = bot_token.replace(":", "_").replace("/", "_") + bot_token_filename = f"{directory}/{bot_token_filename}.session" + app = pyrogram.Client(bot_token_filename, api_id, api_hash) - async def main(num_messages, message_id): - try: - # Calculate the counter to get the correct number of messages. We do this so we can iterate through the messages in reverse order from the latest message. - counter = message_id - num_messages - while message_id >= counter: - message_id -= 1 - async with app: - messages = await app.get_messages(chat_id, message_id) - if messages.date is None: - # Display the message_id not found every 10 messages - if message_id % 10 == 0: - print(f"[-] Message_id {message_id} not found") - counter -= 1 - pass - else: - parse_and_print_message(messages) - if messages.media is not None: - file_id, file_name = get_file_info(messages) - if messages.from_user is not None: - file_name = f"downloads/{messages.from_user.username}/{message_id}_{file_name}" - else: - file_name = f"downloads/{chat_id}/{message_id}_{file_name}" - # download the file - # Keep track of the progress while downloading - async def progress(current, total): - if total != 0: - print(f"{current * 100 / total:.1f}%") - else: - print( - f"[*] Download of {file_name.split('/')[-1]} is complete!" - ) + async def main(num_messages, message_id): + try: + # Calculate the counter to get the correct number of messages. We do this so we can iterate through the messages in reverse order from the latest message. + counter = message_id - num_messages + while message_id >= counter: + message_id -= 1 + async with app: + messages = await app.get_messages(chat_id, message_id) + if messages.date is None: + # Display the message_id not found every 10 messages + if message_id % 10 == 0: + print(f"[-] Message_id {message_id} not found") + counter -= 1 + pass + else: + parse_and_print_message(messages) + if messages.media is not None: + file_id, file_name = get_file_info(messages) + if messages.from_user is not None: + file_name = f"downloads/{messages.from_user.username}/{message_id}_{file_name}" + else: + file_name = ( + f"downloads/{chat_id}/{message_id}_{file_name}" + ) - await app.download_media( - file_id, - file_name=file_name, - progress=progress, - ) - # save to file - if messages.from_user is not None: - username = messages.from_user.username - directory = f'Downloads/{username}/logs' - if not os.path.exists(directory): - os.makedirs(directory) - with open(f'{directory}/{username}_bot.txt', 'a') as file: - file.write(f"Message ID: {messages.id}\n") - file.write( - f"From User ID: {messages.from_user.id} - Username: {messages.from_user.username}\n" - ) - file.write(f"Date: {messages.date}\n") - file.write(f"Text: {messages.text}\n") - file.write(f"Reply_markup: {messages.reply_markup}\n\n") - # Save the whole message to a file - with open(f'{directory}/{username}_bot.json', - 'a') as file: - file.write(str(messages)) - else: - directory = f'Downloads/{chat_id}/logs' - if not os.path.exists(directory): - os.makedirs(directory) - with open(f'{directory}/{chat_id}_bot.txt', 'a') as file: - file.write(f"Message ID: {messages.id}\n") - file.write(f"Date: {messages.date}\n") - file.write(f"Text: {messages.text}\n") - file.write(f"Reply_markup: {messages.reply_markup}\n\n") - # Save the whole message to a file - with open(f'{directory}/{chat_id}_bot.json', 'a') as file: - file.write(str(messages)) - except AttributeError as e: - print(f"Error: {e}") - pass - except Exception as e: - print(f"Error: {e}") - pass + # download the file + # Keep track of the progress while downloading + async def progress(current, total): + if total != 0: + print(f"{current * 100 / total:.1f}%") + else: + print( + f"[*] Download of {file_name.split('/')[-1]} is complete!" + ) - try: - app.run(main(num_messages, message_id)) - except KeyboardInterrupt: - print("\nStopping...") - app.disconnect() - pass + await app.download_media( + file_id, + file_name=file_name, + progress=progress, + ) + # save to file + if messages.from_user is not None: + username = messages.from_user.username + directory = f"Downloads/{username}/logs" + if not os.path.exists(directory): + os.makedirs(directory) + with open(f"{directory}/{username}_bot.txt", "a") as file: + file.write(f"Message ID: {messages.id}\n") + file.write( + f"From User ID: {messages.from_user.id} - Username: {messages.from_user.username}\n" + ) + file.write(f"Date: {messages.date}\n") + file.write(f"Text: {messages.text}\n") + file.write(f"Reply_markup: {messages.reply_markup}\n\n") + # Save the whole message to a file + with open(f"{directory}/{username}_bot.json", "a") as file: + file.write(str(messages)) + else: + directory = f"Downloads/{chat_id}/logs" + if not os.path.exists(directory): + os.makedirs(directory) + with open(f"{directory}/{chat_id}_bot.txt", "a") as file: + file.write(f"Message ID: {messages.id}\n") + file.write(f"Date: {messages.date}\n") + file.write(f"Text: {messages.text}\n") + file.write(f"Reply_markup: {messages.reply_markup}\n\n") + # Save the whole message to a file + with open(f"{directory}/{chat_id}_bot.json", "a") as file: + file.write(str(messages)) + except AttributeError as e: + print(f"Error: {e}") + pass + except Exception as e: + print(f"Error: {e}") + pass + + try: + app.run(main(num_messages, message_id)) + except KeyboardInterrupt: + print("\nStopping...") + app.disconnect() + pass From 6cfdd65ee6f5bfa0351e700a693738051c4c0c8c Mon Sep 17 00:00:00 2001 From: Abhi <85984486+AbhiTheModder@users.noreply.github.com> Date: Sat, 15 Jun 2024 18:20:58 +0000 Subject: [PATCH 3/3] gifs --- helpers/TeleViewer.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/helpers/TeleViewer.py b/helpers/TeleViewer.py index c39760c..0d0b55c 100644 --- a/helpers/TeleViewer.py +++ b/helpers/TeleViewer.py @@ -24,6 +24,7 @@ def get_file_info(data): "MessageMediaType.VOICE", "MessageMediaType.AUDIO", "MessageMediaType.STICKER", + "MessageMediaType.ANIMATION", ]: if key in str(data): media_type = key @@ -43,6 +44,8 @@ def get_file_info(data): return (data.audio.file_id, data.audio.file_name) elif media_type == "MessageMediaType.STICKER": return (data.sticker.file_id, data.sticker.file_name) + elif media_type == "MessageMediaType.ANIMATION": + return (data.animation.file_id, data.animation.file_name) else: return (None, None) except Exception as e: