This is the way i created a newsapi.org sensor; maybe some day someone will make an integration or component out.
-
Go to newsapi.org. Register for an API key.
-
Create news.py python file with this, changing the ‘YOUR_NEWSAPI_API_KEY’ with your API key and 'YOUR_COUNTRY_CODE ’ with country code, like ‘us’ for ‘USA’.
#!/usr/local/bin/python3
import json
import urllib3
import requests
newsapiKey = 'YOUR_NEWSAPI_API_KEY'
newspage = 'https://newsapi.org/v2/top-headlines?country=YOUR_COUNTRY_CODE&pageSize=2&apiKey=' + newsapiKey
textSpeed = 6.5
result_json = ''
urllib3.disable_warnings()
try:
response = requests.get(url=newspage,verify=False)
except requests.exceptions.RequestException as e:
print("SSL Error")
quit()
JSON_response = response.json()
result_json = JSON_response['articles'][0]['title'] + ' / ' + JSON_response['articles'][1]['title']
print ('{ "news":"'+result_json.upper()+'", "secs":'+str(int(len(result_json) / textSpeed)+1)+'}')
- Test you news.py with
python3 news.py
and make sure it works.
- Create a command line sensor in your homeassistant configuration.yaml:
command_line:
- sensor:
name: AWTRIX News
command: "python3 external_data/news.py"
scan_interval: 900
json_attributes:
- news
- secs
value_template: '{{ value_json }}'
I use this sensor for Awtrix light clock, for this, i use the following automation:
- alias: AWTRIX Ulanzi News
trigger:
- platform: state
entity_id: sensor.awtrix_news
action:
- service: mqtt.publish
data:
qos: 2
retain: true
payload: >-
{
"text": "{{ state_attr('sensor.awtrix_news','news') }}",
"icon": "news",
"rainbow": false,
"repeat": 1,
"pushIcon": 1
}
topic: awtrix_ulanzi/custom/news