| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- (in-package :cl-user)
- (defpackage chatikbot.bot
- (:use :cl :chatikbot.utils :chatikbot.macros)
- (:import-from :chatikbot.db
- :set-setting)
- (:import-from :chatikbot.telegram
- :telegram-get-updates
- :send-response)
- (:export :handle-update
- :*bot-user-id*
- :on-next-message))
- (in-package :chatikbot.bot)
- (defvar *bot-user-id* nil "Bot user_id")
- (defvar *telegram-last-update* 0 "Telegram last update_id")
- ;; getUpdates handling
- (defun process-updates ()
- (loop for update in (telegram-get-updates :offset (and *telegram-last-update*
- (1+ *telegram-last-update*))
- :timeout 300)
- ;; do (setf *telegram-last-update*
- ;; (max *telegram-last-update* (aget "update_id" update)))
- do (handle-update update)))
- (defun handle-update (update)
- (log:info update)
- (let ((update-id (aget "update_id" update))
- (reply-to (agets update "message" "reply_to_message" "from" "id")))
- (if (> update-id *telegram-last-update*)
- (progn
- (if (and reply-to (not (equal reply-to *bot-user-id*)))
- (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))))
- (defvar *start-message* "Hello" "Welcome message. Override it")
- (def-message-cmd-handler handle-start (:start)
- (send-response chat-id *start-message*))
- (def-message-admin-cmd-handler handle-admin-settings (:settings)
- (send-response chat-id
- (format nil "~{~{~A~@[ (~A)~]: ~A~}~^~%~}"
- (loop for symbol in *settings*
- collect (list symbol (documentation symbol 'variable) (symbol-value symbol))))))
- (def-message-admin-cmd-handler handle-admin-setsetting (:setsetting)
- (let* ((*package* (find-package :chatikbot))
- (var (read-from-string (car args)))
- (val (read-from-string (format nil "~{~A~^ ~}" (rest args)))))
- (send-response chat-id (format nil "OK, ~A" (set-setting var val)))))
- (defvar *chat-next-message-handlers* (make-hash-table) "Out-of-order chat message handler")
- (defmacro on-next-message (chat-id &body body)
- `(setf (gethash ,chat-id *chat-next-message-handlers*)
- (lambda (message)
- (with-parsed-message message
- ,@body))))
- (def-message-handler chat-next-message-handler (message 1000)
- (let ((handler (gethash chat-id *chat-next-message-handlers*)))
- (when handler
- (unwind-protect
- (handler-case (funcall handler message)
- (error (e)
- (log:error "~A" e)
- (send-response chat-id
- (format nil "Ошибочка вышла~@[: ~A~]"
- (when (member chat-id *admins*) e)))))
- (remhash chat-id *chat-next-message-handlers*)))))
|