Telegram tiene algunos inconvenientes, y algunas características sorprendentes, siendo una de ellas, la función bot. Es algo con mucha potencia que nos permite recibir mensajes usándolo.

Así que básicamente creas un bot de Telegram, y después de algunas configuraciones y preparativos, podemos usarlo para enviar mensajes a cualquier persona o grupo, siempre y cuando sepamos el id del chat entre esa persona y nuestro bot, o si añadimos el bot a un grupo. Espero que estés empezando a ver el poder que esto proporciona.

Lo que haremos aquí es escribir un script en Python que tomará un argumento, de hecho el mensaje de texto que queremos enviar, y lo enviará a nuestro bot. Además, si el bot pertenece a un grupo, todos los miembros del grupo lo recibirán.

Creemos nuestro bot

En Telegram, buscamos a @BotFather, y le enviamos a este contacto un mensaje /start. Él responderá algo similar a

I can help you create and manage Telegram bots. If you're new to the Bot API, please [see the manual](https://core.telegram.org/bots).

  
 You can control me by sending these commands:

  
 /newbot - create a new bot  
 /mybots - edit your bots **[beta]**

  
 Edit Bots
 /setname - change a bot's name  
 /setdescription - change bot description  
 /setabouttext - change bot about info  
 /setuserpic - change bot profile photo  
 /setcommands - change the list of commands  
 /deletebot - delete a bot

  
 Bot Settings
 /token - generate authorization token  
 /revoke - revoke bot access token  
 /setinline - toggle inline mode (https://core.telegram.org/bots/inline)  
 /setinlinegeo - toggle inline location requests (https://core.telegram.org/bots/inline#location-based-results)  
 /setinlinefeedback - change inline feedback (https://core.telegram.org/bots/inline#collecting-feedback) settings  
 /setjoingroups - can your bot be added to groups?  
 /setprivacy - toggle privacy mode (https://core.telegram.org/bots#privacy-mode) in groups

  
 Games
 /mygames - edit your games (https://core.telegram.org/bots/games) [beta]  
 /newgame - create a new game (https://core.telegram.org/bots/games)  
 /listgames - get a list of your games  
 /editgame - edit a game  
 /deletegame - delete an existing game

Ahora respondemos con el /newbot y obtenemos:

Alright, a new bot. How are we going to call it? Please choose a name for your bot.

Así que escribimos el nombre que queremos que tenga. BotFather responde:

Good. Now let's choose a username for your bot. It must end in 'bot'. Like this, for example: TetrisBot or tetris_bot.

De nuevo seguimos las instrucciones e introducimos el nombre de usuario del bot.

Done! Congratulations on your new bot. You will find it at t.me/<your_bot_username>. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you've finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.

Use this token to access the HTTP API:  
<here_we_have_the_token_we_need>  
Keep your token secure and store it safely, it can be used by anyone to control your bot.  
For a description of the Bot API, see this page: https://core.telegram.org/bots/api

Hemos terminado con el bot. Ahora necesitamos el ChatID. Así que tenemos que

  • Añadir el bot al grupo que queremos que reciba los mensajes.
  • Enviarle un mensaje ficticio desde el grupo de Telegram usando este formato: dummy_text @my_bot
  • Ir a la siguiente URL:

https://api.telegram.org/bot<here_goes_our_bot_token>/getUpdates

Y obtendremos un fichero JSON que contiene todas las actualizaciones que impactaron de alguna manera a nuestro bot, por lo que obtendremos el ChatID del grupo al que añadimos nuestro bot. Esto viene como parte del conjunto de datos JSON que pertenece a la actualización que recibió el bot cuando le enviamos el mensaje ficticio.

Ya hemos terminado con el bot y Telegram. Vamos con la segunda parte.

Crear el script Python

Ahora que tenemos todos los datos que necesitamos, el token del bot y el chatID del bot, podemos proceder a escribir nuestro script.

import sys, getopt, argparse, requests
def send_text_to_bot(message):
    token = ''
    chatID = ''
    sendtext = 'https://api.telegram.org/bot' + token + '/sendMessage?chat_id=' + chatID + '&parseMode=Markdown&text=' + message
    response = requests.get(sendtext)
    return response.json()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--message")
    args = argparse.parse_args()

    if (args.message) is not None:
        send_text_to_bot(args.message)
python push_message.py -m 'Hello from the bot side of Telegram'

El script está listo, necesitamos llamarlo desde el shell así:

En definitiva usamos un script para llamar a la API de Telegram, enviar a nuestro bot un mensaje, que al final reenviará al ChatID que le corresponda. Tan simple como eso.

He añadido el script a mi repo de GitLab por si queréis trastear con él. Encuéntralo en el siguiente enlace:

https://gitlab.networkbits.es/acastro/python-telegram-bot-script