Choose random line from list

I’ve got a list of ideas for dinner and I would like Home Assistant to pick one of the ideas at random, when I ask it to.
Does anyone know how this could be done?

1 Like

A little more context would help, but assuming you want to do this in a template somewhere, something like this:

{{ ['chicken', 'pot roast', 'cotton candy'] | random }}
1 Like

Sorry for being so brief.

Right now I’ve got the list in a google docs, it would be essential if HA could pull an item from there, but it isn’t really necessary. I would like it to display the item it pulled on the frontend or for it to push it to my devices, but I can probably find that out myself.

I’ll try and play around with what you gave me, thanks.

I once wanted to do something similar - pull a random line from a local text file but I couldn’t find a way to do it.

Please post back here if you find a way!

I did it the way @pnbruckner suggested. It’s a bit tedious to the first time around, but now it’s done and working.

Yes I do that too but just wanted a way to keep the items in an external file. That would make them dynamically updateable and keep the size of my yaml files down!

Yeah, I would like that too, if you find a solution, please let me know!

I would think you might be able to do that in a python_script, but that is a pretty limited environment, so you might not be able to call open. If that won’t work then you can use a shell_command that calls a real python script that could pull the random line and return it as a result.

1 Like

Yes, I’ve been putting that off as I don’t know Python.
I’ll get round to it sometime.
Lovelace has taken over at the moment. It is pretty amazing how much you can do with it, and you get instant results with no restart-wait-time :slight_smile:

Ok, I’m not asking for a tutorial in Python here. There are lots of online resources for that but…

I can see from the HA docs how to call a python script using shell_command.
I can see lots of (wildly different!) Python examples online of getting a random line from a file.

But I can’t see how to get the result of the script returned to HA?

Of course if the question is not as simple as I am making it, feel free to say!
Thanks.

I can give you more details and an example but it might be a couple days before I have time. I have this bookmarked so I don’t forget. Or maybe someone else will jump on in the meantime.

1 Like

That would be great, thank you.

So, this won’t work from a python_script because it needs to import some modules, which that doesn’t support. But it will work from a shell_command calling an external python script. The basic idea is to have the script not only retrieve the random line from the file, but also use HA’s REST API to write that to HA’s state machine. You can use whatever you like for the entity_id.

Below is the script. Change the URL and PASSWORD accordingly. Copy it into a file on your HA system where a shell_command can find it and give it a ‘.py’ extension (e.g., you could name it random_line.py’.) Your shell_command should look something like this:

python3 random_line.py my_line_file sensor.random_line

This should result in an entity named sensor.random_line whose state is a random line from my_line_file. I tested this script by calling it directly from a command line on a different machine than what is running HA, and it worked fine. It should also work from a shell_command within HA. :pray: :wink:

random_line.py:

#!/usr/bin/env python3

import random
import sys

import requests

URL = 'https://IP:PORT'
PASSWORD = 'YOUR_PASSWORD'

SET_STATE = '{}/api/states/{{}}'.format(URL)
HEADERS = {
    'x-ha-access': PASSWORD,
    'content-type': 'application/json'}

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Must have exactly two arguments: filename, entity_id', file=sys.stderr)
        sys.exit(1)
    filename = sys.argv[1]
    entity_id = sys.argv[2].lower()

    try:
        with open(filename) as f:
            line = random.choice(f.readlines()).strip()
    except:
        print(': '.join(['Read failed', filename]), file=sys.stderr)
        sys.exit(2)

    data = '{{"state": "{}"}}'.format(line)
    try:
        requests.post(SET_STATE.format(entity_id), data=data, headers=HEADERS)
    except:
        print('Writing state to HA failed', file=sys.stderr)
        sys.exit(3)

    sys.exit(0)

Brilliant, thank you very much.
It’s late here now and I won’t be able to try this tomorrow but I will report back when I have it up and running.

Again, thanks.

1 Like