Installing Telegram Notification System

From Domoticz
Jump to: navigation, search

Warning

12th February 2017 - It looks like this method no longer works as described, so please use the Telegram Bot method or correct this page :-).

Introduction

It is easier to use the newer Telegram Bot method to set up Telegram nofitifications if you don't want to use an interactive Telegram client on your Domoticz system - details are here - Telegram Bot.

Telegram is similar to Whatsapp: https://telegram.org/ but with full Cross platform support! https://telegram.org/apps and the ability to control Domoticz via Telegram messages. Further details can be found on the interaction with Domoticz from this forum post: http://www.domoticz.com/forum/viewtopic.php?f=5&t=1985. This page and the connected pages describe how to install Telegram as a service on a Raspberry Pi using the Raspian operating system and how to set up Telegram allow you to remotely control your Domoticz system from anywhere in the world.

Installation - Stage 1

Pre-requisites

These instructions assume you have already installed Domoticz on a Raspberry Pi running Raspbian - however in general they will be a good guide for installation under similar Linux systems.

If you have already used Telegram, then you need to ensure that any activation of telegram through /etc/rc.local is removed and any activation via a daemon is both removed from /etc/init.d and via rc-update.d telegram-daemon remove.

These instructions are general and not specific to any persons Domoticz set-up, however there are a number of items which changes from setup to setup. So, in order to reduce the amount of customisation necessary all system specific variable are set in the environment during startup.

First create your customisation file:

sudo nano /etc/profile.d/DomoticzData.sh
#!/bin/bash
# /etc/profile.d/DomoticzData.sh
# Variables to avoid having to set local system information in individual automation scripts
 
export DomoticzIP=$(hostname -I|sed 's/[ ]*$//')
export DomoticzPort="8080"
export TempFileDir="/var/tmp/"
export TelegramHomePath="/home/pi/tg/"
export TelegramScriptPath=$TelegramHomePath"scripts/user/"
export TelegramGenericPath=$TelegramHomePath"scripts/generic/"
export TelegramScript=$TelegramGenericPath"telegram.sh"
export TelegramCli=$TelegramHomePath"bin/telegram-cli"
export TelegramLog=$TempFileDir"tg.log"
export ReceiveLua=$TelegramGenericPath"receive.lua"
export TelegramTo="FirstName_SecondName"
export EmailTo="[email protected]"

Then set it to be executable:

sudo chmod +x /etc/profile.d/DomoticzData.sh

This single file avoids you having to customise any of the bash or Lua scripts mentioned for automating Telegram and Domoticz.

Getting the Necessary Packages

You are logged in as user pi !!!

sudo apt-get update
sudo apt-get install libreadline-dev libconfig-dev libssl-dev lua5.2 liblua5.2-dev libevent-dev lua-lgi glib-2.0 make git-core libjansson-dev
cd /home/pi/ && git clone --recursive https://github.com/vysheng/tg.git && cd tg && git reset --hard 3ced7bbb27b  #Version 1.3.1

Configuring Telegram

Next step takes a long time, don't stop it, just wait till it is done.

./configure && make     # Takes aprox. 30-45 minutes for a RPI-B
./configure && make -j4 # Takes aprox.  8-9  minutes for a RPI-2B

Now register your number:

bin/telegram-cli -k tg-server.pub

Press TAB key and enter a unique phone number for your Domoticz system (for example:)

+31612345678

Then enter the code you received by SMS. (Or type "call" to retrieve the code)

N.B. The number must be different to the number you will be using to communicate with your Domoticz set-up. N.B. If you are reinstalling telegram-cli and registration fails, then you are picking up your previous registration, so proceed to the next step.

Testing Telegram

When you succesfully registered your number you can send a message. Due a bug you first have to type:

contact_list

Otherwise you won't be able to send a message. Send message:

msg Firstname_Surname Test123
quit

Due this bug we will need to use the Telegram Daemon function.

Start this daemon manually:

cd /home/pi/tg/ && sudo -u pi bin/telegram-cli -vvvvRC -k tg-server.pub -W -dL tg.log -P 1234 &

Check Telegram Daemon is running

ps -ef | grep telegram

You should see something like this:

pi        2030  2023  0 22:35 ?        00:00:00 bin/telegram-cli -vvvvRC -k tg-server.pub-W -dL tg.log -P 1234

Sending Messages

So now we can send messages/text/pictures this way:

