How to read Twitter's Streaming API and reply an user based on a certain keyword?
<p>I am implementing a Twitter bot for fun purposes using <code>Tweepy</code>.</p>

<p>What I am trying to code is a bot that tracks a certain keyword and based in it the bot replies the user that tweeted with the given string.</p>

<p>I considered storing the Twitter's Stream on a <code>.json</code> file and looping the Tweet object for every user but it seems impractical as receiving the stream locks the program on a loop.</p>

<p>So, how could I track the tweets with the Twitter's Stream API based on a certain keyword and reply the users that tweeted it?</p>

<p>Current code:</p>

<pre><code>    from tweepy import OAuthHandler
    from tweepy import Stream
    from tweepy.streaming import StreamListener

class MyListener(StreamListener):
    def on_data(self, data):
        try:
            with open("caguei.json", 'a+') as f:
                f.write(data)
                data = f.readline()
                    tweet = json.loads(data)
                    text = str("@%s acabou de. %s " % (tweet['user']['screen_name'], random.choice(exp)))
                    tweepy.API.update_status(status=text, in_reply_to_status_id=tweet['user']['id'])
                #time.sleep(300)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True
    def on_error(self, status):
        print(status)
        return True

    api = tweepy.API(auth)
    twitter_stream = Stream(auth, MyListener())

    twitter_stream.filter(track=['dengue']) #Executing it the program locks on a loop
</code></pre>

<p>Tweepy <code>StreamListener</code> class allows you to override it's <code>on_data</code> method. That's where you should be doing your logic.</p>

<p>As per the code</p>

<pre><code>class StreamListener(object):

    ... 

    def on_data(self, raw_data):
        """Called when raw data is received from connection.

        Override this method if you wish to manually handle
        the stream data. Return False to stop stream and close connection.
        """
        ...
</code></pre>

<p>So in your listener, you can override this method and do your custom logic.</p>

<pre><code>class MyListener(StreamListener):

    def on_data(self, data):

         do_whatever_with_data(data)
</code></pre>

<p>You can also override several other methods (<em>on_direct_message</em>, etc) and I encourage you to take a look at the code of <strong>StreamListener</strong>. </p>

<p>Update</p>

<p>Okay, you can do what you intent to do with the following:</p>

<pre><code>class MyListener(StreamListener):

    def __init__(self, *args, **kwargs):
        super(MyListener, self).__init__(*args, **kwargs)
        self.file = open("whatever.json", "a+")

    def _persist_to_file(self, data):
        try:
            self.file.write(data)
        except BaseException:
            pass

    def on_data(self, data):
        try:
            tweet = json.loads(data)
            text = str("@%s acabou de. %s " % (tweet['user']['screen_name'], random.choice(exp)))
            tweepy.API.update_status(status=text, in_reply_to_status_id=tweet['user']['id'])
            self._persist_to_file(data)
            return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True

    def on_error(self, status):
        print(status)
        return True
</code></pre>

python api twitter stream tweepy