groupme_bot.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import atexit
  2. from logging.config import dictConfig
  3. from threading import Thread
  4. import random
  5. from flask import Flask, request
  6. import requests
  7. import requests.exceptions
  8. from rollbot import Rollbot, RollbotMessage, RollbotPlugin
  9. import plugins
  10. import db
  11. from config import BOTS_LOOKUP, get_config, get_secret
  12. GLOBAL_ADMINS = get_secret("auths.global")
  13. GROUP_ADMINS = get_secret("auths.group")
  14. dictConfig({
  15. "version": 1,
  16. "formatters": {"default": {
  17. "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
  18. }},
  19. "handlers": {"wsgi": {
  20. "class": "logging.StreamHandler",
  21. "stream": "ext://flask.logging.wsgi_errors_stream",
  22. "formatter": "default"
  23. }},
  24. "root": {
  25. "level": "INFO",
  26. "handlers": ["wsgi"]
  27. }
  28. })
  29. max_msg_len = 1000
  30. split_text = "\n..."
  31. msg_slice = max_msg_len - len(split_text)
  32. def post_groupme_message(msg, group_id):
  33. bot_id = BOTS_LOOKUP[group_id]
  34. msgs = []
  35. rem = msg
  36. while len(rem) > max_msg_len:
  37. msgs.append(rem[:msg_slice] + split_text)
  38. rem = rem[msg_slice:]
  39. msgs.append(rem)
  40. for msg in msgs:
  41. try:
  42. requests.post(
  43. "https://api.groupme.com/v3/bots/post",
  44. json={
  45. "bot_id": bot_id,
  46. "text": msg
  47. },
  48. timeout=10
  49. )
  50. except requests.exceptions.Timeout as t:
  51. app.logger.error(f"GroupMe timed out sending {msg} as {bot_id}", exc_info=t)
  52. except requests.exceptions.HTTPError as h:
  53. app.log_exception(h)
  54. app = Flask(__name__)
  55. app.config["PROPAGATE_EXCEPTIONS"] = True
  56. rollbot = Rollbot(
  57. logger=app.logger,
  58. plugin_classes=RollbotPlugin.find_all_plugins(),
  59. aliases=get_config("aliases"),
  60. responses=get_config("responses"),
  61. sleep_time=float(get_config("sleep_time")),
  62. callback=post_groupme_message,
  63. session_factory=db.Session
  64. )
  65. app.logger.info("Initializing database tables")
  66. db.init_db()
  67. app.logger.info("Finished initializing database")
  68. rollbot.start_plugins()
  69. atexit.register(rollbot.shutdown_plugins)
  70. @app.route("/", methods=["POST"])
  71. def execute():
  72. json = request.get_json()
  73. msg = RollbotMessage.from_groupme(json, global_admins=GLOBAL_ADMINS, group_admins=GROUP_ADMINS)
  74. if msg.group_id not in BOTS_LOOKUP:
  75. app.logger.warning(f"Received message from unknown group ID {msg.group_id}")
  76. return "", 400
  77. t = Thread(target=lambda: rollbot.handle_command(msg))
  78. t.start()
  79. return "", 204
  80. @app.route("/health")
  81. def health():
  82. return "Rollbot healthy!", 200
  83. if __name__ == "__main__":
  84. app.run(host="0.0.0.0", port=6070)