echo "msg Firstname_Surname Test123" | nc 127.0.0.1 1234
echo "send_text Firstname_Surname  /home/pi/domoticz/www/switch_icons.txt" | nc 127.0.0.1 1234
echo "send_photo Firstname_Surname  /home/pi/domoticz/www/images/logo.png" | nc 127.0.0.1 1234

Installation Stage 2

A telegram deamon script is placed in /etc/init.d and added it to the init.d scripts

Download the 150513scripts.tar file from the forum post http://www.domoticz.com/forum/viewtopic.php?f=21&t=6458 into the ~/tg directory and extract this file:

cd ~/tg
tar -xvf 150513scripts.tar

This is required to handle incoming messages (which is a parameter of the start of telegram in the script below)


cd /etc/init.d
sudo nano telegram-cli
sudo chmod +x telegram-cli
sudo update-rc.d telegram-cli remove      #Remove previous version
sudo update-rc.d telegram-cli defaults    #Install new version

Now you can stop or start Telegram and checks its status:

sudo service telegram-cli start
sudo service telegram-cli status
sudo service telegram-cli stop

This daemon works, but it is not clever, as it was written by copying the standard daemon and issues were solved pragmatically. A sleep is needed in order to avoid a network unreachable error on start-up and pkill KILL is used to stop, these solutions work but are overkill and should not be needed.

Troubleshooting - if you have difficulties getting telegram to work correctly, then the first thing to check is the tg.log file. The most common problem is "network unreachable", this appears to be caused by telegram trying to start up before networking has fully started, try changing from sleep 1 to sleep 5 in /etc/init.d/telegram-cli. If you have not place tg.log on a ram disk, then it may be worthwhile deleting the file before rebooting in order to have a short file to examine.

/etc/init.d/telegram-cli

#! /bin/sh
### BEGIN INIT INFO
# Provides:          telegram-cli
# Required-Start:    $network $remote_fs $syslog $domoticz.sh
# Required-Stop:     $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Commandline interface for Telegram chat program - this instance designed to work with Domoticz
# Description:       Telegram-cli is a (unofficial) cli version of Telegram to chat from your console.
#                    This is an init script do make it a daemon.
#                    When used as daemon in conjuction  with LUA (scripting) you can use it to send your system
#                    commands to execute via other Telegram apps (PC - Phone - Web or other) while not
#                    logged in to the system.
#
#                    Note #1: This version of the init script is developed for raspbian (rapberry PI port of Debian Wheezy).
#
#                    Note #2: All parameters are set from /etc/profile.d/DomoticzData.sh
#
#                    See: https://github.com/vysheng/tg for more information.
#                    Derived from https://github.com/vysheng/tg/issues/436 (updated 9th April 2015)
### END INIT INFO
 
# Do NOT "set -e"
 
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin
DESC="Telegram Messaging System"
NAME=telegram-cli
USERNAME=pi
DAEMON=/home/$USERNAME/tg/bin/$NAME
# Get the preset variables
. /etc/profile.d/DomoticzData.sh
TelegramKeyFile=$TelegramHomePath"tg-server.pub"
DAEMON_ARGS="-W -U pi -G pi -k $TelegramKeyFile -L $TelegramLog -P 1234 -s $ReceiveLua -d -vvvRC"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
 
. /lib/lsb/init-functions
 
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
 
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
 
# Carry out specific functions when asked to by the system
case "$1" in
 
    start)
        echo -n "Starting $DESC ... "
        sleep 5 && . /etc/profile.d/DomoticzData.sh && start-stop-daemon --start --background --make-pidfile $PIDFILE --pidfile $PIDFILE \
            --exec $DAEMON -- $DAEMON_ARGS || true
        echo "Done."
    ;;
 
    stop)
        echo -n "Stopping $DESC ... "
        start-stop-daemon --stop --retry 2 --pidfile $PIDFILE \
            --exec $DAEMON || true
    rm -f $PIDFILE
    echo "Done."
 
    ;;
    restart)
        echo -n "Restarting $DESC "
        start-stop-daemon --stop --retry 2 --pidfile $PIDFILE \
            --exec $DAEMON || true
        rm -f $PIDFILE
        . /etc/profile.d/DomoticzData.sh && start-stop-daemon --start --background --make-pidfile $PIDFILE --pidfile $PIDFILE \
            --exec $DAEMON -- $DAEMON_ARGS || true
        echo "Done."
    ;;
 
    status)
        status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
    ;;
 
    *)
        N=/etc/init.d/$NAME
        echo "Usage $NAME: $SCRIPTNAME {start|stop|restart|status}"
        exit 1
    ;;
 
