math4tots
math4tots

Reputation: 8869

Writing a notification program using Tweepy

In trying to learn the Python-tweepy api, I put together a little bit of code that tells me if there has been any new tweets within the most recent ~10 second interval (of course, in practice it is more than 10 seconds because code aside from sleep(10) also takes some time to run):

from getApi import getApi
from time import sleep
from datetime import datetime

api = getApi()
top = api.home_timeline()[0].id

while True:
    l = api.home_timeline()
    if top != l[0].id:
        top = l[0].id
        print 'New tweet recognized by Python at: %s' % str(datetime.now())
    sleep(10)

getApi is just a few lines of Python I wrote to manage OAuth using tweepy. The getApi method returns the tweepy api, with my account authenticated.

It seems very inefficient that I would have to ask twitter again and again whether there are any new tweets. Is this how it is normally done? If not, what would be the 'canonical' way to do it?

I would have imagined that there would be some code like:

api.set_home_timeline_handler(tweetHandler)

and tweetHandler would be called whenever there is a new tweet.

Upvotes: 2

Views: 1696

Answers (1)

izeed
izeed

Reputation: 1731

It's the way the twitter API works - you have ask every time you want to know about stuff on twitter. But beware of rate limiting https://dev.twitter.com/docs/rate-limiting every 10 sec is above the max.

Alternatively there is streaming api: https://dev.twitter.com/docs/streaming-api/methods that works like you imagined, but it is for bigger tasks than checking your timeline.

Upvotes: 1

Related Questions