Create a virtual device (not app) which can be used for sending notifications using Telegram as the platform. This works well with multiple bots and posting to different chat rooms. Each device is self-contained and bot tokens and/or chat IDs can overlap without issue. For example, I have two set up - one for myself, and one for a family group.
Screenshot of the notifications in action:
Code here:
telegram_notifications_bot.groovy
Telegram Bot Setup Instructions:
To set up, you need to create a Telegram Bot and know its API key / token. You also need to know the chat ID of the chat you want to send messages to. This can be a direct chat (for example just to you) or the chat ID of a group (for announcing to multiple people).
Create a bot by communicating with the @BotFather on Telegram. He'll walk you through the steps.
@BotFather will give you your bot API key in the form of #####:text
For the chat ID, you'll need to message your new bot with your normal Telegram account. Once you have done that, there will be a pending update for your bot. You can fetch that update and get the chat ID from the JSON. This can be done in the browser by calling this URL:
https://api.telegram.org/bot<BOTID>/getUpdates
Parse chat ID from the response JSON:
{
"ok":true,
"result":[{
"update_id": ####UPDATEID####,
"message": {
"message_id":5,
"from":{"id": ####YOURUSERID####,
"is_bot":false,
"first_name": ...,
"username": ...,,
"language_code":"en"
},
"chat":{
"id": ####CHATID#####,
"first_name": ...,
"username": ...,
"type":"private"
},
"date":1575988451,
"text":"test"}}]
}
In this example, ####CHATID#### is the value you need for the preferences for the device.
Hubitat Setup Instructions
In the console:
- Go to "Drivers Code", and add a new driver. Save the contents of this file there. !
- On "Devices" tab, add a new virtual device and change the type to Telegram.
- Enter your bot API key and chat ID in the preferences and click "save preferences".
If all went correctly, you should receive a message from the bot in Telegram (Initializing Telegram Hubitat bot). For example, from the built in Notifications app:
This device will then be able to be used for notifications throughout Hubitat.
Low hanging fruit update would be to have the code automatically pull the chat ID of the most recent message using the steps above, but in code. For now, though, it's really easy to grab the chatID manually.
Bi-directional communication (issuing commands to a Telegram bot) is very possible, either through polling (leading to delays), or telegram can notify using webhooks for nearly instant communication. I'm one day into using Hubitat, so I'm not sure yet if there's an easy way to expose a public endpoint for Telegram to call, so webhooks may be more challenging to implement.