• First Steps
  • General
  • Projects
Facebook Twitter YouTube
Tutorials for Raspberry Pi Tutorials for Raspberry Pi
  • Hardware & GPIO
  • Sensors & Components
  • Scale
  • Cases
  • Fingerprint
  • Gas Sensor
  • Heartbeat
  • German
Tutorials for Raspberry Pi Tutorials for Raspberry Pi
Home»Projects»Control Raspberry Pi via Telegram Messenger

Control Raspberry Pi via Telegram Messenger

Facebook Twitter LinkedIn Tumblr Email Reddit
Raspberry Pi Telegram Messenger
Share
Facebook Twitter LinkedIn Email Tumblr Reddit Telegram WhatsApp

This tutorial demonstrates how to automatically run scripts for text commands via Telegram after the installation on the Raspberry was covered in the previous tutorial. This allows you to, for example, easily query the status of your Pi’s on the go or simply perform actions remotely via your messenger.

Preparations

First I create a script that performs my actions, for example, I want to shut down my Pi, reboot and see the uptime. I prefer Python, but of course, any other script is possible, too (e.g., bash).
I name my script tg_actions.py.

sudo nano /home/pi/tg/tg_actions.py

In order to be able to execute different actions with a script, I use command line arguments, so that e.g. sudo python /home/pi/tg/tg_actions.py argument is recognized.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/python
 
import sys
import os
from datetime import timedelta
 
if sys.argv[1] == "shutdown":
    print "System is shutting down"
    os.system("shutdown now")
elif sys.argv[1] == "reboot":
    print "System will be rebooted"
    os.system("shutdown -r now")
elif sys.argv[1] == "uptime":
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime_string = str(timedelta(seconds = uptime_seconds))
        print(uptime_string[:-7])
#else:
#if nothing matches

The List can be expanded as desired, for example, the GPIO pins could also be read out

Set up Telegram

So that Telegram can react automatically to various Interactions (receiving Texts / Images / etc.), One can create a Lua Script. An example script is available in the Telegram directory under test.lua. I will edit this file as it already has ready-made functions for receiving etc.

sudo nano /home/pi/tg/test.lua

Since I want to respond only to text messages, for the time being, is the function on_msg_receive (msg) to be edited:

Lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
function on_msg_receive (msg)
    if started == 0 then
        return
    end
    if msg.out then
        return
    end
 
    --For the "has read" tick
    if msg.text then
        mark_read (msg.from.print_name, ok_cb, false)
    end
 
    --only allow one Number/contact
    if msg.from.print_name ~= 'Contact_Name' then
        os.execute("/home/pi/tg/send_script " .. msg.from.print_name .. " 'Invalid number.'")
        return
    end
    if (string.lower(msg.text) == 'uptime') then
        local handle = io.popen("sudo python /home/pi/tg/tg_actions.py uptime")
        local res = handle:read("*a")
        handle:close()
        os.execute("/home/pi/tg/send_script ".. msg.from.print_name .." '"..res.."' ")
        --Alternative:
        --send_msg (msg.from.print_name, res)
        return
    elseif (string.lower(msg.text) == 'shutdown') then
        local handle = io.popen("sudo python /home/pi/tg/tg_actions.py shutdown")
        local res = handle:read("*a")
        os.execute("/home/pi/tg/send_script "..msg.from.print_name.." '"..res.."' ")
        handle:close()
        return
    elseif (string.lower(msg.text) == 'reboot') then
        local handle = io.popen("sudo python /home/pi/tg/tg_actions.py reboot")
        local res = handle:read("*a")
        handle:close()
        os.execute("/home/pi/tg/send_script ".. msg.from.print_name .." '"..res.."' ")
        return
    else
        os.execute("/home/pi/tg/send_script ".. msg.from.print_name .." 'Error' ")
    end
 
end

In lines 15, 22, 30, 36 and 39, I call another script. This is not absolutely necessary; I wrote the alternative command in line 14. Anyone who still wants to send an answer via an additional script can create one:

sudo nano ~/tg/send_script

The content is:

Shell
1
2
#!/bin/bash
/home/pi/tg/bin/telegram-cli -k /home/pi/tg/tg-server.pub -W -e "msg $1 $2"

