CACTUS ELECTRONICS

Using Telegram-cli on Raspberry Pi

Introduction

Several posts and articles about using Telegram-cli can be found on the internet covering from simple instant messages and file transfers to execution of commands, applications and actions on the operating system. Similar tasks can also be accomplished without installing Telegram on the target system using what are called bots or Telegram accounts that are operated by software and residing on the Telegram servers. Scripts can be run on the target system to interact with bots and execute the desired actions. For details and information on the Telegram bots you can refer to this link. To have a look over a complete application using a Telegram bot API this link from Luca Dentella is very good and easy to implement.

On this post I will show you how to install Telegram-cli using a Raspberry Pi 2 model B running Archlinux as well as how to trigger events as turning on an LED, receiving temperature information and taking and receiving a picture using Picamera.

Below picture shows the whole system.

all_system

And here a close up over the RPI 2

RPI_close

Installing Telegram.

All the Telegram-cli code and documentation is posted on GitHub by vysheng. The installation instruction covers several distros and platforms, but the information on the Archlinux section is intended for the Intel X86 or i686 architecture. For the ARM-7 architecture (Raspberry Pi), you have to download the source code, compile and build it. I will not re-invent the wheel here as there are several very good articles showing all details installing Telegram as for example this excellent post. Most published articles are based on RPI running Raspbian, which is not much of a difference , still this post shows the way I’ve successfully installed on Archlinux so let’s get started:

It is a good practice to update the system before installing applications, so lets run

    #pacman –Syu

In my case, the updating procedure took about 25 minutes, it will depend how old your installation or last update was.

Make a directory where you want to have the installation (usually under your home directory)

cd to above created directory (in my case $~/telegram) and run:

    $git clone --recursive https://github.com/vysheng/tg.git && cd tg

In case you do not have git installed just “pacman” it!

When it finishes downloading, continue with

./configure

Now, in my particular case and version of telegram , configure ended with the following error:

“ no libnconfig ; try configure –disable-libconfig.

But trying above ended up with another error

“no libjasson, try configure –disable-json . Therefore, I’ve ended running :

$./configure --disable-libconfig --disable-json

This worked with no errors. However , I did not want to have an installation missing stuff so I installed the missing dependencies as follows:

#pacman –S libconfig
#pacman –S jansson

Now ./configure did worked fine and ended with no errors, so I’ve continued:

 make

This took about 25 minutes in my case and ended with no errors.

That’s it! Telegram is installed so I’ve now typed in:

$ bin/telegram-cli -k tg-server.pub

But it terminates immediately with errors as follows:

