Create helpers in automation

I wrote this little script to achieve just that. I currently creates a text_helper but can be adjusted to create any kind of helper:

#!/usr/bin/env python3

import json
import sys

import requests
import websocket

HOMEASSISTANT_URL = "<your homeassistant url>" # e.g. homeassistant.domain.tld or 192.168.1.1
USE_HTTPS = True
TOKEN = "<your long lived access token>"

REST_URL = f"{'https' if USE_HTTPS else 'http'}://{HOMEASSISTANT_URL}/api/states"
WS_URL = f"{'wss' if USE_HTTPS else 'ws'}://{HOMEASSISTANT_URL}/api/websocket"

if len(sys.argv) != 2:
    print(f"Usage: python {sys.argv[0]} <helper_name>")
    sys.exit(1)

helper_to_create = sys.argv[1]
helper_to_create_full = "input_text." + helper_to_create

entity_state = requests.get(
    url=f"{REST_URL}/{helper_to_create_full}",
	headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"},
	timeout=10,
)
if "entity_id" in entity_state.text:
    sys.exit(0)

ws = websocket.create_connection(WS_URL)
ws.send(json.dumps({"type": "auth", "access_token": TOKEN}))
result = json.loads(ws.recv())

req_create_helper = {
    "id": 1,
    "type": "input_text/create",
    "name": helper_to_create,
}
ws.send(json.dumps(req_create_helper))

ws.close()

It checks whether the helper already exists and if not creates it.

1 Like