Newest tweets on tweepy for python? - python

I'm using tweepy to find tweets containing a certain word, but I want to just get the newest tweets from the last five minutes up. How would I go about this? This is my code at the moment.
import tweepy
consumer_key = "**********"
consumer_secret = "**********"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token("**********", "**********")
api = tweepy.API(auth)
public_tweets = api.search(q = "", since = "2015-09-26", language = "EN")
for tweet in public_tweets:
print(tweet.text)

First of all: I edited your post to remove your credentials, I would suggest you get new ones from twitter and never share them again.
Also change your api.search (Rest API) to the Streaming API. This will give you a portion of tweets that match your criteria for the moment you open that connection.
For example
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
consumer_key = '****'
consumer_secret = '****'
access_token = '****'
access_secret = '****'
class Listener(StreamListener):
def on_status(self, status):
try:
print(str(status.text.encode('utf-8')))
except Exception as e:
print(e)
def on_error(self, status_code):
print(status_code)
while True:
try:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
twitterStream = Stream(auth, Listener())
twitterStream.filter(q=['python'])
except Exception as e:
print(e)

Related

Tweepy StreamListener: Tweet when a specified account Tweets

I have a Twitter bot that is following one specific account.
When that account Tweets, I want my bot to Tweet.
So far I have the below code:
import tweepy
import time
import sys
import inspect
consumer_key = 'xxxxxxx'
consumer_secret = 'xxxxxxxx'
access_token = 'xxxxxxx'
access_token_secret = 'xxxxxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth.secure = True
print "Test Message"
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
if status.user.screen_name.encode('UTF-8').lower() == 'xxxxxx': #account I am following
api.update_status('Test Tweet') # tweet that is sent from my bot
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=MyStreamListener())
myStream.filter(track=['xxxxxx'])
However, when I run this code from the command line, it runs without a problem but does not react to any Tweets from the specified account.
It seems like the if statement within your on_status method isn't properly indented.
If that's not the case, to properly debug this, you need to add an on_error method to your MyStreamListener class so that you're able to determine what, if any, error/status code is being returned by Twitter's API.
See the Handling Errors section of the Streaming With Tweepy documentation.

How to save the result of tweepy filter into a json file?

I'm setting a streaming listener, and then filter the tweets by a specific keyword and the location bounding box, and I want to save the filtering result into a json file.
But I found that all the result from streaming listener is in the json file, not just the filtered results.
I think it probably because the 'save json file' code is in the class Mystreamlistener, and the filtering code is behind it.
But I don't know how to revise my code. Here is my code:
This is my first code:
try:
import json
except ImportError:
import simplejson as json
import tweepy, sys
from time import sleep
import csv
consumer_key = 'XX'
consumer_secret = 'XX'
access_token = 'XX'
access_token_secret = 'XX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
box = [-178.2,6.6,-49.0,83.3]
import tweepy
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text.encode('utf-8'))
with open('government.json', 'a') as f:
tweet=str(status.user)
nPos=tweet.index("_json=")
tweet=tweet[nPos+6:]
ePos=tweet.index("id=")
tweet=tweet[:ePos-2]
f.write(tweet+'\n')
def on_error(self, status_code):
if status_code == 420:
#returning False in on_data disconnects the stream
return False
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(api.auth, listener=myStreamListener)
myStream.filter(track=['trump'], locations=(box))
I already tried the answer from Ajeet Khan in question:
How to save a tweepy Twitter stream to a file?
But I don't know how to call the class, the second code is what I tried according to Ajeet Khan's answer.
try:
import json
except ImportError:
import simplejson as json
import tweepy, sys
from time import sleep
import csv
consumer_key = 'XX'
consumer_secret = 'XX'
access_token = 'XX'
access_token_secret = 'XX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
box = [-178.2,6.6,-49.0,83.3]
import tweepy
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text.encode('utf-8'))
def on_error(self, status_code):
if status_code == 420:
#returning False in on_data disconnects the stream
return False
class StdOutListener(tweepy.StreamListener):
def on_data(self, status):
#print data
with open('fetched_tweets.txt','a') as tf:
tf.write(status)
return True
def on_error(self, status):
print(status)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(api.auth, listener=myStreamListener)
myStream.filter(track=['trump'], locations=(box))
StdOutListener()

Collecting URI's From Tweets

I am currently writing a python program that utilizes Tweepy & the Twitter API, and extracts URI links from tweets on twitter.
This is currently my code. How do I modify it so that it only outputs the URIs from tweets(if there is one included)?
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "-"
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keyword: '#NFL'
twitterator = stream.filter(track=[ '#NFL' ])
for tweet in twitterator:
print "(%s) #%s %s" % (tweet["created_at"], tweet["user"]["screen_name"], tweet["text"])
for url in tweet["entities"]["urls"]:
print " - found URL: %s" % url["expanded_url"]
I've modified your code to only print URLs if present:
#Import the necessary methods from tweepy library
import json
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "-"
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
tweet = json.loads(data)
for url in tweet["entities"]["urls"]:
print " - found URL: %s" % url["expanded_url"]
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keyword: '#NFL'
stream.filter(track=[ '#NFL' ])

How to get last update Twitter API

How to get time last status update on Twitter ? use python and tweepy
help please
These are the commands that I used to read tweets from my personal Twitter account using Python. I hope you can use the same to read the last status update from Twitter.
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python'
stream.filter(track=['python'])

Tweepy filter doesn't work correctly

I try obtain user's tweets by user id via filter method, but I have no results. I saw the same questions on forums, but it doesn't help me. Can someone help me resolve this problem?
my code:
from tweepy import StreamListener
from tweepy import Stream
import tweepy
access_token = ""
access_token_secret = ""
consumer_key = ""
consumer_secret = ""
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class StdOutListener(StreamListener):
def on_data(self, data):
# process stream data here
print(data)
def on_error(self, status):
print(status)
if __name__ == '__main__':
listener = StdOutListener()
twitterStream = Stream(auth, listener)
twitterStream.filter(follow=['1680410522'])
twitterStream.filter(track=['UserName']) worked for me.

Categories