Monday, March 15, 2010

The Middleman knows your name!

I modified @fakemiddleman so that some quotes can contain place holders to be filled in while running. The only one that I've implemented is a name token that gets replaced with the screen name of someone who follows @fakemiddleman. The code for creating a list of all the users that follow you was new to me and I thought I'd post a version of it here as an example. The function returns a random follower and rebuilds the list of followers any time the number of followers that the user has doesn't match the length of the local list. The list is built by paging through http://api.twitter.com/statuses/followers.json with a cursor. The cursor is required for long lists of followers since there's a maximum number of records that will be returned on each request.

import twitter, random

FOLLOWERS = []
def get_name():
    global FOLLOWERS
    api = twitter.Twitter("user", "pass")
    num_followers = api.users.show(\
                      screen_name =\
                      'fakemiddleman')
    if num_followers != len(FOLLOWERS):
        FOLLOWERS = []
        next_cursor = -1
        while next_cursor != 0:
            res = api.statuses.followers(\
                    screen_name='fakemiddleman',\
                    cursor=str(next_cursor))
            for u in res['users']:
                FOLLOWERS.append(u['screen_name'])
            next_cursor = res['next_cursor']
    if len(FOLLOWERS) == 0:
        return "Dubbie"
    return random.choice(FOLLOWERS)


P.S Does anyone know a good way to format code snippets for posting on a blog?

No comments:

Post a Comment