From ca53cd6049af25d89a21243eb9666001cd3497d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ivan=20=C5=A0ari=C4=87?= Date: Sat, 16 Dec 2023 16:36:07 +0100 Subject: [PATCH] switch to thread approach --- main.py | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/main.py b/main.py index d26cc94..22f06f8 100644 --- a/main.py +++ b/main.py @@ -3,9 +3,29 @@ from mongo_client.repository import Repository import os import logging +from threading import Thread from slack_client.slack import SlackClient +class DetectorFacade: + + def __init__(self, detector, slack_verification_token, read_channel): + self.detector = detector + self.slack_verification_token = slack_verification_token + self.read_channel = read_channel + + def process(self, content): + if content["token"] != self.slack_verification_token: + app.logger.info("Invalid token") + return + if "event" in content and "files" in content["event"]: + app.logger.info("Received event contains files") + # TODO: switch to manageable list of channel ids + if content["event"]["channel"] == self.read_channel: + detector.detect(content["event"]["files"][0]["url_private_download"]) + else: + app.logger.info(f'Channel ID {content["event"]["channel"]} is not on read list. Skipping event') + app = Flask(__name__) @@ -21,24 +41,17 @@ slack_client = SlackClient(os.environ['SLACK_API_TOKEN']) repository = Repository(os.environ['MONGO_CONNECTION_STRING']) detector = Detector(os.environ['WRITE_SLACK_CHANNEL_ID'], slack_client, repository) +detector_facade = DetectorFacade(detector, os.environ['SLACK_VERIFICATION_TOKEN'], os.environ['READ_SLACK_CHANNEL_ID']) @app.route('/api/events', methods=['POST']) -async def add_message(): +def add_message(): content = request.get_json(silent=True) app.logger.info("received incoming event %s", content) if content["type"] == "url_verification": # TODO: get token from initial challenge instead of using env variable return content["challenge"] - if content["token"] != os.environ['SLACK_VERIFICATION_TOKEN']: - app.logger.info("Invalid token") - return "Invalid token" - if "event" in content and "files" in content["event"]: - app.logger.info("Received event contains files") - # TODO: switch to manageable list of channel ids - if content["event"]["channel"] == os.environ['READ_SLACK_CHANNEL_ID']: - detector.detect(content["event"]["files"][0]["url_private_download"]) - else: - app.logger.info(f'Channel ID {content["event"]["channel"]} is not on read list. Skipping event') + Thread(target=detector_facade.process, args=(content,)).start() return "OK" + \ No newline at end of file