1
0

foursquare.lisp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. (in-package #:chatikbot)
  2. (defparameter *fsq-checkins-url* "https://api.foursquare.com/v2/checkins/recent"
  3. "URL of recent checkins API")
  4. (defparameter *fsq-api-url* "https://api.foursquare.com/v2/~A"
  5. "Foursquare API URL")
  6. (defvar *fsq-access-token* nil "Access token for a user under which the process is run")
  7. (defvar *fsq-last-timestamp* nil "Timestamp of the last checkin. To only fetch latest")
  8. (defun %fsq-api-call (method &optional params)
  9. (let* ((resp
  10. (yason:parse
  11. (flexi-streams:octets-to-string
  12. (handler-case
  13. (bordeaux-threads:with-timeout (5)
  14. (drakma:http-request
  15. (format nil *fsq-api-url* method)
  16. :parameters
  17. (list*
  18. (cons "oauth_token" *fsq-access-token*)
  19. (cons "v" "20150811")
  20. params)))
  21. (bordeaux-threads:timeout (e)
  22. (declare (ignore e))
  23. (error "Timeout")))
  24. :external-format :utf-8)
  25. :object-as :alist))
  26. (meta (aget "meta" resp)))
  27. (when (not (= 200 (aget "code" meta)))
  28. (error (format nil "Foursquare API error, code ~A, errorType '~A', errorDetail '~A'"
  29. (aget "code" meta) (aget "errorType" meta) (aget "errorDetail" meta))))
  30. (aget "response" resp)))
  31. (defun fsq-fetch-checkins (&optional after-timestamp limit)
  32. (aget "recent"
  33. (%fsq-api-call "checkins/recent"
  34. (list (cons "afterTimestamp" (or after-timestamp "0"))
  35. (cons "limit" (or limit "20"))))))
  36. (defun fsq-fetch-new-checkins ()
  37. (let ((recent (fsq-fetch-checkins *fsq-last-timestamp*)))
  38. (when (first recent)
  39. (setf *fsq-last-timestamp* (princ-to-string (1+ (aget "createdAt" (first recent))))))
  40. recent))
  41. (defun fsq-fetch-friends (&optional offset)
  42. (list*
  43. (aget "user" (%fsq-api-call "users/self"))
  44. (aget "items"
  45. (aget "friends"
  46. (%fsq-api-call "users/self/friends"
  47. (list (cons "offset" (or offset "0"))))))))
  48. (defun fsq-format-checkin (checkin &optional with-dates)
  49. (when checkin
  50. (let ((user (aget "user" checkin))
  51. (venue (aget "venue" checkin)))
  52. (format nil "📍 ~@[~A~]~@[ ~A~]~@[ в ~A~]~@[ (~A)~]~@[ 📢 ~A~]~:[~; ~A~]"
  53. (aget "firstName" user) (aget "lastName" user)
  54. (aget "name" venue) (first (aget "formattedAddress" (aget "location" venue)))
  55. (aget "shout" checkin)
  56. with-dates (local-time:format-timestring
  57. nil
  58. (local-time:unix-to-timestamp (aget "createdAt" checkin))
  59. :format '(:year "-" (:month 2) "-" (:day 2) " " (:hour 2) ":" (:min 2)))))))