使用 Tweepy 的自动直接消息响应

Automated Direct Message Response using Tweepy

我目前正在使用 python 中的 tweepy 包作为 DM 侦听器。我希望在收到他们的消息时向发件人发送回复。我有以下内容:

class StdOutListener( StreamListener ):
    def __init__( self ):
        self.tweetCount = 0

    def on_connect( self ):
        print("Connection established!!")

    def on_disconnect( self, notice ):
        print("Connection lost!! : ", notice)

    def on_data( self, status ):
        status = str(status)
        try:
            json_acceptable_string = status.replace('\','')
            #string to dict
            status=json.loads(json_acceptable_string)
            if 'direct_message' in status.keys():
                print '\n'
                print status[u'direct_message'][u'sender_screen_name'] +' sent: '+ status[u'direct_message'][u'text']
                message=str(status[u'direct_message'][u'text'])
                api.send_direct_message(screen_name=str(status[u'direct_message'][u'sender_screen_name']),text='Out of office now - will respond to you asap')
                print 'auto response submitted'
            else:
                #not direct message flow
                pass
        except:
            #not important flows - couldn't convert to json/not correct flow in stream
            pass
        return True

def main():
    global api
    try:
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.secure = True
        auth.set_access_token(access_token, access_token_secret)
        api = API(auth)
        print(api.me().name)
        stream = Stream(auth, StdOutListener())
        stream.userstream()

    except BaseException as e:
        print("Error in main()", e)

if __name__ == '__main__':
    main()

出于某种原因,我可以看到用户的打印语句以及他们发送的内容,但是当它到达 send_direct_message 方法时挂起。 奇怪的是,如果我给自己发消息,我会在循环时收到一连串的消息。这是因为它是 on_data() 吗?我怎样才能让其他发件人使用它?

更新:已解决 - 重新生成令牌并添加条件以检查发件人,基本上将我自己列入黑名单。

更新:已解决 - 重新生成令牌并添加条件以检查发件人,基本上将我自己列入黑名单。