Share

En esta entrada veremos como generar un script en python para interactuar con nuestros servidores vía Telegram:

Instalar las librerías que se necesitan:

pip install future

pip install urllib3

pip install certifi

pip install python-telegram-bot

 

El template sería algo así:

 
#
# Code to interact with your server.
#
import telegram
import sys
import logging
import os


bot = telegram.Bot("API")
#chat_id=_NUMERO_



def log_update(update):
  message = update.message.text.encode('utf-8')
  bot_chat_id = update.message.chat.id
  update_id = update.update_id
  first_name = update.message.from_user.first_name
  last_name = update.message.from_user.last_name
  from_id = update.message.from_user.id

  if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
    logging.debug('Update %d from %s %s (%d) in chat %d received:', update_id,first_name, last_name, from_id, bot_chat_id)
    logging.debug(update)
  else:
    logging.info('Update %d from %s %s (%d) in chat %d: Received "%s"', update_id,first_name, last_name, from_id, bot_chat_id, message)


try:
    LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
except IndexError:
    LAST_UPDATE_ID = None

while(True):


    for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=30):
      bot_chat_id = update.message.chat.id
      message = update.message.text.encode('utf-8')
      update_id = update.update_id
      log_update(update)
      if chat_id >= 0 and chat_id != bot_chat_id:
        logging.warning('Unauthorized chat_id %d found. Update ignored.', bot_chat_id)
        continue

#command help
      if '/help' == message:
        status = "/GetFile - Get a file.\n/ExecCommand - Exec a pre set command.\n/OtherCommands - Send a Message"
        bot.sendMessage(chat_id = bot_chat_id, text=status, parse_mode=telegram.ParseMode.MARKDOWN)

#command NewPasswordsFile

      elif '/GetFile' == message:
        fd=open('/path/to/file.txt','r')
        bot.sendDocument(chat_id=bot_chat_id, document=fd)
        fd.close()

      elif '/ExecCommand' == message:
        os.system('echo command to exec > /path/to/file')

      elif '/OtherCommands' == message:
        bot.sendMessage(chat_id=bot_chat_id,text='Ideas are welcome :P, use /Suggest idea to submit crazy features.')

      else:
        #bot.sendMessage(chat_id=bot_chat_id,text='Welcome to My bot. Accepted commands:\n\n/help - Info aobut commands.')
        os.system('echo x > /dev/null')

      LAST_UPDATE_ID = update_id + 1
   

A disfrutarlo 🙂

Share

I. Creando bot de telegram

Hay múltiples posts donde este proceso está bastante bien documentado pero creo que es útil tener todos los pasos aquí. Y como se trata de facilitar el proceso, describo el proceos yendo al grano.

I.a Desde el buscador de Telegram localizad a @BotFather, un bot para controlarlos a todos.

BotFather para gestionar Bots en Telegram

BotFather permite gestionar Bots en Telegram

I.b Comenzamos a interacturar con @BotFather con el comando /start

El comando /start te permite hablar con BotFather

El comando /start te permite hablar con BotFather

I.c Usamos el comando /newbot para crear un nuevo bot

Elige nombre para el bot y a continuación el nombre de usuario (éste último debe terminar en ‘bot’, ejemplo Scada_bot)

Si todo va bien, obtendremos nuestro token para interactuar con la API de Telegram

Obteniendo un Token para interactuar con la API HTTP de Telegram

Obteniendo un Token para interactuar con la API HTTP de Telegram

Tan sencillo como esto! Ya tienes un bot en telegran y su token para interacturar con la API HTTP.