groupme.py 4.3 KB

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