Browse Source

Fix webhook response and update_id handling

Innokenty Enikeev 9 năm trước cách đây
mục cha
commit
9fba84d25f
2 tập tin đã thay đổi với 15 bổ sung10 xóa
  1. 13 9
      chatikbot.lisp
  2. 2 1
      server.lisp

+ 13 - 9
chatikbot.lisp

@@ -25,7 +25,7 @@
 (with-db (db)
   (run-hooks :db-init))
 
-(defvar *telegram-last-update* nil "Telegram last update_id")
+(defvar *telegram-last-update* 0 "Telegram last update_id")
 
 ;; getUpdates handling
 (defun process-updates ()
@@ -33,18 +33,22 @@
                                                          (1+ *telegram-last-update*))
                                             :timeout 300)
      do (setf *telegram-last-update*
-              (max (or *telegram-last-update* 0)
-                   (aget "update_id" update)))
+              (max *telegram-last-update* (aget "update_id" update)))
      do (handle-update update)))
 
 (defun handle-update (update)
   (log:info update)
-  (let ((reply-to (aget "id" (aget "from" (aget "reply_to_message" (aget "message" update))))))
-    (if (and reply-to (not (equal reply-to (parse-integer *telegram-token* :end (position #\: *telegram-token*)))))
-        (log:info "Reply not to bot")
-        (loop for (key . value) in update
-           unless (equal "update_id" key)
-           do (run-hooks (keyify (format nil "update-~A" key)) value)))))
+  (let ((update-id (aget "update_id" update))
+        (reply-to (aget "id" (aget "from" (aget "reply_to_message" (aget "message" update))))))
+    (if (> update-id *telegram-last-update*)
+        (progn
+          (if (and reply-to (not (equal reply-to (parse-integer *telegram-token* :end (position #\: *telegram-token*)))))
+              (log:info "Reply not to bot")
+              (loop for (key . value) in update
+                 unless (equal "update_id" key)
+                 do (run-hooks (keyify (format nil "update-~A" key)) value)))
+          (setf *telegram-last-update* update-id))
+        (log:warn "Out-of-order update" update-id))))
 
 (def-message-admin-cmd-handler handle-admin-settings (:settings)
   (send-response chat-id

+ 2 - 1
server.lisp

@@ -24,7 +24,8 @@
       (let ((stream (hunchentoot:raw-post-data :want-stream t)))
         (setf *random-state* (make-random-state t))
         (setf (flex:flexi-stream-external-format stream) :utf-8)
-        (handle-update (yason:parse stream :object-as :alist)))
+        (handle-update (yason:parse stream :object-as :alist))
+        "OK")
     (error (e) (log:error e))))
 
 (hunchentoot:define-easy-handler (oauth-handler :uri "/oauth") (code error state)