refactor slack logger

This commit is contained in:
2025-08-07 23:18:45 +03:00
parent 55ca235946
commit 988b7e964e
5 changed files with 91 additions and 12 deletions

43
app/slack.py Normal file
View File

@@ -0,0 +1,43 @@
from pymongo.errors import PyMongoError
from requests.exceptions import RequestException
import os
import requests
SLACK_DOORLOG_CALLBACK = os.environ["SLACK_DOORLOG_CALLBACK"] # webhook logs to private channel or "DEV" to print to console.
def add_slack_routes(app):
app.app.register_listener(slack_log, "after_server_start") # consumes SLACK_DOORLOG_CALLBACK and app.ctx.db
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"
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)