How to Automate Twitter – continued …

English: Python logo Deutsch: Python Logo

English: Python logo Deutsch: Python Logo (Photo credit: Wikipedia)

Pre-warning – I wrote this pretty late at night for me, and it doesn’t actually work at the moment – consider this an Agile release process …

Ok, so here is version 0.01 of the automated Twitter utility (I will be using it to re-publicise this blog entry, along with a couple of others – so this could either be a brilliant advert or a dire warning!1). I’ve changed the frequency criteria somewhat from the original, there are now 24 re-tweets with an hours increase in delay between each ( e.g. tweet, 1 hour, 2 hours, 3 hours up to and including 24 hours – overall this spreads out 24 tweets over 11 days or so ) – I’ll give that a go, and maybe experiment from there. I’ve also included a schedule file reference into the configuration file so that it is easier to change should it be neccesary. The overall lack of semi-colons and brackets has given me a nervous twitch, but other than that, given that I’m pretty new to Python, that was – all in all – not a terrible experience !

#!/usr/bin/env python

##########################
# Python Auto Re-Tweeter #
# (C) Simon Biles 2012   #
# http://www.biles.net   #
##########################
# Version 0.01 -         #
# A first stab at it !   #
##########################

# All those tasty Python imports

import argparse
import datetime
import struct
import sys
import tweepy
from ConfigParser import SafeConfigParser

# Get the command line arguments

parser = argparse.ArgumentParser(description='Regular Tweet Generator.')
parser.add_argument('-s','--schedule', action='store_true', help='Schedule a Tweet for the next 7 days')
parser.add_argument('-r', '--run', action='store_true', help='Run the schedule')
parser.add_argument('-u','--update', action='store_true', help='Update Status Tweet immediately')
parser.add_argument('tweet', nargs='?')
args = parser.parse_args();

# Global variable

time_fmt = "%Y-%m-%d %H:%M"

# Get the config file data

parser = SafeConfigParser()
parser.read('twitter.conf')
CONSUMER_KEY = parser.get('consumer_keys','CONSUMER_KEY')
CONSUMER_SECRET = parser.get('consumer_keys','CONSUMER_SECRET')
ACCESS_KEY = parser.get('access_keys','ACCESS_KEY')
ACCESS_SECRET = parser.get('access_keys','ACCESS_SECRET')
FILE_NAME = parser.get('file_name', 'SCHEDULE_FILE')

# Main body

# Quick Command Line Status Update

if args.run == False and args.schedule == False and args.update == True:
   auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
   auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
   api = tweepy.API(auth)
   api.update_status(sys.argv[1])
   sys.exit()

# Schedule a Tweet by adding it to the schedule file

elif args.run == False and args.schedule == True and args.update == False:
   file_obj = open(FILE_NAME, 'a')
   current = datetime.datetime.now()
   nexttweet = current;
   count = 0
   while (count < 24):
      diff = datetime.timedelta(hours=count)
      nexttweet = nexttweet + diff
      tweettime = nexttweet.strftime(time_fmt) + " " + args.tweet +"\n"
      file_obj.write(tweettime)
      count = count + 1
   file_obj.close 
   sys.exit()# Parse the schedule file and see if anything should have happend within 5 minutes of now.elif args.run == True and args.schedule == False and args.update == False:
   file_obj = open(FILE_NAME, 'r')
   auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
   auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
   api = tweepy.API(auth)
   current = datetime.datetime.now()
   baseformat = "16s 1x"
   for line in file_obj:
      line = line.rstrip('\n')
      numremain = len(line) - struct.calcsize(baseformat)
      lformat = "%s %ds" % (baseformat, numremain)
      tweettime, tweet = struct.unpack(lformat, line)
      linetime = datetime.datetime.strptime(tweettime, time_fmt)
      delta = linetime - current
      if delta <= datetime.timedelta(minutes=5) and delta >= datetime.timedelta(minutes=-5):
         api.update_status(tweet)
   file_obj.close
   sys.exit()

I think that it works ok, I’m going to carry out testing in live – like all good practice guides suggest you shouldn’t ! I’m going to set it to run with the -r command line switch from cron every five minutes.

There are one or two features that I think that I should look into in the near-ish future:

  • Cleaning up the schedule file – obviously it is only going to get longer and longer and thus the program will consume more and more resources as it tries to parse it.
  • I’d like to automate the script so that it monitors my Twitter account for updates from WordPress, and then adds those to the schedule immediately – I’m lazy you see …
  • I’m sure that there are a few better ways of doing things in there, and also there could be a little more in the way of commentary and instruction ( there are also, frankly, one or two bits that work, but that I don’t understand how ! )

Ah well, onward and upward eh 😉


1. Ok, it’s a dire warning … It worked on the command line, honest !

UPDATE: If you decide to go live and test there, you then spend time hurriedly chasing down the bugs in your code which you just posted on your blog so as not to look like a complete berk … You have been warned !

UPDATE 2: Hmmm … Not _actually_ working, that’s a bit lousy … Ah, wait. I think I know what the problem is ! You need to specify the full path to the file in the config as cron doesn’t run in the same path ! Right take 3 !

UPDATE 3: Ok, that didn’t work … Back to the drawing board. Unfortunately I don’t have time now 😦 so I’ll have to come back in another post later … Arrrrggghhh !

Tagged , , , , , , , , ,

One thought on “How to Automate Twitter – continued …

  1. […] in haste repent at leisure ! ( If you don’t know what I’m talking about – see here. ) I’m glad to say that I recently read a book1 on business that suggested that an Agile […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: