Raspberry Telegram Bot y Motion

Vamos a crear y utilizar un Bot de Telegram para que funcione con Motion en Raspberry Pi.

 
Raspberry Telegram Bot y Motion
 

¿Cómo crear un Bot para Telegram en Raspberry Pi?

 
Para crear un bot para avisos por Telegram interactuando con Motion de Raspberry, necesitamos hacer lo siguiente:

  • Averiguarmos nuestro ID de Telegram con IDBot
  • Usamos Botfather para crear un bot y un TOKEN asociado
  • Instalaremos pyTelegramBotAPI para que la Raspberry pueda “hablarnos” por Telegram
  • Instalaremos “Motion Detection Telegram” para que cuando Motion detecte movimiento y capture fotos, “Motion Detection Telegram” nos las envíe directamente por Telegram.

 
En este artículo:

 

 

1. QUÉ PODEMOS HACER CON UN BOT EN TELEGRAM

 

Con un bot de Telegram creado con @BotFather podremos realizar multitud de funciones:

 
botfather Telegram Bot y Raspberry Pi
 

 

2. Instalar Telegram y usar el bot IDBot (@myidbot)

 
Lo primero hemos de instalar la app de Telegram en nuestro smartphone. También podemos instalar Telegram via Web.
 
Usaremos el bot IDBot (@myidbot ) para averiguar nuestra id de usuario en Telegram.
 
Telegram myidbot

 

Primero comenzamos con el comando

/start

Después, con el comando

/getid

nos devolverá un número, que es nuestra id de Telegram, y hemos de apuntarlo para posteriormente introducirlo en la API de Telegram y poder usar nuestro bot, que crearemos posteriormente con @BotFather.
 
telegram myidbot getid

 

Llega el momento de utilizar el padrino de los bots de Telegram: BotFather, que nos permitirá crear nuestro bot con la API de Telegram.
 

 

3.BOTFATHER

 

Ahora usaremos @BotFather para crear un bot.

botfather telegram creamos un bot
 

 

3.1 Comenzamos con@BotFather

 
Comenzamos con el comando

/start

telegram botfather start
 
Aquí podemos ver algunos de los comandos que podemos usar para controlar la configuración de nuestro bot creado con @BotFather :
 
comandos botfather telegram

 

 
Ahora podemos ver cómo creamos el nuevo bot con @BotFather, y le daremos un nombre, y un username (nombre de usuario):

Comenzamos con el comando

/newbot

después contestamos a lo que nos va preguntando @BotFather, y le damos un nombre a nuestro bot

y seguimos otorgándole un nombre de usuario (username):

 

telegram botfather crea new bot

 

Así que ya tenemos nuestro bot creado. Lo más importante después de crear el bot y darle nombre, es conseguir el TOKEN de Telegram API para este bot. @BotFather nos lo proporciona después de darle nombre y username a nuestro bot:
 

 

3.2 TOKEN de Telegram para nuestro bot

 
telegram botfather bot api token
 
Use this token to access de HTTP API:

xxxxxx9460:AAGmoxxxxxxxxxxxxxxxxxxxxxx
 

Este TOKEN es lo más importante, ya que nos permitirá autenticarnos con la API de Telegram e interactuar con nuestro bot y hacer que comience a funcionar.
 

 

3.3 Foto para nuestro bot

 
Si queremos poner una foto a nuestro bot, utilizamos el comando

/setuserpic

 
telegram botfather setuserpic

 

 

Si necesitamos más ayuda, utilizamos el comando

/help

Que nos mostrará los comandos disponibles para utilizar con GodFather y configurar nuestro bot.
 

 

3.4 Comandos disponibles con @GodFather

 

I can help you create and manage Telegram bots. If you’re new to the Bot API, please see the manual.

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

/setinlinegeo – toggle inline location requests

/setinlinefeedback – change inline feedback settings

/setjoingroups – can your bot be added to groups?

/setprivacy – toggle privacy mode in groups

Games

/mygames – edit your games [beta]

/newgame – create a new game

/listgames – get a list of your games

/editgame – edit a game

/deletegame – delete an existing game

 

 

4. Ahora vamos a integrar nuestro bot de Telegram con la API de Telegram en Raspberry Pi, y usarlo con Motion.

 

Vamos a instalar en nuestra Raspberry Pi la pyTelegramBotAPI de Eternnoir, que se trata de una implementación en Python de la API de Telegram Bot, y nos permitirá utilizar la API de Telegram en nuestra Raspberry Pi.

 

 

4.1 Instalar pyTelegramBotAPI

 
Lo instalamos simplemente con:
 

apt-get install pip
pip install pyTelegramBotAPI

 

pip install pyTelegramBotAPI

 

 

Después veremos que para utilizar Motion con la API de Telegram existe otro paquete (Motion detection Telegram) que podemos instalar para que trabaje conjuntamente con pyTelegramBotAPI de Eternnoir . Lo vemos a continuación.

 

pyTelegramBotAPI para Raspberry
 

 

4.2 Instalar MOTION DETECTION TELEGRAM

 
Instalaremos Motion Detection Telegram con:

git clone https://github.com/ttan/motion-detection-telegram.git

 
Y ya podemos comenzar a configurarlo. Los archivos importantes son

motion.py, que es el archivo donde introduciremos el TOKEN de nuestro bot de Telegram.
 
En mi caso lo modifiqué un poco para que solo enviara las imágenes usando el bot de Telegram, así:

import requests, glob, os
import sys
 
list_of_files = glob.glob('/etc/motion/cam1/*.jpg') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
 
url = 'https://api.telegram.org/bot1234567890/' #REPLACE WITH BOT TOKEN, leaving 'bot' in the url
r1 = requests.post(url+'sendMessage', data={"chat_id": 00000000, "text": 'Motion detected'}) #REPLACE CHAT ID
fileName = latest_file
r3 = requests.post(url+'sendPhoto', files={'photo': open(fileName, 'rb')}, data={"chat_id": 00000000}) #REPLACE CHAT ID

 
Tendremos que modificar el “Bot Token“, añadiendo el nuestro, y dejando la palabra “bot” delante como se puede ver.
También modificamos el “chat_id“, poniendo el nuestro.
 
motion detection telegram - motion py token bot id
 
y motion.conf, que es el archivo con el que configuraremos los parámetros de Motion y la cámara.
 

Para más info sobre Motion en Raspberry, puedes revisar todos los artículos al respecto AQUÍ.

 

 

5. MOTION FUNCIONANDO EN Raspberry Pi y mandando fotos por Telegram

 
Ahora ya tenemos la API de Telegram instalada en la Raspberry Pi, e integrada con Motion Detection Telegram, que permite que Motion funcione con Telegram y nos envie las capturas/videos que vaya capturando:
 
telegram bot motion
 

 
Agradecimientos a Forajido6 🙂