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