2015-08-20 93 views
0

我正在學習python,並且在幾個星期前就開始了。我試圖編寫一個代碼來檢查流媒體API中特定hashtag的tweets,然後在tweet以前沒有發佈到句柄的情況下回復tweet。在運行代碼時,我儘量避免超出速率限制,以免發生任何錯誤。但是有一個重複的地位問題,Twitter偶爾會提起一次。我希望代碼能夠繼續運行,而不是在遇到問題時停下來。請幫忙。以下是代碼:在Tweepy中處理錯誤

import tweepy 
from tweepy import Stream 
from tweepy.streaming import StreamListener 
from tweepy import OAuthHandler 
import json 
import time 

consumer_key = 
consumer_secret = 
access_token = 
access_secret = 

auth = OAuthHandler(consumer_key, consumer_secret) 
auth.set_access_token(access_token, access_secret) 

def check(status): 
    datafile = file('C:\Users\User\Desktop\Growth Handles.txt', 'r') 
    found = False 
    for line in datafile: 
     if status.user.screen_name in line: 
      found = True 
      break 
    return found 


class MyListener(StreamListener): 


    def on_status(self, status): 
     f=status.user.screen_name 
     if check(status) : 
      pass 
     else: 
      Append=open('Growth Handles.txt' , 'a') 
      Append.write(f + "\n") 
      Append.close() 
      Reply='@' + f + ' Check out Tomorrowland 2014 Setlist . http://.... ' 
      api = tweepy.API(auth) 
      api.update_status(status=Reply) 
      time.sleep(45) 
     return True 

    def on_error(self, status): 
     print(status) 
     return True 



twitter_stream = Stream(auth, MyListener()) 
twitter_stream.filter(track=['#musiclovers']) 

回答

1

在情況下,update_status方法引發錯誤

try: 
    api.update_status(status=Reply) 
except: 
    pass 

萬一twitter_stream斷開連接。

twitter_stream = Stream(auth, MyListener()) 
while True: 
    twitter_stream.filter(track=['#musiclovers']) 

警告 - 如果達到一定的限度,或者他們的系統抓住你濫發你的應用程序可能會得到禁止。檢查Twitter Rules