groupme.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. from datetime import datetime
  2. import json
  3. import traceback
  4. import asyncio
  5. import logging
  6. import os
  7. import toml
  8. from fastapi import FastAPI, BackgroundTasks, Response
  9. from pydantic import BaseModel
  10. import rollbot
  11. from commands import config
  12. logging.config.fileConfig("logging.conf", disable_existing_loggers=False)
  13. with open(os.environ.get("SECRET_FILE", "secrets.toml"), "r") as sfile:
  14. secrets = toml.load(sfile)
  15. database_file = os.environ.get("DATABASE_FILE", secrets["database_file"])
  16. groupme_bots = secrets["groupme_bots"]
  17. groupme_token = secrets["groupme_token"]
  18. groupme_admins = secrets["admins"]["origin"]
  19. group_admins = secrets["admins"]["channel"]
  20. max_msg_len = 1000
  21. split_text = "\n..."
  22. msg_slice = max_msg_len - len(split_text)
  23. class GroupMeMessage(BaseModel):
  24. sender_id: str
  25. group_id: str
  26. name: str
  27. text: str
  28. created_at: int
  29. attachments: list[dict[str, str]]
  30. class GroupMeBot(rollbot.Rollbot[GroupMeMessage]):
  31. def __init__(self):
  32. super().__init__(config.extend(rollbot.CommandConfiguration(bangs=("!",))), database_file)
  33. def read_config(self, key):
  34. cfg = secrets
  35. for part in key.split("."):
  36. cfg = cfg.get(part, None)
  37. if cfg is None:
  38. return None
  39. return cfg
  40. def parse(self, msg: GroupMeMessage):
  41. return rollbot.Message(
  42. origin_id="GROUPME",
  43. channel_id=msg.group_id,
  44. sender_id=msg.sender_id,
  45. timestamp=datetime.fromtimestamp(msg.created_at),
  46. origin_admin=msg.sender_id in groupme_admins,
  47. channel_admin=msg.sender_id in group_admins.get(msg.group_id, ()),
  48. sender_name=msg.name,
  49. text=msg.text,
  50. attachments=[rollbot.Attachment(d["type"], json.dumps(d)) for d in msg.attachments],
  51. )
  52. async def upload_image(self, data: bytes):
  53. async with self.context.request.post(
  54. "https://image.groupme.com/pictures",
  55. headers={
  56. "Content-Type": "image/png",
  57. "X-Access-Token": groupme_token,
  58. },
  59. data=data,
  60. ) as upload:
  61. upload.raise_for_status()
  62. return (await upload.json())["payload"]["url"]
  63. async def post_message(self, bot_id: str, text: str, attachments: list[dict[str, str]]):
  64. await self.context.request.post(
  65. "https://api.groupme.com/v3/bots/post",
  66. json={
  67. "bot_id": bot_id,
  68. "text": text,
  69. "attachments": attachments,
  70. },
  71. timeout=10,
  72. )
  73. async def respond(self, res: rollbot.Response):
  74. if res.origin_id != "GROUPME":
  75. self.context.logger.error(f"Unable to respond to {res.origin_id}")
  76. return
  77. bot_id = groupme_bots.get(res.channel_id, None)
  78. if bot_id is None:
  79. self.context.logger.error(f"Unable to respond to group {res.channel_id} in GroupMe")
  80. return
  81. message = ""
  82. attachments = []
  83. try:
  84. for att in res.attachments:
  85. if att.name == "image":
  86. if isinstance(att.body, bytes):
  87. attachments.append(
  88. {
  89. "type": "image",
  90. "url": await self.upload_image(att.body),
  91. }
  92. )
  93. else:
  94. attachments.append({"type": "image", "url": att.body})
  95. except:
  96. self.context.debugging = "".join(traceback.format_exc())
  97. message += "Failed to upload one or more attachments!\n"
  98. self.context.logger.exception("Failed to upload attachment")
  99. if res.text is not None:
  100. message += res.text
  101. msgs = []
  102. while len(message) > max_msg_len:
  103. msgs.append(message[:msg_slice] + split_text)
  104. message = message[msg_slice:]
  105. msgs.append(message)
  106. await self.post_message(bot_id, msgs[0], attachments)
  107. for m in msgs[1:]:
  108. await asyncio.sleep(0.1)
  109. await self.post_message(bot_id, m, [])
  110. app = FastAPI()
  111. bot = GroupMeBot()
  112. @app.on_event("startup")
  113. async def startup():
  114. await bot.on_startup()
  115. @app.on_event("shutdown")
  116. async def shutdown():
  117. await bot.on_shutdown()
  118. @app.post("/", status_code=204)
  119. async def receive(message: GroupMeMessage, tasks: BackgroundTasks):
  120. tasks.add_task(bot.on_message, message)
  121. return Response(status_code=204)
  122. @app.get("/health", status_code=204)
  123. def health():
  124. return Response(status_code=204)