import os import requests from pymongo.errors import PyMongoError from requests.exceptions import RequestException from sanic import Blueprint slack_app = Blueprint("slack", __name__) # webhook logs to private channel or "DEV" to print to console. SLACK_DOORLOG_CALLBACK = os.environ["SLACK_DOORLOG_CALLBACK"] def slack_post(msg): if SLACK_DOORLOG_CALLBACK == "DEV": print(f"[DEV SLACK]: {msg}") return try: requests.post(SLACK_DOORLOG_CALLBACK, json={"text": msg}).raise_for_status() except RequestException as e: print(f"[SLACK]: {e}") def approvedStr(approved: bool) -> str: if approved: return "Permitted" return "Denied" # consumes SLACK_DOORLOG_CALLBACK and app.ctx.db async def slack_log(app, loop): pipeline = [ { "$match": { "operationType": "insert", } } ] while True: try: async with app.ctx.db.eventlog.watch(pipeline) as stream: async for event in stream: ev = event["fullDocument"] msg = "%s %s access for %s via %s" % ( approvedStr(ev["approved"]), ev["door"], ev["user"]["name"], ev("method"), ) slack_post(msg) except PyMongoError as e: print(e)