(in-package :passepartout) (defun discord-get-token () (vault-get-secret :discord)) (defun discord-send (action context) "Sends a message via Discord REST API." (declare (ignore context)) (let* ((payload (getf action :payload)) (meta (getf action :meta)) (channel-id (or (getf meta :channel-id) (getf payload :chat-id))) (text (or (getf payload :text) (getf action :text))) (token (discord-get-token))) (when (and token channel-id text) (handler-case (dex:post (format nil "https://discord.com/api/v10/channels/~a/messages" channel-id) :headers '(("Authorization" . ,(format nil "Bot ~a" token)) ("Content-Type" . "application/json")) :content (cl-json:encode-json-to-string `((content . ,text)))) (error (c) (log-message "DISCORD ERROR: ~a" c)))))) (defun discord-poll () "Polls Discord via HTTP GET /channels/{id}/messages. In production, a WebSocket connection to the Gateway is preferred for real-time events." (let* ((token (discord-get-token))) (when token (handler-case (dolist (channel '("channel-id-here")) ;; configured channel IDs (let* ((last-id (getf (gethash "discord" *gateway-configs*) :last-update-id 0)) (url (format nil "https://discord.com/api/v10/channels/~a/messages?after=~a" channel last-id)) (response (dex:get url :headers `(("Authorization" . ,(format nil "Bot ~a" token)))))) (let ((messages (ignore-errors (cdr (assoc :message (cl-json:decode-json-from-string response)))))) (dolist (msg (and (listp messages) messages)) (let* ((id (cdr (assoc :id msg))) (content (cdr (assoc :content msg))) (author (cdr (assoc :author msg))) (author-id (cdr (assoc :id author))) (is-bot (cdr (assoc :bot author)))) (when (and id content (not is-bot)) (setf (getf (gethash "discord" *gateway-configs*) :last-update-id) id) (unless (ignore-errors (hitl-handle-message content :discord)) (stimulus-inject (list :type :EVENT :meta (list :source :discord :chat-id channel) :payload (list :sensor :user-input :text content)))))))))) (error (c) (log-message "DISCORD POLL ERROR: ~a" c))))))