Fix Telegram “target” Validation Error In Home Assistant

by Kenji Nakamura 57 views

Hey guys! 👋 Let's dive into this tricky error some of you might be facing when using the Telegram action in Home Assistant with Node-RED. It’s a bit of a head-scratcher, but we'll get through it together! 💪

The Bug: “ValidationError: “target” must be of type object”

The issue arises when you're trying to send a message via Telegram using the Home Assistant service in Node-RED. You might encounter this error message: ValidationError: “target” must be of type object. This pops up even when you think you've correctly set the target chat ID. 😫

Digging Deeper into the Problem

So, what's going on? The Home Assistant Telegram action expects the target parameter to be the chat ID where the message should be sent. According to the documentation, this target should be either a single chat ID or an array of chat IDs. For example, you might try:

{
  "message": "please pick one",
  "inline_keyboard": [
    [["option 1", "redacted"]],
    [["option 2", "redacted"]],
    [["option 3", "redacted"]]
  ],
  "target": -12345
}

Or even:

"target": [-12345]

And just to be extra sure:

let chat = new Array(-12345);
...
"target": chat

But alas, the error persists! 😩

The Plot Thickens: Validation Woes

It seems the validation process within the plugin is where things go awry. It appears to be expecting a Home Assistant entity object, rather than a simple integer or array of integers. If you try to trick it by formatting the target like this:

"target": {"entity_id": [-356227518]}

The validation might pass, but Home Assistant will throw a fit because it's expecting an integer or an array of integers, not an object. 🤯

{
  "__enc__": true,
  "type": "error",
  "data": {
    "name": "HomeAssistantError",
    "message": "expected int @ data['target'][0]",
    "stack": "HomeAssistantError: expected int @ data['target'][0]\n    at getErrorData (/data/node_modules/node-red-contrib-home-assistant-websocket/dist/common/errors/inputErrorHandler.js:53:13)\n    at inputErrorHandler (/data/node_modules/node-red-contrib-home-assistant-websocket/dist/common/errors/inputErrorHandler.js:73:38)\n    at ActionController._InputOutputController_preOnInput (/data/node_modules/node-red-contrib-home-assistant-websocket/dist/common/controllers/InputOutputController.js:69:51)"
  }
}

Interestingly, hardcoding the JSON directly into a Home Assistant action step works just fine. The issue only crops up when the JSON is passed from a previous step in the payload. This suggests the validation is being overly strict when processing payloads from previous steps. 🤔

It's clear that the validation needs a little tweaking to account for different use cases! 😉

Reproducing the Bug: A Step-by-Step Guide

Want to see this bug in action? Here’s how you can reproduce it:

  1. Set up: Make sure you have Home Assistant with the Telegram integration configured and at least one authorized chat. ✅

  2. Create a Flow: In Node-RED, create a function node connected to a Home Assistant action node. 🔗

  3. Function Node: Configure the function node to return a simple message for Telegram, like this:

    return { payload: { "message": "message", 
    "target": 12345} };
    
  4. Action Node: In the Home Assistant action node, use the telegram_bot.send_message service and pass msg.payload as the data. ⚙️

  5. Run it: Execute the flow, and you should see the validation error pop up. 💥

Expected Behavior

The validation should recognize and allow the correct parameter format for the Telegram action. We expect the message to be sent to the specified chat ID without any validation errors. 🤩

Example Flow

Here’s an example flow you can import into Node-RED to reproduce the issue:

