Telegram – Send Messages, Photos, Animated Gifs from your Raspberry Pi and RPi Web Cam

This tutorial has been created to work with RPi Web Cam Interface (for more details see: https://elinux.org/RPi-Cam-Web-Interface)

Telegram (an IM platform similar to WhatsApp) has the ability to send messages and pictures from your RPi Web Cam to your phone or desktop whenever motion is detected for instant notification. Plus it’s FREE! 🙂
 
To find out more visit: https://telegram.org
 
We will be using a Telegram Bot which is specifically designed to work with software, meaning that a message can be sent using bash scripts: https://telegram.org/blog/bot-revolution
 
Start by installing the Telegram app on your phone or desktop (this process will create your account – https://telegram.org), and then sign up for a Telegram bot using Botfather with the instructions here: https://core.telegram.org/bots#6-botfather.
 
Make a note of your API Token and bot username (the one that must end in bot)
 
We now need to obtain your bot’s chatid. To do this, enter the bot username in the Telegram search field (either in Contacts or Chats), then select the bot to initiate a chat with it, and then send a message. This process will establish a conversation (or chat) between you and the bot, identified as a chatid.
 
To find the chatid, enter the following URL in a browser (your API token goes after and right next to /bot):

https://api.telegram.org/botReplaceThisWithTheBotFatherToken/getUpdates

 
e.g, if your API is “123456789:jekcjrnekjrhteuncheiucnf”:

https://api.telegram.org/bot123456789:jekcjrnekjrhteuncheiucnf/getUpdates

 
You need the “id” number from the output it produces:

"message":{"message_id":2872,"from":{"id":987654321,

 
In the example above, this would be “987654321”
 
If you only see {“ok”:true,”result”:[]}, it means you haven’t yet sent your bot a message from your account.
 
Ok, so now that you have your API token and chatid, we can use the Pi to send you a message. Let’s send a test message to start with by entering the following from the Pi command line (substituting with your API and chatid where relevant):

curl -s -X POST https://api.telegram.org/bot123456789:jekcjrnekjrhteuncheiucnf/sendMessage -d text="A message from your bot" -d chat_id=987654321

 
Now we need to wrap this up in a script to send you notifications when motion is detected.

Create a new config file to store variables for Telegram

sudo nano /var/www/html/macros/configfile.cfg

Enter the following text into that file, replacing where necessary

#!/bin/bash
 
#Replace text within and including the arrow brackets <> with your own details
 
#Camera details
cameraName="<Mycam>"  
 
#Telegram details
tokenurl="https://api.telegram.org/bot<your API key>"
chatid="<your chat id>"
 
#Folder paths
webfolder="/var/www/html"
nomsg="/home/pi/nomsgfile.lck"
logfile="${webfolder}/scheduleLog.txt"
curlout="${webfolder}/curlout.txt"  #Keeps a log of the curl output for troubleshooting
 
 
#Logging function
logging () {
  #logging yes true "This is my error message"
  #$1 yes/no - send telegram msg
  #$2 true/false - disable audible notification or pop-up msg on receiving device
 
  ext="$1"
  notification="$2"
  msg="$3"
 
  NOW="`date +"-%Y/%m/%d %H:%M:%S-"`"
  echo "$msg"
  echo "${NOW} ${msg}" >> $logfile
  if [ $ext == "yes" ]; then
    curl -s \
      -X POST \
      ${tokenurl}/sendMessage \
      -d text="$msg" \
      -d disable_notification=${notification} \
      -d chat_id=${chatid} >> ${curlout} &
  fi
}

Create a new macro file that will be run whenever motion is detected

sudo nano /var/www/html/macros/motion_event.sh

Copy in the following text

#!/bin/bash
. /var/www/html/macros/configfile.cfg
 
#If you wish to disable notifications, create a file using "touch /home/pi/nomsgfile.lck"
if [ -f $nomsg ]; then
  logging no true "Message alerting has been disabled, exiting..."
exit
fi
 
#Copy the low res snapshot image from memory to a file
cp /dev/shm/mjpeg/cam.jpg ${webfolder}/cam_new.jpg
 
#On motion detection start (parameter is 1 for on, 0 for off)
fileparams=$1
if [ $fileparams -eq 1 ]
then
  #Send both a single text message and a photo because sometimes the photo message times out if the Telegram servers are busy
  
  logging yes false "Motion detected from ${cameraName}"
 
  curl -s -X POST \
    ${tokenurl}/sendPhoto \
    -F chat_id=${chatid} \
    -F photo="@${webfolder}/cam_new.jpg" \
    -F caption="Motion detected on ${cameraName}" >> ${curlout} &
 
fi

We now just need to make the motion_event.sh file executable and change the ownership:

sudo chmod +x /var/www/html/macros/motion_event.sh
sudo chown www-data:www-data /var/www/html/macros/motion_event.sh
sudo chown www-data:www-data /var/www/html/macros/configfile.cfg

To trigger motion detection within RPi Web Cam you need to ensure that Motion detect mode is set to Internal (or Monitor). For more details on how to configure this please see: https://elinux.org/RPi-Cam-Web-Interface#Motion_Detection

Advertisements

6 thoughts on “Telegram – Send Messages, Photos, Animated Gifs from your Raspberry Pi and RPi Web Cam

  1. Good job! Works like a charm. Do you also know how to make a custom button to start/stop messaging. Sometimes I get to many alerts when I’m at home triggering the motion detection myself.
    Gr. Rob

    Like

    1. Thanks Rob, glad you found it useful!

      Yes, I do have an easy way to disable monitoring from my phone using IFTTT DO buttons that I have written up here: https://quavoce.wordpress.com/2017/01/17/rpi-cam-web-interface-turn-on-and-off-motion-detection-using-ifttt-do-buttons/

      However I do need to update that tutorial because IFTTT has changed a bit since then (DO is more integrated into the main IFTTT app now for example), and I’ve made the Raspi-Runner script more secure. Another update is that the script creates the lock file that /var/www/html/macros/motion_event.sh looks for to stop triggering alerts.

      I’ll reply again to this once I’ve updated it.

      Like

  2. Hi

    I have copied the code but I can’t get it to work I have managed to get the bot so send me a message through the curl example
    but I now can’t get it to send a message after I have clicked motion detection start and it triggers to recored a video it then wont send a message or do i have to make some setting changes somewhere

    I’m running Debian strech with PHP 7 all other settings as default

    I’m new to this so sorry if i have missed something simple

    Like

    1. Hi David – thanks for the heads up – I’ve updated the guide at the end to include the need to enable motion detect and added a link to the wiki for further details.

      Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s