Search code examples
pythontwittertweepy

Using tweepy to get a keyword from a specific user


I'm trying to create a listener to a very specific twitter account (mine), so I can do some automation, if I tweet something with a "special" code at the end (could be a character like "…") it will trigger an action, like adding the previous characters to a database.

So, I used Tweepy and I'm able to create the listener, filter keywords and so, but it will filter keywords from all the Tweetverse. This is my code:

import tweepy

cfg = { 
    "consumer_key"        : "...",
    "consumer_secret"     : "...",
    "access_token"        : "...",
    "access_token_secret" : "..." 
    }

auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
api = tweepy.API(auth)

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print(status.text)
        return True

    def on_error(self, status):
        print('error ',status)
        return False

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth=auth, listener=myStreamListener)

myStream.filter(track=['…'])

It will filter all the messages containing a "…" no matter who wrote it, so I added to the last line the parameter follow='' like:

myStream.filter(follow='myTwitterName', track=['…'])

It always gives me a 406 error, if I use myStream.userstream('myTwitterName') it will give me, not just the Tweets I write, but also my whole timeline.

So, what am I doing wrong?

EDIT

I just find my first error. I was using user's screen name, not Twitter ID. Now I got rid of the 406 error, but still doesn't work. I placed the Twitter ID in the follow parameter, but does absolutely nothing. I tried both, with my account and with an account that is too "live", like CNN (ID = 759251), I see new tweets coming in my browser, but nothing on the listener.

If you're interested on knowing your own Twitter ID, I used this service: http://gettwitterid.com/


Solution

  • OK, solved. It was working from the very beggining, I made two mistakes:

    • To solve the 406 error all it has to be done, is to use Twitter id instead of Twitter name.

    • The listener was apparently doing nothing, because I was sending "big" tweets, that is, tweets longer than 140 chars. In this case, you shouldn't use status.text, but status.extended_tweet['full_text']

    • You must check for the existance of the extended_tweet, if it is not in the status received, then you should use the text