foursquare.lisp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. (handler-case
  11. (bordeaux-threads:with-timeout (5)
  12. (json-request (format nil *fsq-api-url* method)
  13. :parameters (list*
  14. (cons "oauth_token" *fsq-access-token*)
  15. (cons "v" "20150811")
  16. params)))
  17. (bordeaux-threads:timeout () (error "Timeout"))))
  18. (meta (aget "meta" resp)))
  19. (when (not (= 200 (aget "code" meta)))
  20. (error (format nil "Foursquare API error, code ~A, errorType '~A', errorDetail '~A'"
  21. (aget "code" meta) (aget "errorType" meta) (aget "errorDetail" meta))))
  22. (aget "response" resp)))
  23. (defun fsq-fetch-checkins (&optional after-timestamp limit)
  24. (aget "recent"
  25. (%fsq-api-call "checkins/recent"
  26. (list (cons "afterTimestamp" (or after-timestamp "0"))
  27. (cons "limit" (or limit "20"))))))
  28. (defun fsq-fetch-new-checkins ()
  29. (let ((recent (fsq-fetch-checkins *fsq-last-timestamp*)))
  30. (when (first recent)
  31. (setf *fsq-last-timestamp* (princ-to-string (1+ (aget "createdAt" (first recent))))))
  32. recent))
  33. (defun fsq-fetch-friends (&optional offset)
  34. (list*
  35. (aget "user" (%fsq-api-call "users/self"))
  36. (aget "items"
  37. (aget "friends"
  38. (%fsq-api-call "users/self/friends"
  39. (list (cons "offset" (or offset "0"))))))))
  40. (defun fsq-format-checkin (checkin &optional with-dates)
  41. (when checkin
  42. (let ((user (aget "user" checkin))
  43. (venue (aget "venue" checkin)))
  44. (format nil "📍 ~@[~A~]~@[ ~A~]~@[ в ~A~]~@[ (~A)~]~@[ 📢 ~A~]~:[~; ~A~]"
  45. (aget "firstName" user) (aget "lastName" user)
  46. (aget "name" venue) (first (aget "formattedAddress" (aget "location" venue)))
  47. (aget "shout" checkin)
  48. with-dates
  49. (local-time:format-timestring
  50. nil
  51. (local-time:unix-to-timestamp (aget "createdAt" checkin))
  52. :format '(:year "-" (:month 2) "-" (:day 2) " " (:hour 2) ":" (:min 2)))))))