Skip to content

Instantly share code, notes, and snippets.

@olanystrom
Created April 25, 2019 12:42
Show Gist options
  • Save olanystrom/1316a7620a4d9ff1b9b21494c501b3b7 to your computer and use it in GitHub Desktop.
Save olanystrom/1316a7620a4d9ff1b9b21494c501b3b7 to your computer and use it in GitHub Desktop.
Polis to slack bot
#!/bin/env python3
import requests
import json
import logging
from diskcache import Cache
from datetime import datetime
logging.basicConfig(
filename='polisapi.log',
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
polisurl = "https://polisen.se/api/events"
slackurl = "https://hooks.slack.com/services/YOUR-SLACK-WEBHOOK-INCOMING-URL"
jsonheaders = {'content-type': 'application/json'}
thismonth = datetime.now().strftime("%Y-%m-%d")
polisquery = {"locationname":"Solna;Täby;Järfälla;Ekerö;Haninge:Sollentuna;Sundbyberg;Vallentuna;Lidingö","DateTime":thismonth}
logging.info('Before polis-request')
polisrapport = requests.request("GET", polisurl, params=polisquery)
with Cache('.polisidcache') as idcache:
for pr in polisrapport.json():
prid = pr['id']
if prid in idcache:
logging.info(f"{prid} finns i min cache, skriver inte ut")
else:
logging.info(f"{prid} finns inte min cache, skickar till slack")
idcache.set(pr['id'], True, expire=172800)
jsontext = {"attachments": [ { "pretext": pr['name'], "fallback": pr['summary'],
"title": pr['type'],"text": pr['summary'] + "\n" + pr['url']} ] }
response = requests.request("POST", slackurl, data=json.dumps(jsontext), headers=jsonheaders)
idcache.expire()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment