chatikbot.lisp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. (in-package #:chatikbot)
  2. (defvar *admins* nil "Admins chat-ids")
  3. ;; Load config file
  4. (alexandria:when-let (file (probe-file
  5. (merge-pathnames "config.lisp"
  6. (asdf:component-pathname
  7. (asdf:find-system '#:chatikbot)))))
  8. (load file))
  9. ;; Init database
  10. (db-init)
  11. ;; Load settings
  12. (load-settings)
  13. ;; Load plugins
  14. (defsetting *plugins* nil "List of enabled plugins")
  15. (dolist (plugin *plugins*)
  16. (handler-case
  17. (load (merge-pathnames (format nil "~A.lisp" plugin)
  18. (asdf:component-pathname
  19. (asdf:find-system '#:chatikbot))))
  20. (error (e) (log:error e))))
  21. ;; Init plugin's database
  22. (with-db (db)
  23. (run-hooks :db-init db))
  24. (defvar *telegram-last-update* nil "Telegram last update_id")
  25. ;; getUpdates handling
  26. (defun process-updates ()
  27. (loop for update in (telegram-get-updates :offset (and *telegram-last-update*
  28. (1+ *telegram-last-update*))
  29. :timeout 300)
  30. do (setf *telegram-last-update*
  31. (max (or *telegram-last-update* 0)
  32. (aget "update_id" update)))
  33. do (handle-update update)))
  34. (defun handle-update (update)
  35. (log:info update)
  36. (loop for (key . value) in update
  37. unless (equal "update_id" key)
  38. do (run-hooks (string-to-event (format nil "update-~A" key)) value)))
  39. (defcron process-watchdog ()
  40. (close
  41. (open (merge-pathnames ".watchdog"
  42. (asdf:component-pathname
  43. (asdf:find-system '#:chatikbot)))
  44. :direction :output
  45. :if-exists :supersede
  46. :if-does-not-exist :create)))
  47. (defun cleanup ()
  48. ;; Clear prev threads
  49. (mapc #'trivial-timers:unschedule-timer (trivial-timers:list-all-timers))
  50. (let ((old-updates (find "process-updates"
  51. (bordeaux-threads:all-threads)
  52. :key #'bordeaux-threads:thread-name
  53. :test #'equal)))
  54. (when old-updates
  55. (bordeaux-threads:destroy-thread old-updates))))
  56. (defun start ()
  57. (cleanup)
  58. ;; Run 'starting' hooks to set up schedules
  59. (run-hooks :starting)
  60. ;; Start getUpdates thread
  61. (bordeaux-threads:make-thread
  62. (lambda () (loop-with-error-backoff #'process-updates))
  63. :name "process-updates")
  64. ;; Notify admins
  65. (dolist (admin *admins*)
  66. (telegram-send-message admin (format nil "chatikbot started at ~A" (format-ts (local-time:now))))))