> telegram-cli: tgl/mtproto-utils.c:101: BN2ull: Assertion \`0' failed.
SIGNAL received

I’ve copied and pasted the error message on Google and upon several hits mentioning they’ve fixed the issue commenting out the lines 101 and 108 showing assert (0) in /tgl/mtproto-utils.c file.

When I’ve edited this file I’ve found 2 more lines with assert (0) and I’ve ended up commenting out them all as lines 101, 108, 116 and 122. I know that this is not an elegant solution but worth to try.

Running make again is fast as make will only rebuild the file mtproto-utils.c and any other file including it and not the whole bunch of source files as when it ran for first time. After this ( make sure the RPI is online) , I’ve ran.

alarm@alarmpi tg\]$ bin/telegram-cli -k tg-server.pub

And now it is working and it prompts the user to enter a cellular phone number.

alarm@alarmpi tg\]$ bin/telegram-cli -k tg-server.pub
Telegram-cli version 1.4.1, Copyright (C) 2013-2015 Vitaly Valtman
Telegram-cli comes with ABSOLUTELY NO WARRANTY; for details type \`show\_license'.
This is free software, and you are welcome to redistribute it
under certain conditions; type \`show\_license' for details.
Telegram-cli uses libtgl version 2.1.0
Telegram-cli includes software developed by the OpenSSL Project
for use in the OpenSSL Toolkit. (http://www.openssl.org/)
I: config dir=\[/home/alarm/.telegram-cli\]
phone number:

The Telegram user must be configured using a cell phone number as all Telegram accounts must be associated to a particular phone number. Enter a mobile phone number and hit enter . The idea here is to use a telephone that will not be used to chat with the RPI as it will be the same account . You can use a friend’s phone or any other phone available from which you can receive the authorization code and ideally with not an active Telegram account already running on it unless you do not mind to have 2 accounts in parallel.

Upon entering the phone number , it will ask if you want to register. I did not test what happens upon answering no. Answering yes will prompt for first name , then last name and then requiring a code as follows:

code ('CALL' for phone code):

This is an authentication code that will be received on the mobile number entered at previous step. Check the inbox as you should receive the 5 digit code in just seconds after entering the mobile number. Type it in and hit enter.

The Telegram-cli application is now all set. You just need to create another new account on your own cell phone or all the phones as well as devices you plan to use to contact the RPI remotely.

Once you have Telegram also running on your phone, if you have the mobile number used for the RPI in your contacts, you should find it from the contacts menu in the Telegram application. At this point you can start sending and receiving messages back and forth to test connectivity with the RPI.

Refer to the GitHub web page for the info on all the commands you can use on Telegram-cli

Once you are familiar with this , you can move on for other more interesting stuff as triggering actions and events on the RPI by sending text messages.

If at some point you decide or need to use a different phone to associate with the RPI account, you need to delete the folder ~.telegram and start the registration process all over again with the new mobile number.

Control events and actions with scripts

The telegram-cli application uses a scripting language called Lua to implement callback functions . So, you need to verify it is installed in your system or install it by running :

#pacman –S lua lua-lgi

As part of the installation files from Telegram-cli there is a Lua template script that can be easily edited to decode and perform the actions we want. Go to the telegram installation folder, cd to the tg folder and look for the file test.lua. In order to keep this original file , I saved it as action3.lua to then add code in it, if for some reason this file is messed up, the original is always available to start over.

As we will decode incoming text messages we will use the function on_msg_receive(msg)(shown on below figure) which starts at line 72

lua_function1

Starting from line 96, we will insert if conditions following the same structure as in the ‘ping and ‘PING’ examples.

1. Sending temperature readings

To measure temperature I use a DS18b20 evaluated by a Python script which simply reads the sensor output and saves the temperature in a text file .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/python
tempfile = open("/sys/bus/w1/devices/10-000801a537a5/w1\_slave")
thetext = tempfile.read()
tempfile.close()
tempdata = thetext.split("\\n")\[1\].split(" ")\[9\]
temperature = float (tempdata\[2:\])
temperature = temperature / 1000
print ("temperature is :",temperature)
temper = str(temperature)
file\_out = open("temp.txt", "w")
file\_out.write(temper)
file\_out.close()

The Lua function runs this Python script, replies the sender with a text message as an acknowledge , then , reads the 1 line file with the temperature value and send it away. The Lua script is using a function send_msg() on telegram-cli.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/lua
if (msg.text == 'Temp') then
    mark_read(msg.from.print_name, ok_cb, false)
    os.execute('sudo python temp2.py')
    send_msg (msg.from.print_name, 'room temp checked!', ok_cb, false)
    local k = io.open("temp.txt", "rb")
    local z = ""
    z = k:read()
    k:close()
    send_msg (msg.from.print_name, z, ok_cb, false)
return
  end

A more straightforward way is to avoid reading the file with Lua and instead using the send_txt() function which reads the file and send the contents at once.

2. Actuating an LED connected to the GPIO

In this case, I am using a Python script that will make the LED flash 5 times The Lua script executes the Python scripts and it sends an acknowledge message.

The Python script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/python

import RPi.GPIO as GPIO
import sys
import time

GPIO.setmode(GPIO.BCM) # Use Broadcom numbering
led = 18
GPIO.setup(led, GPIO.OUT)
print (" Turning ON BLUE LED ****")

GPIO.output(led, 0)

for x in range ( 0, 5):
    GPIO.output(led, 1)
    time.sleep(0.2)
    GPIO.output(led, 0)
    time.sleep(0.2)

and the Lua function:

1
2
3
4
5
6
#!/usr/bin/lua
if (msg.text == 'led') then
    os.execute('sudo python single_LED.py')
    send_msg (msg.from.print_name, 'largue el LED !', ok_cb, false)
   return
end

3. Taking a picture using Picamera.

For this I use a Bash script which take the picture and saves it as a JPG file. The Lua script uses the function send_photo() to read the JPG file and send with telegram.

  #!/bin/bash
  cd /home/alarm/Downloads/tg
  /opt/vc/bin/raspistill -t 1000 -w 460 -h 308 -o teo.jpg

and the Lua function:

  #!usr/bin/lua

   if (msg.text == 'Pic') then
       os.execute('./pic.sh')
       send_msg (msg.from.print_name, 'Processing Pic!', ok_cb, false)
       send_photo (msg.from.print_name, 'teo.jpg', ok_cb, false)
      return
    end

The Lua script can be downloaded by clicking here.

I think Telegram-cli is one of the best and reliable ways to interact with a Raspberry pi from the internet. Simple with no need to use static IP addresses and / or port forwarding , plus the unlimited freedom of interacting with the RPI independently of which wired or wireless network it may be connected with , or, in other words, if the RPI can reach the internet , it can be controllable and accessed from anywhere without any additional configuration.

As mentioned at the beginning, there are other ways of using Telegram via bots. On another post I will show how to get the same results using same events and actions covered in this article without using Telegram –cli application but the Telegram-Bot instead.