Telegram messenger bot

Has anyone had any experience with combining the telegram messenger bot api with openhab. I was thinking it would be cool to use it to send commands, or receive status. https://core.telegram.org/bots, https://core.telegram.org/bots/api.

I’m interested too

First release ready :slight_smile:

2 Likes

Cool, i’m looking forward to test it :slight_smile:

At the moment you can use it to send messages. If you need I can give you jar.

To test it you need to create a bot and use token and chat_id

  1. Open a chat with BotFather (search BotFather in telegram client and press start)
  2. write /newbot, follow instruction and save the token
  3. open a new chat with your new bot and send a message like Hello
  4. open a browser and use this address with your token https://api.telegram.org/bot/getUpdates
  5. From result you will see result[0].message.from.id - this is the chat_id

Put in conf file and start to send message :slight_smile:

To test token and chat id you can try with this
https://api.telegram.org/bot/sendMessage?chat_id=<chat_id>&text=your_message

It would be perfect if you would send me the jar. Do you know if it will be part of the official bindings to openhab?

Other things that would be cool in the future, that you can interact with the bot. Example: request a specific temperature sensor, chart, or turn on/off switches.

My friend has done a pull request, so I hope to see it soon!
This is the first step, to write bot side need much more time ;-(

Walter

i know the bot can send you notifications, is the current binding able to set commands to openhab ?

Simple telegram bot on node.js


const TelegramBot = require('node-telegram-bot-api');
var StringBuilder = require('stringbuilder');
// Put there you chat id's 
var CHAT_IDS = [22222]
// URL of openhab server
var URL = "http://127.0.0.1:8080/rest/items";

// replace the value below with the Telegram token you receive from @BotFather
const token = '1111:xxx';

// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true });
var Client = require('node-rest-client').Client;


// Matches "/echo [whatever]" (for testing)
bot.onText(/\/echo (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message
  console.log(msg.chat.id)
  const chatId = msg.chat.id;
  if (CHAT_IDS.contains(chatId)) {
    const resp = match[1]; // the captured "whatever"
    // send back the matched "whatever" to the chat
    bot.sendMessage(chatId, resp);
  }

});

// get all items
bot.onText(/\/items/, (msg) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  if (CHAT_IDS.contains(chatId)) {

    var client = new Client();
    client.get(URL, function (data, response) {
      //build answer
      var sb = new StringBuilder({ newline: '\n' });
      sb.appendLine('Items:');
      data.forEach(function (element) {
         // out format 
        sb.appendLine('{0} ({1}) ->  {2}', element['label'], element['name'], element['state']);
      }, this);

      sb.build(function (err, result) {
        res = result;
        bot.sendMessage(chatId, res);
      });
    });
  }
});


// set item value
bot.onText(/\/set (.+) (.+)/, (msg, match) => {
  const chatId = msg.chat.id;
  if (CHAT_IDS.contains(chatId)) {

    const item = match[1];
    const state = match[2];
    var client = new Client();

    // set content-type header and data as json in args parameter 
    var args = {
      data: state,
      headers: { "Content-Type": "text/plain" },
      requestConfig: {
        timeout: 1000, //request timeout in milliseconds 
        noDelay: true, //Enable/disable the Nagle algorithm 
        keepAlive: true, //Enable/disable keep-alive functionalityidle socket. 
        keepAliveDelay: 1000 //and optionally set the initial delay before the first keepalive probe is sent 
      },
      responseConfig: {
        timeout: 1000 //response timeout 
      }
    };
    client.post(URL + "/" + item, args, function (data, response) {
      if (data instanceof Buffer) {
        var answer = new Client();
        client.get(URL + "/" + item + "/state", function (dt, resp) {
          bot.sendMessage(chatId, item + ':' + dt.toString('utf-8'));
        });
      }
      else {
        bot.sendMessage(chatId, 'Item does not exists');
      }
    });
  }
});

// get item value
bot.onText(/\/item (.+)/, (msg, match) => {
  // 'msg' is the received Message from Telegram
  // 'match' is the result of executing the regexp above on the text content
  // of the message

  const chatId = msg.chat.id;
  if (CHAT_IDS.contains(chatId)) {

    const item = match[1];
    var client = new Client();
    var answer = new Client();
    client.get(URL + "/" + item + "/state", function (dt, resp) {
      console.log(dt);
      if (dt instanceof Buffer) {
        bot.sendMessage(chatId, item + ':' + dt.toString('utf-8'));
      }
      else {
        bot.sendMessage(chatId, 'Item does not exist!');
      }
    });
  }
});


Array.prototype.contains = function (obj) {
  return this.indexOf(obj) > -1;
}

Telegram bot commands:

/items - get all items
/item itemname - get item
/set itemname value - set value for item

1 Like

Since I am migrating from Domoticz to OpenHab (I think I now need a more robust solution) I was using the mentioned chat on domoticz, described here
https://www.domoticz.com/wiki/Remote_Control_of_Domoticz_by_Telegram_Bot
and it can do the chat by offering cards and options. You would get list of all the rooms as chat cards (buttons), and then all the items and actions in the room, something like this http://tech.scargill.net/wp-content/uploads/2017/03/33008-1.jpg

If I understood how it works, it opens a request to the server every minute and then waits one minute for message before timeout, and if it gets any messages then it would react based on the message.

I was using it before but it would crash once a week, and I then lost motivation. But I have read that latest changes improve stability.

It is very intuitive to “chat” with the bot by clicking the cards, actually much easier then f.eks. imperihome, it works nice and clean for me with a good user flow.

It could be a very nice feature to integrate it with the openhab

Hello guys,
I had same problem, so I decided to write a simple bridge application in java (spring boot) to control OpenHab using Telegram and REST API.
It supports only 4 commands at the moment, but works pretty well and is easily extendable. You can run it on the same machine with OpenHab.

Here is a description and instructions how to use it: