(in-package #:chatikbot) (defvar *admins* nil "Admins chat-ids") ;; Load config file (alexandria:when-let (file (probe-file (merge-pathnames "config.lisp" (asdf:component-pathname (asdf:find-system '#:chatikbot))))) (load file)) ;; Init database (db-init) ;; Load settings (load-settings) ;; Load plugins (defsetting *plugins* nil "List of enabled plugins") (dolist (plugin *plugins*) (handler-case (load (merge-pathnames (format nil "~A.lisp" plugin) (asdf:component-pathname (asdf:find-system '#:chatikbot)))) (error (e) (log:error e)))) ;; Init plugin's database (with-db (db) (run-hooks :db-init db)) (defvar *telegram-last-update* nil "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 (or *telegram-last-update* 0) (aget "update_id" update))) do (handle-update update))) (defun handle-update (update) (log:info update) (loop for (key . value) in update unless (equal "update_id" key) do (run-hooks (string-to-event (format nil "update-~A" key)) value))) (defcron process-watchdog () (close (open (merge-pathnames ".watchdog" (asdf:component-pathname (asdf:find-system '#:chatikbot))) :direction :output :if-exists :supersede :if-does-not-exist :create))) (defun cleanup () ;; Clear prev threads (mapc #'trivial-timers:unschedule-timer (trivial-timers:list-all-timers)) (let ((old-updates (find "process-updates" (bordeaux-threads:all-threads) :key #'bordeaux-threads:thread-name :test #'equal))) (when old-updates (bordeaux-threads:destroy-thread old-updates)))) (defun start () (cleanup) ;; Run 'starting' hooks to set up schedules (run-hooks :starting) ;; Start getUpdates thread (bordeaux-threads:make-thread (lambda () (loop-with-error-backoff #'process-updates)) :name "process-updates") ;; Notify admins (dolist (admin *admins*) (telegram-send-message admin (format nil "chatikbot started at ~A" (format-ts (local-time:now))))))