Automation to react on mqtt

I send a mqtt message to home assistant to obtain the state of an entity, and send this back with mqtt
I am a beginner, tryed for hours now, with variables etc. browsed a lot, did not find an answer
anyone ?

- id: antwoordpy
  alias: antwoord op mqtt vraag
  trigger:
  - platform: mqtt
    topic: mqttvraag
  action:
  - service: mqtt.publish
    data_template:
      payload_template: '{{states.{{trigger.payload}}.state}}'
      topic: mqttantwoord 

shouldnt the topic be: homeassistant/mqttvraag
You can check this using a mqtt client and connect to the mqtt broker.
Same goes for the reply, is that the correct topic?

payload_template: '{{states.{{trigger.payload}}.state}}'
I think this way is not preferred with the states.entity.state see:

payload_template: "{{states(trigger.payload)}}"
Should return the state of the entity you published.

Can i ask why you do it like this?

Hi Dujith,
thanks for the answer.

trigger mqtt subscribe receives “switch.sonoff_1”, this works,

I changed as you wrote :

“{{states(trigger.payload)}}”

compiling gives

template value should be a string for dictionary value @ data[0][‘data_template’]

why i am working on this : I consider transferring my domotica from domoticz to home assistant
i have a lot of complex python scripts, I want to keep using
therefore I need to know the state of entity’s in home assistant on demand

Could you post the automation?

This hereunder works, but obviously, I want to use the trigger.payload :

- id: antwoordpy
  alias: antwoord op mqtt vraag
  trigger:
  - platform: mqtt
    topic: mqttvraag
  action:
  - service: mqtt.publish
    data_template:
      payload_template: '{{states.switch.sonoff_1.state}}'
      topic: mqttantwoord

Thats weird, just tested this out and it give me back a valid response for that enitity

trigger:
  - platform: mqtt
    topic: mqttvraag
condition: []
action:
  - service: mqtt.publish
    data:
      qos: 0
      retain: false
      payload_template: "{{states(trigger.payload)}}"
      topic: mqttantwoord

image

how !!! thanks a lot, should be data instead of data_template did it !!
this helps a lot !!! makes interaction with external python scripts easy .