I used to use Telegram action mainly to receive some alerts or notifications from OpenHAB, but as I have to establish a SSH tunnel to connect home and check system status I found it useful to be able to trigger some rules directly from Telegram. This is what I have:
TelegramMenu.py (which I run at startup with “python TelegramMenu.py”). It runs in the back
# Based on https://github.com/eternnoir/pyTelegramBotAPI
# and the work of my good friend Tomás (TPG)
# Other useful link: https://www.mindk.com/blog/how-to-develop-a-chat-bot/
import telebot
import os
from subprocess import call
bot = telebot.TeleBot("xxxxxxx:yyyyyyyyyyyyy") #<<<<<Insert Telegram API Key here
logFilename = open('/var/log/openhab2/telegrammenu.log','a')
# Handles /menu command
# It is required to register the command with BotFather issuing a /setcommands
# Icons codification can be found at https://apps.timwhitlock.info/emoji/tables/unicode
@bot.message_handler(commands=['menu'])
def send_menu(message):
if message.chat.type == "private":
keyboard = telebot.types.InlineKeyboardMarkup()
keyboard.row(
telebot.types.InlineKeyboardButton('\xF0\x9F\x92\xA5 Motion', callback_data='MOTIONSTATUS'),
telebot.types.InlineKeyboardButton('\xF0\x9F\x9A\xA8 Arm/Disarm', callback_data='ARMALARM')
)
keyboard.row(
telebot.types.InlineKeyboardButton('\xF0\x9F\x92\xB9 Temps', callback_data='TEMPS'),
telebot.types.InlineKeyboardButton('\xE2\x9C\xB4 Status', callback_data='STATUS')
)
bot.send_message(<chatID>,"Main Menu...",reply_markup=keyboard)
#callback del keyboard de markup
@bot.callback_query_handler(func=lambda call: True)
def iq_callback(query):
# Sends Telegram received command through MQTT to OH2
os.system("/usr/bin/mosquitto_pub -t TelegramMenuCommand -m " + query.data)
def main_loop():
while 1:
try:
print >>logFilename, "Polling..." #python 2
#print("Polling...", file=logFilename) #python 3
bot.polling(none_stop=True, timeout=60)
while 1:
time.sleep(3)
except Exception as er:
print >>logFilename, "Unexpected exception: "+str(er) #python 2
#print("Unexpected exception: "+str(er), file=logFilename) #python 3
if __name__ == '__main__':
try:
main_loop()
except KeyboardInterrupt:
print >> sys.stderr, '\nExiting by user request.\n'
sys.exit(0)
Now there is an Item that will receive the TelegramCommand:
String TelegramMenuCommandString { mqtt="<[broker:TelegramMenuCommand:state:default]" }
And finally a rule that execute the commands received:
rule "Telegram Menu Actions"
when
Item TelegramMenuCommandString received update
then
//Emoticons from https://www.charbase.com
//logInfo("TelegramMenu", "TelegramMenuCommandString received command " + receivedCommand)
if (TelegramMenuCommandString.state == NULL) {
return
} else if (TelegramMenuCommandString.state == 'ARMALARM') {
if (HomeAlarmEnabled.state == ON) {
HomeAlarmEnabled.sendCommand(OFF)
HomeAlarmFired.sendCommand(OFF)
} else {
HomeAlarmEnabled.sendCommand(ON)
}
//} else if (TelegramMenuCommandString.state == 'MOTIONSTATUS') { //Served from HomeAlarm.rules
} else if (TelegramMenuCommandString.state == 'TEMPS') {
.... Code preparing status response here ....
sendTelegram("TelegramBot", TemperaturesStr)
} else if (TelegramMenuCommandString.state == 'STATUS') {
.... Code preparing status response here ....
sendTelegram("TelegramBot", StatusStr)
}
TelegramMenuCommandString.postUpdate(NULL)
end
That is all I need. If I issue a /menu command to the Telegram chat with my bot the python script answers with a buttons keyboard, containing 2 rows of 2 buttons (can contain more lines or rows at will) and whenever I press one of the buttons an action gets executed within my OpenHAB installation. Simple and very useful for me