[
    {
        "id": "4bde0420f3bfa646",
        "type": "tab",
        "label": "debug telegram through hass",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "9c9b567ae9907ce1",
        "type": "api-call-service",
        "z": "4bde0420f3bfa646",
        "name": "through function",
        "server": "60d4bb145eef1827",
        "version": 7,
        "debugenabled": true,
        "action": "telegram_bot.send_message",
        "floorId": [],
        "areaId": [],
        "deviceId": [],
        "entityId": [],
        "labelId": [],
        "data": "msg.payload",
        "dataType": "jsonata",
        "mergeContext": "",
        "mustacheAltTags": false,
        "outputProperties": [],
        "queue": "none",
        "blockInputOverrides": false,
        "domain": "telegram_bot",
        "service": "send_message",
        "x": 600,
        "y": 140,
        "wires": [
            []
        ]
    },
    {
        "id": "a959acb83bf77151",
        "type": "http in",
        "z": "4bde0420f3bfa646",
        "name": "",
        "url": "do",
        "method": "get",
        "upload": false,
        "skipBodyParsing": false,
        "swaggerDoc": "",
        "x": 100,
        "y": 160,
        "wires": [
            [
                "9e20d280dd8e6c94",
                "5f95f0979e88f40b",
                "1bb49bd3188902d6"
            ]
        ]
    },
    {
        "id": "9e20d280dd8e6c94",
        "type": "function",
        "z": "4bde0420f3bfa646",
        "name": "generate keyboard",
        "func": "\nreturn { payload: { \"message\": \"message\", \n\"target\": {\"entity_id\":[12345] }} };\n",
        "outputs": 1,
        "timeout": 0,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 310,
        "y": 100,
        "wires": [
            [
                "dded6ee6c6075b52",
                "9c9b567ae9907ce1"
            ]
        ]
    },
    {
        "id": "5f95f0979e88f40b",
        "type": "http response",
        "z": "4bde0420f3bfa646",
        "name": "f",
        "statusCode": "201",
        "headers": {},
        "x": 350,
        "y": 260,
        "wires": []
    },
    {
        "id": "dded6ee6c6075b52",
        "type": "debug",
        "z": "4bde0420f3bfa646",
        "name": "debug 14",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 540,
        "y": 320,
        "wires": []
    },
    {
        "id": "1bb49bd3188902d6",
        "type": "api-call-service",
        "z": "4bde0420f3bfa646",
        "name": "hardcoded",
        "server": "60d4bb145eef1827",
        "version": 7,
        "debugenabled": true,
        "action": "telegram_bot.send_message",
        "floorId": [],
        "areaId": [],
        "deviceId": [],
        "entityId": [],
        "labelId": [],
        "data": "{\"message\":\"please pick one\",\"target\":12345}",
        "dataType": "json",
        "mergeContext": "",
        "mustacheAltTags": false,
        "outputProperties": [],
        "queue": "none",
        "blockInputOverrides": false,
        "domain": "telegram_bot",
        "service": "send_message",
        "x": 590,
        "y": 220,
        "wires": [
            []
        ]
    },
    {
        "id": "60d4bb145eef1827",
        "type": "server",
        "name": "Home Assistant",
        "version": 5,
        "addon": false,
        "rejectUnauthorizedCerts": true,
        "ha_boolean": "y|yes|true|on|home|open",
        "connectionDelay": true,
        "cacheJson": true,
        "heartbeat": false,
        "heartbeatInterval": "30",
        "areaSelector": "friendlyName",
        "deviceSelector": "friendlyName",
        "entitySelector": "friendlyName",
        "statusSeparator": ": ",
        "statusYear": "hidden",
        "statusMonth": "short",
        "statusDay": "numeric",
        "statusHourCycle": "default",
        "statusTimeFormat": "h:m",
        "enableGlobalContextStore": false
    },
    {
        "id": "89bc1edb92f9825f",
        "type": "global-config",
        "env": [],
        "modules": {
            "node-red-contrib-home-assistant-websocket": "0.77.2"
        }
    }
]

How to Import the Flow

  1. Copy the JSON code above.
  2. In your Node-RED editor, click the menu button (three horizontal lines) in the top-right corner.
  3. Select “Import” -> “Clipboard”.
  4. Paste the JSON code into the import dialog and click “Import”.

Environment Information

Here’s some environment info that might be helpful:

  • Version: 0.77.2
  • Home Assistant version: 2025.7.4
  • Companion version: 4.1.2
  • Node-RED version: 4.1.0
  • Docker: yes
  • Add-on: no
  • Node.js version: v20.19.4 x64 linux
  • OS: Linux 5.15.0-143-generic x64

Final Thoughts

This validation issue can be a real pain, but hopefully, by understanding the problem and how to reproduce it, we can get it sorted out. Hang in there, and let's keep making our smart homes even smarter! 🚀🏡