For loop inside telegram bot inline keyboard template

Hi!
I want to make some automation that use actual HA configuration to build inline keyboard inside telegram bot.
I try to use code like this:

  • alias: ‘Telegram light response’
    hide_entity: true
    trigger:
    platform: event
    event_type: telegram_command
    event_data:
    command: ‘/light’
    action:
    • service: telegram_bot.send_message
      data_template:
      title: ‘Hello!’
      message: ‘Light!’
      inline_keyboard: >-
      {% for state in states.light -%}
      - /light_on_{{state.entity_id}}
      {% endfor %}

But it doesn’t work.
Error in log file:
2018-04-08 11:59:33 ERROR (SyncWorker_1) [homeassistant.components.telegram_bot] Error sending message: Button_data_invalid. Args: (11763502, ‘Hello!\nLight!’), kwargs: {‘parse_mode’: ‘Markdown’, ‘disable_notification’: False, ‘disable_web_page_preview’: None, ‘reply_to_message_id’: None, ‘reply_markup’: <telegram.inline.inlinekeyboardmarkup.InlineKeyboardMarkup object at 0x7f0afa0c0278>, ‘timeout’: None}

What’s wrong?

I have same problem.

Did you find a solution, I’ve a similar problem.

Yes. But I use appdaemon for telegram bot now. It allows make more complex things.

My code is working:

        {{-'['-}} 
        {%- for r in states.switch -%}
        {% if r.state=='on'%}
        {{'[["'}}{{r|regex_findall_index('\.(\w+)')}}{{-'","/actionlink"]]'-}}
        {%- if loop.last == false %},
        {%- endif -%}
        {%- endif -%}
        {%- endfor -%}         
        {{-']'-}}

You can’t template YAML like that. But you can use a list output from a template directly

So this should work:

- alias: 'Telegram light response'
      hide_entity: true
      trigger:
    platform: event
    event_type: telegram_command
    event_data:
     command: '/light'
      action:
    - service: telegram_bot.send_message
      data_template:
        title: 'Hello!'
        message: 'Light!'
        inline_keyboard: >
          {{
            states.light
              | map(attribute='entity_id')
              | map('regex_replace', '^' , ' /light_on_')
              | list
          }}

Does this give the same result as your template?

        {{
          '[[["' 
          ~ states.switch
              | map(attribute='object_id')
              | list
              | join('","/actionlink"]], [["')
          ~ '","/actionlink"]]]'
        }}

Not sure why you need all these nested lists, but I don’t use the telegram integration, so it might be required :slight_smile:

I assumed it was some sort of odd markdown language to make buttons.

1 Like