Telegram - Setting Up Remote Control - Bash Scripts
Introduction
Once you have set up the Telegram Remote Control Foundations, then you can extend by adding your own Bash scripts into the user script directory - Telegram - Setting Up Remote Control - Foundations.
And if you follow the framework then you will not need to customise the scrips you create if you change your system set up and you won't need to strip out personal details when you share the script.
All the system specific variables for your scripts should be picked up from /etc/profile.d/DomoticzData.sh by refernce to the environment variables from your script: $DomoticzIP, $DomoticzPort, $TempFileDir & $TelegramScript; some other environment varaibles are defined but won't be used by your script - $TelegramHomePath, $TelegramScriptPath, $TelegramGenericPath, $TelegramCli, $TelegramLog, $ReceiveLua, $TelegramTo & $EmailTo.
receive.lua will call Bash scripts passing the Telegram FirstName_SecondName as the 1st parameter and then the rest of the command line after the first space, so doorbell fred.jpg bert.jpg - will pass execute the command - doorbell.sh Joe_Bloggs fred.jpg bert.jpg - excatly as the script would need to be called from the command line.
Check Domoticz Update Script
This script does follow the framework needing no system specific customisation and using standard environment variables - based on original script.
Create the script:
nano /home/pi/tg/scripts/user/checkdomoticzupdate.sh
chmod +x /home/pi/tg/scripts/user/checkdomoticzupdate.sh
Script contents:
#!/bin/sh
SendTo=$1
ActVersionFile=$TempFileDir"Actversion.txt"
RevisionFile=$TempFileDir"Revision.txt"
UpdateFile=$TempFileDir"Update.txt"
if [ -f $RevisionFile ];
then
LatelyChecked=`cat $RevisionFile | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
else
LatelyChecked=1000
fi
ActVersion=`curl -s -i -H "Accept: application/json" "$DomoticzIP:$DomoticzPort/json.htm?type=command¶m=checkforupdate&forced=true" |grep "ActVersion" `
Revision=`curl -s -i -H "Accept: application/json" "http://127.0.0.1:8080/json.htm?type=command¶m=checkforupdate&forced=true" |grep "Revision" `
echo $LatelyChecked
echo $ActVersion > $ActVersionFile
echo $Revision > $RevisionFile
InstalledVersion=`cat $ActVersionFile | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
UpdateVersion=`cat $RevisionFile | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
if [ $InstalledVersion -le $UpdateVersion ] && [ $UpdateVersion -eq $LatelyChecked ] ; then
echo "No Update Available"
$TelegramScript msg $SendTo No Update Available
exit # Exit script
fi
if [ $InstalledVersion -le $UpdateVersion ] && [ $UpdateVersion -ge $LatelyChecked ] ; then
echo "Domoticz Update Available! \n $InstalledVersion= Current Version\n $UpdateVersion= Latest Version\n sourceforge.net/p/domoticz/code/commit_browser" > $UpdateFile
echo $TelegramScript send_text $SendTo $UpdateFile
$TelegramScript send_text $SendTo $UpdateFile
else
echo $TelegramScript msg $SendTo No Update Available
$TelegramScript msg $SendTo No Update Available
fi
You might want to add it to the crontab:
sudo crontab -e
Add this line to check for updates every hour:
0 * * * * /home/pi/tg/scripts/user/checkdomoticzupdate.sh Firstname_Secondname >/dev/null 2>&1
N.B. Not all the scripts below currently make full use of the framework, they have been left as inspiration.
Letterbox Script
This does not use the simple framework.
Create the script:
mkdir /home/pi/domoticz/scripts/bash/
touch /home/pi/domoticz/scripts/bash/Brievenbus.sh
chmod +x /home/pi/domoticz/scripts/bash/Brievenbus.sh
nano /home/pi/domoticz/scripts/bash/Brievenbus.sh
Script contents:
#!/bin/sh
SendTo=$1
IP=$2 # IP address Camera
##########################################################
SnapFile=$TempFileDir"snapshot.jpg"
$TelegramScript msg $SendTo Er is nieuwe post bezorgd!
if ping -c 1 $IP > /dev/null ; then # if IPCAM is online then:
$TelegramScript msg SendTo Kijk wie er post heeft bezorgd:
(su - pi -c "wget http://"$DomoticzIP":"$DomoticzPort"/camsnapshot.jpg?idx=1 && sudo mv camsnapshot.jpg?idx=1 "$SnapFile)&
sleep 1
$TelegramScript send_photo $SendTo $SnapFile
/bin/rm $SnapFile
else
$TelegramScript msg $SendTo IP-cam niet beschikbaar.
fi
Doorbell Script
Create the script:
#!/bin/sh
SendTo=$1
#################################################################
IP=$2 # IP address Camera
##########################################################
SnapFile=$TempFileDir"snapshot.jpg"
$TelegramScript msg $SendTo Er is zojuist aangebeld!
if ping -c 1 $IP > /dev/null ; then # if IPCAM is online then:
(su - pi -c "wget "$DomoticzIP":"$DomoticzPort"/camsnapshot.jpg?idx=1 && sudo mv camsnapshot.jpg?idx=1 "$SnapFile)&
$TelegramScript msg $SendTo Kijk wie er aangebeld heeft:
sleep 1
$TelegramScript send_photo $SendTo $SnapFile
/bin/rm $SnapFile
else
$TelegramScript msg $SendTo IP-cam niet beschikbaar.
fi
Check Domoticz Update Script
This does not use the simple framework.
Create the script:
touch /home/pi/domoticz/scripts/bash/Check_Domoticz_Update.sh
chmod +x /home/pi/domoticz/scripts/bash/Check_Domoticz_Update.sh
nano /home/pi/domoticz/scripts/bash/Check_Domoticz_Update.sh
Script contents:
#!/bin/sh
LatelyChecked=`cat /tmp/Revision.txt | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
ActVersion=`curl -s -i -H "Accept: application/json" "http://127.0.0.1:8080/json.htm?type=command¶m=checkforupdate&forced=true" |grep "ActVersion" `
Revision=`curl -s -i -H "Accept: application/json" "http://127.0.0.1:8080/json.htm?type=command¶m=checkforupdate&forced=true" |grep "Revision" `
echo $ActVersion > /tmp/ActVersion.txt
echo $Revision > /tmp/Revision.txt
InstalledVersion=`cat /tmp/ActVersion.txt | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
UpdateVersion=`cat /tmp/Revision.txt | awk -F: '{print $2, $3}' | sed 's/\"//g' | sed 's/,//'`
if [ $InstalledVersion -le $UpdateVersion ] && [ $UpdateVersion -eq $LatelyChecked ] ; then
echo "Geen Update beschikbaar"
exit # Exit script
fi
if [ $InstalledVersion -le $UpdateVersion ] && [ $UpdateVersion -ge $LatelyChecked ] ; then
echo "Domoticz Update Beschikbaar! \n $InstalledVersion=Huidige Versie\n $UpdateVersion=Nieuwste Versie\n sourceforge.net/p/domoticz/code/commit_browser" > /tmp/Update.txt
echo "send_text Firstname_Surname /tmp/Update.txt" | nc 127.0.0.1 1234
fi
You might want to add it to the crontab:
sudo crontab -e
Add this line to check for updates every hour:
0 * * * * /home/pi/domoticz/scripts/bash/Check_Domoticz_Update.sh >/dev/null 2>&1
Customising the Automation Scripts
In all the scripts in the scripts/user directory do not need any user customisation, as they find the correct IP and Port for your Raspberry Pi plus the correct locations for your temporary files, from /etc/profile.d/DomoticzData.sh set up earlier in the installation of Telegram.
smiliesoverview.sh
A neat little script which sends a series of smilies on request. Type smiliesoverview on your Telegram client and your Raspberry Pi will send you back a range of different icons. This script should need no customisation if you have not changed your installation of Telegram from the instructions.
#!/bin/bash
# Settings
SendMsgTo=$1
# array of icons
declare -a icons=("smiley " "crying smiley " "sleeping smiley " "beer " "double beer "\
"wine " "double red excam ‼️" "yellow sign exclamation mark ⚠️ " "camera " "light(on) "\
"open sun " "battery " "plug " "film " "music " "moon " "sun ☀️" "sun behind some clouds "\
"clouds ☁️" "lightning ⚡️" "umbrella ☔️" "snowflake ❄️")
## now loop through the above array of icons
for icon in "${icons[@]}"
do
$TelegramScript msg $SendMsgTo "$icon"
done
temperature.sh
If you have temperature sensors, then this script will send you back the sensors temperatures and humidities when you send a message temperature from your Telegram client. You need to change the IP address and Port to match your Domoticz setup, correct the file name for TmpFileName to point to an existing directory on your Raspberry Pi and look up the IDs of your temperature sensors on the Device page of Domoticz and replace the values in arr array. There is also a weather forecasting part, which I haven't got to work correctly.
#!/bin/bash
# Change arr's rid values below to match the sensors on your devices page in Domoticz
SendMsgTo=$1
TelegramSendMsg=$TelegramScript
TmpFileName=$TempFileDir'WeatherFile.txt'
# array of temperature / humidity sensor indexes
declare -a arr=("79" "736" "747" "433")
## now loop through the above array
for index in "${arr[@]}"
do
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid='$index 2>/dev/null | jq -r .result[].Name`
ResultString+=" "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid='$index 2>/dev/null | jq -r .result[].Temp`
ResultString+="°C "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid='$index 2>/dev/null | jq -r .result[].Humidity`
ResultString+="%\n"
done
echo $ResultString
#Outside prediction
ResultString+="%, prediction "
ForeCast=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=26' 2>/dev/null | jq -r .result[].Forecast`
echo $ForeCast
case "$ForeCast" in
2) ResultString+=" " #Partly Cloudy
;;
3) ResultString+="☁️" #Cloudy
;;
*) echo `curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=14' 2>/dev/null | jq -r .result[].ForecastStr`
;;
esac
#Send
echo -e $ResultString > $TmpFileName
#echo telegram-cli -W -e "send_document SendMsgTo $TmpFileName"
$TelegramSendMsg send_text $SendMsgTo $TmpFileName
systemstatus.sh
Customise the same values as for temperature.sh, then find the ids for each of the items mentioned and change the number after rid= to the id of your device, for me CPU temperature's id is 1, CPU usage's id is 386, etc.. Then send systemstatus from your Telegram client and find out how your Raspberry Pi is doing.
#!/bin/bash
# Change the rid values below to match the sensors on your devices page in Domoticz
# Settings
SendMsgTo=$1
TmpFileName=$TempFileDir'SystemStatus.txt'
#Send sensor values with telegram
$TelegramScript msg $SendMsgTo "Please wait, gathering data..."
##############################################################################
ResultString="CPU temperature: "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=1' 2>/dev/null | jq -r .result[]."Temp"`
ResultString+="°C\n"
ResultString+="CPU Usage: "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=386' 2>/dev/null | jq -r .result[]."Data"`
ResultString+="\n"
ResultString+="Memory Usage: "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=385' 2>/dev/null | jq -r .result[]."Data"`
ResultString+="\n"
ResultString+="SD usage: "
ResultString+=`curl 'http://'$DomoticzIP':'$DomoticzPort'/json.htm?type=devices&rid=388' 2>/dev/null | jq -r .result[]."Data"`
ResultString+="\n"
Updates=`sudo aptitude search '~U' | wc -l`
if [[ $Updates -ge 1 ]] ; then
ResultString+="-Apt-get updates available: "
ResultString+=`sudo aptitude search '~U' | wc -l`
ResultString+="\n"
fi
if [[ $InstalledVersion -le $UpdateVersion ]] ; then
InstalledVersion=`curl "http://"$DomoticzIP":"$DomoticzPort"/json.htm?type=command¶m=checkforupdate&forced=true" 2>/dev/null | jq -r ."ActVersion"`
UpdateVersion=`curl "http://"$DomoticzIP":"$DomoticzPort"/json.htm?type=command¶m=checkforupdate&forced=true" 2>/dev/null | jq -r ."Revision"`
ResultString+="-Domoticz update available! (version "
ResultString+=$UpdateVersion
ResultString+=") "
ResultString+="\n"
fi
##############################################################################
echo -e $ResultString > $TmpFileName
$TelegramScript send_text $SendMsgTo $TmpFileName
houselightsoff.sh
Hopefully from looking at the previous scripts you will have seen that nothing magical is happening, basically the Telegram server on your Raspberry Pi has been set up to look for a script everytime you send it a message, hence you send temperature and the server executes the script temperature.sh in the scripts/user directory. In this way you can now control your Domoticz server from Telegram, I have created a simple script which off all the lights in my house. First you need to customise all the variables mentioned for temperature.sh, IP address / port and temporary file directory. Currently the script is set up to turn off a group whose id is 3, so if you have a suitable group, then you can just replace the idx=3 with number of your group, type houselightsoff into your Telegram client and all your houselights will go out. Otherwise change this json - /json.htm?type=command¶m=switchscene&idx=3&switchcmd='Off' based on the json / API to do whatever it is you want Domoticz to do for your, you could then rename the script to something more sensible for you, openblinds.sh, so you type openblinds into Telegram to get Domoticz to open your blinds.
#!/bin/bash
# Settings
SendMsgTo=$1
TmpFileName=$TempFileDir'houselightsoff.txt'
$TelegramScript msg $SendMsgTo "Switching All House Lights Off"
echo "number"
#Attic
ResultString="House Lights Off - "
ResultString+=" "
ResultString+=`curl "http://"$DomoticzIP":"$DomoticzPort"/json.htm?type=command¶m=switchscene&idx=3&switchcmd='Off'" 2>/dev/null | jq -r .\"status\"`
#Send
echo $ResultString
echo -e $ResultString > $TmpFileName
$TelegramScript send_text $SendMsgTo $TmpFileName