How to change attributes from a script?

I want to set one attribute of an entity from a script. How do I do that? I couldn’t find anything like that in the documentation. Do I have to create a service? If so, how do I do that?

OK, I found a workaround. I sent an API request through the rest_command service. It is by far not an ideal solution. For one, I have to set all the attributes and the state at the same time, like this:

rest_command:
  set_foobar_attribute:
    url: http://localhost:8123/api/states/foo.bar
    method: post
    payload: >
      "state": {{ states.foo.bar.state }},
      "attributes": {
        "to_change": "whatever",
        "not_to_change": {{ states.foo.bar.attributes.not_to_change }}
      }

Obviously, this is ugly. If Home Assistant does not provide a solution for this, the best would be to create a custom service. Is it possible to include a Python code from the homeassistant config directory?

1 Like

I don’t know how to do this in YAML, but I can point out that it is straightforward in appdaemon using the set_state method.

This is probably not doing what you intend it to do. This doesn’t affect the state machine and will be lost after any update.

Thanks, it seems like AppDaemon is something like what I have in mind. I will look deeper into the documentation.

AppDaemon works. I feel it’s a bit overkill for the task, but it gets the job done.

@andrey: Yes, it is exactly what I intend to do. I may have to reset the attribute at every state change, but that was the first idea at the first place (setting the icon attribute to reflect the state).

Old thread, I know. But IS it possible to affect the state machine? How can we programmatically change attributes on an entity and have the changes stick?