Telegram Bot with Raspberry Pi Camera: send Images

This tutorial covers how to use Raspberry Pi Camera to send images to Telegram Bot. In this post, we will create a Telegram Bot that integrates with Raspberry Pi so that we can send commands to caputre images with the Raspberry Pi Camera and show it in the Telegram.

We have already covered a topic like this using a different device, you can read ESP32-CAM Telegram Bot. The code is developed using Python.

Telegram Raspberry Pi Camera project overview

Before starting it is useful to have an overview about what we will build and how we will integrate Raspberry Pi and Telegram:

How to use Telegram Bot with Raspberry Pi and Camera

Once we have created and configurated the Telegram Bot (we will see how to do it later), we can start sending messages to the Raspberry Pi that is listening. In more detail, when we will send a command /photo, the Raspberry Pi using the Camera will capture the image and send it back to the Telegram Bot.

How to create a Telegram bot

If you want to create your Telegram bot, you can use your smartphone or the Telegram Web interface. The first step is looking for @BotFather that is the bot that will guide you during the process. Below, it is shown how to do the next steps:

Create Telegram bot

In the end, you will have your Bot Id that you have to use in the next steps.

Other Raspberry Pi Project:
How to use Raspberry Pi with Google Cloud IoT
Raspberry Pi IoT: Influx DB, Grafana and MQTT

Adding the Telegram library

Connect to your Raspberry Pi and open a shell. The first step is installing the library that we will use to connect to the bot. To this goal, we will use Telepot library:

sudo pip install telepotCode language: Bash (bash)

If you don’t have pip installed, you can use the following command:

sudo apt-get install python-pipCode language: Bash (bash)

That’s all. The Telegram library is ready and we can start developing our code.

Connect Raspberry Pi to Telegram Bot

Once the bot is created, the next step is developing the Python code that interacts with the Bot and receives commands.

Now, open in Raspberry Pi an editor to develop the Python code to connect the Raspberry Pi to Telegram Bot. I used Python3 IDLE. Create a new file and name it telegrambot.py:

import telepot
import time
import os
from picamera import PiCamera
path=os.getenv("HOME")

# Handling message from Telegram
def handleMessage(msg):
     id = msg['chat']['id'];
     command = msg['text'];
     print ('Command ' + command + ' from chat id' + str(id)); 
     if (command == '/photo'):   
       print ("Taking picture…");   
       # Initialize the camera   
       camera = PiCamera();   
       camera.start_preview()   
       camera.capture(path + '/pic.jpg',resize=(640,480))   
       time.sleep(2)   
       camera.stop_preview()   
       camera.close()   
       # Seding picture   
       bot.sendPhoto(id, open(path + '/pic.jpg', 'rb'))
     else:     
       bot.sendMessage(id, "Command not found..")
 
bot = telepot.Bot('your_bot_id');
bot.message_loop(handleMessage);
print ("Listening to bot messages….");
while 1:
    time.sleep(10);     Code language: Python (python)

The code is quite simple. After importing the necessary libraries, it is necessary to configure the bot using the id we get when we have created the bot:

bot = telepot.Bot('your_bot_id');Code language: Python (python)

next, we have to attach a message handler so that we can manage the incoming messages from the Telegram bot:

bot.message_loop(handleMessage);Code language: Python (python)

Handling incoming messages from Telegram Bot

Now, we cand handle the incoming messages defining a function where we will check if the command holds the string /photo:

def handleMessage(msg):
     id = msg['chat']['id'];
     command = msg['text'];
     print ('Command ' + command + ' from chat id' + str(id)); 
     if (command == '/photo'):   
       print ("Taking picture…");   
       # Initialize the camera   
       # Seding picture   
     else:     
       bot.sendMessage(id, "Command not found..")Code language: PHP (php)

First, the python code extracts the chat id that we will use the send responses back and the message (we called it command). Next, the code verifies if the command is /photo , otherwise, it sends back a warning message.

Capturing the image using Raspberry Pi and send it

In this last step, it is necessary to capture the image and send it back to the user. To do it, we will the Raspberry Pi camera. Before using the camera, check if it is enabled using:

raspi-config

next:

Raspberry Pi enable camera

and then:

Enable camera with Raspberry Pi

Then, we can use the camera:

# Initialize the camera   
camera = PiCamera();   
camera.start_preview()   
camera.capture(path + '/pic.jpg',resize=(640,480))   
time.sleep(2)   
camera.stop_preview()   
camera.close()   
# Seding picture   
bot.sendPhoto(id, open(path + '/pic.jpg', 'rb'))Code language: Python (python)

The code captures the image with 640×480 and stores it using pic.jpg. After it, the code sends the picture to the client:

bot.sendPhoto(id, open(path + '/pic.jpg', 'rb')); Code language: Python (python)

Testing Telegram with Raspberry Pi

Now, you can run the code using the command:

python3 telegrambot.pyCode language: Python (python)

Now, look for @SwARaspPiBot and write the following command:

/photo

The result is shown here:

How to use Raspberry Pi camera with Telegram bot to send images

while in the Raspberry Pi we have:

Pyhton code to integrate Raspberry Pi with Telegram bot

If you are interested in capturing images you can read:

How to use ESP32-CAM with Tensorflow.js
How to capture images with ESP32-CAM
Image classification using ESP32-CAM

Wrapping up

At the end of this tutoria, you have learned how to integrate Raspberry Pi with Telegram Bot. Using Telepot library, we can handle the incoming messages from the Telegram Bot to the Raspberry Pi. With the camera connected to Raspberry Pi we can caputre images and send it back. You can further expand this project controlling the Raspberry GPIO pins.

  • Add Your Comment