Monday, June 6, 2016

Send photos with Telegram

In the last post we saw how to use the Telegram bot APIs to send a message from a Raspberry Pi to our smartphone.

This time I will show you how easy is sending a photo using the same APIs and the Python library. You can use the same APIs also for sending videos and audio files with really small efforts.

First of all be sure to have the library installed. If you need help on installing it, just see the previous post or go directly to the library site.

Anyway note that on some system you may need to install another library before. This usually happens if you are using Python 2.x instead of Python 3.x for coding your scripts.

If the Telegram library gives an error when trying to install, just install this one before and then retry:

sudo pip install future

Now let's see the code for sending an image:

import telegram
import picamera

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

# Sets the id for the active chat
chat_id=123456789

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

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

Again this is a really simple script. Let's see how it works...

At the beginning we just import the Telegram and the PiCamera libraries. Then the bot is created like we did in the previuos post.

After this we need the chat id. Remember that a bot cannot start a chat by itself, so you need to send it a message from your smartphone to create the chat and be able to retrieve its id. Then you can just store this number into a file or write it down to use it direcly in your script as I did above (the chat id used above is of course a fake number).

Now we need to get an image. You can use also different formats and you can get it from other sources. In this example I just get a snapshot from the PiCamera.

The last line is the one that actually sends the image. You need to specify the chat id and the file obiect (created with the open() standard function).

You can also send an image from the web by using the following syntax for the last line:

bot.sendPhoto(chat_id=chat_id, photo="http://www.thingiverse.com/img/thingiverse-logo-2015.png")

just use the image link instead of the open() function and you are done.

As I wrote above, you can also send different type of files. You only need to use the right function. For example you can use

sendAudio() to send an audio file
sendVideo() to send a video clip
sendDocument() to send a generic file

and so on. Take a look at the telegram library docs to find all the supported functions.

As you can see, Telegram is much easier to use from a Raspberry Pi than Yowsup, so if you need to communicate with your device I really suggest you to use this software.

28 comments:

  1. Nice article. And very useful, thank you!
    There is www.ravintolakoneetvaasa.fi company, it could be useful for someone.
    Have a nice day! :)

    ReplyDelete
  2. Many thanks. I'm probably jumping ahead of your plans here but how do I get the Pi to sit and wait for incoming messages then react based on those messages like your older whatsapp scripts? i.e. Send "CPU Temp" from my phone and the Pi replies with "Current CPU Temp is ..." Or send "Light On" and it turns on a relay hooked to the GPIO.

    ReplyDelete
  3. @The Big Grey Beard would really like such a code. got any ideas?

    ReplyDelete
  4. 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:~ $

    If you can help me

    ReplyDelete
    Replies
    1. It seems that there is some access issue to the image. Try to send an already created image, instead of capturing it, just to try. And look at the file permissions of the captured picture, to see if there is something wrong...

      Delete
    2. not just for image
      so for text and for every thing say this error

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

      Delete
    4. Please one help me
      i'm need for your help
      when i run this code say me this error:

      pi@raspberrypi:~ $ sudo python telnew.py
      Traceback (most recent call last):
        File "telnew.py", line 17, in
          bot.sendPhoto(chat_id=281800458, photo=open("/home/pi/result.jpg"))
        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

      Delete
    5. The issue coul be from the token or the chat id. Maybe you closed the chat, so the id is no longer valid. In this case you need to open a new chat. Also check if the token is right and complete.
      If nothing works, then try creating a new bot and a new chat with it.

      Delete
    6. my chat is opened and my token is right, may be my error in install python-telegram package in module
      i don't know how solve it
      very thanks for reply me
      i'm waiting for your answer if you know
      regards

      Delete
    7. i created a new chat and a new bot
      but say me the same error
      this my error :

      Traceback (most recent call last):
        File "/home/pi/tel.py", line 38, in
          bot.sendMessage(chat_id=281800458 , text="Some activity detected for the past 5 seconds!")
        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 207, in post
          **urlopen_kwargs)
        File "/usr/local/lib/python2.7/dist-packages/telegram/utils/request.py", line 150, in _request_wrapper
          raise Unauthorized()
      Unauthorized: Unauthorized

      Help?!

      Delete
    8. Just for info, did you install the "future" library as stated above in this post? Maybe this could be the issue...

      Delete
    9. Yes of course, i installed "future" library
      but say the some error :


      Traceback (most recent call last):


      Help?!

      Delete
  5. I have installed future and followed the instructions on here. Still I get an error. The photo is taken but nothing happens after that. Instead I get this error:
    Traceback (most recent call last):
    File "send_photo.py", line 16, in
    bot.sendPhoto(chat_id=314156066, 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. I searched a lot about this in the last days, but the only thing found is that the problem is in the chat id or in the bot itself. Also I tried to create a new bot, but never got this error. Maybe you should try asking directly in the python-telegram forum...

      Delete
    2. Mr. Carlo Mascellani you say Also I tried to create a new bot, but never got this error.
      you use raspbrry pi with LCD or you use laptop with VNC server !??

      Delete
    3. None of these. I always use my rpis with ssh, so i'm connecting with Putty (on Windows).
      Of course only console, no graphical interface.

      Delete
    4. i will be crazy because of this problem.
      if you can please try to solve it
      thank's for you in advance

      Delete
    5. I can send text but i can't send photo
      please help

      Delete
  6. Thank's for allah
    I solved this problem
    and now i can send photo and text to telegram
    Thank's for you Mr. Carlo Mascellani

    i solved by using this code:

    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!")
    bot.sendPhoto(chat_id=chat_id, photo="http://www.thingiverse.com/img/thingiverse-logo-2015.png")

    ReplyDelete
    Replies
    1. i have tried this but i am getting syntax error:chat_id=updates[-1].message.chat_id with that line please help

      Delete
    2. check if it's written correctly. Syntax errors mean that you probably wrote something wrong. Also check that there are no extra characters after the last one of the line.

      Delete
  7. Telegram Messenger in its state-of-the-art updates have brought a new function of custom sticker sets. In its blog put up Telegram mentioned that now artists can post their custom sticker sets via the Telegram @stickers bot. every sticky label set will gets a everlasting link, so that customers can without problems upload new stickers and proportion them with their pals.

    ReplyDelete
  8. Thanks for sharing. I tried it and was only able to send text. Any way to solve this?

    ReplyDelete
    Replies
    1. Cannot say without any kind of info. Anyway, try using the code from Nashwan Adnan's comment just above. If this works than it's probably an issue with the media you are trying to send...

      Delete
  9. hi, i got some error. why error name 'bot' is not define.. at bot.sendPhoto.,, that code take the picture but does not send to telegram.. pleas help me

    ReplyDelete
    Replies
    1. "bot not defined" means that the telegram.bot(...) command returned null and the bot has not been created. Check that the token of your bot is correct.

      Delete
  10. hi , i need help , how do i send photos saved in my raspberry pi to the phone via telegram\
    Please provide me with a code

    ReplyDelete

Note: Only a member of this blog may post a comment.