import atexit from logging.config import dictConfig from threading import Thread import random from flask import Flask, request import requests import requests.exceptions from rollbot import Rollbot, RollbotMessage, RollbotPlugin import plugins import db from config import BOTS_LOOKUP, get_config, get_secret GLOBAL_ADMINS = get_secret("auths.global") GROUP_ADMINS = get_secret("auths.group") dictConfig({ "version": 1, "formatters": {"default": { "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s", }}, "handlers": {"wsgi": { "class": "logging.StreamHandler", "stream": "ext://flask.logging.wsgi_errors_stream", "formatter": "default" }}, "root": { "level": "INFO", "handlers": ["wsgi"] } }) def post_groupme_message(msg, group_id): bot_id = BOTS_LOOKUP[group_id] try: requests.post( "https://api.groupme.com/v3/bots/post", json={ "bot_id": bot_id, "text": msg }, timeout=10 ) except requests.exceptions.Timeout as t: app.logger.error(f"GroupMe timed out sending {msg} as {bot_id}", exc_info=t) except requests.exceptions.HTTPError as h: app.log_exception(h) app = Flask(__name__) app.config["PROPAGATE_EXCEPTIONS"] = True rollbot = Rollbot( logger=app.logger, plugin_classes=RollbotPlugin.find_all_plugins(), aliases=get_config("aliases"), responses=get_config("responses"), sleep_time=float(get_config("sleep_time")), callback=post_groupme_message, session_factory=db.Session ) app.logger.info("Initializing database tables") db.init_db() app.logger.info("Finished initializing database") rollbot.start_plugins() atexit.register(rollbot.shutdown_plugins) @app.route("/", methods=["POST"]) def execute(): json = request.get_json() msg = RollbotMessage.from_groupme(json, global_admins=GLOBAL_ADMINS, group_admins=GROUP_ADMINS) if msg.group_id not in BOTS_LOOKUP: app.logger.warning(f"Received message from unknown group ID {msg.group_id}") return "", 400 t = Thread(target=lambda: rollbot.handle_command(msg)) t.start() return "", 204 @app.route("/health") def health(): return "Rollbot healthy!", 200 if __name__ == "__main__": app.run(host="0.0.0.0", port=6070)