Learning Python Network Programming

(Sean Pound) #1

APIs in Action


'status': text,
'in_reply_to_status_id': reply_to_id}
url = 'https://api.twitter.com/1.1./statuses/update.json'
response = requests.post(url, params=params, auth=auth_obj)
response.raise_for_status()

And add this below the print() call at the end of process_tweet(), at the same
indentation level:


post_reply(tweet['id'], reply, auth_obj)

Now, if you run this and then check your test account's Twitter notifications,
you will see some replies.


The post_reply() function just calls the endpoint by using the following
parameters to inform Twitter on what to post:



  • status: This is the text of our reply tweet.

  • in_reply_to_status_id: This is the ID of the tweet that we're replying to.
    We supply this so that Twitter can link the tweets as a conversation.


When testing this, we might get some 403 status code responses. This is okay, it's just
that Twitter refuses to let us post two tweets with identical text in a row, which we
may find happens with this set up, depending on what test tweets we send.


Final touches


The building blocks are in place, and we can add our main loop to make the program
a daemon. Add the time module to the imports at the top, and then change the main
section to what is shown here:


if __name__ == '__main__':
auth_obj = init_auth()
since_id = 1
error_count = 0
while error_count < 15:
try:
for tweet in get_mentions(since_id, auth_obj):
process_tweet(tweet)
since_id = max(since_id, tweet['id'])
error_count = 0
except requests.exceptions.HTTPError as e:
print('Error: {}'.format(str(e)))
error_count += 1
time.sleep(60)
Free download pdf