1
0

foursquare.lisp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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)
  32. (aget "recent"
  33. (%fsq-api-call "checkins/recent"
  34. (list (cons "afterTimestamp" (or after-timestamp "0"))))))
  35. (defun fsq-fetch-new-checkins ()
  36. (let ((recent (fsq-fetch-checkins *fsq-last-timestamp*)))
  37. (when (first recent)
  38. (setf *fsq-last-timestamp* (princ-to-string (1+ (aget "createdAt" (first recent))))))
  39. recent))
  40. (defun fsq-fetch-friends (&optional offset)
  41. (list*
  42. (aget "user" (%fsq-api-call "users/self"))
  43. (aget "items"
  44. (aget "friends"
  45. (%fsq-api-call "users/self/friends"
  46. (list (cons "offset" (or offset "0"))))))))
  47. (defun fsq-format-checkin (checkin &optional with-dates)
  48. (when checkin
  49. (let ((user (aget "user" checkin))
  50. (venue (aget "venue" checkin)))
  51. (format nil "📍 ~@[~A~]~@[ ~A~]~@[ в ~A~]~@[ (~A)~]~@[ 📢 ~A~]~:[~; ~A~]"
  52. (aget "firstName" user) (aget "lastName" user)
  53. (aget "name" venue) (first (aget "formattedAddress" (aget "location" venue)))
  54. (aget "shout" checkin)
  55. with-dates (local-time:format-timestring
  56. nil
  57. (local-time:unix-to-timestamp (aget "createdAt" checkin))
  58. :format '(:year "-" (:month 2) "-" (:day 2) " " (:hour 2) ":" (:min 2)))))))