Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Our program will be running as a daemon, polling Twitter periodically to see
whether there are any new tweets for us to process and reply to. When we poll the
mentions timeline, we will download any new tweets that were received in a single
batch since our last poll, so that we can process all of them without having to
poll again.


Polling for Tweets


Let's add a function for checking and retrieving new tweets from our mentions
timeline. We'll get this to work before we add the loop. Add the new function
underneath verify_credentials(), and then add a call this function to the main
section, as shown here; also, add json to the list of the imports at the beginning of
the file:


def get_mentions(since_id, auth_obj):
params = {'count': 200, 'since_id': since_id,
'include_rts': 0, 'include_entities': 'false'}
url = 'https://api.twitter.com/1.1/' \
'statuses/mentions_timeline.json'
response = requests.get(url, params=params, auth=auth_obj)
response.raise_for_status()
return json.loads(response.text)

if __name__ == '__main__':
auth_obj = init_auth()
since_id = 1
for tweet in get_mentions(since_id, auth_obj):
print(tweet['text'])

Using get_mentions(), we check for and download any tweets that mention our
app account by connecting to the statuses/mentions_timeline.json endpoint.
We supply a number of parameters, which Requests passes on as a query string.
These parameters are specified by Twitter and they control how the tweets will be
returned to us. They are as follows:



  • 'count': This specifies the maximum number of tweets that will be returned.
    Twitter will allow 200 tweets to be received by a single request made to this
    endpoint.

  • 'include_entities': This is used for trimming down some extraneous
    information from the tweets retrieved.

  • 'include_rts': This tells Twitter not to include any retweets. We don't want
    the user to receive another time update if someone retweets our reply.

Free download pdf