(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) (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))) (defun send-dont-understand (chat-id &optional text reply-id) (let ((resp (eliza text))) (log:info text resp) (when resp (send-response chat-id resp reply-id)))) (defun handle-unknown-message (message) (let ((chat-id (aget "id" (aget "chat" message))) (text (aget "text" message))) (log:info "handle-unknown-message" message) (send-dont-understand chat-id (preprocess-input text)) t)) (add-hook :update-message 'handle-unknown-message t) ;; Schedule (defmacro defcron (name (&rest schedule) &body body) (let ((schedule (or schedule '(:minute '* :hour '*)))) `(progn (defun ,name () (handler-case (progn ,@body) (error (e) (log:error e)))) (add-hook :starting #'(lambda () (clon:schedule-function ',name (clon:make-scheduler (clon:make-typed-cron-schedule ,@schedule) :allow-now-p t) :name ',name :thread t) (values)))))) (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))) (defsetting *plugins* nil "List of enabled plugins") (defun start () ;; 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))) ;; Load 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)))) ;; 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))))))