Tweeting the Bee Movie one word at a time

I was sitting at work last week and thought that it would be funny to make a Bee Movie Twitter Bot. I really wanted to gain experience working with the Twitter API and was planning on making a simple bot that tweeted out a word occassionally. This sounded fun to play with the API, but then I thought about it and wanted to take it one step further. That's when @BeeMovieByWord was born.

The premise is simple... You tweet at the account, and it will respond with the next word of the script. The bot is actually written in Python and was much simpler than I anticipated.

#!/usr/bin/python
from twitter import *  
import os, json

with open('persistence.json') as data_file:  
    metadata = json.load(data_file)
data_file.close()

with open('script.txt') as script_file:  
    script_words = script_file.readlines()
script_file.close()

with open('pending_tweets.txt') as tweets_file:  
    pending_tweets = tweets_file.readlines()
tweets_file.close()  
pending_tweets = [x.strip() for x in pending_tweets]

nextWordNum = metadata['nextWordNumber']  
lastMentionTweetID = metadata['lastMentionTweetId']  
tweetID = lastMentionTweetID

ACCOUNT = 'BEEMOVIEBYWORD'  
APPLICATION = 'BEEMOVIEBYWORD'

TWITTER_KEY = os.environ[ACCOUNT + '_TWITTER_KEY']  
TWITTER_SECRET = os.environ[ACCOUNT + '_TWITTER_SECRET']  
TWITTER_CONSUMER_KEY = os.environ[APPLICATION + '_TWITTER_CONSUMER_KEY']  
TWITTER_CONSUMER_SECRET = os.environ[APPLICATION + '_TWITTER_CONSUMER_SECRET']

t = Twitter(  
    auth=OAuth(TWITTER_KEY, TWITTER_SECRET, TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET))

# Get your "mentions" timeline
mentions = t.statuses.mentions_timeline(since_id=lastMentionTweetID)

responseTweets = []  
print "New Mentions (" + str(len(mentions)) + ")"  
for mention in reversed(mentions):  
    username = mention['user']['screen_name']
    tweetID = mention['id_str']
    print "@" + username + ": " + mention['text']
    tweetLink = "https://twitter.com/" + username + "/status/" + tweetID
    print tweetLink
    nextWord = script_words[nextWordNum].strip()
    nextWordNum += 1
    responseTweet = nextWord + " " + tweetLink
    print "Response: " + responseTweet
    pending_tweets.append(responseTweet)
    print
print

# Send the first pending tweet
print "Pending Tweets (" + str(len(pending_tweets)) + ")"  
if pending_tweets:  
    firstPending = pending_tweets.pop(0)
    print "sending tweet: " + firstPending
    t.statuses.update(
                status=firstPending)

with open('pending_tweets.txt', 'w') as tweets_file:  
    for tweet in pending_tweets:
        tweets_file.write(tweet + "\n")


# Save the persistence back
persistence = {'lastMentionTweetId': tweetID, 'nextWordNumber': nextWordNum}  
with open('persistence.json', 'w') as f:  
    json.dump(persistence, f)

This source code is also available here as gist on Github.

Try it out! Send a tweet to @BeeMovieByWord