Learning Python Network Programming

(Sean Pound) #1
Chapter 3


  • 'since_id': This tells Twitter to only return the tweets with IDs above this
    value. Every tweet has a unique 64-bit integer ID, and later tweets have
    higher value IDs than earlier tweets. By remembering the ID of the last tweet
    we process and then passing it as this parameter, Twitter will filter out the
    tweets that we've already seen.


Before running the aforementioned, we want to generate some mentions for our
account so that we have something to download. Log into your Twitter test account
and then create a couple of tweets that contain @username, where you replace
username with your app account's username. After this, when you go into the
Mentions section of the Notifications tab of your app account, you will see
these tweets.


Now, if we run the aforementioned code, then we will get the text of our mentions
printed to screen.


Processing the Tweets


The next step is to parse our mentions and then generate the times that we want
to include in our replies. Parsing is a straightforward process. In this, we just
check the 'text' value of the tweets, but it takes a little more work to generate the
times. In fact, for this, we'll need a database of cities and their time zones. This is
available in the pytz package, which can be found at PyPi. For doing this, install
the following package:


$ pip install pytz


Downloading/unpacking pytz


...


And then, we can write our tweet processing function. Add this function underneath
get_mentions(), and then add datetime and pytz to the list of the imports at the
beginning of the file:


def process_tweet(tweet):
username = tweet['user']['screen_name']
text = tweet['text']
words = [x for x in text.split() if
x[0] not in ['@', '#']]
place = ' '.join(words)
check = place.replace(' ', '_').lower()
found = False
for tz in pytz.common_timezones:
tz_low = tz.lower()
if check in tz_low.split('/'):
Free download pdf