import asyncio from telethon import TelegramClient from telethon.errors import FloodWaitError, RPCError class TelegramForwarder: def __init__(self, api_id, api_hash, phone_number): self.api_id = api_id self.api_hash = api_hash self.phone_number = phone_number self.client = TelegramClient('session_' + phone_number, api_id, api_hash) async def list_chats(self): try: await self.client.connect() if not await self.client.is_user_authorized(): await self.client.send_code_request(self.phone_number) await self.client.sign_in(self.phone_number, input('Enter the code: ')) dialogs = await self.client.get_dialogs() with open(f"chats_of_{self.phone_number}.txt", "w") as chats_file: for dialog in dialogs: print(f"Chat ID: {dialog.id}, Title: {dialog.title}") chats_file.write(f"Chat ID: {dialog.id}, Title: {dialog.title}\n") print("List of groups printed successfully!") except Exception as e: print(f"Error listing chats: {e}") async def safe_send_message(self, destination, text): """Safely send a message with error handling""" try: await self.client.send_message(destination, text) return True except FloodWaitError as e: print(f"Flood wait: Waiting {e.seconds} seconds...") await asyncio.sleep(e.seconds + 5) return False except RPCError as e: print(f"RPC Error: {e}") await asyncio.sleep(10) return False except Exception as e: print(f"Unexpected error sending message: {e}") await asyncio.sleep(10) return False async def process_message(self, message, keywords, source_name): """Process a single message with proper error handling""" try: if not hasattr(message, 'text') or message.text is None: print(f"Skipping non-text message from {source_name} (ID: {message.id})") return None, "None" ref_msg = "None" if message.reply_to_msg_id: try: reply_messages = await self.client.get_messages(message.chat_id, ids=message.reply_to_msg_id) if reply_messages and hasattr(reply_messages, 'text'): ref_msg = reply_messages.text except Exception as e: print(f"Error getting reply message: {e}") message_text = message.text or "[No text content]" message_id = str(message.id) reply_id = str(message.reply_to_msg_id) if message.reply_to_msg_id else "None" formatted_message = ( f"{keywords}\n{message_id}\n\n{message_text}\n\n" f"Message_is_reply_of:\n{reply_id}\n\n{ref_msg}" ) if message.edit_date: formatted_message = f"{keywords}\nEdited Message:\n{message_id}\n\n{message_text}\n\n" \ f"Message_is_reply_of:\n{reply_id}\n\n{ref_msg}" # Print the detailed output as in original script print(f"Message contains: {message_text}") print(f"\nReply of Message: {ref_msg}\n") return formatted_message, ref_msg except Exception as e: print(f"Error processing message from {source_name}: {e}") return None, "None" async def forward_messages_to_channel(self, source_chat_id, destination_channel_id, keywords): try: await self.client.connect() if not await self.client.is_user_authorized(): await self.client.send_code_request(self.phone_number) await self.client.sign_in(self.phone_number, input('Enter the code: ')) # Configuration for different sources destination_channel_id_UK = -1002477328454 sources = { "UK": { "keywords": "MyOwnUK: ", "source_chat_id": -1002466214276, "last_message_id": None, "previous_message": None }, "Younus": { "keywords": "Younus: ", "source_chat_id": -1002562218812, "last_message_id": None, "previous_message": None }, "Ankit": { "keywords": "Ankit: ", "source_chat_id": -1001178695857, "last_message_id": None, "previous_message": None }, "Pablo": { "keywords": "Pablo: ", "source_chat_id": -1001897903474, "last_message_id": None, "previous_message": None }, "GSociety": { "keywords": "GSociety: ", "source_chat_id": -1001883957585, "last_message_id": None, "previous_message": None }, "FXM": { "keywords": "FXM: ", "source_chat_id": -1001959885205, "last_message_id": None, "previous_message": None } } # Initialize last message IDs for source_name, config in sources.items(): try: last_message = await self.client.get_messages(config['source_chat_id'], limit=1) if last_message: config['last_message_id'] = last_message[0].id print(f"Initialized last_message_id for {source_name}: {config['last_message_id']}") except Exception as e: print(f"Error initializing last message ID for {source_name}: {e}") config['last_message_id'] = 0 while True: try: print("\nChecking for messages and forwarding them...") # Print current last message IDs print( f"LMID UK: {sources['UK']['last_message_id']}, " f"Younus: {sources['Younus']['last_message_id']}, " f"Ankit: {sources['Ankit']['last_message_id']}, " f"Pablo: {sources['Pablo']['last_message_id']}, " f"GSociety: {sources['GSociety']['last_message_id']}, " f"FXM: {sources['FXM']['last_message_id']}" ) for source_name, config in sources.items(): try: messages = await self.client.get_messages( config['source_chat_id'], min_id=config['last_message_id']-1 if config['last_message_id'] else None, limit=None ) for message in reversed(messages): try: if message.text != config['previous_message']: config['previous_message'] = message.text formatted, ref_msg = await self.process_message(message, config['keywords'], source_name) if formatted: success = await self.safe_send_message(destination_channel_id_UK, formatted) if success: print(f"Message forwarded from {source_name}") config['last_message_id'] = max(config['last_message_id'], message.id) if config['last_message_id'] else message.id except Exception as e: print(f"Error processing individual message from {source_name}: {e}") except Exception as e: print(f"Error getting messages from {source_name}: {e}") await asyncio.sleep(3) except Exception as e: print(f"Major error in main loop: {e}") await asyncio.sleep(30) continue except Exception as e: print(f"Fatal error in forward_messages_to_channel: {e}") raise def read_credentials(): try: with open("credentials.txt", "r") as file: lines = file.readlines() api_id = lines[0].strip() api_hash = lines[1].strip() phone_number = lines[2].strip() return api_id, api_hash, phone_number except FileNotFoundError: print("Credentials file not found.") return None, None, None except Exception as e: print(f"Error reading credentials: {e}") return None, None, None def write_credentials(api_id, api_hash, phone_number): try: with open("credentials.txt", "w") as file: file.write(api_id + "\n") file.write(api_hash + "\n") file.write(phone_number + "\n") except Exception as e: print(f"Error writing credentials: {e}") async def main(): api_id, api_hash, phone_number = read_credentials() if api_id is None or api_hash is None or phone_number is None: api_id = input("Enter your API ID: ") api_hash = input("Enter your API Hash: ") phone_number = input("Enter your phone number: ") write_credentials(api_id, api_hash, phone_number) forwarder = TelegramForwarder(api_id, api_hash, phone_number) destination_channel_id = -1002477328454 keywords = "MyOwnUK: " source_chat_id = -1002466214276 try: await forwarder.forward_messages_to_channel(source_chat_id, destination_channel_id, keywords) except KeyboardInterrupt: print("\nScript stopped by user") except Exception as e: print(f"Fatal error in main: {e}") finally: await forwarder.client.disconnect() if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print("\nApplication terminated by user") except Exception as e: print(f"Fatal error: {e}")