├── LICENSE.txt ├── OSINT_TELEGRAM.py ├── README.md └── requirements.txt /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Ivancastl 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OSINT_TELEGRAM.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import pyfiglet 4 | from telethon import TelegramClient, functions 5 | from telethon.tl.types import User 6 | import asyncio 7 | from collections import Counter 8 | import requests 9 | from cryptography.fernet import Fernet 10 | 11 | class TelegramOSINT: 12 | def __init__(self): 13 | self.config_file = "telegram_osint_config.enc" 14 | self.key_file = "telegram_osint_key.key" 15 | self.api_id = None 16 | self.api_hash = None 17 | self.load_or_request_credentials() 18 | self.show_banner() 19 | 20 | def show_banner(self): 21 | """Muestra el banner ASCII art""" 22 | os.system('cls' if os.name == 'nt' else 'clear') 23 | print(pyfiglet.figlet_format("Telegram Scout", font="slant")) 24 | print("🕵️ Herramienta de análisis para Telegram") 25 | print("👤 Creado por @ivancastl") 26 | print("🌐 Grupo: t.me/+_g4DIczsuI9hOWZh") 27 | print("="*60 + "\n") 28 | 29 | def get_encryption_key(self): 30 | """Genera o recupera la clave de encriptación""" 31 | if not os.path.exists(self.key_file): 32 | with open(self.key_file, "wb") as f: 33 | f.write(Fernet.generate_key()) 34 | with open(self.key_file, "rb") as f: 35 | return f.read() 36 | 37 | def load_or_request_credentials(self): 38 | """Carga o solicita las credenciales""" 39 | if os.path.exists(self.config_file): 40 | try: 41 | cipher_suite = Fernet(self.get_encryption_key()) 42 | with open(self.config_file, "rb") as f: 43 | encrypted_data = f.read() 44 | creds = json.loads(cipher_suite.decrypt(encrypted_data).decode()) 45 | self.api_id = creds.get('api_id') 46 | self.api_hash = creds.get('api_hash') 47 | except Exception as e: 48 | print(f"⚠️ Error cargando credenciales: {e}") 49 | self.request_and_save_credentials() 50 | else: 51 | self.request_and_save_credentials() 52 | 53 | def request_and_save_credentials(self): 54 | """Solicita y guarda las credenciales de forma segura""" 55 | self.show_banner() 56 | print("🔑 Configuración de credenciales\n") 57 | 58 | self.api_id = input("Introduce tu api_id: ").strip() 59 | self.api_hash = input("Introduce tu api_hash: ").strip() 60 | 61 | try: 62 | cipher_suite = Fernet(self.get_encryption_key()) 63 | encrypted_data = cipher_suite.encrypt(json.dumps({ 64 | 'api_id': self.api_id, 65 | 'api_hash': self.api_hash 66 | }).encode()) 67 | with open(self.config_file, "wb") as f: 68 | f.write(encrypted_data) 69 | print("\n🛡️ Credenciales guardadas de forma segura") 70 | except Exception as e: 71 | print(f"\n🔴 Error guardando credenciales: {e}") 72 | input("\nPresiona Enter para continuar...") 73 | 74 | async def buscar_usuarios(self, client, query): 75 | """Busca usuarios en Telegram""" 76 | try: 77 | result = await client(functions.contacts.SearchRequest( 78 | q=query, 79 | limit=50 80 | )) 81 | 82 | if result.users: 83 | print(f"\n📡 Se encontraron {len(result.users)} coincidencias:") 84 | for user in result.users: 85 | print(f"\n📄 ID: {user.id}") 86 | print(f"👤 Username: @{user.username}" if user.username else "👤 Username: [Ninguno]") 87 | print(f"📛 Nombre: {user.first_name or ''} {user.last_name or ''}") 88 | print(f"📱 Teléfono: {user.phone or '[Oculto]'}") 89 | print("-"*40) 90 | else: 91 | print(f"\n🤔 No se encontraron coincidencias para '{query}'") 92 | except Exception as e: 93 | print(f"\n🔴 Error buscando usuarios: {e}") 94 | 95 | async def obtener_historial_grupo(self, client): 96 | """Obtiene el historial de mensajes de un grupo""" 97 | group_link = input("🔗 Introduce el enlace del grupo: ").strip() 98 | 99 | try: 100 | group = await client.get_entity(group_link) 101 | file_path = "historial_grupo.txt" 102 | 103 | if os.path.exists(file_path): 104 | file_path = file_path.replace(".txt", "_new.txt") 105 | 106 | user_counter = Counter() 107 | 108 | with open(file_path, "w", encoding="utf-8") as file: 109 | print(f"\n⏳ Obteniendo mensajes de {group.title}...") 110 | 111 | async for message in client.iter_messages(group): 112 | sender = await message.get_sender() 113 | username = sender.username if isinstance(sender, User) and sender.username else "[Sin username]" 114 | is_bot = "Sí" if isinstance(sender, User) and sender.bot else "No" 115 | 116 | if isinstance(sender, User): 117 | user_counter[sender.id] += 1 118 | 119 | file.write(f"\nID: {message.id}") 120 | file.write(f"\nFecha: {message.date}") 121 | file.write(f"\nDe: {message.sender_id} (@{username})") 122 | file.write(f"\nEs Bot: {is_bot}") 123 | file.write(f"\nMensaje: {message.text or '[Sin texto]'}") 124 | file.write("\n" + "-"*40 + "\n") 125 | 126 | # Estadísticas 127 | file.write("\nTOP 10 USUARIOS MÁS ACTIVOS:\n") 128 | for user_id, count in user_counter.most_common(10): 129 | file.write(f"ID {user_id}: {count} mensajes\n") 130 | 131 | print(f"\n📁 Historial guardado en {file_path}") 132 | print(f"📊 Total mensajes procesados: {sum(user_counter.values())}") 133 | 134 | except Exception as e: 135 | print(f"\n🔴 Error obteniendo mensajes: {e}") 136 | 137 | async def obtener_id_grupo(self, client): 138 | """Obtiene el ID de un grupo o canal""" 139 | group_username = input("🔗 Introduce el username o enlace del grupo: ").strip() 140 | 141 | try: 142 | group = await client.get_entity(group_username) 143 | print(f"\n📄 ID del grupo/canal: {group.id}") 144 | print(f"📛 Nombre: {group.title}") 145 | except Exception as e: 146 | print(f"\n🔴 Error obteniendo ID: {e}") 147 | 148 | async def buscar_palabra_clave(self, client): 149 | """Busca una palabra clave en todos los grupos""" 150 | keyword = input("🕵️ Introduce la palabra clave: ").strip() 151 | contador = 0 152 | group_counter = Counter() 153 | file_path = "resultados_busqueda.txt" 154 | 155 | if os.path.exists(file_path): 156 | file_path = file_path.replace(".txt", "_new.txt") 157 | 158 | with open(file_path, "w", encoding="utf-8") as file: 159 | file.write(f"RESULTADOS PARA: '{keyword}'\n\n") 160 | 161 | try: 162 | print(f"\n🕵️ Buscando '{keyword}' en todos los grupos...") 163 | 164 | async for dialog in client.iter_dialogs(): 165 | if dialog.is_group or dialog.is_channel: 166 | print(f"💬 Escaneando {dialog.name}...") 167 | 168 | async for message in client.iter_messages(dialog, search=keyword): 169 | file.write(f"\n[Grupo] {dialog.name} (ID: {dialog.id})") 170 | file.write(f"\n[Fecha] {message.date}") 171 | file.write(f"\n[Usuario] {message.sender_id}") 172 | file.write(f"\n[Mensaje] {message.text or '[Sin texto]'}") 173 | file.write("\n" + "-"*40 + "\n") 174 | group_counter[dialog.id] += 1 175 | contador += 1 176 | 177 | except Exception as e: 178 | print(f"\n🔴 Error en búsqueda: {e}") 179 | 180 | finally: 181 | file.write("\nESTADÍSTICAS:\n") 182 | for group_id, count in group_counter.most_common(10): 183 | group = await client.get_entity(group_id) 184 | file.write(f"{group.title}: {count} menciones\n") 185 | 186 | print(f"\n🏁 Se encontraron {contador} mensajes con '{keyword}'") 187 | print(f"📄 Resultados guardados en {file_path}") 188 | 189 | async def run(self): 190 | """Ejecuta la aplicación principal""" 191 | client = TelegramClient("telegram_scout_session", self.api_id, self.api_hash) 192 | await client.start() 193 | 194 | while True: 195 | self.show_banner() 196 | print("⚙️ Menú Principal") 197 | print("1 📡 Buscar usuarios") 198 | print("2 📥 Obtener historial de grupo") 199 | print("3 📄 Obtener ID de grupo") 200 | print("4 🕵️ Buscar por palabra clave") 201 | print("5 🚪 Salir\n") 202 | 203 | choice = input("🚩 Selecciona una opción: ").strip() 204 | 205 | if choice == "1": 206 | query = input("📡 Término de búsqueda: ") 207 | await self.buscar_usuarios(client, query) 208 | elif choice == "2": 209 | await self.obtener_historial_grupo(client) 210 | elif choice == "3": 211 | await self.obtener_id_grupo(client) 212 | elif choice == "4": 213 | await self.buscar_palabra_clave(client) 214 | elif choice == "5": 215 | print("\n👋 ¡Hasta pronto!") 216 | break 217 | else: 218 | print("\n⚠️ Opción no válida") 219 | 220 | input("\nPresiona Enter para continuar...") 221 | 222 | await client.disconnect() 223 | 224 | if __name__ == "__main__": 225 | try: 226 | osint_tool = TelegramOSINT() 227 | asyncio.run(osint_tool.run()) 228 | except KeyboardInterrupt: 229 | print("\n🛑 Programa interrumpido") 230 | except Exception as e: 231 | print(f"\n🔴 Error crítico: {e}") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Telegram OSINT 🚀 2 | 3 | **TelegramOSINTT** es un script diseñado para interactuar con la API de Telegram utilizando **Telethon**. 4 | Este script permite realizar tareas relacionadas con **Open-Source Intelligence (OSINT)**, 5 | como buscar usuarios, obtener historiales de mensajes, monitorear palabras clave y generar estadísticas. 6 | 7 | ## funcionalidades 8 | 1. 🔍 **Buscar Usuarios**: Encuentra usuarios por nombre, ID o username. 9 | 2. 💬 **Obtener Historial de Mensajes**: Descarga los mensajes de un grupo o canal de Telegram 10 | y genera estadísticas de los 10 usuarios más activos. 11 | 3. 🆔 **Obtener el ID de un Grupo**: Identifica el ID único de cualquier grupo o canal. 12 | 4. 🗣️ **Monitorear Palabras Clave**: Escanea todos los mensajes de tus grupos o canales para 13 | encontrar coincidencias con palabras clave y genera estadísticas de los 10 grupos con más menciones. 14 | 15 | ## 📦 instalación 16 | 17 | 18 | ### **Paso 1:** 19 | # Clona este repositorio 20 | ```bash 21 | git clone https://github.com/Ivancastl/telegramOSINT.git 22 | ``` 23 | 24 | ### **Paso 2:** 25 | # Accede al directorio del proyecto. 26 | ```bash 27 | cd telegramOSINT 28 | ``` 29 | 30 | ### **Paso 3:** 31 | # Instala las dependencias necesarias. 32 | ```bash 33 | pip install -r requirements.txt 34 | ``` 35 | 36 | ### **Paso 4:** 37 | # Ejecuta el script principal 38 | ```bash 39 | python OSINT_TELEGRAM.py 40 | ``` 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyfiglet 2 | telethon 3 | requests 4 | cryptography 5 | 6 | --------------------------------------------------------------------------------