Telegram Bot: Respond to Telegram Command by executing an action

:face_with_monocle: About this blueprint

What does it do?

This blueprint listens to a Telegram Command and executes a sequence of actions if listened.

:gear: Configuration

Requirements

Input fields

  • Command: Required command to listen for. Must start with ‘/’. Example: /start

  • Command @ Bot Username: Optional command to ensure compatibility in group chats. Must use this format /[email protected]_bot. Example: /[email protected]_bot_username_bot

  • Sequence: What should happen when receiving this command.

Available variables for templating

Event data received from telegram are parsed as variables so that they are easily used in templates. These variables can be used within this automation:

  • telegram_args: List of words sent after command. You can get each word by its index: telegram_args[0], telegram_args[1], etc.

  • telegram_args_as_text: Single plain text string from arguments’ list. Useful if you need full text, not single words.

  • telegram_sender_first_name: Sender’s first name.

  • telegram_sender_last_name: Sender’s last name.

  • telegram_sender_full_name: Sender’s full name, as first_name + " " + last_name

  • telegram_sender_user_id: Sender’s user id.

  • telegram_chat_id: Chat id.

Template example

Use format {{ variable_name }} to indicate that it is a template, as usual in Home Assistant.

Example: Hi {{ telegram_sender_first_name }}! You said {{ telegram_args_as_text }} after the command.

Why does “Command @ Bot Username” field exist?

If you upload a list of commands in your bot settings (in Telegram), when you type / in a message, it automatically suggests you commands from the list. In case you are typing to the bot in a group chat, command suggestions will add “@your_bot_username_bot” to your command. So, when Home Assistant receives them, it wouldn’t recognize them unless you also define the same command adding @your_bot_username_bot as a trigger.

It would be easier to use templates in trigger automation and avoid defining the command twice, but it is not yet supported. If anybody gets an easier way to do this, please let me know and I will update this blueprint.

:pushpin: Related blueprints:

:arrow_down: How to get this blueprint?

Click the badge to import this Blueprint (needs Home Assistant Core 2021.3 or higher):

Open your Home Assistant instance and show the blueprint import dialog with a specific blueprint pre-filled.

Or you can also:

  • Import this Blueprint by using the forum topic URL
  • Copy-paste the content of the following frame in a new file inside your configuration’s blueprint folder:

