Thursday, April 14, 2016

Using Telegram with Raspberry Pi

Until few months ago to communicate with my Raspberry Pi I used Yowsup that is able to connect to the Whatsapp servers.

Unfortunately this method has several issues that made me choose something different... First of all the need of a sim card or at least a phone number not used for other Whatsapp connections, the frequent changes on the Whatsapp protocol and so to the Yowsup libraries that force you to always check for them and eventually update the software and your scripts also on the RPi and least but not last the fact that Whatsapp do not like that their servers are used with a software that is not their messenger!

There are several different solutions to communicate with a RPi. One that I'm using is Pushover, but it's just a one way system (from RPi to the smartphone). It works quite well if you just need text notifications, but if you need something really like Whatsapp the solution could be Telegram.

Probably you already heard about this software. It's quite similar to Whatsapp, but it has many more features that make it a perfect software for our needs. Of course it's free, so you have to pay nothing to use it.

The first thing to note is that Telegram can create bots. A bot is just a "user" without a phone number and it can be managed by a software.
The (really) good thing is that this feature is mantained by the Telegram staff, so they can use the same kind of interface and changing the way it works, without any kind of work by the users.

The bad thing about bots is that they cannot start a chat on their own. You need to add them to a group or start a conversation with them before you can receive from them. Anyway this must be done just once before starting your scripts the first time.

If you need more info about Telegram bots, just visit their intro section.

Now let's see how to create a bot. Of course you need to have the Telegram app installed (note that you can install it also on a computer, not only on smartphones).
Then start a chat with @BotFather. This is the main Telegram bot and you can use it to create your bots:


To create a new bot, just send the command /newbot and BotFather wil ask you to give it a name and then a user name. The user name has to terminate with the string bot:


Note that the user name is stored in the Telegram databases, so it's must have never been used before.

Now the bot has been created and BotFather tells you something important:


