butterrobot/butterrobot/app.py

74 lines
2.2 KiB
Python
Raw Normal View History

2020-04-22 21:58:06 +00:00
import traceback
2020-10-28 10:19:30 +00:00
from flask import Flask, request
2020-04-22 21:58:06 +00:00
import structlog
import butterrobot.logging # noqa
from butterrobot.config import ENABLED_PLUGINS
2020-08-11 10:57:56 +00:00
from butterrobot.objects import Message
2020-04-22 21:58:06 +00:00
from butterrobot.plugins import get_available_plugins
from butterrobot.platforms import PLATFORMS
from butterrobot.platforms.base import Platform
logger = structlog.get_logger(__name__)
2020-10-28 10:19:30 +00:00
app = Flask(__name__)
2020-04-22 21:58:06 +00:00
available_platforms = {}
plugins = get_available_plugins()
2020-08-11 11:29:24 +00:00
enabled_plugins = [
plugin for plugin_name, plugin in plugins.items() if plugin_name in ENABLED_PLUGINS
]
2020-04-22 21:58:06 +00:00
2020-10-28 10:19:30 +00:00
def handle_message(platform: str, message: Message):
for plugin in enabled_plugins:
2020-10-28 10:19:30 +00:00
for response_message in plugin.on_message(message):
available_platforms[platform].methods.send_message(response_message)
2020-10-28 10:19:30 +00:00
@app.before_first_request
def init_platforms():
2020-04-22 21:58:06 +00:00
for platform in PLATFORMS.values():
logger.debug("Setting up", platform=platform.ID)
try:
2020-10-28 10:19:30 +00:00
platform.init(app=app)
2020-04-22 21:58:06 +00:00
available_platforms[platform.ID] = platform
logger.info("platform setup completed", platform=platform.ID)
2020-08-07 12:50:34 +00:00
except platform.PlatformInitError as error:
logger.error("Platform init error", error=error, platform=platform.ID)
2020-04-22 21:58:06 +00:00
@app.route("/<platform>/incoming", methods=["POST"])
@app.route("/<platform>/incoming/<path:path>", methods=["POST"])
2020-10-28 10:19:30 +00:00
def incoming_platform_message_view(platform, path=None):
2020-04-22 21:58:06 +00:00
if platform not in available_platforms:
return {"error": "Unknown platform"}, 400
try:
2020-10-28 10:19:30 +00:00
message = available_platforms[platform].parse_incoming_message(
2020-08-11 11:29:24 +00:00
request=request
)
2020-04-22 21:58:06 +00:00
except Platform.PlatformAuthResponse as response:
return response.data, response.status_code
except Exception as error:
2020-08-11 11:29:24 +00:00
logger.error(
"Error parsing message",
2020-08-11 11:29:24 +00:00
platform=platform,
error=error,
traceback=traceback.format_exc(),
)
2020-04-22 21:58:06 +00:00
return {"error": str(error)}, 400
2020-08-11 11:37:17 +00:00
if not message or message.from_bot:
2020-04-22 21:58:06 +00:00
return {}
2020-10-28 10:19:30 +00:00
# TODO: make with rq/dramatiq
handle_message(platform, message)
2020-04-22 21:58:06 +00:00
return {}
@app.route("/healthz")
def healthz():
return {}