hooks.lisp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. (in-package #:chatikbot)
  2. (defvar *update-hooks* (make-hash-table) "Update hooks storage")
  3. (defun run-update-hooks (hook-name update)
  4. (let ((hooks (gethash hook-name *update-hooks*)))
  5. (labels ((try-handle (func)
  6. (funcall func update)))
  7. (unless (some #'try-handle hooks)
  8. (log:info "unhandled" update)))))
  9. (defun add-update-hook (hook-name handler &optional append)
  10. (let ((existing (gethash hook-name *update-hooks*))
  11. (func (if (functionp handler) handler (symbol-function handler))))
  12. (unless (member func existing)
  13. (setf (gethash hook-name *update-hooks*)
  14. (if append (append existing (list func))
  15. (cons func existing))))))
  16. (defun delete-update-hook (hook-name handler)
  17. (setf (gethash hook-name *update-hooks*)
  18. (remove (if (functionp handler) handler (symbol-function handler))
  19. (gethash hook-name *update-hooks*))))
  20. (defun key-to-hook-name (key)
  21. (intern (string-upcase (substitute #\- #\_ key)) :keyword))
  22. (defmacro def-message-handler (name (message) &body body)
  23. `(progn
  24. (defun ,name (,message)
  25. (let ((message-id (aget "message_id" ,message))
  26. (from-id (aget "id" (aget "from" ,message)))
  27. (chat-id (aget "id" (aget "chat" ,message)))
  28. (text (aget "text" ,message)))
  29. (declare (ignorable message-id from-id chat-id text))
  30. (handler-case (progn ,@body)
  31. (error (e)
  32. (log:error "~A" e)
  33. (bot-send-message chat-id
  34. (format nil "Ошибочка вышла~@[: ~A~]"
  35. (when (member chat-id *admins*) e)))))))
  36. (add-update-hook :message ',name)))
  37. (defmacro def-message-cmd-handler (name (&rest commands) &body body)
  38. `(def-message-handler ,name (message)
  39. (when (and text (equal #\/ (char text 0)))
  40. (multiple-value-bind (cmd args) (parse-cmd text)
  41. (when (member cmd (list ,@commands))
  42. (log:info cmd message-id chat-id from-id args)
  43. ,@body
  44. t)))))