使用Tweepy

时间:2015-08-18 23:05:18

标签: python tweepy

我是python的新手,我正在尝试学习如何创建基本的Twitter机器人。我正在尝试使用流API并获取句柄名称。我从文件中检查是否已经对获取的句柄发布了帖子。如果是,那么我忽略了其他我发布。当一个新句柄进来时代码工作,但是当一个重复的句柄到来时,我得到以下错误:

C:\Users\User\Desktop>Stream-Reply_new.py
Traceback (most recent call last):
  File "C:\Users\User\Desktop\Stream-Reply_new.py", line 50, in <module>
    twitter_stream.filter(track=['#musiclovers'])
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 430, in filter
    self._start(async)
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 346, in _start
    self._run()
  File "C:\Python27\lib\site-packages\tweepy\streaming.py", line 286, in _run
    raise exception
NameError: global name 'status' is not defined

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():
    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() :
            pass
        else:
            Append=open('Growth Handles.txt' , 'a' )
            Append.write(f)
            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'])

2 个答案:

答案 0 :(得分:0)

我不是tweepy的专家,但我唯一能看到的地方&#39; status&#39;被用作全局名称,但未定义,是在&#39; check()&#39; function,在哪里尝试检查grep,但状态未定义为全局名称。

也许您应该将状态作为参数发送到此功能 -

if status.user.screen_name in line:

答案 1 :(得分:0)

您可以使用try除外编写代码。

try:
    f=status.user.screen_name
    Append=open('Growth Handles.txt' , 'a' )
    Append.write(f)
    Append.close()
    Reply='@' + f + ' Check out Tomorrowland 2014 Setlist . http://.... '
    api = tweepy.API(auth)
    api.update_status(status=Reply)
    time.sleep(45)
return True
except Exception: 
  pass

这样你就可以处理你的错误,但主程序会因为传递而继续运行。