Community Notifications (This forum) Sensor in Home Assistant

I started looking the other day for a way to integrate the notifications from this forum into my Home Assistant instance so I could see if there was anything new for me to check out (despite the fact I visit the forum a million times a day anyway). To my amazement, there was no way of doing this.

Therefore, im going to show how to get your latest notifications into Home Assistant, like so;

image

The forum is run on Discourse and I found some snippets of info at Notifications of Replies in this Forum to HA however there is lots of confision reading about Discourse between an Admin API and a User API.

I found a fantastic tool at Generate user API key for Discourse / Robin van Boven / Observable which allows you to enter the HA Community URL (https://community.home-assistant.io) and then click to request permission. This will bring you to this site and you can click to authorise the creation of a Read Only access api. Clicking authorise will generate a block of code which needs to be copy and pasted back into the API generating website.

You should then have a valid response and a new “User-Api-Key:”

Your API access token can be viewed and removed should you wish by going into Preferences > Apps on this site. Unless your change the name on the API Generating page, it will show as “SourceCred Discourse Plugin”

Now you are ready to pull your notification settings into your HA using a rest sensor

rest:
 - resource: https://community.home-assistant.io/notifications.json
   headers:
     User-Api-Key: !secret community_api_key
   scan_interval: 60
   sensor:
     - name: "Community Notification - 0"
       json_attributes_path: "$.notifications[0]"
       value_template: '{{ value_json.notifications[0].created_at }}'
       json_attributes:
         - notification_type
         - read
         - post_number
         - topic_id
         - fancy_title
         - slug
         - data

Ive then created a template sensor to set up the correct icons, urls etc depending on the type of notification types

template:
  - sensor:
      - name: Community Notification - 0 - Post
        unique_id: sensor.community_notifcation_0_post
        icon: >
            {% set nt                   = state_attr('sensor.community_notification_0', 'notification_type') %}
            
            {% if nt == 1 %}            {# Mentioned #}
              mdi:at
            {% elif nt == 2 %}          {# New Reply #}
              mdi:reply
            {% elif nt == 3 %}          {# Quoted #}
              mdi:format-quote-close
            {% elif nt == 4 %}          {# Edited #}
              mdi:pencil-outline
            {% elif nt == 5 %}          {# New Like #}
              mdi:cards-heart
            {% elif nt == 6 %}          {# New Private Message #}
              mdi:email-outline
            {% elif nt == 8 %}          {# Invite Accepted #}
              mdi:account
            {% elif nt == 9 %}          {# New Post #}
              mdi:reply
            {% elif nt == 11 %}         {# Linked #}
              mdi:link-variant
            {% elif nt == 12 %}         {# Badge Granted #}
              mdi:decagram
            {% elif nt == 14 %}         {# Solution #}
              mdi:checkbox-marked-outline
            {% else %}                  {# Catch All #}
              mdi:help-circle
            {% endif %}        
        state: >
            {% set nt                   = state_attr('sensor.community_notification_0', 'notification_type') %}
            {% set title                = state_attr('sensor.community_notification_0', 'fancy_title') %}
            {% set username             = states.sensor.community_notification_0.attributes.data.display_username %}
            {% set badge                = states.sensor.community_notification_0.attributes.data.badge_name %}
            
            {% if nt in [1, 2, 3, 4, 5, 6, 9, 11, 14] %} 
                {{ username }} - {{ title}}
            {% elif nt in [8] %} 
                '{{ username }}' accepted your invitation
            {% elif nt in [12] %} 
                Earned '{{ badge }}'
            {% else %} 
                {# Catch All #}
                Unknown Notification
            {% endif %}        
        attributes:
          url: >
            {% set nt                   = state_attr('sensor.community_notification_0', 'notification_type') %}
            {% set slug                 = state_attr('sensor.community_notification_0', 'slug') %}
            {% set topic                = state_attr('sensor.community_notification_0', 'topic_id') %}
            {% set post                 = state_attr('sensor.community_notification_0', 'post_number') %}
            {% set display_username     = states.sensor.community_notification_0.attributes.data.display_username %}
            {% set badge_id             = states.sensor.community_notification_0.attributes.data.badge_id %}
            {% set badge_slug           = states.sensor.community_notification_0.attributes.data.badge_slug %}
            {% set username             = states.sensor.community_notification_0.attributes.data.username %}

            {% if nt in [1, 2, 3, 4, 5, 6, 9, 11, 14] %} 
                https://community.home-assistant.io/t/{{ slug }}/{{ topic }}/{{ post }}/
            {% elif nt in [8] %} 
                https://community.home-assistant.io/u/{{ display_username }}
            {% elif nt in [12] %} 
                https://community.home-assistant.io/badges/{{ badge_id }}/{{ badge_slug }}?username={{ username }}
            {% else %}
                {# Catch All #}
            {% endif %}       
          read: '{{ state_attr(''sensor.community_notification_0'', ''read'') }}'
          created_at: '{{ states(''sensor.community_notification_0'') }}'

This will pull a sensor into Home assistant with the correct URL and Icons based upon the notification type.

I am only aware of the following notification types. I know I will be missing some so if anyone can add any info to this list I will update the sensor

  • Mentioned
  • New Reply
  • Quoted
  • Edited
  • New Like
  • New Private Message
  • New Post
  • Linked
  • Badge Granted
  • Solution - Added 26/5/21
  • Invite Accepted - Added 26/5/21

Personally, I have duplicated the above sensors to give me the last 5 notifications from the community and then displayed them using GitHub - thomasloven/lovelace-template-entity-row: 🔹 Display whatever you want in an entities card row.

type: entities
entities:
  - type: 'custom:template-entity-row'
    entity: sensor.community_notification_0_post
    name: '{{ states(config.entity) }}'
    secondary: >
      {% set last_updated_seconds = as_timestamp(now()) -
      as_timestamp(strptime(state_attr(config.entity, 'created_at'),
      '%Y-%m-%dT%H:%M:%S'))  %} 

      {% set days = (last_updated_seconds // (60 * 60 * 24)) | int %} {% set
      hours = (last_updated_seconds // (60 * 60)) | int %} {% set minutes =
      (last_updated_seconds // 60) | int %} {% set seconds =
      (last_updated_seconds // (60 // 60)) | int %}    

      {% set seconds = seconds - (minutes * 60) - (days * 24 * 60 * 60) - (hours
      * 60 * 60) %} {% set minutes = minutes - (days * 24 * 60) - (hours * 60)
      %} {% set hours =  hours - (days * 24) %} {% set weeks = (days // 7) | int
      %}
           
      {% set days = (days | int) - (weeks * 7) %}

      {% macro phrase(value, name) %}
           {%- set value = value | int %}
           {%- set end = 's' if value > 1 else '' %}
           {{- '{} {}{}'.format(value, name, end) if value | int > 0 else '' }}
      {%- endmacro %}
             
      {% set text = [ phrase(weeks, 'week'), phrase(days, 'day'), phrase(hours,
      'hour'), 
                      phrase(minutes, 'min'), phrase(seconds, 'sec') ] | select('!=','') | list | join(', ') %}
      {% set last_comma = text.rfind(',') %} {% if last_comma > 0 %}
           {% set text = text[:last_comma] + ',' + text[last_comma + 1:] %}
      {%- endif %}   {{ text }} ago
    state: null
title: Home Assistant Community

I hope people find this helpful.

4 Likes

The template sensor has been updated today to include “Solution” and “Invite Accepted” events too.
If anyone know of any other events please let me know and ill add them in.

1 Like

Hi Craig Nice work, how did you duplicate the sensor? do I need to do both the sensor and the rest command and do I need to change anything else?

thanks

Hi MrRodz

To duplicate the reset sensor add a second sensor

rest:
 - resource: https://community.home-assistant.io/notifications.json
   headers:
     User-Api-Key: !secret community_api_key
   scan_interval: 60
   sensor:
     - name: "Community Notification - 0"
       json_attributes_path: "$.notifications[0]"
       value_template: '{{ value_json.notifications[0].created_at }}'
       json_attributes:
         - notification_type
         - read
         - post_number
         - topic_id
         - fancy_title
         - slug
         - data
     - name: "Community Notification - 1"
       json_attributes_path: "$.notifications[1]"
       value_template: '{{ value_json.notifications[1].created_at }}'
       json_attributes:
         - notification_type
         - read
         - post_number
         - topic_id
         - fancy_title
         - slug
         - data

You will see the array of notifications which makes up the path has been changed from
notifications[0] to notifications[1], If you need to add more just keep going in this way (i show the last 5 notifications.

Then the same process needs to be done in the template sensor too - so add a second sensor and everywhere it references community_notification_0 change to community_notification_1 etc

Hope this helps you out.
Please just ask if there is anything else you need help with.

1 Like

Thank you I’ve got it working with 5 entries like yours.

1 Like

My next task is to have a light like the Alexa that pulse if I have messages waiting. Ill update you if I get it working :slight_smile:

Hi @Craig_McGowan

im having an issue where I can’t pull data from 6:59 am to 18:56, this has happened on two days now. have you seen this issue?
Screenshot 2021-05-28 at 19.34.27
Screenshot 2021-05-28 at 19.34.16

Hey,

No, ive had no outages at all.

image

Im assuming its either going to be a network issue your end, or as its near enough the same time both days - maybe your getting blocked from the API? The only reason I can think of is too many requests - did you keep the scan_interval at 60? Or did you lower it?

The discourse documents suggest the limit of daily calls to the API for a user to be 2880. This would be enough for an API request every 30 seconds so unless youve reduced the scan interval to less than this, or have set up multiple template sensors to access the API, then we should be well within the limits. Of course, these are just default limits and the HA guys could have adjusted these. But the fact mine works fine suggests not.

You can replace this:

{% if is_state_attr('sensor.community_notification_0', 'notification_type', 1) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 2) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 3) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 4) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 5) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 6) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 9) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 11) or
      is_state_attr('sensor.community_notification_0', 'notification_type', 14) 
      %} 

with this:

{% if state_attr('sensor.community_notification_0', 'notification_type') in [1, 2, 3, 4, 5, 6, 9, 11, 14] %} 

You can also replace all of this:

{% if is_state_attr('sensor.community_notification_0', 'notification_type', 1) %} {# Mentioned #}
  mdi:at
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 2) %} {# New Reply #}
  mdi:reply
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 3) %} {# Quoted #}
  mdi:format-quote-close
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 4) %} {# Edited #}
  mdi:pencil-outline
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 5) %} {# New Like #}
  mdi:cards-heart
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 6) %} {# New Private Message #}
  mdi:email-outline
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 8) %} {# Invited Accepted #}
  mdi:account
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 9) %} {# New Post #}
  mdi:reply
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 11) %} {# Linked #}
  mdi:link-variant
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 12) %} {# Badge Granted #}
  mdi:decagram
{% elif is_state_attr('sensor.community_notification_0', 'notification_type', 14) %} {# Solution #}
  mdi:checkbox-marked-outline
{% else %} {# Catch All #}
  mdi:help-circle
{% endif %}

with this:

{% set nt = state_attr('sensor.community_notification_0', 'notification_type') %}
{% set icons = { 1: 'at', 2: 'reply', 3: 'format-quote-close',
                 4: 'pencil-outline', 5: 'cards-heart', 6: 'email-outline',
                 8: 'account', 9: 'reply', 11: 'link-variant',
                 12: 'decagram', 14: 'checkbox-marked-outline' } %}
mdi:{{ icons[nt] if nt in icons.keys() else 'help-circle' }}
1 Like

I left the scan intervals at 60, a bit strange I that it happens at the same time. but didn’t happen yesterday so will wait and see. I couldn’t work out how to manually trigger the rest from the developer tab, just to test the api calls. All other network features seemed to be working ok. Did you have a way to test the rest api call? I’ll try to test the api next time it goes down to see if I can isolate the issue.

thanks

That is odd then. Hopefully it’s fine from now on for you.

Did anything appear in your logs?

https://community.home-assistant.io/notifications.json should show your notifications too, if your logged in as a user to this site. The rest sensor makes use of a API key to access this when not logged in.

Thanks @123 , always thankful for your jinja shorthand. Can you help me with this though please - Ive used your first shorthand but the second one, which chooses the mdi icon, id like to keep a comment of the notification type

            {% set nt = state_attr('sensor.community_notification_0', 'notification_type') %}
            {% set icons = { 
                 1: 'at',                       {# Mentioned #}
                 2: 'reply',                    {# New Reply #}
                 3: 'format-quote-close',       {# Quoted #}
                 4: 'pencil-outline',           {# Edited #}
                 5: 'cards-heart',              {# New Like #}
                 6: 'email-outline',            {# New Private Message #}
                 8: 'account',                  {# Invited Accepted #}
                 9: 'reply',                    {# New Post #}
                 11: 'link-variant',            {# Linked #}
                 12: 'decagram',                {# Badge Granted #}
                 14: 'checkbox-marked-outline'  {# Solution #}
            } %}
            mdi:{{ icons[nt] if nt in icons.keys() else 'help-circle' }}

Jinja doesnt seem to like comments here though, Any tips please?

Thanks

Because you’re not inserting Jinja comments between lines of Jinja code, you’re inserting them inside the definition of a dictionary (which mangles the dictionary).

If you absolutely must have comments you’ll need to use the long chain of if-elif-elif statements. However, you can reduce it a bit by assigning state_attr('sensor.community_notification_0', 'notification_type') to a Jinja variable and using the variable in the if-elif-elif.

1 Like