(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 :bot-send-message) (: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) (bot-send-message chat-id *start-message*)) (def-message-admin-cmd-handler handle-admin-settings (:settings) (bot-send-message 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))))) (bot-send-message 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 (remhash chat-id *chat-next-message-handlers*) (handler-case (funcall handler message) (error (e) (log:error "~A" e) (bot-send-message chat-id (format nil "Ошибочка вышла~@[: ~A~]" (when (member chat-id *admins*) e))))))))