• Bhavya Putta

Using Telegram Bot with Raspberry Pi - Sharing Text and Files

Updated: Nov 22, 2020


Sharing texts and files

The Internet of Things is a new era in computing technologies. IoT includes many machines and devices interacting with each other. It plays a major role in the automation and interconnection of numerous devices. Devices are interconnected over the internet to monitor a task or to communicate with each other. They interact and detect anomalies, send alerts, share files, switch on, or switch off a particular device, and can do numerous other tasks.


In this article, let's discuss how to connect a Raspberry Pi with a Telegram Bot to share text and files. #Telegram is a cloud-based application used for the instant exchange of text and files. The Telegram Bot API allows it to interact with machines as well. The Telegram app is used from one's mobile to send commands to the #RaspberryPi, thereby enabling us to communicate with it. The components required, details of the hardware used, configuring the Telegram Bot, and the #code to be executed are discussed here. Let's head towards the project and know how it works.


Hardware used


All Components

The components used here are:

1) Raspberry Pi

2) USB Cable

3) SC Card

Let's know about them now.


Raspberry Pi


Raspberry Pi 3 Model B+

It is a tiny single-board computer with so many uses that it's possibly the biggest British invasion since "The Beatles". It was originally developed to promote the teaching of Programming in schools of developing countries. It is also widely used in many DIY projects. The Raspberry Pi 3 Model B+ used here is the last version of the 3rd Gen single board computers. It has 1GB LPDDR2 SDRAM, 4 USB 2.0 ports, a Micro SD port for loading your operating system and storing data, a CSI camera port, a DSI display port, and a 5V/2.5A DC power input.


USB Cable


USB cable for power supply

The Raspberry Pi should be powered via the micro USB port using a cable. The input rated voltage is 5V, and the current is 2.5A.


SD Card


16 GB SD card loaded with Raspbian OS

The 16 GB SD card used is loaded with the Raspbian OS. The #Raspbian is a Debian #Linux based OS specially designed for the Raspberry Pi. It is a primary operating system for the family of single-board computers of the Raspberry Pi series. It is now a 64bit version with the name Raspberry Pi OS and doesn't use the Raspbian core.


Configuring the Telegram Bot


Chat Bot Configuration
  • Firstly, install the Telegram app from the play store.

  • Now search for BotFather and open it. This is where a new Bot can be created.

  • Type /start and you will get a menu. Then type /newbot, and you will be asked for a name and username for the new Bot.

  • The username must end with 'Bot'.

  • Now a congratulations message will be displayed, and an Auth Token will be provided, which is used in creating a channel between the Raspberry Pi and Telegram Bot.


Commands Used
  • Then enter /set commands to enable commands for your bot.

  • Specify the name of your Bot and now enter the commands you require.

  • The commands used here are hi(To show the welcome message), time(To show current time), file(To share the specified file), image(To share the specified image).


setcommands Output
  • Once the commands are set, you can find them as shown in the image. So you can just select the one you require and need not enter them every single time.


Code


Now that we have configured the Telegram Bot, let's look into the code executed.

import time, datetime
import telepot
from telepot.loop import MessageLoop

Firstly, time and datetime modules are imported. Then the telepot module is imported. The message loop is imported from the telepot module.

now = datetime.datetime.now()

The 'now' variable is initialized with the current time. The time at which the command is sent will be recorded.

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Received: %s' % command

The function 'action' is defined that takes 'msg' as the argument. A 'msg' consists of a chat id and a command. Chat id is the details of the Bot and command is the text received from the Telegram. Then the received command is printed using the print statement as shown.


    if command == '/hi':
        telegram_bot.sendMessage (chat_id, str("Hi Parimal!! Welcome to Learn Electronics"))
    elif command == '/time':
        telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
    elif command == '/file':
        telegram_bot.sendDocument(chat_id, document=open('/home/pi/Desktop/fire_sms.py'))
    elif command == '/picture':
        telegram_bot.sendDocument(chat_id, document=open('/home/pi/Desktop/OpGL/3d-model.png'))

The above piece of code executes the actions for the specified commands. If the command received is :

  • 'hi' - The sendMessage function sends the specified message to the Telegram Bot with the mentioned chat id.

  • 'time' - The sendMessage function displays the current time in the format Hours and Minutes in the Telegram Bot.

  • 'file' - The sendDocument function shares the selected file with Telegram Bot.

  • 'image' - The sendDocument function shares the chosen image with the Telegram Bot.

The sendMessage and sendDocument functions are present in the telepot module. The chat id must be specified for both the functions and the path of the file or image must be provided in the sendDocument function.

telegram_bot = telepot.Bot('Your-API-Token-For-The-Bot')

The telegram_bot variable is initialized, and a channel is created between the Raspberry Pi and Telegram Bot by entering the Auth token given by BotFather.

MessageLoop(telegram_bot, action).run_as_thread()
print 'Lets have a chat session...'

while 1:
    time.sleep(10)

Now the message loop function is defined and made to run as a thread. After the thread is established, we can send any number of messages and communicate with the Raspberry Pi. To make it run forever, an infinite while loop is inserted with a sleep time of 10 seconds.


The complete code looks as follows -


import time, datetime
import telepot
from telepot.loop import MessageLoop

now = datetime.datetime.now()

def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print 'Received: %s' % command

    if command == '/hi':
        telegram_bot.sendMessage (chat_id, str("Hi Parimal!! Welcome to Learn Electronics"))
    elif command == '/time':
        telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
    elif command == '/file':
        telegram_bot.sendDocument(chat_id, document=open('/home/pi/Desktop/fire_sms.py'))
    elif command == '/picture':
        telegram_bot.sendDocument(chat_id, document=open('/home/pi/Desktop/OpGL/3d-model.png'))

telegram_bot = telepot.Bot('Your-API-Token-For-The-Bot')

MessageLoop(telegram_bot, action).run_as_thread()
print 'Lets have a chat session...'

while 1:
    time.sleep(10)

Download the complete code here.

raspi_telebot (Main)
.txt
Download TXT • 898B

Note: Please change the file format to .py(python file) format before you upload the code to the Raspberry Pi.


Working


Hardware Unpowered
Hardware Powered

The SD card is inserted into the Raspberry Pi and is powered up. It connects to the computer through Wi-Fi.


Python IDE

The code is written in a notepad and is saved with an extension .py which specifies that it is a python code file.


SSN Terminal

Open the SSN(Secure Socket Shell) terminal and enter the name of the python code file saved. Now start sending your commands from the telegram Bot created. The Raspberry Pi executes your commands and gives the required response. This way, we can share text and files by using Telegram with Raspberry Pi.


Bot Output

Thus, the Raspberry Pi answering the given commands is shown in the above image. The specified responses are achieved. The back end execution of the code at the SSN terminal is shown below.


SSN Terminal Output

Watch the video attached for a more firm approach.


Video By - Sai Parimal

The open-source Linux operating system of Raspberry Pi makes it handier in many #IoT projects. It is now widely used in Home and industrial #automation and also in the manufacture of many commercial products. We hope this was fun and interesting. Changes can be made to the code to execute many new commands. Do try them and know what all you can do with this tiny interesting device - The Raspberry Pi.

SEE ALSO


Control the brightness of an LED with Raspberry Pi

Sending Mobile Notification Alert for Fire using Raspberry Pi and Blynk - IoT

Interfacing DHT11 sensor with Raspberry pi and LCD

  • Facebook
  • YouTube
  • Instagram
  • LinkedIn
LearnElectronics
Contact Us
© Copyright - LearnElectronics 2021