Use Trigger Data in automation Action

I have an automation that looks at my phones Last notification state, and if it’s a text message performs this action (only for testing):

service: Notify.SMTPAddress
data:
  message: "{{ trigger.to_state.state }} {{ trigger.to_state }}"
  title: test email
  target: [email protected]
  data:
    from: [email protected]
enabled: true

When I look at the trace I see the following data (only a sample, not all as it’s pretty long:

params:
  domain: notify
  service: EmailAddress
  service_data:
    message: >-
      744f <state sensor.sm_g986u_last_notification=744f;
      android.appInfo=ApplicationInfo{bfc6f38 com.samsung.android.messaging},
      android.conversationUnreadMessageCount=0,
      android.hiddenConversationTitle=null, 
	  android.infoText=null,
      android.isGroupConversation=False, 
	  android.largeIcon=Icon(typ=BITMAP
      size=90x90), 
	  android.messages=['
	    {extras={},
		sender_person=android.app.Person@a70dab32,
		sender=\u2068+PhoneNumber\u2069, text=Y, time=1714589805000}',
      '{extras={}, sender_person=android.app.Person@8f1f3a17,
      sender=\u2068+**PhoneNumber**\u2069, text=G, time=1714589917000}',

How would I get the PhoneNumber from the Trigger.??? in the automation action?

It’s hard to tell with the state object cut in half, but I think it should be:

{{ (trigger.to_state.attributes['android.messages'][0]['sender']).replace('\u2068', '').replace('\u2069', '') }}

Thank you, not really sure why I didn’t think of attributes. Still not a 100% working, but it’s a start.

I am trying to do this - or similar. I want to trigger a notification (or possibly a Google Sheets entry) when I receive a message from a particular sender/ number. What did you use as a trigger in your automation? Unless I’m missing that here somehow. I know it would probably be an manual event with a template. I have about the same info given from Developer Tools "android.messages:

    {extras={}, sender_person=android.app.Person@a67c8223, sender=Me,
    text=Another test, time=1727400769667}"

I would like to get the trigger to be a message from “Me”. Extra credit if I can also use the text (ie “Another test”) in the action. ChatGPT is next to useless or maybe I’m just not asking/ understanding correctly.
I tried triggering with any new notification and that works, but the template I have for the condition doesn’t -
value_template: >
{{ ‘Me’ in trigger.event.data[‘android.messages.sender’] }}
Obviously, the action template would have to be different too if I do it this way. I tried using “Templates” in Developer tools, but I’m still lost. Thanks

That’s because android.messages doesn’t return a true dictionary, it returns a list of dictionary-shaped strings… which can be a pain in the ass to work around, depending on what your specific needs are.

I’ve played around with a few variations on this method a little bit, but I’ve never gotten any of them to a place where it’s something I would consider completely reliable.

1 Like

No, you’re right.

OK, that’s a good start. Please format code correctly for the forum (see here).

First step is to get the trigger working, done. Now we need to sort out your condition. Open up the automation trace for the last triggering, click Download Trace, and post the contents of that file here formatted as code, which you can do between a pair of three backticks, like this:

```
PASTE CODE HERE
```

Don’t worry if it’s long. That should show us the event data that the condition is looking at.

You can’t really do that with triggers and events. It’s useful for trying out templates working on faked-up data structures, though.

Let’s take a look at the automation trace when posted. May be able to convert it with |from_json or similar.

1 Like

I thought I posted this a while back, but guess I hadn’t. Here’s the two automations I created for my text message needs. sm_g986u is my phone name, your value will vary.

Detects a new text from my wife, and sends a notification with Notify Me to Alexa. I kept missing her txt messages, so needed something to help me out:

alias: Erika - New Text Message
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.sm_g986u_last_notification
condition:
  - condition: state
    entity_id: sensor.sm_g986u_last_notification
    attribute: package
    state: com.samsung.android.messaging
  - condition: template
    value_template: >-
      {{ 'Erika' in state_attr('sensor.sm_g986u_last_notification',
      'android.title') }}
    enabled: true
action:
  - data:
      message: >-
        New Text from {{ state_attr(trigger.to_state.entity_id, "android.title")
        }}
    action: notify.notifyme
mode: single

This automation forwards the text I got to my Wife via here Text message email address (check with your provider for yours) and is the original automation I was trying to do:

alias: Erika - Verification Codes
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.sm_g986u_last_notification
condition:
  - condition: state
    entity_id: sensor.sm_g986u_last_notification
    attribute: package
    state: com.samsung.android.messaging
  - condition: or
    conditions:
      - condition: template
        value_template: "{{ 'Your code is' in trigger.to_state.state }}"
        enabled: true
      - condition: template
        value_template: "{{ 'Your verification code is' in trigger.to_state.state }}"
        enabled: true
action:
  - data:
      message: Test - {{ trigger.to_state.state }}
      title: test email
      target: [email protected]
      data:
        from: [email protected]
    enabled: true
    action: notify....._gmail_com
mode: single

1 Like

Silly me - I pasted the code from the visual editor. Here is the code for the yaml condition:

condition:
  - condition: template
    value_template: |-
      value_template: >
        {{ 'Me' in trigger.event.data['android.messages.0.sender'] }

Even copying and pasting that was an experience for me - I had no idea about the back-tick or where it was on the keyboard. Tilde yes but missed “back-tick”. Pre 80s high school.
Here’s my attempt at pasting the trace. It IS very long:

{
  "trace": {
    "last_step": "condition/0",
    "run_id": "211abc31d442b31b11a1e950bca0750a",
    "state": "stopped",
    "script_execution": "failed_conditions",
    "timestamp": {
      "start": "2024-09-27T15:02:51.141756+00:00",
      "finish": "2024-09-27T15:02:51.142631+00:00"
    },
    "domain": "automation",
    "item_id": "1695074365574",
    "trigger": "state of sensor.moto_g_stylus_5g_last_notification",
    "trace": {
      "trigger/0": [
        {
          "path": "trigger/0",
          "timestamp": "2024-09-27T15:02:51.141807+00:00",
          "changed_variables": {
            "this": {
              "entity_id": "automation.notification_test",
              "state": "on",
              "attributes": {
                "id": "1695074365574",
                "last_triggered": "2024-09-27T06:22:13.126877+00:00",
                "mode": "single",
                "current": 0,
                "friendly_name": "MotoGStylus text from Sally"
              },
              "last_changed": "2024-09-27T06:22:09.877518+00:00",
              "last_reported": "2024-09-27T06:22:13.127547+00:00",
              "last_updated": "2024-09-27T06:22:13.127547+00:00",
              "context": {
                "id": "01J8S29TM6RT5FXNQWPGWYNN7R",
                "parent_id": "01J8S29TM6EFCSXH3HEP0EVVTP",
                "user_id": null
              }
            },
            "trigger": {
              "id": "0",
              "idx": "0",
              "alias": null,
              "platform": "state",
              "entity_id": "sensor.moto_g_stylus_5g_last_notification",
              "from_state": {
                "entity_id": "sensor.moto_g_stylus_5g_last_notification",
                "state": "Monitoring for mail",
                "attributes": {
                  "android.appInfo": "ApplicationInfo{bc8e904 com.hermes.enotifylite}",
                  "android.infoText": "null",
                  "android.largeIcon": "null",
                  "android.progress": 0,
                  "android.progressIndeterminate": false,
                  "android.progressMax": 0,
                  "android.reduced.images": true,
                  "android.remoteInputHistory": "null",
                  "android.showChronometer": false,
                  "android.showWhen": true,
                  "android.subText": "null",
                  "android.text": "null",
                  "android.title": "Monitoring for mail",
                  "category": "null",
                  "channel_id": "com.hermes.enotify.channel_foreground",
                  "group_id": "null",
                  "is_clearable": false,
                  "is_ongoing": true,
                  "package": "com.hermes.enotifylite",
                  "post_time": 1727449343422,
                  "icon": "mdi:bell-ring",
                  "friendly_name": "moto g stylus 5G Last notification"
                },
                "last_changed": "2024-09-27T14:58:10.386289+00:00",
                "last_reported": "2024-09-27T15:02:25.458850+00:00",
                "last_updated": "2024-09-27T15:02:25.458850+00:00",
                "context": {
                  "id": "01J8T02BDJJMCFBM2KN6QQ6GM7",
                  "parent_id": null,
                  "user_id": null
                }
              },
              "to_state": {
                "entity_id": "sensor.moto_g_stylus_5g_last_notification",
                "state": "Testing ",
                "attributes": {
                  "android.appInfo": "ApplicationInfo{bd959bc com.google.android.apps.googlevoice}",
                  "android.car.EXTENSIONS": "{invisible_actions={0={extras={android.support.allowGeneratedReplies=true}, showsUserInterface=false, remoteInputs=null, semanticAction=2, icon=2131231034, title=Mark as Read, actionIntent=PendingIntent{f73a1af: android.os.BinderProxy@99530df}}}}",
                  "android.conversationUnreadMessageCount": 0,
                  "android.hiddenConversationTitle": "null",
                  "android.infoText": "null",
                  "android.isGroupConversation": false,
                  "android.largeIcon": "Icon(typ=BITMAP size=111x111)",
                  "android.messages": [
                    "{extras={}, sender_person=android.app.Person@2778a1ee, sender=Me, text=Testing , time=1727449365316}"
                  ],
                  "android.messagingStyleUser": "{key=null, uri=null, icon=null, name=You, isBot=false, isImportant=false}",
                  "android.messagingUser": "android.app.Person@9aa2142",
                  "android.people.list": [
                    "android.app.Person@7ac64d3e"
                  ],
                  "android.progress": 0,
                  "android.progressIndeterminate": false,
                  "android.progressMax": 0,
                  "android.reduced.images": true,
                  "android.remoteInputHistory": "null",
                  "android.selfDisplayName": "You",
                  "android.showChronometer": false,
                  "android.showWhen": true,
                  "android.subText": "[email protected]",
                  "android.support.v4.app.extra.COMPAT_TEMPLATE": "androidx.core.app.NotificationCompat$MessagingStyle",
                  "android.template": "android.app.Notification$MessagingStyle",
                  "android.text": "Testing ",
                  "android.title": "Me",
                  "android.wearable.EXTENSIONS": "{background=android.graphics.Bitmap@f4fc9a, actions=[android.app.Notification$Action@662a9cb]}",
                  "category": "msg",
                  "channel_id": "2TXT",
                  "group_id": "null",
                  "is_clearable": true,
                  "is_ongoing": false,
                  "package": "com.google.android.apps.googlevoice",
                  "post_time": 1727449369127,
                  "icon": "mdi:bell-ring",
                  "friendly_name": "moto g stylus 5G Last notification"
                },
                "last_changed": "2024-09-27T15:02:51.140015+00:00",
                "last_reported": "2024-09-27T15:02:51.140015+00:00",
                "last_updated": "2024-09-27T15:02:51.140015+00:00",
                "context": {
                  "id": "01J8T034G42BRTFCKAVWZWMPZM",
                  "parent_id": null,
                  "user_id": null
                }
              },
              "for": null,
              "attribute": null,
              "description": "state of sensor.moto_g_stylus_5g_last_notification"
            }
          }
        }
      ],
      "condition/0": [
        {
          "path": "condition/0",
          "timestamp": "2024-09-27T15:02:51.141850+00:00",
          "error": "In 'template' condition: UndefinedError: 'dict object' has no attribute 'event'"
        }
      ]
    },
    "config": {
      "id": "1695074365574",
      "alias": "MotoGStylus text from Sally",
      "trigger": [
        {
          "platform": "state",
          "entity_id": [
            "sensor.moto_g_stylus_5g_last_notification"
          ],
          "to": null
        }
      ],
      "condition": [
        {
          "condition": "template",
          "value_template": "value_template: >\n  {{ 'Me' in trigger.event.data['android.messages.0.sender'] }} \n  "
        }
      ],
      "action": [
        {
          "action": "notify.persistent_notification",
          "metadata": {},
          "data": {
            "message": "It worked"
          }
        }
      ]
    },
    "blueprint_inputs": null,
    "context": {
      "id": "01J8T034G5CD1RQBQAVXFS8Y7G",
      "parent_id": "01J8T034G42BRTFCKAVWZWMPZM",
      "user_id": null
    }
  },
  "logbookEntries": []
}

I made sure I had just sent a message from “Me”; last notification pulls up everything - push, weather. text, etc.
Thanks for the help. If nothing else at least I found out how to ask a question correctly here

1 Like

You have a state trigger not an event trigger. Try this as your value_template:

{{ 'android.messages' in trigger.to_state.attributes and
   'sender=Me,' in trigger.to_state.attributes['android.messages'][0] }}

First section protects against errors from notifications that aren’t related to messages.

1 Like

Got the first automation working - had to copy/paste/edit twice since my keyboard is dumb (right - the keyboard). Have to take a break and do my grocery shopping, but I’m pretty confident I can use some version of the second one too. Thank you so much for your help and prompt response.

The OP seems to have worked it out for me, but I appreciate your help. Already learned a few things - hopefully I don’t “unlearn” them LOL. Thanks again

That’s the wonderful part of the forums it will always be here to help you remember. Glad I was able to help out.

1 Like

I am happy when I find an answer to a question somebody else answered. I have asked a few here without being able to enunciate them properly. I should have asked already (in the past few years) about how to keep the syntax and spacing on copied text. I’m sure I will be using the back-tick key often now. Thanks again for your time and knowledge.