2012-05-07 42 views
1

在努力學習Python的tweepy API的通知程序,我放在一起的代碼一點點,告訴我,如果有內部一直在最近的10秒的時間間隔(中〜當然,任何新的鳴叫,在實踐中,超過10秒,因爲代碼除了sleep(10)還需要一些時間來運行):編寫使用Tweepy

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是Python短短的幾行,我寫使用tweepy管理的OAuth。 getApi方法返回tweepy api,並通過我的帳戶進行身份驗證。

似乎非常低效的,我將不得不到Twitter一次又一次地詢問是否有新的鳴叫。這是通常的做法嗎?如果不是,那麼「規範」的方式是什麼?

我想象會有一些這樣的代碼:

api.set_home_timeline_handler(tweetHandler) 

,每當有一個新的鳴叫tweetHandler將被調用。

回答

1

這就是twitter API的工作方式 - 每當你想要了解Twitter上的內容時,你都會問。但要小心每10秒限速https://dev.twitter.com/docs/rate-limiting高於最大值。

或者有流API:https://dev.twitter.com/docs/streaming-api/methods的作品像你想象中的,但它是比檢查你的時間表更大的任務。