Tag Twitter

Posts: 11

A Twitter Bot in Groovy Script - Part 2

Just a quick update.

I'm trying to integrate my R2D2 Groovy Script into RapidMiner but I've run into problems. Originally I tried to copy and paste the groovy script from my last post directly into the Execute Script operator in RapidMiner (v7.2) but when I executed it, it failed. It gave me Classpath errors and problems calling the TwitterFactory Class.

I had installed the Twitter4j JAR file into my /lib directory and checked all my environmental path configurations. I was going nuts until I asked Helge from our Support group.

It turns out that many Java related security enhancements were made in RapidMiner v7.2. Most notably was the disabling of "reflection" which is used by the TwitterFactory class in Twitter4j. This is what cause it blow up when I executed it.

Helge suggested to try it with version 7.1, and I did. It worked perfectly.

So what to do now? Either I build the entire Twitter Bot by hand in Groovy or I just go back to my Python one.

Decisions.

comments

A Twitter Bot in Groovy Script - Part 1

For the last two years I've been working with the Twython package to build my (R2D2) Twitter Bot. It's been successful and I've learned how to hack Python better than I ever did before.

Now I'm setting my sites on building a Twitter Bot using Groovy Script. Why Groovy Script? Groovy is a lot like Python in the sense that it's a dynamic programming language. It can be used everywhere, easily, because of the JVM. Plus, I always wanted to teach myself Java so I thought this is a good way to get started.

Of course you can argue that I should just jump into Java but this feels more fun right now. I always learn better if I have a fun little project to work on, so I want to rebuild my R2D2 Bot in Groovy.

Hello World!

Everyone starts with "Hello World" and I did too. The simple program looks different and a bit more complex than python.

In Python it's:

print "R2D2 says hi!"

In Groovy Script it's way more complex. I have to create an R2D2 class, tell the class that it will be using strings, and then print my "hello world-ish" message.

class R2D2 {
    static void main (String[] args){
        print ("R2D2 says hi!");
    }

Posting a Tweet

After I finished that introductory task, I then started to scour the Internet for a Twython like Java package. I discovered Twitter4j.

At first glance it reminded me of the Twython package but it seemed a lot harder - at first. It wasn't until I started poking through the example code and questions on Stackflow that I found a script I could modify. Note: This is not my script 100%, I'll give attribution to the author when I figure out where I got it from again. The closest post I got is this one.

The first thing I needed to do was download the Twitter4j package and I discovered a handy way to do just that. I just added

@Grab(group="org.twitter4j", module="twitter4j-core", version="4.0.4")

to the top of my script and everytime it runs it will download the twitter4j-core JAR. Probably not a good thing to do everytime but I'm just learned how to do this. In the future I'll make sure that it's already downloaded and properly referenced in the script.

Next I had to import the methods I was going to use. The methods are ".Status," ".Twitter,", ".TwitterFactory," etc. This is just the same as it is in Python when I want to import only select modules into the script. Note: a key one is the ".ConfigurationBuilder" which is what you need to do the Twitter OAuth stuff.

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

The orignal author of this script then creates a class called TweetMain. He tells the class that he's going use some strings and assign them to the ConfigurationBuilder method. Those strings happen to be ConsumerKey, ConsumerSecret, OAuthAccessToken, and OAuthAccessSecret, also known as your Twitter keys. All those keys are needed to auto post to Twitter and you can get this info from apps.twitter.com.

What happens next is opening a connection to Twitter by using the TwitterFactory method and passing the keys to Twitter. Once the instance is established then you can use the ".Status" method to post your tweet and then print out to your console that the status was successfully updated.

The Final Script

The final script looks like this:

@Grab(group="org.twitter4j", module="twitter4j-core", version="4.0.4")

import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TweetMain {
    public static void main(String[] args) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true)
        .setOAuthConsumerKey("XXXXX")
        .setOAuthConsumerSecret("XXXXXX")
        .setOAuthAccessToken("XXXXXXX")
        .setOAuthAccessTokenSecret("XXXXXXXX");


        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();     
        Status status;
        try {
            status = twitter.updateStatus("R2D2 loves #GroovyScript");
            System.out.println("Successfully updated the status to [" + status.getText() + "].");
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

You'll have to replace the "XXXX's" with your own Twitter keys but this test script works.

The next task is to have Groovy open a text file, randomly parse a line and post that as a Tweet. That'll be Part 2 when I figure out how to do it.

comments

A Simple Blog Post Tweeter

I continue on my journey to rebuild this blog's traffic. One idea I had was to build a simple Python based blog post tweeter. I would select a blog post at random and then tweet it to my @neuralmarket Twitter account. I chose Python because of the Twython package. It made for a simple connection to my Twitter account and was easy to parse a text file.

The idea was this. I create a text file of all the blog posts I want to retweet - appended with a bit.ly link - and write a catchy tweet. I would then run the Python script to select at random a pre-written tweet from the text file. When I'm ready, I can cron job this script and run it once or twice a day. Over time I can add or delete pre-written tweets or try to optimize them for SEO.

I suggest that all my readers try this, it's not hard and is simple to follow.

The Twitter Token

First you have to get a Twitter token. This allows you the Python script to post on your behalf and there are four bits of information you need. First visit dev.twitter.com and navigate to the application owner access token page. There you can learn on how to make a single application and generate the follow api values:

  1. Consumer Key

  2. Consumer Secret

  3. Access Token

  4. Access Token Secret

You'll need these four items for the Python script below.

The text file

Next, create a simple text file (TXT extension) and put a single tweet per line. Make sure to add your blog post link. I use bit.ly to shorten my long URLs.

Here's an example of my text file:

Autogenerate Blog Posts with .@Rapidminer http://bit.ly/1RRb0Hd

A simple Stock Trend Following model in .@Rapidminer http://bit.ly/1UjDta0

What does Value really mean? For reals! http://bit.ly/1Y4PaaK

What to expect from being a Sales Engineer at a Startup http://bit.ly/1Y4PR3A

Make sure to save this file in the same directory as your Python script. I keep all my scripts and files in a Dropbox folder so I can access it anywhere.

The Code

Now here's the code. I'm going to "XXX" out my consumer and access keys, you'll have to add your own from the first step above.

#!/usr/bin/env python
import sys
import os
import random

from twython import Twython, TwythonError

CONSUMER_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXXXXX'
ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXXXX'
ACCESS_SECRET = 'XXXXXXXXXXXXXXXXXXXXXX'

#Use the following path structure for linux machine

#f = open('/home/path/to/tweet.txt', 'r')

#Use the following path structure for a windows machine

f = open('C:\\path\\to\\tweet.txt', 'r')

lines = f.readlines()
f.close()

post = random.choice(lines)

api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

try: 
    api.update_status(status="R2D2 says: " + post)
except TwythonError as e:
    print e

It's as simple as that. Just remember you need to install the Twython package and I wrote this script in Python v2.7. Any questions, just drop me a comment.

comments

My latest Twitter "Likes"

https://www.youtube.com/watch?v=U1DMrt8dhn4

NSFW: I know this isn't a Twitter Like, but a blast from the past. This is not me. lol

Must read.

comments