Skip to content

Instantly share code, notes, and snippets.

@samn
Last active October 16, 2019 22:11
Show Gist options
  • Save samn/6231768 to your computer and use it in GitHub Desktop.
Save samn/6231768 to your computer and use it in GitHub Desktop.
Using the Twitter API with Clojure
(ns media-dog
(:require [twitter.oauth :as oauth]
[twitter.callbacks.handlers :as handlers]
[twitter.api.streaming :as streaming]
[cheshire.core :as json])
(:import (twitter.callbacks.protocols AsyncStreamingCallback)))
(def creds (oauth/make-oauth-creds
; consumer key
"CDdirssorFxBYmWWQmM1xw"
; consumer secret
"BUZF55CDKbKjRby4a5Fh5e3TAA6Y5aUSFF6cCQzduGk"
; user access token
""
; user access token secret
""))
(defn on-bodypart
"A streaming on-bodypart handler.
baos is a ByteArrayOutputStream. (str baos) is the response body (encoded as JSON).
This handler will print the expanded media URL of Tweets that have media."
[response baos]
;; parse the tweet (true means convert to keyword keys)
(let [tweet (json/parse-string (str baos) true)
;; retrieve the media array from the tweet.
;; see https://dev.twitter.com/docs/tweet-entities
media (get-in tweet [:entities :media])
urls (map :expanded_url media)]
;; doseq can include a conditional inline with its binding
;; we'll only iterate and print when urls isn't empty
(doseq [url urls :when (not (empty? urls))]
(println url))))
handlers/exception-print
;; print out API errors
handlers/get-twitter-error-message
;; construct a response handler:
;; see https://github.com/adamwynne/twitter-api/blob/master/src/twitter/callbacks/handlers.clj
;; for the handler code
(def async-streaming-callback
(AsyncStreamingCallback.
;; our custom handler, it's called for each Tweet that comes in from the Streaming API.
on-bodypart
; return the Twitter API error message on failure
handlers/get-twitter-error-message
;; just print exceptions to the console when there's an exception
handlers/exception-print))
(defn -main
"The main function for this ns (like public static void main in Java).
query is a command line argument and is used to filter tweets containing that String.
Try dogs :) :) :)"
[query]
(println "Printing media urls for tweets containing" query)
(streaming/statuses-filter :oauth-creds creds :callbacks async-streaming-callback :params {:track query}))
(defproject class3 "0.1.0-SNAPSHOT"
:description "Prints media urls from tweets matching a query."
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
;; media-dog/-main is run when you do `lein run`
:main media-dog
:dependencies [[org.clojure/clojure "1.5.1"]
[twitter-api "0.7.4"]
[cheshire "5.2.0"]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment