瀏覽代碼

Handling groupme's message length limit

Kirk Trombley 5 年之前
父節點
當前提交
75366b1951
共有 1 個文件被更改,包括 24 次插入13 次删除
  1. 24 13
      src/groupme_bot.py

+ 24 - 13
src/groupme_bot.py

@@ -33,22 +33,33 @@ dictConfig({
     }
 })
 
+max_msg_len = 1000
+split_text = "\n..."
+msg_slice = max_msg_len - len(split_text)
+
 
 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)
+    msgs = []
+    rem = msg
+    while len(rem) > max_msg_len:
+        msgs.append(rem[:msg_slice] + split_text)
+        rem = rem[msg_slice:]
+    msgs.append(rem)
+    for msg in msgs:
+        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__)