Mastering Interactive Alerts: Leveraging Telegram Bot for Rich Notifications in Home Assistant

Represent Mastering Interactive Alerts: Leveraging Telegram Bot for Rich Notifications in Home Assistant article
3m read

In the smart home, timely and informative alerts are crucial. While Home Assistant offers various notification channels, integrating a Telegram Bot unlocks interactive communication. Imagine receiving a camera snapshot on motion detection, or arming your alarm directly from a Telegram message. This guide will cover setting up Telegram notifications, integrating rich media, and leveraging interactive buttons for transformative alerts.

Why Telegram?

Telegram excels with its robust API, rich media support (photos, videos), and interactive keyboards. This enables actionable prompts directly from your chat app, allowing for complex automations.

Prerequisites

  • Running Home Assistant instance.
  • Telegram account.

Step-by-Step Setup: Telegram Bot

1. Create Your Telegram Bot

Use Telegram's official bot, @BotFather.

  1. Search @BotFather in Telegram.
  2. Send /newbot. Follow prompts for name (e.g., "MyHA_Notifications") and unique username (e.g., "myhanotifications_bot").
  3. Save the provided HTTP API token securely.

2. Get Your Chat ID

To receive messages, your bot needs your chat_id.

  1. Start a chat with your new bot; send any message.
  2. In browser, go to https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates (replace token).
  3. Find the "id" field in the "chat" object. This is your chat_id. It's negative for groups, positive for private chats.
  4. Save this chat_id. For group chats, add the bot to the group and send a message there first.

3. Configure Home Assistant

Use secrets.yaml for sensitive info.

  1. Update secrets.yaml:
    # secrets.yaml
    telegram_bot_token: "YOUR_BOT_TOKEN_HERE"
    telegram_chat_id: YOUR_CHAT_ID_HERE # e.g., -123456789 or 123456789
    
  2. Configure configuration.yaml:
    # configuration.yaml
    telegram_bot:
      - platform: polling
        api_key: !secret telegram_bot_token
        allowed_chat_ids:
          - !secret telegram_chat_id
    
    notify:
      - name: telegram_notifications
        platform: telegram
        chat_id: !secret telegram_chat_id
    

    telegram_bot handles incoming messages; notify sends them.

  3. Restart Home Assistant: Check config, then restart.

Advanced Notification Examples

1. Simple Text Notification

Send basic messages using telegram_notifications service.

# automation.yaml
alias: Front Door Opened Notification
trigger:
  - platform: state
    entity_id: binary_sensor.front_door
    to: 'on'
action:
  - service: notify.telegram_notifications
    data:
      message: "The front door has been opened!"
mode: single

2. Sending Images/Snapshots

Useful for security cameras.

# automation.yaml
alias: Motion Detected Snapshot
trigger:
  - platform: state
    entity_id: binary_sensor.motion_sensor_front_door
    to: 'on'
condition:
  - condition: state
    entity_id: alarm_control_panel.home_alarm
    state: 'armed_away'
action:
  - service: camera.snapshot
    data:
      entity_id: camera.front_door
      filename: "/config/www/tmp/front_door_snapshot_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"
  - delay: 500 #ms
  - service: notify.telegram_notifications
    data:
      message: "Motion detected at front door!"
      data:
        photo:
          - file: "/config/www/tmp/front_door_snapshot_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"
            caption: "Front door activity"
mode: single

Ensure /config/www exists for snapshots.

3. Interactive Notifications with Inline Keyboards

Embed buttons for actions back in Home Assistant. Telegram's strength lies here.

# automation.yaml
alias: Turn Off Lights Prompt
trigger:
  - platform: time
    at: "23:00:00"
condition:
  - condition: state
    entity_id: light.living_room_lights
    state: 'on'
action:
  - service: notify.telegram_notifications
    data:
      message: "Turn off living room lights?"
      data:
        inline_keyboard:
          - "Yes:/turn_off_lights"
          - "No:/do_nothing"
mode: single

Handle button presses with a telegram_bot automation:

# automation.yaml
alias: Handle Telegram Light Command
trigger:
  - platform: event
    event_type: telegram_callback
    event_data:
      data: "/turn_off_lights"
action:
  - service: light.turn_off
    entity_id: light.living_room_lights
mode: single

telegram_callback data matches inline keyboard definition after colon.

Best Practices for Robust Integration

1. Secure Bot Token & Chat ID

Always use !secret. Never hardcode sensitive info directly in your configuration files.

2. Rate Limiting / Cooldowns

Prevent spam and avoid Telegram rate limits. Implement cooldowns (e.g., 5 minutes for repetitive events).

# Example with cooldown
alias: Notify Door Open Cooldown
trigger:
  - platform: state
    entity_id: binary_sensor.front_door
    to: 'on'
condition:
  - condition: template
    value_template: "{{ (as_timestamp(now()) - as_timestamp(states.automation.notify_door_open_cooldown.attributes.last_triggered | default(0))) > 300 }}" # 5 minutes
action:
  - service: notify.telegram_notifications
    data:
      message: "Front door opened (cooldown active)."
mode: single

3. Structure Messages with Templates

Use Jinja2 for dynamic, rich messages.

# automation.yaml
alias: Battery Low Alert
trigger:
  - platform: numeric_state
    entity_id: sensor.my_device_battery
    below: 15
action:
  - service: notify.telegram_notifications
    data:
      message: "‼️ Battery Alert! ‼️\n\n{{ state_attr('sensor.my_device_battery', 'friendly_name') }} battery is at {{ states('sensor.my_device_battery') }}%. Recharge soon!"
      data:
        parse_mode: html # For bold text & emojis
mode: single

Note on parse_mode: html: Telegram supports a subset of HTML tags. Refer to the Telegram Bot API docs for details.

4. Error Handling & Fallbacks

Consider fallback notifications (e.g., persistent Home Assistant notifications, Pushover) if Telegram is unavailable or your internet connection fails.

5. Manage Group Access

If adding your bot to a group, use allowed_chat_ids in configuration.yaml to restrict who can send commands to your bot.

6. Persistent Storage for Snapshots

Manage snapshot storage (e.g., /config/www/tmp/) to prevent disk space issues, especially on SD cards.

Conclusion

Telegram Bot integration empowers an interactive smart home. Receive rich, contextual info and respond directly from chat. These steps and practices create a robust, responsive notification system.

Avatar picture of NGC 224
Written by:

NGC 224

Author bio: DIY Smart Home Creator

There are no comments yet
loading...