Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (54 sloc) 2.44 KB
/* Written by Damián Adams
* Groovy'fied by Søren Berg Glasius
* October 2016
import groovy.json.JsonSlurper
import java.text.SimpleDateFormat
@Grab(group='org.twitter4j', module='twitter4j-core', version='4.0.5')
import twitter4j.Status
import twitter4j.Twitter
import twitter4j.TwitterException
import twitter4j.TwitterFactory
@Grab(group='org.jsoup', module='jsoup', version='1.9.2')
import org.jsoup.Jsoup
final int CHARACTER_LENGTH = 140
// NO need to create on each iteration
Twitter twitter = TwitterFactory.getSingleton()
while(true) {
try {
final String BOARD_NAME = "/r9k/"
println "Retrieving $BOARD_NAME data..."
List threadCatalog = new JsonSlurper().parse(THREAD_CATALOG_REQUEST_URL) // Parses JSONObjects into Maps and JSONArrays into Lists.
// Store all active threads from the board.
List<String> listOfThreads = threadCatalog.collect {
// Get the threads no as a list
// Retrieve all posts from 20% of the most recent threads in the board catalog.
List<String> listOfComments = listOfThreads.take(listOfThreads.size().intdiv(5)).collect { chosenThreadNo ->
threadPageUrl = "${BOARD_NAME}thread/${chosenThreadNo}.json".toURL()
Map threadPage = new JsonSlurper().parse(threadPageUrl)
Thread.sleep(2000) // Respect the 4chan API rules.
// Get comments from the posts as a list
}.flatten().collect {
// Get the text comment
it ? Jsoup.parse(it).text() : it
}.findAll {
// Limit to tweetable comments
it && it.size() <= CHARACTER_LENGTH && !it.contains("www") && !it.contains("http")
// Choose a random comment for Twitter posting.
String chosenComment = listOfComments[new Random().nextInt(listOfComments.size())]
println "${new Date().format('EEE, d MMM yyyy HH:mm:ss Z')} - Updated Twitter status with: $chosenComment"
// Wait for a while (15 mins) until the next tweet.
catch(Exception ex) {
println "Error while retrieving and posting data. Trying again..."