google.lisp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. (in-package #:chatikbot)
  2. (defparameter +google-search-url+ "http://www.google.com/search")
  3. (defun google-search (query)
  4. (loop
  5. for result across (clss:select ".g" (xml-request +google-search-url+
  6. :parameters (list (cons "q" query)
  7. (cons "hl" "en"))))
  8. for a = (ignore-errors (elt (clss:select ".r>a" result) 0))
  9. for uri = (and a (quri:uri (plump:get-attribute a "href")))
  10. for q = (and uri (aget "q" (quri:url-decode-params (quri:uri-query uri))))
  11. when (and q (equal (quri:uri-path uri) "/url"))
  12. collect (list
  13. (cons :url q)
  14. (cons :title (select-text "" a))
  15. (cons :desc (select-text ".st" result)))))
  16. (defun google-format-search-results (results)
  17. (format nil "~{~A. ~A~^~%~}"
  18. (loop for i from 1
  19. for result in results
  20. append (list i
  21. (format nil "[~A](~A)~@[~% ~A~]"
  22. (aget :title result)
  23. (aget :url result)
  24. (replace-all (aget :desc result)
  25. '(#\Newline) ""))))))
  26. ;;; Hooks
  27. (def-message-cmd-handler handler-cmd-google (:google :g :г :q)
  28. (bot-send-message chat-id
  29. (google-format-search-results
  30. (subseq
  31. (google-search (format nil "~{~A~^ ~}" args))
  32. 0 3))
  33. :parse-mode "markdown"
  34. :disable-web-preview 1))