I am using Twython to get a stream of tweets. I used this tutorial, expect that I am not using GPIO.
My code is the following:
import time
from twython import TwythonStreamer
TERMS='#stackoverflow'
APP_KEY='MY APP KEY'
APP_SECRET='MY APP SECRET'
OAUTH_TOKEN='MY OATH TOKEN'
OAUTH_TOKEN_SECRET='MY OATH TOKEN SECRET'
class BlinkyStreamer(TwythonStreamer):
def on_success(self, data):
if 'text' in data:
print data['text'].encode('utf-8')
try:
stream = BlinkyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track=TERMS)
except KeyboardInterrupt
That outputs a stream of all tweets containing #stackoverflow. But I want to output the tweet if it is from a certain user, e.g. #StackStatus.
I am running this on a Raspberry Pi.
How would I do that? Any help is appreciated!
Edit: if there is another, other or easier, way to execute some script when a new tweet is placed by some user, please let me know, this would solve my question as well!
The 'follow' parameter does not work as stated above by teknoboy. Correct usage is with the user's ID, not their screen name. You can get user IDs using http://gettwitterid.com/.
The third parameter available is Location - you can use 1, 2 or 3 of then as desired. They become linked with "OR", not 'AND'.
Example Usage:
SearchTerm = 'abracadabra' # If spaces are included, they are 'OR', ie finds tweets with any one of the words, not the whole string.
Tweeter = '25073877' # This is Donald Trump, finds tweets from him or mentioning him
Place = '"47.405,-177.296,1mi"' # Sent from within 1 mile of Lat, Long
stream.statuses.filter(track=SearchTerm, follow=Tweeter, location=Place)
you should supply the filter with the follow parameter to stream specific users' tweets.
if you wish to only follow one user, you can define
FOLLOW='StackStatus'
and change the appropriate line to
stream.statuses.filter(track=TERMS, follow=FOLLOW)
if you wish to see all the user's tweets, regardless of keyword, you can omit the track parameter:
stream.statuses.filter(follow=FOLLOW)
Related
I'm trying to identify interesting people to follow on Twitter. To do this,
I want to find users who post a tweet containing various keywords and then
filter out users whose bios don't contain certain keywords.
I'm using the following code to identify the tweets, and then automatically
follow the users who tweeted them:
naughty_words = ["example"]
good_words = ["example", "example"]
filter = " OR ".join(good_words)
blacklist = " -".join(naughty_words)
keywords = filter + blacklist
twitter = Twython(consumer_key, consumer_secret, access_token,
access_token_secret)
search_results = twitter.search(q=keywords, count=10)
try:
for tweet in search_results["statuses"]:
try:
st=tweet["entities"]["user_mentions"]
if st != []:
twitter.create_friendship(screen_name=st[0]["screen_name"])
except TwythonError as e:
print(e)
except TwythonError as e:
print(e)
This code is working great, but I want to filter my results more, as this
method returns a lot of users that I don't want to follow! Does anyone know
how I could amend this to include a second filter that looks at users'
bios?
According to the Twitter Doc, you can search for users based on a query string. However, if I check the Twython API documentation, it seems that this call is not directly supported. Tweepy, on the other hand, provides a corresponding method API.search_users, see here.
I don't think that you can search for users and tweets in one request. So might might have to stick to your current tweet search, and check each tweet if you have already seen this users. If not, you have to get the user's profile and check if they satisfy your conditions (probably batches of users to limit the number of API calls).
Edit: You probably can use Twython to search for users as well. While it does not provide a dedicated method, it provides a generic method get where you can make calls to any endpoint. So it might look something like :
get('users/search', params={'q': 'soccer music -sex -porn'})
I haven't tried it myself, but that's what I can get from the Twython Docs.
I am trying to search in twitter using Tython, but it seems that the library has a limitation on 140 characters. With the new feature of python, i.e. 280 characters length, what can one do?
This is not a limitation of Twython. The Twitter API by default returns the old 140-character limited tweet. In order to see the newer extended tweet you just need to supply this parameter to your search query:
tweet_mode=extended
Then, you will find the 280-character extended tweet in the full_text field of the returned tweet.
I use another library (TwitterAPI), but I think you would do something like this using Twython:
results = api.search(q='pizza',tweet_mode='extended')
for result in results['statuses']:
print(result['full_text'])
Unfortunately, I am unable to find anything related "Tython". However, if searching twitter data (in this case posts) and/or gathering metadata is your goal, I would recommend you having a look into the library TwitterSearch.
Here is a quick example from the provided link with searching for Twitter-posts containing the words Gutenberg and Doktorarbeit.
from TwitterSearch import *
try:
tso = TwitterSearchOrder() # create a TwitterSearchOrder object
tso.set_keywords(['Guttenberg', 'Doktorarbeit']) # let's define all words we would like to have a look for
tso.set_language('de') # we want to see German tweets only
tso.set_include_entities(False) # and don't give us all those entity information
# it's about time to create a TwitterSearch object with our secret tokens (API auth credentials)
ts = TwitterSearch(
consumer_key = 'aaabbb',
consumer_secret = 'cccddd',
access_token = '111222',
access_token_secret = '333444'
)
# this is where the fun actually starts :)
for tweet in ts.search_tweets_iterable(tso):
print( '#%s tweeted: %s' % ( tweet['user']['screen_name'], tweet['text'] ) )
except TwitterSearchException as e: # take care of all those ugly errors if there are some
print(e)
I'm trying to write my first twitter bot, and what I specifically want it to do is to reply when a specific user tweets something. Instead of searching for every user that mentions the word 'taco' I want to only search for when a small list of people mention 'taco'. For example, my bot only looks for tweets from Bob and Sue that mention 'taco', but not tweets from Fred. I'm not finding what I need.
From the Tweepy documentation, you should probably use the method API.user_timeline to read a specific user tweets.
API.user_timeline([user_id/screen_name])
Returns the 20 most recent statuses posted from the
authenticating user or the user specified.
Parameters:
user_id – Specifies the ID of the user
screen_name – Specifies the screen name of the user
You could accomplish this through the user timeline API endpoint; however, depending on how many terms and users you want to track, you'd have to worry about rate limits (the user timeline endpoint rate limit is pretty high, 300/app auth/15 mins, 150/user auth/15 mins = 450/15 mins), and also the fact that you'd have to call the endpoint manually at some time interval.
Another way to do this is by using the streaming API endpoint, specifically the user stream. Follow everyone you want to reply to, and then create some rules for specific phrases. As followed users post tweets, they should stream to your user stream endpoint. You'd just have to have a listener running, with some logic for tracked users/phrases.
track = {
'taco': ['Bob', 'Sue'],
'salsa': ['John', 'Steve'],
'guacamole': ['Mary', 'Fred']
}
You'd subclass Tweepy's StreamListener:
class TacoListener(tweepy.StreamListener):
def on_status(self, status):
# Note, I rolled my own Twitter API wrapper, and just had a glance at the Tweepy docs, so some of this syntax might be incorrect, change it as required
# I think Tweepy has syntax like: status.text; I'll just refer to the fields as they appear in the Twitter JSON payload
for k, v in track.items():
if k in status.get('text') and status.get('screen_name') in v:
tweet = ""
for name in v:
tweet += "#" + name
tweet += " are talking about " + k + "! Yum."
api.update_status(status=tweet)
How would I limit the number of results in a twitter search?
This is what I thought would work...tweetSearchUser is user input in another line of code.
tso = TwitterSearchOrder() # create a TwitterSearchOrder object
tso.set_keywords(["tweetSearchUser"]) # let's define all words we would like to have a look for
tso.setcount(30)
tso.set_include_entities(False) # and don't give us all those entity information
Was looking at this reference
https://twittersearch.readthedocs.org/en/latest/advanced_usage_ts.html
tried this, seems like it should work but can't figure out the format to enter the date...
tso.set_until('2016-02-25')
You should use set_count as specified in the documentation.
The default value for count is 200, because it is the maximum of tweets returned by the Twitter API.
I'm new to the tweepy library. I am able to capture a twitter stream if I use a filter like the one shown below, looking for tweets containing the word snow in the text field.
import tweepy
ckey = ''
csecret = ''
atoken = ''
asecret = ''
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["snow"])
However, I don't know how to capture all tweets without doing any filtering. If I leave off the last line of the above code, the program runs, but I don't get any tweets. If I change the track parameter to track=[] or track=[""], I receive an error code of 406 from the Twitter API.
I am using Python 3.4.2.
You can use twitterStream.sample() as the last line for that. It will fetch all the tweets for you.
Dont do a search by location. It would limit out those tweets which dont have geolocation enabled. What I suggest is to use stream.sample() instead. IT doesnt have any necessary parameters. See tweepy docs for more info.
the streaming API can only be used with at least one predicate parameter, as specified in the twitter documentation.
luckily, there's also a locations parameter, and you can pass the value [-180,-90,180,90] to get tweets from every point on earth.
so, in your snippet above, the last line should be:
twitterStream.filter(locations=[-180,-90,180,90])
the only filtering you'll get is that the user must not have turned the geotagging off.