blueprint:

  name: 'Telegram Bot: Respond to Telegram Command by executing an action'

  description: >

    Listen to a Telegram Command and execute an action if listened

   

    ## "Command" field

    Command to listen for. Must start with '/'.

   

    _Example:_ `/start`

    ## "Command @ Bot Username" field

    Optional command to ensure compatibility in group chats. Must use this format `/[email protected]_bot`.

    _Example:_ `/[email protected]_bot_username_bot`

   

    #### Why does this field exist?

    If you upload a list of commands in your bot settings (in Telegram), when you type `/` in a message, it automatically suggests you commands from the list. In case you are typing to the bot in a group chat, command suggestions will add "@your_bot_username_bot" to your command. So, when Home Assistant receives them, it wouldn't recognize them unless you also define the same command adding `@your_bot_username_bot` as a trigger.

    It would be easier to use templates in trigger automation and avoid defining the command twice, but it is not yet supported. If anybody gets an easier way to do this, please [let me know](https://community.home-assistant.io/u/marc-romu) and I will update this blueprint.

    ## "Sequence" field

    What should happen when receiving this command. You can use variables explained below.

   

    ## Available telegram variables in this blueprint

    These variables are received from telegram. You can use them in templates within this automation:

      - `telegram_args`: List of words sent after command. You can get each word by its index: `telegram_args[0]`, `telegram_args[1]`, etc.

      - `telegram_args_as_text`: Single plain text string from arguments' list. Useful if you need full text, not single words.

      - `telegram_sender_first_name`: Sender's first name.

      - `telegram_sender_last_name`: Sender's last name.

      - `telegram_sender_full_name`: Sender's full name, as `first_name + " " + last_name`

      - `telegram_sender_user_id`: Sender's user id.

      - `telegram_chat_id`: Chat id.

    #### Template example

    Use format `{{ variable_name }}` to indicate that it is a template, as usual in Home Assistant.

    `Hi {{ telegram_sender_first_name }}! You said {{ telegram_args_as_text }} after the command.`

  domain: automation

  input:

    telegram_command:

      name: Command

      description: 'REQUIRED. Example: /start'

      selector:

        text:

          multiline: false

    telegram_command_at_bot:

      name: Command

      description: 'Optional, only needed to call commands in group chats using suggestions from command list. Example: /[email protected]_bot'

      default: ''

      selector:

        text:

          multiline: false

    sequence:

      name: Sequence

      description: "What should happen when receiving this command. You can use variables explained above."

      selector:

        action: {}

mode: parallel

max: 10

max_exceeded: warning

trigger:

- platform: event

  event_type: telegram_command

  event_data:

    command: !input 'telegram_command'

- platform: event

  event_type: telegram_callback

  event_data:

    data: !input 'telegram_command'

- platform: event

  event_type: telegram_command

  event_data:

    command: !input 'telegram_command_at_bot'

- platform: event

  event_type: telegram_callback

  event_data:

    data: !input 'telegram_command_at_bot'

variables:

  telegram_command: !input 'telegram_command'

  telegram_command_at_bot: !input 'telegram_command_at_bot'

  telegram_args: "{{ trigger.event.data['args'] }}"

  telegram_args_as_text: "{% for arg in telegram_args %}{{ arg }} {% endfor %}"

  telegram_sender_first_name: "{{ trigger.event.data['from_first'] }}"

  telegram_sender_last_name: "{{ trigger.event.data['from_last'] }}"

  telegram_sender_full_name: "{{ telegram_sender_first_name }} {{ telegram_sender_last_name }}"

  telegram_sender_user_id: "{{ trigger.event.data['user_id'] }}"

  telegram_chat_id: "{{ trigger.event.data['chat_id'] }}"

condition:

action: !input 'sequence'

Changelog

  • 2021-10-28: Add field “Command @ Bot Username” to ensure compatibility in group chats and Chat ID variable. Improved description.
  • 2021-10-11: Parse telegram arguments and other event data received by Home Assistant and allow to use them as variables in templates. Also updated blueprint’s description.
  • 2021-05-09: First version

Hi, I installed your blueprint and created the below automation. When I run it the words “TTS Test” are broadcast on the speaker. When I however type “/say something” into telegram, nothing happens. My telegram integration works as I have Node-red flow that reacts to commands from telegram. I am however wanting to move away from Node-red and do everything via these automatons.

Once I get this working I would like to know how do to change things so that whatever is typed after my command, becomes the message.

telegram_bot:
  - platform: polling
    api_key: !secret telegram_api_key
    allowed_chat_ids:
      - !secret telegram_chat_id1

notify:
  - platform: telegram
    name: hcourt
    chat_id: !secret telegram_chat_id1

1 Like

Nice feature request! I just updated the blueprint definition to get event data from Telegram and set them as variables so that they are useable in templates. I also updated description for better explaining.

Furthermore, I realized that arguments from telegram commands are received as a list of single words, so I added a variable called telegram_args_as_text that transforms the list back to a string of plain text.

Now, for example, if you type /say How are you?, arguments are stored in these two variables:

  • telegram_args gets 'How', 'are', 'you?'
  • telegram_args_as_text gets How are you?

Thanks for this, unfortunately, I must have a config issue. I can send notifications to Telegram but Hass does not appear to see any /commands. When I type in "/talk Hi " nothing happens.

If I install Node-Red and use the Telegram nodes there then it all works so I think I have the correct API keys and IDs but can’t get it read Telegram commands when not using Node-Red (used the same config details that I used when connecting via Node-Red.

Also tried

image

But the display still does not change to cast mode i.e. I do not appear to be reading the commands that are being typed in.

Use {{ telegram_args_as_text }} in message field. Without {{ }} will not be replaced with the variable. I think that TTS service doesn’t allow templates in user interface mode, so it will automatically change to YAML mode, but no problem.

To debug your configuration, you can follow these steps:

  1. Create another automation with this blueprint: Telegram Bot: Respond to Telegram Command with a text message
  2. Listen to the same command. In your case: /talk
  3. Set the message filed as You said: {{ telegram_args_as_text }}

With this configuration, Telegram Bot should respond to your message with the arguments.

Then, try to send a message to your bot like /talk How are you?. You should receive back a message saying: You said: How are you?.

Both blueprints use the same internal configuration, so if this one works, the other one should work. If it doesn’t, maybe you have some configuration issue with the action. You could try to debug it using developer tools tab in your Home Assistant instance.

I hope it helps!

Thanks again :slight_smile: I will give the debugging tools a go.