1
0

bot.lisp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. :send-response)
  9. (:export :handle-update))
  10. (in-package :chatikbot.bot)
  11. (defvar *telegram-last-update* 0 "Telegram last update_id")
  12. ;; getUpdates handling
  13. (defun process-updates ()
  14. (loop for update in (telegram-get-updates :offset (and *telegram-last-update*
  15. (1+ *telegram-last-update*))
  16. :timeout 300)
  17. ;; do (setf *telegram-last-update*
  18. ;; (max *telegram-last-update* (aget "update_id" update)))
  19. do (handle-update update)))
  20. (defun handle-update (update)
  21. (log:info update)
  22. (let ((update-id (aget "update_id" update))
  23. (reply-to (aget "id" (aget "from" (aget "reply_to_message" (aget "message" update))))))
  24. (if (> update-id *telegram-last-update*)
  25. (progn
  26. (if (and reply-to (not (equal reply-to *bot-user-id*)))
  27. (log:info "Reply not to bot")
  28. (loop for (key . value) in update
  29. unless (equal "update_id" key)
  30. do (run-hooks (keyify (format nil "update-~A" key)) value)))
  31. (setf *telegram-last-update* update-id))
  32. (log:warn "Out-of-order update" update-id))))
  33. (defvar *start-message* "Hello" "Welcome message. Override it")
  34. (def-message-cmd-handler handle-start (:start)
  35. (send-response chat-id *start-message*))
  36. (def-message-admin-cmd-handler handle-admin-settings (:settings)
  37. (send-response chat-id
  38. (format nil "~{~{~A~@[ (~A)~]: ~A~}~^~%~}"
  39. (loop for symbol in *settings*
  40. collect (list symbol (documentation symbol 'variable) (symbol-value symbol))))))
  41. (def-message-admin-cmd-handler handle-admin-setsetting (:setsetting)
  42. (let* ((*package* (find-package :chatikbot))
  43. (var (read-from-string (car args)))
  44. (val (read-from-string (format nil "~{~A~^ ~}" (rest args)))))
  45. (send-response chat-id (format nil "OK, ~A" (set-setting var val)))))