So that both scripts have corresponding rights, we assign them:

sudo chmod +x ~/tg/send_script
sudo chmod +x ~/tg/tg_actions.py

If this script does not work for someone, tazzie has come up with an alternative.

Attention: It is important that the number(s) of the sender has been stored by means of add_contact, otherwise no automatic Reply can be made.

Some Users report that the lua Script shows the following error: lua: /usr/share/lua/5.2/lgi/namespace.lua:149: Typelib file for namespace 'Notify' (any version) not found
If that is the case, the inner part of

-- Notification code {{{
...
-- }}}

should be deleted from the test.lua.

 

Start Telegram

The created Script must now be started with the messenger so that it can react to messages. So that it runs in the background you can start it like this:

screen -dmS TelegramCLI ~/tg/bin/telegram-cli -s ~/tg/test.lua -k ~/tg/tg-server.pub

If an error occurs, you still have to install screen, if not already done:

sudo apt-get install screen

Here is a process with my Raspberry Pi.

 

To start it automatically, follow this tutorial or use crontab:

crontab -e

At the end of the file, write the following line:

@reboot sleep 60 && screen -dmS TelegramCLI /home/pi/tg/bin/telegram-cli -s /home/pi/tg/test.lua -k /home/pi/tg/tg-server.pub

 

For those who want to do everything in the Lua script, there is a nice Lua GPIO Extension.

.lua messenger python script sms replacement telegram to control whatsapp
Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
Previous ArticleTelegram Messenger on the RaspberryPi
Next Article Raspberry Pi: APA102 LED Strip (RGB) per Python steuern

Related Posts

Control all GPIOs with the Raspberry Pi REST API via Python

Using TensorFlow Lite with Google Coral TPU on Raspberry Pi 4

Raspberry Pi Samba Server: Share Files in the Local Network

Build Live Text Recognition with the Raspberry Pi (OCR)

7 Comments

  1. Mohd Amir Syafiq Bin Mohd Azmer on 2. September 2018 9:37

    how to make my friends in telegram group can use the shutdown etc. command?

    Reply
    • viswa on 17. February 2019 15:09

      is the tutorial working for you? i did the same thing but its not working for me
      if you can help this is my mail “viswanmv2@gmail.com” please mail me.

      Reply
  2. viswa on 17. February 2019 15:18

    i did exactly as you did. i can interact and send msgs to other mobiles through pi’s telegram-cli, but am not able to run those scripts. how do pi knows to which no. it should respond?
    why did u use lua script especially ? if you can do scripting in python itself.
    how to know if my script is actually working, where to place the script file, what if i dont give the chmod +x permissions… too many question i have. if you reply, please reply in english

    Reply
  3. viswa on 25. January 2020 17:23

    it is not clear how to use between android telegram and pi tg

    Reply
  4. Shak on 6. March 2020 9:42

    Great tutorial!
    Worked for me, but telegram-cli deamon stops responding after sending message, even it’s via other screen daemon. Anyone has an idea why?

    Reply
  5. DB on 26. April 2020 15:18

    Thank you very much for this post, really useful.

    Do you think is possible to pass parameters via Telegram ? Like “reboot 5” for instance to reboot in 5 min… but with that number being a real parameter.

    I’m looking for a way to pass parameters via telegram to once of my scripts in a dynamic way.

    Reply
    • Felix on 26. April 2020 16:04

      You could try to extract the parameter from the message.

      Reply

Leave A Reply Cancel Reply

Configure and read out the Raspberry Pi gas sensor (MQ-X)

Review of the 7″ Raspberry Pi Touchscreen Display

How to setup a Raspberry Pi Security Camera Livestream

Read Capacitive Soil Moisture Sensor DFROBOT Gravity on the Raspberry Pi

Raspberry Pi: Control Relay switch via GPIO

Raspberry Pi LCD Display: 16×2 Characters Display (HD44780)

Subscribe to Blog
Subscribe to Raspberry Pi Tutorials and don't miss any new Tutorial!
Subscribe

Thank you!

We will contact you soon.

Tutorials for Raspberry Pi
Facebook Twitter YouTube
  • Contact & Disclaimer

Type above and press Enter to search. Press Esc to cancel.