bot.lisp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. (in-package :cl-user)
  2. (defpackage chatikbot.bot
  3. (:use :cl :chatikbot.utils :chatikbot.macros)
  4. (:import-from :chatikbot.db
  5. :set-setting)
  6. (:import-from :chatikbot.telegram
  7. :telegram-get-updates
  8. :bot-send-message)
  9. (:export :handle-update
  10. :*bot-user-id*
  11. :on-next-message))
  12. (in-package :chatikbot.bot)
  13. (defvar *bot-user-id* nil "Bot user_id")
  14. (defvar *telegram-last-update* 0 "Telegram last update_id")
  15. ;; getUpdates handling
  16. (defun process-updates ()
  17. (loop for update in (telegram-get-updates :offset (and *telegram-last-update*
  18. (1+ *telegram-last-update*))
  19. :timeout 300)
  20. ;; do (setf *telegram-last-update*
  21. ;; (max *telegram-last-update* (aget "update_id" update)))
  22. do (handle-update update)))
  23. (defun handle-update (update)
  24. (log:info update)
  25. (let ((update-id (aget "update_id" update))
  26. (reply-to (agets update "message" "reply_to_message" "from" "id")))
  27. (if (> update-id *telegram-last-update*)
  28. (progn
  29. (if (and reply-to (not (equal reply-to *bot-user-id*)))
  30. (log:info "Reply not to bot")
  31. (loop for (key . value) in update
  32. unless (equal "update_id" key)
  33. do (run-hooks (keyify (format nil "update-~A" key)) value)))
  34. (setf *telegram-last-update* update-id))
  35. (log:warn "Out-of-order update" update-id))))
  36. (defvar *start-message* "Hello" "Welcome message. Override it")
  37. (def-message-cmd-handler handle-start (:start)
  38. (bot-send-message *start-message*))
  39. (def-message-admin-cmd-handler handle-admin-settings (:settings)
  40. (bot-send-message (format nil "~{~{~A~@[ (~A)~]: ~A~}~^~%~}"
  41. (loop for symbol in *settings*
  42. collect (list symbol (documentation symbol 'variable) (symbol-value symbol))))))
  43. (def-message-admin-cmd-handler handle-admin-setsetting (:setsetting)
  44. (let* ((*package* (find-package :chatikbot))
  45. (var (read-from-string (car *args*)))
  46. (val (read-from-string (spaced (cdr *args*)))))
  47. (bot-send-message (format nil "OK, ~A" (set-setting var val)))))
  48. (defvar *chat-next-message-handlers* (make-hash-table) "Out-of-order chat message handler")
  49. (defmacro on-next-message (&body body)
  50. `(setf (gethash *chat-id* *chat-next-message-handlers*)
  51. (lambda () ,@body)))
  52. (def-message-handler chat-next-message-handler (1000)
  53. (let ((handler (gethash *chat-id* *chat-next-message-handlers*)))
  54. (when handler
  55. (remhash *chat-id* *chat-next-message-handlers*)
  56. (handler-case (funcall handler)
  57. (error (e)
  58. (log:error "~A" e)
  59. (bot-send-message (format nil "Ошибочка вышла~@[: ~A~]"
  60. (when (is-admin) e))))))))