groupme.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from datetime import datetime
  2. import json
  3. import traceback
  4. import asyncio
  5. import logging
  6. import toml
  7. from fastapi import FastAPI, BackgroundTasks, Response
  8. from pydantic import BaseModel
  9. import rollbot
  10. from commands import config
  11. logging.config.fileConfig("logging.conf", disable_existing_loggers=False)
  12. with open("secrets.toml", "r") as sfile:
  13. secrets = toml.load(sfile)
  14. groupme_bots = secrets["groupme_bots"]
  15. groupme_token = secrets["groupme_token"]
  16. groupme_admins = secrets["admins"]["origin"]
  17. group_admins = secrets["admins"]["channel"]
  18. max_msg_len = 1000
  19. split_text = "\n..."
  20. msg_slice = max_msg_len - len(split_text)
  21. class GroupMeMessage(BaseModel):
  22. sender_id: str
  23. group_id: str
  24. name: str
  25. text: str
  26. created_at: int
  27. attachments: list[dict[str, str]]
  28. class GroupMeBot(rollbot.Rollbot[GroupMeMessage]):
  29. def __init__(self):
  30. super().__init__(
  31. config.extend(rollbot.CommandConfiguration(bangs=("!",))), "/tmp/rollbot.db"
  32. )
  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)