diff --git a/source/_components/notify.telegram.markdown b/source/_components/notify.telegram.markdown index 6145e24ee0f..5afe840e143 100644 --- a/source/_components/notify.telegram.markdown +++ b/source/_components/notify.telegram.markdown @@ -18,7 +18,8 @@ The `telegram` platform uses [Telegram](https://web.telegram.org) to delivery no The requirements are: - You need a [Telegram bot](https://core.telegram.org/bots). Please follow those [instructions](https://core.telegram.org/bots#6-botfather) to create one and get the token for your bot. Keep in mind that bots are not allowed to contact users. You need to make the first contact with your user. Meaning that you need to send a message to the bot from your user. -- The `chat_id` of an user. +- You need to configure a [Telegram bot in Home Assistant](/components/telegram_bot) and define there your API key and the allowed chat ids to interact with. +- The `chat_id` of an allowed user. To retrieve your `chat_id`, contact any of the Telegram bots created for this purpose (@myidbot, @get_id_bot) @@ -45,22 +46,51 @@ $ python3 To enable Telegram notifications in your installation, add the following to your `configuration.yaml` file: ```yaml -# Example configuration.yaml entry +# Example configuration.yaml entry for the Telegram Bot +telegram_bot: + platform: webhooks + api_key: ABCDEFGHJKLMNOPQRSTUVXYZ + allowed_chat_ids: + - CHAT_ID_1 + - CHAT_ID_2 + - CHAT_ID_3 + +# Example configuration.yaml entry for the notifier notify: - name: NOTIFIER_NAME platform: telegram - api_key: ABCDEFGHJKLMNOPQRSTUVXYZ - chat_id: YOUR_CHAT_ID + chat_id: CHAT_ID_2 ``` Configuration variables: - **name** (*Optional*): Setting the optional parameter `name` allows multiple notifiers to be created. The default value is `notify`. The notifier will bind to the service `notify.NOTIFIER_NAME`. -- **api_key** (*Required*): The API token of your bot. - **chat_id** (*Required*): The chat ID of your user. To use notifications, please see the [getting started with automation page](/getting-started/automation/). +### {% linkable_title Text message %} + +```yaml +... +action: + service: notify.NOTIFIER_NAME + data: + title: '*Send a message*' + message: 'That's an example that _sends_ a *formatted* message with a custom keyboard.' + data: + keyboard: + - '/command1, /command2' + - '/command3, /command4' +``` + +Configuration variables: + +- **message** (*Required*): Message text. +- **title** (*Optional*): Will be composed as '%title\n%message'. +- **keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom keyboard. +- **inline_keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. + ### {% linkable_title Photo support %} ```yaml @@ -81,10 +111,15 @@ action: caption: I.e. for a Title ``` +Configuration variables: + - **url** or **file** (*Required*): For local or remote path to an image. - **caption** (*Optional*): The title of the image. - **username** (*Optional*): Username for a URL which require HTTP basic authentication. - **password** (*Optional*): Username for a URL which require HTTP basic authentication. +- **keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom keyboard. +- **inline_keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. + ### {% linkable_title Document support %} @@ -99,13 +134,16 @@ action: document: file: /tmp/whatever.odf caption: Document Title xy - ``` +Configuration variables: + - **url** or **file** (*Required*): For local or remote path to a document. - **caption** (*Optional*): The title of the document. - **username** (*Optional*): Username for a URL which require HTTP basic authentication. - **password** (*Optional*): Username for a URL which require HTTP basic authentication. +- **keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom keyboard. +- **inline_keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. ### {% linkable_title Location support %} @@ -123,7 +161,10 @@ action: longitude: 117.22743 ``` +Configuration variables: + - **location** (*Required*): For local or remote path to an image. - **latitude** (*Required*): The latitude to send. - **longitude** (*Required*): The longitude to send. - +- **keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom keyboard. +- **inline_keyboard** (*Optional*): List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. diff --git a/source/_components/telegram_bot.markdown b/source/_components/telegram_bot.markdown index e969170558a..40df6e973fc 100644 --- a/source/_components/telegram_bot.markdown +++ b/source/_components/telegram_bot.markdown @@ -11,12 +11,132 @@ logo: telegram.png ha_release: 0.42 --- -Use Telegram on your mobile device to send messages or commands to your Home Assistant. +Use Telegram on your mobile or desktop device to send and receive messages or commands to/from your Home Assistant. + +This component creates notification services to send, or edit previously sent, messages from a [Telegram Bot account](https://core.telegram.org/bots) configured either with the [polling](/_components/telegram_bot.polling.markdown) method or with the [webhooks](/_components/telegram_bot.webhooks.markdown) one, and trigger events when receiving messages. -A command looks like `/thecommand` +### {% linkable_title Notification services %} +Available services: `send_message`, `send_photo`, `send_document`, `send_location`, `edit_message`, `edit_replymarkup`, `edit_caption`, `answer_callback_query`. -When received by hass it will fire a `telegram_command` event on the event bus with the following `event_data`: +#### {% linkable_title Service `telegram_bot/send_message` %} +Send a notification. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `message` | no | Message body of the notification. | +| `title` | yes | Optional title for your notification. Will be composed as '%title\n%message'. | +| `target` | yes | An array of pre-authorized chat_ids to send the notification to. Defaults to the first allowed chat_id. | +| `parse_mode` | yes | Parser for the message text: `html` or `markdown`. | +| `disable_notification` | yes | True/false for send the message silently. iOS users and web users will not receive a notification, Android users will receive a notification with no sound. Defaults to False. | +| `disable_web_page_preview`| yes | True/false for disable link previews for links in the message. | +| `keyboard` | yes | List of rows of commands, comma-separated, to make a custom keyboard. Example: `["/command1, /command2", "/command3"]` | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/send_photo` %} +Send a photo. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `url` | no | Remote path to an image. | +| `file` | no | Local path to an image. | +| `caption` | yes | The title of the image. | +| `username` | yes | Username for a URL which require HTTP basic authentication. | +| `password` | yes | Password for a URL which require HTTP basic authentication. | +| `target` | yes | An array of pre-authorized chat_ids to send the notification to. Defaults to the first allowed chat_id. | +| `disable_notification` | yes | True/false for send the message silently. iOS users and web users will not receive a notification, Android users will receive a notification with no sound. Defaults to False. | +| `keyboard` | yes | List of rows of commands, comma-separated, to make a custom keyboard. Example: `["/command1, /command2", "/command3"]` | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/send_document` %} +Send a document. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `url` | no | Remote path to a document. | +| `file` | no | Local path to a document. | +| `caption` | yes | The title of the document. | +| `username` | yes | Username for a URL which require HTTP basic authentication. | +| `password` | yes | Password for a URL which require HTTP basic authentication. | +| `target` | yes | An array of pre-authorized chat_ids to send the notification to. Defaults to the first allowed chat_id. | +| `disable_notification` | yes | True/false for send the message silently. iOS users and web users will not receive a notification, Android users will receive a notification with no sound. Defaults to False. | +| `keyboard` | yes | List of rows of commands, comma-separated, to make a custom keyboard. Example: `["/command1, /command2", "/command3"]` | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/send_location` %} +Send a location. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `latitude` | no | The latitude to send. | +| `longitude` | no | The longitude to send. | +| `target` | yes | An array of pre-authorized chat_ids to send the notification to. Defaults to the first allowed chat_id. | +| `disable_notification` | yes | True/false for send the message silently. iOS users and web users will not receive a notification, Android users will receive a notification with no sound. Defaults to False. | +| `keyboard` | yes | List of rows of commands, comma-separated, to make a custom keyboard. Example: `["/command1, /command2", "/command3"]` | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/edit_message` %} +Edit a previusly sent message in a conversation. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `message_id` | no | Id of the message to edit. When answering a callback from a pressed button, the id of the origin message is in: `{{ trigger.event.data.message.message_id }}`. | +| `chat_id` | no | The chat_id where to edit the message. | +| `message` | no | Message body of the notification. | +| `title` | yes | Optional title for your notification. Will be composed as '%title\n%message'. | +| `parse_mode` | yes | Parser for the message text: `html` or `markdown`. | +| `disable_web_page_preview`| yes | True/false for disable link previews for links in the message. | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/edit_caption` %} +Edit the caption of a previusly sent message. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `message_id` | no | Id of the message to edit. When answering a callback from a pressed button, the id of the origin message is in: `{{ trigger.event.data.message.message_id }}`. | +| `chat_id` | no | The chat_id where to edit the caption. | +| `caption` | no | Message body of the notification. | +| `disable_web_page_preview`| yes | True/false for disable link previews for links in the message. | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/edit_replymarkup` %} +Edit the inline keyboard of a previusly sent message. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `message_id` | no | Id of the message to edit. When answering a callback from a pressed button, the id of the origin message is in: `{{ trigger.event.data.message.message_id }}`. | +| `chat_id` | no | The chat_id where to edit the reply_markup. | +| `disable_web_page_preview`| yes | True/false for disable link previews for links in the message. | +| `inline_keyboard` | yes | List of rows of commands, comma-separated, to make a custom inline keyboard with buttons with asociated callback data. Example: `["/button1, /button2", "/button3"]` or `[[["Text btn1", "/button1"], ["Text btn2", "/button2"]], [["Text btn3", "/button3"]]]` | + +#### {% linkable_title Service `telegram_bot/answer_callback_query` %} +Respond to a callback query originated by clicking on an online keyboard button. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. + +| Service data attribute | Optional | Description | +|---------------------------|----------|--------------------------------------------------| +| `message` | no | Unformatted text message body of the notification. | +| `callback_query_id` | no | Unique id of the callback response. In the `telegram_callback` event data: `{{ trigger.event.data.id }}` | +| `show_alert` | yes | True/false for show a permanent notification. Defaults to False. | + +### {% linkable_title `Telegram` notification platform %} + + +The [Telegram notification platform](/_components/notify.telegram.markdown) requires the `telegram_bot` component to work with, and it's designed to generate a customised shortcut (`notify.USERNAME`) to send notifications (messages, photos, documents and locations) to a particular `chat_id` with the old syntax, allowing backward compatibility. + +The required yaml configuration now reduces to: +```yaml +notify: + - name: NOTIFIER_NAME + platform: telegram + chat_id: USER_CHAT_ID +``` + +### {% linkable_title Event triggering %} + + +A command looks like `/thecommand`, or `/othercommand with some args`. + +When received by Home Assistant it will fire a `telegram_command` event on the event bus with the following `event_data`: ```yaml command: "/thecommand" @@ -26,13 +146,34 @@ from_last: "" user_id: "" ``` +Any other message not starting with `/` will be processed as simple text, firing a `telegram_text` event on the event bus with the following `event_data`: + +```yaml +text: "some text received" +from_first: "" +from_last: "" +user_id: "" +``` + +if the message is sent from a [press from an inline button](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating), for example, a callback query is received, and Home Assistant will fire a `telegram_callback` event with: + +```yaml +data: "" +message: +from_first: "" +from_last: "" +user_id: "" +id: "" +chat_instance: "" +``` + ### {% linkable_title Configuration samples %} Simple ping pong example. ```yaml -alias: 'telegram bot that reply pong to ping' +alias: 'Telegram bot that reply pong to ping' hide_entity: true trigger: platform: event @@ -95,3 +236,171 @@ An example to show the use of event_data in the action: message: > Message from {% raw %}{{ trigger.event.data["from_first"] }}. {% for state in trigger.event.data["args"] %} {{ state }} {% endfor %}{% endraw %} ``` + +### {% linkable_title Sample automations with callback queries and inline keyboards %} + +Quick example to show some of the callback capabilities of inline keyboards with a dumb automation consisting in a simple repeater of normal text that presents an inline keyboard with 3 buttons: 'EDIT', 'NO' and 'REMOVE BUTTON': +- Pressing 'EDIT' changes the sent message. +- Pressing 'NO' only shows a brief notification (answering the callback query). +- Pressing 'REMOVE BUTTON' changes the inline keyboard removing that button. + +Text repeater: +```yaml +- alias: 'Telegram bot that repeats text' + hide_entity: true + trigger: + platform: event + event_type: telegram_text + action: + - service: telegram_bot.send_message + data_template: + title: '*Dumb automation*' + target: '{{ trigger.event.data.user_id }}' + message: 'You said: ``` {{ trigger.event.data.text }} ```' + disable_notification: true + inline_keyboard: + - '/edit,/NO' + - '/remove button' +``` + +Message editor: +```yaml +- alias: 'Telegram bot that edits the last sent message' + hide_entity: true + trigger: + platform: event + event_type: telegram_callback + event_data: + data: '/edit' + action: + - service: telegram_bot.answer_callback_query + data_template: + callback_query_id: '{{ trigger.event.data.id }}' + message: 'Editing the message!' + show_alert: true + - service: telegram_bot.edit_message + data_template: + message_id: '{{ trigger.event.data.message.message_id }}' + chat_id: '{{ trigger.event.data.user_id }}' + title: '*Message edit*' + inline_keyboard: + - '/edit,/NO' + - '/remove button' + message: > + Callback received from {{ trigger.event.data.from_first }}. + Message id: {{ trigger.event.data.message.message_id }}. + Data: ``` {{ trigger.event.data.data }} ``` +``` + +Keyboard editor: +```yaml +- alias: 'Telegram bot that edits the keyboard' + hide_entity: true + trigger: + platform: event + event_type: telegram_callback + event_data: + data: '/remove button' + action: + - service: telegram_bot.answer_callback_query + data_template: + callback_query_id: '{{ trigger.event.data.id }}' + message: 'Callback received for editing the inline keyboard!' + - service: telegram_bot.edit_replymarkup + data_template: + message_id: 'last' + chat_id: '{{ trigger.event.data.user_id }}' + inline_keyboard: + - '/edit,/NO' +``` + +Only acknowledges the 'NO' answer: +```yaml +- alias: 'Telegram bot that simply acknowledges' + hide_entity: true + trigger: + platform: event + event_type: telegram_callback + event_data: + data: '/NO' + action: + - service: telegram_bot.answer_callback_query + data_template: + callback_query_id: '{{ trigger.event.data.id }}' + message: 'OK, you said no!' +``` + +For a more complex usage of the `telegram_bot` capabilities, using [AppDaemon](https://home-assistant.io/docs/ecosystem/appdaemon/tutorial/) is advised. + +This is how the previous 4 automations would be through a simple AppDaemon app: + +```python +import appdaemon.appapi as appapi + +class TelegramBotEventListener(appapi.AppDaemon): + """Event listener for Telegram bot events.""" + + def initialize(self): + """Listen to Telegram Bot events of interest.""" + self.listen_event(self.receive_telegram_text, 'telegram_text') + self.listen_event(self.receive_telegram_callback, 'telegram_callback') + + def receive_telegram_text(self, event_id, payload_event, *args): + """Text repeater.""" + assert event_id == 'telegram_text' + user_id = payload_event['user_id'] + msg = 'You said: ``` %s ```' % payload_event['text'] + keyboard = ['/edit,/NO', '/remove button'] + self.call_service('telegram_bot/send_message', + title='*Dumb automation*', + target=user_id, + message=msg, + disable_notification=True, + inline_keyboard=keyboard) + + def receive_telegram_callback(self, event_id, payload_event, *args): + """Event listener for Telegram callback queries.""" + assert event_id == 'telegram_callback' + data_callback = payload_event['data'] + callback_id = payload_event['id'] + user_id = payload_event['user_id'] + + if data_callback == '/edit': # Message editor: + # Answer callback query + self.call_service('telegram_bot/answer_callback_query', + message='Editing the message!', + callback_query_id=callback_id, + show_alert=True) + + # Edit the message origin of the callback query + msg_id = payload_event['message']['message_id'] + user = payload_event['from_first'] + title = '*Message edit*' + msg = 'Callback received from %s. Message id: %s. Data: ``` %s ```' + keyboard = ['/edit,/NO', '/remove button'] + self.call_service('telegram_bot/edit_message', + chat_id=user_id, + message_id=msg_id, + title=title, + message=msg % (user, msg_id, data_callback), + inline_keyboard=keyboard) + + elif data_callback == '/remove button': # Keyboard editor: + # Answer callback query + self.call_service('telegram_bot/answer_callback_query', + message='Callback received for editing the ' + 'inline keyboard!', + callback_query_id=callback_id) + + # Edit the keyboard + new_keyboard = ['/edit,/NO'] + self.call_service('telegram_bot/edit_replymarkup', + chat_id=user_id, + message_id='last', + inline_keyboard=new_keyboard) + + elif data_callback == '/NO': # Only Answer to callback query + self.call_service('telegram_bot/answer_callback_query', + message='OK, you said no!', + callback_query_id=callback_id) +``` \ No newline at end of file diff --git a/source/_components/telegram_bot.polling.markdown b/source/_components/telegram_bot.polling.markdown index 6536e349ada..3470f57ce68 100644 --- a/source/_components/telegram_bot.polling.markdown +++ b/source/_components/telegram_bot.polling.markdown @@ -14,7 +14,7 @@ ha_release: 0.42 Telegram chatbot polling implementation. -One of two bot implementations supported by Telegram. Your hass does not have to be exposed to the internet. +One of two bot implementations supported by Telegram. Your Home Assistant does not have to be exposed to the internet. To integrate this into Home Assistant, add the following section to your `configuration.yaml` file: @@ -33,6 +33,7 @@ Configuration variables: - **allowed_chat_ids** (*Required*): A list of user in the `user_id` Telegram format enabled to interact to webhook - **api_key** (*Required*): The API token of your bot. +- **parse_mode** (*Optional*): Default parser for messages if not explicit in message data: 'html' or 'markdown'. Default is 'markdown'. -To get your `chat_id` and `api_key` follow the instructions [here](/components.notify.telegram) . +To get your `chat_id` and `api_key` follow the instructions [here](/components/notify.telegram/) . diff --git a/source/_components/telegram_bot.webhooks.markdown b/source/_components/telegram_bot.webhooks.markdown index 7bb8c601914..3fa940723d5 100644 --- a/source/_components/telegram_bot.webhooks.markdown +++ b/source/_components/telegram_bot.webhooks.markdown @@ -21,11 +21,12 @@ To integrate this into Home Assistant, add the following section to your `config ```yaml # Example configuration.yaml entry http: - base_url: # the hass https url which is exposed to the internet. + base_url: # the Home Assistant https url which is exposed to the internet. telegram_bot: platform: webhooks api_key: telegram api key + parse_mode: html allowed_chat_ids: - 12345 - 67890 @@ -36,8 +37,9 @@ Configuration variables: - **allowed_chat_ids** (*Required*): A list of user in the `user_id` Telegram format enabled to interact to webhook - **api_key** (*Required*): The API token of your bot. - **trusted_networks** (*Optional*): Telegram server access ACL as list. Defaults to `149.154.167.197-233`. +- **parse_mode** (*Optional*): Default parser for messages if not explicit in message data: 'html' or 'markdown'. Default is 'markdown'. -To get your `chat_id` and `api_key` follow the instructions [here](/components.notify.telegram) . +To get your `chat_id` and `api_key` follow the instructions [here](/components/notify.telegram) . Full configuration sample: