IvanCastl

Python bot phishing

Jan 9th, 2025
613
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.29 KB | Cybersecurity | 1 0
  1. import logging
  2. import requests
  3. from telegram import Update
  4. from telegram.ext import CommandHandler, MessageHandler
  5. from telegram.ext import ApplicationBuilder, filters
  6. from pyzbar.pyzbar import decode
  7. from PIL import Image
  8. import io
  9. import base64
  10.  
  11. # Configura el token de tu bot
  12. API_KEY_BOT = '6485736000:AAFmLqJtt30rzuZyHJHBJYFtgyGzXVeSMcxh_6w'
  13. # Tu clave API de VirusTotal
  14. API_KEY_VIRUSTOTAL = 'e8a8asa1a71d181d17b7a252f0a00idkadjkadjadhk0a968c55a8408e017'
  15.  
  16. # Configuración del logging
  17. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  18. logger = logging.getLogger(__name__)
  19.  
  20. # Función para decodificar QR
  21. def decode_qr(image_data):
  22.     image = Image.open(io.BytesIO(image_data))
  23.     decoded_objects = decode(image)
  24.     if decoded_objects:
  25.         return decoded_objects[0].data.decode("utf-8")
  26.     else:
  27.         return None
  28.  
  29. # Función para consultar la URL en VirusTotal
  30. def check_url(url):
  31.     # Codificar la URL
  32.     encoded_url = base64.urlsafe_b64encode(url.encode()).decode().strip("=")
  33.  
  34.     # Hacer la solicitud GET a la API de VirusTotal
  35.     headers = {
  36.         'x-apikey': API_KEY_VIRUSTOTAL
  37.     }
  38.     response = requests.get(f'https://www.virustotal.com/api/v3/urls/{encoded_url}', headers=headers)
  39.  
  40.     if response.status_code == 200:
  41.         data = response.json()
  42.         stats = data['data']['attributes']['last_analysis_stats']
  43.         return stats
  44.     else:
  45.         return None
  46.  
  47. # Comando para comenzar el bot
  48. async def start(update: Update, context):
  49.     await update.message.reply_text("¡Hola! Envíame una imagen QR y te diré si es una URL segura o solo un texto.")
  50.  
  51. # Función que maneja los mensajes de texto
  52. async def handle_message(update: Update, context):
  53.     await update.message.reply_text("Por favor, envíame una imagen QR para analizarla.")
  54.  
  55. # Función que maneja las imágenes enviadas
  56. async def handle_image(update, context):
  57.     if update.message.photo:
  58.         # Get the file object
  59.         file = await update.message.photo[-1].get_file()
  60.  
  61.         # Download the file to a local path
  62.         await file.download_to_drive('qr_image.jpg')
  63.     else:
  64.         await update.message.reply_text("No photo found in the message.")
  65.  
  66.     # Abrimos la imagen descargada y la procesamos
  67.     with open('qr_image.jpg', 'rb') as f:
  68.         qr_text = decode_qr(f.read())
  69.    
  70.     if qr_text:
  71.         if qr_text.startswith("http") or qr_text.startswith("www"):
  72.             # Si es una URL, consultamos VirusTotal
  73.             stats = check_url(qr_text)
  74.             if stats:
  75.                 # Crear un mensaje bonito dependiendo del análisis
  76.                 message = f"URL decodificada: {qr_text}\n"
  77.                 message += f"Análisis realizado:\n"
  78.                 message += f"Maliciosa: {stats['malicious']}\n"
  79.                 message += f"Sospechosa: {stats['suspicious']}\n"
  80.                 message += f"Segura: {stats['harmless']}\n"
  81.                 message += f"No detectada: {stats['undetected']}\n"
  82.                
  83.                 if stats['malicious'] > 0:
  84.                     message += "⚠️ ¡Esta URL podría ser peligrosa! ⚠️"
  85.                 else:
  86.                     message += "✅ ¡La URL parece segura! ✅"
  87.             else:
  88.                 message = "No se pudo obtener los datos de la URL. Por favor, intenta de nuevo."
  89.         else:
  90.             # Si es solo texto
  91.             message = f"El QR contiene el siguiente texto: {qr_text}\n\nEsto no es una URL, solo texto."
  92.        
  93.         await update.message.reply_text(message)
  94.     else:
  95.         await update.message.reply_text("Lo siento, no pude detectar un código QR válido en la imagen. Por favor, envíame una imagen QR válida.")
  96.  
  97. def main():
  98.     # Crear la aplicación con ApplicationBuilder
  99.     application = ApplicationBuilder().token(API_KEY_BOT).build()
  100.  
  101.     # Manejar comandos
  102.     application.add_handler(CommandHandler("start", start))
  103.  
  104.     # Manejar imágenes
  105.     application.add_handler(MessageHandler(filters.PHOTO, handle_image))  # Cambio aquí
  106.  
  107.     # Manejar mensajes de texto
  108.     application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))  # Cambio aquí
  109.  
  110.     # Iniciar el bot (sin usar asyncio.run())
  111.     application.run_polling()
  112.  
  113. if __name__ == '__main__':
  114.     main()
Tags: python
Add Comment
Please, Sign In to add comment