esac

/home/pi/tg/scripts/generic/telegram.sh

The telegram.sh script is inside the previously extracted tar file, you can also make this manually:

sudo nano /home/pi/tg/scripts/generic/telegram.sh
sudo chmod +x /home/pi/tg/scripts/generic/telegram.sh
#!/bin/sh
# Send msg/photo/text etc. using Telegram message service => (https://github.com/vysheng/tg/blob/master/README.md#supported-commands)
(echo "$@" | nc 127.0.0.1 1234)&

This script wraps up the mechanism for sending messages and commands in general to Telegram - https://github.com/vysheng/tg/blob/master/README.md#supported-commands

Format is:

telegram.sh command FirstName_SecondName message or filename

For example:

telegram.sh msg Joe_Bloggs Hello how is it going

Adding Telegram Messaging Scripts and Functions

In Bash Scripts

The direct call would be:

/home/pi/tg/scripts/generic/telegram.sh msg Joe_Bloggs Domoticz still running

But it is better to use the environmental variables we set earlier:

$TelegramScript msg $TelegramTo Domoticz still running

If your script needs parameters from the command line then have a look at the page - Telegram - Setting Up Remote Control - Bash Scripts - as if you follow the same order, then the script can be integrated with the Remote Control system and called by receive.lua.

In Lua Functions

The direct call would be:

os.execute("/home/pi/tg/scripts/generic/telegram.sh msg Joe_Bloggs Domoticz still running")

But it is more flexible to use the environmental variables, which are directly available when using receive.lua:

os.execute(TelegramScript..' msg '..TelegramTo..' Domoticz still running')

If you are using a different script then you need to pull in the environment variables at the start of the script:

-- -------------------------------------------------------
-- All these value are set in /etc/profile.d/DomoticzData.sh
DomoticzIP=os.getenv("DomoticzIP")
DomoticzPort=os.getenv("DomoticzPort")
TempFileDir=os.getenv("TempFileDir")
ScriptPath=os.getenv("TelegramScriptPath")
TelegramScript=os.getenv("TelegramScript")
-- -------------------------------------------------------
 
TempFileName = TempFileDir.."TempTelegram.txt"
DeviceFileName = TempFileDir.."AutoAllDevData.tmp"
ReportFileName = TempFileDir.."SwitchReport.tmp"

You only need to pull in the ones you use.

Also if you follow the function format on the Telegram - Setting Up Remote Control - Lua Functions page, then these functions can be called by Remote Control using Telegram messages.

In Domoticz Lua Functions

As Lua functions run by Domoticz are run within Domoticz, the environment variables defined in DomoticzData.sh need to be available to Domoticz, add these two lines into /etc/init.d/domoticz.sh, just before #Exit if the package is not installed

# Get the preset variables so that they are available for Lua functions within Domoticz
. /etc/profile.d/DomoticzData.sh

Now all the variables can be available to your Domoticz Lua script by adding in the appropriate os.getenv calls as detailed under the In Lua Functions section.

Remote Control with Telegram

telegram-cli takes a Lua script which recieves incoming message and is able to interact with Domoticz. By defining commands and linking them to Lua functions or Bash scripts - On Light or Temperature.

To understand what is possible have a look at Telegram - Setting Up Remote Control - Functionality, this page shows what to expect when you can remotely control your Domoticz set-up using telegram.

To set this up see these pages below, you need to follow the foundations page, then you get some Lua functions and Bash scripts anyway, if you follow up on the other pages, then you can create your own.

The first step is to set up the Lua script and the initial scripts - Telegram - Setting Up Remote Control - Foundations.

Then it is easy to create some specific Lua functions based on the information on the this wiki - Telegram - Setting Up Remote Control - Lua Functions.

There are lots of Bash scripts on the Wiki which can be linked into Telegram - Telegram - Setting Up Remote Control - Bash Scripts.

Telegram have now introduced a system for creating your own bot - Telegram Bot

Domoticz sending Telegram messages

Since Domoticz version #2444 it is possible to set a custom HTTP/Action for notifications.


Set recipient name in the #TO field.


URL/Action:

script:///home/pi/tg/scripts/generic/telegram.sh msg "#TO" "#MESSAGE"


TG.png