Last active
February 9, 2016 21:49
-
-
Save jarhoads/2b74a3ce9a0df28462a4 to your computer and use it in GitHub Desktop.
A simple example using the twitter API and a simple Markov generator to create a simple Trump bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package twittergen; | |
import twitter4j.Status; | |
import twitter4j.Twitter; | |
import twitter4j.TwitterException; | |
import twitter4j.TwitterFactory; | |
import java.util.ArrayList; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Random; | |
import textgen.MarkovTextGeneratorLoL; | |
public class GetTimeline { | |
private String user; | |
private List<String> statusTexts; | |
private MarkovTextGeneratorLoL textGen; | |
public final static String URL_REGEX = "https?://\\S+\\s?"; | |
public GetTimeline(String uid){ | |
this.user = uid; | |
Twitter twitter = new TwitterFactory().getInstance(); | |
statusTexts = new LinkedList<String>(); | |
textGen = new MarkovTextGeneratorLoL(new Random()); | |
try { | |
List<Status> statuses; | |
statuses = twitter.getUserTimeline(user); | |
System.out.println("Showing @" + user + "'s user timeline."); | |
for (Status status : statuses) { | |
System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); | |
statusTexts.add(status.getText()); | |
} | |
} catch (TwitterException te) { | |
System.out.println("Failed to get timeline for @" + user + " : " + te.getMessage()); | |
} | |
} | |
public List<String> getStatuses(){ | |
return new ArrayList<String>(statusTexts); | |
} | |
public String generateText(){ | |
StringBuilder trainer = new StringBuilder(); | |
for(String status : statusTexts){ | |
trainer.append(status); | |
} | |
String trainText = trainer.toString().replaceAll(URL_REGEX, ""); | |
textGen.train(trainText); | |
String s = ""; | |
try { | |
s = textGen.generateText(20); | |
} catch (Exception e) { | |
System.out.println("Error thrown. " + e.getMessage()); | |
} | |
return s; | |
} | |
public static void main(String[] args) { | |
String userID = "realDonaldTrump"; | |
GetTimeline trump = new GetTimeline(userID); | |
List<String> trumpisms = trump.getStatuses(); | |
System.out.println(); | |
System.out.println("The following shit has been said by trump in the past few days: "); | |
for(String trumpSaid : trumpisms){ | |
// take out the urls from the donald | |
// comment this out if you want the donald's links | |
String urlregex = GetTimeline.URL_REGEX; | |
trumpSaid = trumpSaid.replaceAll(urlregex, ""); | |
System.out.println(trumpSaid); | |
} | |
System.out.println(); | |
System.out.println("What will Trump say next..."); | |
System.out.println(trump.generateText()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment