import re import csv from telethon import TelegramClient from telethon.tl.types import MessageEntityUrl, MessageEntityTextUrl from tqdm.asyncio import tqdm # Replace with your API credentials and phone number api_id = 25216912 api_hash = 'f65f6050fe9b342a4996c59e4283ab5e' phone_number = '+967730426743' # e.g., '+123456789' group_identifier = 'aaa2222p' # Use username, ID, or invite link # CSV file to save the links csv_file = 'aaa2222p.csv' # Initialize the client client = TelegramClient('mbot1', api_id, api_hash) from tqdm import tqdm # Import tqdm for progress bar async def fetch_telegram_links(): await client.start(phone_number) print("Client created. Fetching messages...") # Resolve the group entity group_entity = await client.get_entity(group_identifier) # Get the total number of messages in the group for tqdm total_messages = (await client.get_messages(group_entity, limit=1)).total # Initialize tqdm progress bar progress_bar = tqdm(total=total_messages, desc="Fetching messages") # Open CSV file in append mode with open(csv_file, mode='a', newline='', encoding='utf-8') as file: writer = csv.writer(file) # Write header only if the file is empty if file.tell() == 0: writer.writerow(['Telegram Links']) # Iterate through all messages in the group async for message in client.iter_messages(group_entity): if not message.text: progress_bar.update(1) # Update progress bar continue # Extract links from message entities (URLs and text URLs) if message.entities: for entity in message.entities: if isinstance(entity, (MessageEntityUrl, MessageEntityTextUrl)): url = None if isinstance(entity, MessageEntityUrl): # Extract URL directly from the message text url = message.text[entity.offset:entity.offset + entity.length] elif isinstance(entity, MessageEntityTextUrl): # Extract URL from the entity's URL field url = entity.url if url and ('t.me/' in url or 'telegram.me/' in url): writer.writerow([url]) # Write link to CSV immediately # Use regex to find Telegram links in message text (including non-hyperlinked) matches = re.finditer(r'(https?://)?(www\.)?(t|telegram)\.me/\S+', message.text) for match in matches: url = match.group(0) if not url.startswith('http'): url = f'https://{url}' writer.writerow([url]) # Write link to CSV immediately progress_bar.update(1) # Update progress bar # Close the progress bar progress_bar.close() print(f"\nFinished fetching messages. Links saved to {csv_file}") await client.disconnect() # Run the async function with client: client.loop.run_until_complete(fetch_telegram_links())