The token (in the picture above it's just an example) will be used by our scripts to use the bot, so do not lose it!

You could also change some detail about your bot, like the picture or a description, but this would go beyond the scope of this post.
To use a Telegram bot with a Raspberry Pi you need to install the Python Telegram Bot library. To do so just use the following command from the shell:

pip install python-telegram-bot

if you do not have pip installed, just use this before the previous statement:

sudo apt-get install python-pip

After installing this library we can use it in our scripts. Let's use the following script:

import telegram

# Connect to our bot
bot = telegram.Bot(token="123456789:ABCDabcdefgYGscai2d_hakusnci7Hdks")

# Waits for the first incoming message
updates=[]
while not updates:
    updates = bot.getUpdates()

# Gets the id for the active chat
print updates[-1].message.text
chat_id=updates[-1].message.chat_id

# Sends a message to the chat
bot.sendMessage(chat_id=chat_id, text="It works!")

This is just a small and simple script, just to show you how to get messages and sending them. Let's see how it works...

After importing the library, a new bot is created, The token parameter is exactly the one provided by the BotFather when you created your bot.

Then we just loop waiting for messages. This should be done at least the first time in order to get the chat id needed to send messages with the script. You can also print it and use the value directly the next time as the chat id will remain the same until you delete it.

Note that messages will stay available in the Telegram servers for about 24 hours and then they are deleted. This means that if you cannot receive them (maybe because of an internet connection issue) you could lose them. Another thing you should remember is that if there are messages stored in the servers, the getUpdates command will always return them, even if you already read them, so if you need to wait only for new messages there are more actions to be performed.

At the end we are sending a message to the specified chat and if there are no problems, you should receive the answer from the RPi.

Please remember that this is an extermely simple script to use the Telegram library for Python. With the bot API you can also send and receive photos, audio files, documents and so on. There are tons of features that can be useful and they can also be easily accessed.

Please refer to the Telegram bot API for futher information.

Time permitting (lately I'm quite busy...) I will make a new post with a more complex script to communicate with Raspberry Pi using Telegram. Until then you can surely make your own attempts with the library.

22 comments:

  1. Thank you so much. This is a really easy way of automation with python and raspberry pi. I connected a PIR sensor to my raspberry pi at home, it sends a message to me, when someone comes to my home

    ReplyDelete
  2. i cant install ((pip install python-telegram-bot))
    say me error
    if you can help me
    regards

    ReplyDelete
    Replies
    1. Maybe pip is not installed. Try
      sudo apt-get install python-pip
      before installing the telegram library.

      Delete
    2. very thanks Carlo Mascellani for fast answer
      i installed pip
      say me this error

      Exception:
      Traceback (most recent call last):
        File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
          status = self.run(options, args)
        File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 342, in run
          prefix=options.prefix_path,
        File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 784, in install
          **kwargs
        File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 851, in install
          self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
        File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files
          isolated=self.isolated,
        File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 345, in move_wheel_files
          clobber(source, lib_dir, True)
        File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 316, in clobber
          ensure_dir(destdir)
        File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir
          os.makedirs(path)
        File "/usr/lib/python2.7/os.py", line 157, in makedirs
          mkdir(name, mode)
      OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/certifi-2016.9.26.dist-info'

      Delete
    3. Just use
      sudo pip install...
      Instead of just pip install...

      Delete
    4. i tried
      but i can't

      when i use sudo pip install say me this:
      pi@raspberrypi:~ $ sudo pip install
      You must give at least one requirement to install (see "pip help install")

      Delete
    5. This comment has been removed by the author.

      Delete
    6. I just did not write everything (saw the 3 dots?). Full command would be
      sudo pip install python-telegram-bot

      Delete
    7. i didn't write every thing
      i write :
      sudo pip install python-telegram-bot
      say me error
      i'm very need for solve this problem
      thank's for you
      i'm waiting for answer
      regards

      Delete
    8. now when i enter command:
      sudo pip install python-telegram-bot

      say me this error:

          with open(path, 'rb') as stream:
      IOError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/protobuf-3.1.0.post1-py2.7.egg/EGG-INFO/namespace_packages.txt'
      pi@raspberrypi:~ $ sudo python tele.py
      Traceback (most recent call last):
        File "tele.py", line 1, in
          import telegram
      ImportError: No module named telegram
      pi@raspberrypi:~ $ 

      Delete
    9. Thank's very much
      i installed the library by this command:
      sudo pip install python-telegram-bot

      but now when i run a python script for send photo say me this error:

      pi@raspberrypi:~ $ sudo python tele.py
      Traceback (most recent call last):
        File "tele.py", line 16, in
          bot.sendPhoto(chat_id=281800458, photo=open('./capture.jpg', 'rb'))
        File "/usr/local/lib/python2.7/dist-packages/telegram/bot.py", line 125, in decorator
          result = func(self, *args, **kwargs)
        File "/usr/local/lib/python2.7/dist-packages/telegram/bot.py", line 151, in decorator
          result = self._request.post(url, data, timeout=kwargs.get('timeout'))
        File "/usr/local/lib/python2.7/dist-packages/telegram/utils/request.py", line 199, in post
          result = self._request_wrapper('POST', url, body=data.to_form(), headers=data.headers)
        File "/usr/local/lib/python2.7/dist-packages/telegram/utils/request.py", line 150, in _request_wrapper
          raise Unauthorized()
      telegram.error.Unauthorized: Unauthorized
      pi@raspberrypi:~ $ 

      Delete
    10. this python code :

      import telegram
      import picamera

      # Connect to our bot
      bot = telegram.Bot(token="281800458:AAGc88ix59qMtCCn_6jNM4sqYjsM8vGX8T4")

      # Sets the id for the active chat
      chat_id=281800458

      #Get the photo
      camera=picamera.PiCamera()
      camera.capture('./capture.jpg')
      camera.close()

      # Sends a message to the chat
      bot.sendPhoto(chat_id=281800458, photo=open('./capture.jpg', 'rb'))

      Delete
    11. any help?
      for sending photo to telegram

      Delete
  3. I seem to have the same problem. The cam takes the picture but that's it. After that this error occurs.

    Traceback (most recent call last):
    File "send_photo.py", line 16, in
    bot.sendPhoto(chat_id=123456789, photo=open('./capture.jpg', 'rb'))
    File "/usr/local/lib/python2.7/dist-packages/telegram/bot.py", line 125, in decorator
    result = func(self, *args, **kwargs)
    File "/usr/local/lib/python2.7/dist-packages/telegram/bot.py", line 151, in decorator
    result = self._request.post(url, data, timeout=kwargs.get('timeout'))
    File "/usr/local/lib/python2.7/dist-packages/telegram/utils/request.py", line 199, in post
    result = self._request_wrapper('POST', url, body=data.to_form(), headers=data.headers)
    File "/usr/local/lib/python2.7/dist-packages/telegram/utils/request.py", line 150, in _request_wrapper
    raise Unauthorized()
    telegram.error.Unauthorized: Unauthorized

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  4. can i ask for your help. is it possible for me to request the GPS location of the Pi from telegram? I have searched everywhere, but i can not find it.

    ReplyDelete
    Replies
    1. I also tried to search something and found almost nothing... The only things I have found are:
      GPS coordinates are sent as a media (like photos and videos). At this link you can see that GeoPoint is treated like inputMediaPhoto and similars: core.telegram.org/type/InputMedia
      Second thing I found is a comment from 13/06/2016 saying that GPS coordinates are not sent because of a bug, but I did not found anything about a fix of this error...

      Delete
    2. I see, then i cant do anything about that then.

      Delete
    3. also sir, do you know how to send a picture to telegram from raspberry pi by using the picamera?

      Delete
  5. Hi,

    i have running the telegram bot in putty using raspberry.if turn off putty my telegram bot not working on raspberry. i need to run telegram bot 24/7 . what i need to do further to run telegram bot automatically in background using raspberry.

    kindly help me.

    thanks,

    Pandiyan

    ReplyDelete
    Replies
    1. There are several options to start a program at boot, but there are differences between Debian wheezy and jessie. Anyway you can just search on google to find lots of pages on this topic.

      Delete