How To improve Telegram Bot commands by using args?

I’m not sure about the way to get that working with the YAML automation, but I can talk about a Node-red automation. This is the way I automate everything and I made absolutely the same automation as you are trying to do in a matter of minutes, everything is so simple with Node-red! :wink:
In fact for my whole Telegram automation I never had to configure anything in the configuration / automation files, all the telegram setup is done within Node-RED.

My Home Assistant is a Docker container running on my Raspberry Pi, then Node-red is running on another container.

The nodes I used are:

Let me walk you through how my flow works, I wanted the command to be “light {light} {state}”, for example “light kitchen on”, and then the bot responds with “Turned on the kitchen light”.

Here’s the whole flow:

The first node is activated when a message that starts with light is received, for that I used regular expression, to match every message starting with “light …”:

Then the content of the message is passed to the next node, and can be accessed with “msg.payload.text”.
The next node is a function that will get arguments, simply separating the message in a list of words, and then build the HA service to execute the action:

var text = msg.payload.text;
var splitted = text.split(' ')
var payload = {
    'domain': 'light',
    'service': 'turn_' + splitted[2],
    'data': {
        'entity_id': 'light.' + splitted[1]
    }
}
return {'payload': payload};

So the json service to call is passed to the next node, which sends the service to Home Assistant. The configuration is left empty, as it will be overwritten by the payload built just before.

The next node is a function building the message the bot will send, based on the arguments of the command.

var state = msg.payload.service.split('_')[1]
var light = msg.payload.data.entity_id.split('.')[1]
var text = 'Got it, turned '+ state + ' the '+ light + ' light.';

return {'payload': {'text':text}};

Finally the last node is a Telegram payload, configured with “sendMessage”, to send the previously built message.

Let me know if you need any help, I’d be very glad to help you to get it working! :slight_smile:

EDIT: so frustrating that as a new user I couldn’t use more than one image… I uploaded my flow so you can just copy paste to use it on your Node-red installation : https://flows.nodered.org/flow/a1dd5b6026545a9d5e2d097498480c9d

1 Like