ferdj40

Repost bot

Jul 22nd, 2026
14,317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.23 KB | None | 0 0
  1. from telethon import TelegramClient, events
  2. import asyncio
  3. import logging
  4.  
  5. # Configuración de logging
  6. logging.basicConfig(
  7. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  8. level=logging.INFO
  9. )
  10. logger = logging.getLogger(__name__)
  11.  
  12. # ===================== CONFIGURACIÓN =====================
  13. # Obtén estos valores de https://my.telegram.org
  14. API_ID = 'TU_API_ID'
  15. API_HASH = 'TU_API_HASH'
  16. BOT_TOKEN = 'TU_BOT_TOKEN' # Obtén esto de @BotFather
  17.  
  18. # IDs de los canales (pueden ser username o ID numérico)
  19. SOURCE_CHANNEL = '@canal_origen' # O -1001234567890
  20. TARGET_CHANNEL = '@canal_destino' # O -1001234567890
  21.  
  22. # Extensiones de archivo a repostear
  23. ALLOWED_EXTENSIONS = ('.zip', '.rar', '.7z', '.tar', '.gz', '.3mf', '.stl')
  24. # =========================================================
  25.  
  26.  
  27. # Crear el cliente del bot
  28. bot = TelegramClient('bot_session', API_ID, API_HASH)
  29.  
  30.  
  31. @bot.on(events.NewMessage(chats=SOURCE_CHANNEL))
  32. async def repost_handler(event):
  33. """
  34. Maneja los nuevos mensajes del canal origen y los repostea al destino
  35. """
  36. try:
  37. message = event.message
  38.  
  39. # Verificar si el mensaje tiene un archivo
  40. if message.media and message.document:
  41. # Obtener el nombre del archivo
  42. file_name = None
  43. for attribute in message.document.attributes:
  44. if hasattr(attribute, 'file_name'):
  45. file_name = attribute.file_name
  46. break
  47.  
  48. # Verificar si es una extensión permitida
  49. if file_name and any(file_name.lower().endswith(ext) for ext in ALLOWED_EXTENSIONS):
  50. logger.info(f"📥 Reposteando archivo: {file_name}")
  51.  
  52. # Repostear el mensaje completo (archivo + caption si existe)
  53. await bot.forward_messages(
  54. entity=TARGET_CHANNEL,
  55. messages=message.id,
  56. from_peer=SOURCE_CHANNEL
  57. )
  58.  
  59. logger.info(f"✅ Archivo reposteado exitosamente: {file_name}")
  60. else:
  61. logger.debug(f"⏭️ Archivo ignorado (extensión no permitida): {file_name}")
  62. else:
  63. logger.debug("⏭️ Mensaje sin archivo, ignorado")
  64.  
  65. except Exception as e:
  66. logger.error(f"❌ Error al repostear mensaje: {e}")
  67.  
  68.  
  69. async def main():
  70. """
  71. Función principal para iniciar el bot
  72. """
  73. logger.info("🤖 Iniciando bot...")
  74.  
  75. # Conectar con el token del bot
  76. await bot.start(bot_token=BOT_TOKEN)
  77.  
  78. # Obtener información del bot
  79. me = await bot.get_me()
  80. logger.info(f"✅ Bot conectado: @{me.username}")
  81. logger.info(f"📡 Escuchando mensajes en: {SOURCE_CHANNEL}")
  82. logger.info(f"📤 Reposteando a: {TARGET_CHANNEL}")
  83. logger.info(f"📁 Extensiones permitidas: {', '.join(ALLOWED_EXTENSIONS)}")
  84. logger.info("🟢 Bot funcionando. Presiona Ctrl+C para detener.")
  85.  
  86. # Mantener el bot corriendo
  87. await bot.run_until_disconnected()
  88.  
  89.  
  90. if __name__ == '__main__':
  91. try:
  92. asyncio.run(main())
  93. except KeyboardInterrupt:
  94. logger.info("🛑 Bot detenido por el usuario")
Tags: Repost bot
Advertisement