Good morning,
I am trying to download the people that is twitting certain words in an area by this python code:
import sys
import tweepy
consumer_key="LMhbj3fywfKPNgjaPhOwQuFTY"
consumer_secret=" LqMw9x9MTkYxc5oXKpfzvfbgF9vx3bleQHroih8wsMrIUX13nd"
access_key="3128235413-OVL6wctnsx1SWMYAGa5vVZwDH5ul539w1kaQTyx"
access_secret="fONdTRrD65ENIGK5m9ntpH48ixvyP2hfcJRqxJmdO78wC"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
if 'busco casa' in status.text.lower():
print (status.text)
def on_error(self, status_code):
print (sys.stderr, 'Encountered error with status code:', status_code)
return True # Don't kill the stream
def on_timeout(self):
print (sys.stderr, 'Timeout...')
return True # Don't kill the stream
sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(locations=[-78.37,-0.20,-78.48,-0.18])
I am getting this error:
Encountered error with status code: 401
I read in this link https://dev.twitter.com/overview/api/response-codes that the error is caused by:
Authentication credentials were missing or incorrect.
Also returned in other circumstances, for example, all calls to API v1 endpoints now return 401 (use API v1.1 instead).
The authentication is there with updated keys. How should I use API v1.1?
Thanks,
Anita
If it says that your credentials are incorrect, you might want to check your credentials: you need to remove the whitespaces in your consumer secret for your code to work.
Also, I just tested your credentials (without whitespaces) and they are working. I can do whatever I want on behalf of your application. I suggest you very quickly go to https://apps.twitter.com and generate new ones. Never share your credentials. Especially online where everyone can see them.
Related
I need my Twitter app to tweet some information, but something is going wrong.
First, I created an app and tried this code to test credentials:
auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_SECRET")
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication Successful")
except:
print("Authentication Error")
And got "Authentication Error".
Then I tried to write a tweet directly using
client = tweepy.Client(bearer_token, consumer_key, consumer_secret, access_token, access_token_secret)
client.create_tweet(text="********")
And now I got "tweepy.errors.Forbidden: 403 Forbidden" What should I do?
It's impossible to determine what exactly is happening in the first instance, since you're suppressing the actual error and printing that on any exception. You'll need to provide the full traceback for anyone to know what's going on with it.
However, if you have Essential access to the Twitter API, you won't be able to use Twitter API v1.1, and you'll encounter a 403 Forbidden error.
See the FAQ section about that in Tweepy's documentation for more information.
For the latter error, make sure your app has the write permission.
See the FAQ section about that in Tweepy's documentation for more information.
Do you want to post a tweet via V2? here is the solution I just answered to myself!
Install tweepy, then do as I do to tweet "Yeah boy! I did it".
!pip3 install tweepy --upgrade # to install and upgrade tweepy if you didn't.
Then make your BEARER, CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, and ACCESS_SECRET ready. If you don't know how to find them you should check Developer Platform -> Developer Portal -> Projects & Apps -> click on your project -> then look for "Keys and tokens"
import tweepy
client = tweepy.Client(bearer_token=BEARER, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token=ACCESS_KEY, access_token_secret=ACCESS_SECRET)
client.create_tweet(text="Yeah boy! I did it")
This worked for me 100% tested. I still don't know if I can quote or reply to a tweet with V2 or not.
Whenever a user logs in to my application and searches I have to start a streaming API for fetching data required by him.
Here is my stream API class
import tweepy
import json
import sys
class TweetListener(tweepy.StreamListener):
def on_connect(self):
# Called initially to connect to the Streaming API
print("You are now connected to the streaming API.")
def on_error(self, status_code):
# On error - if an error occurs, display the error / status code
print('An Error has occured: ' + repr(status_code))
return False
def on_data(self, data):
json_data = json.loads(data)
print(json_data)
Here is my python code file which calls class above to start Twitter Streaming
import tweepy
from APIs.StreamKafkaApi1 import TweetListener
consumer_key = "***********"
consumer_secret = "*********"
access_token = "***********"
access_secret = "********"
hashtags = ["#ipl"]
def callStream():
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
tweetListener = TweetListener(userid,projectid)
streamer = tweepy.Stream(api.auth, tweetListener)
streamer.filter(track=hashtags, async=True)
if __name__ == "__main__":
callStream()
But if I hit more than twice my application return error code 420.
I thought to change API(using multiple keys) used to fetch data whenever Error 420 occurs.
How to get error raised by the on_error method of TweetListener class in def callStream()
I would like to add onto #Andy Piper's answer. Response 420 means your script is making too many requests and has been Rate Limited. To resolve this, here is what I do(in class TweetListener):
def on_limit(self,status):
print ("Rate Limit Exceeded, Sleep for 15 Mins")
time.sleep(15 * 60)
return True
Do this and the error will be handled.
If you persist on using multiple keys. I am not sure but try exception handling on TweetListener and streamer, for tweepy.error.RateLimitError and use recursive call of the function using next API key?
def callStream(key):
#authenticate the API keys here
try:
tweetListener = TweetListener(userid,projectid)
streamer = tweepy.Stream(api.auth, tweetListener)
streamer.filter(track=hashtags, async=True)
except tweepy.TweepError as e:
if e.reason[0]['code'] == "420":
callStream(nextKey)
return True
Per the Twitter error response code documentation
Returned when an application is being rate limited for making too many
requests.
The Twitter streaming API does not support more than a couple of connections per user and IP address. It is against the Twitter Developer Policy to use multiple application keys to attempt to circumvent this and your apps could be suspended if you do.
I'm trying to access the Twitter stream which I had working previously while improperly using Tweepy. Now that I understand how Tweepy is intended to be used I wrote the following Stream.py module. When I run it, I get error code 401 which tells me my auth has been rejected. But I had it working earlier with the same consumer token and secret. Any ideas?
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import TweepError
from tweepy import error
#Removed. I have real keys and tokens
consumer_key = "***"
consumer_secret = "***"
access_token="***"
access_token_secret="***"
class CustomListener(StreamListener):
""" A listener handles tweets are the received from the stream.
This is a basic listener that just prints received tweets to stdout."""
def on_status(self, status):
# Do things with the post received. Post is the status object.
print status.text
return True
def on_error(self, status_code):
# If error thrown during streaming.
# Check here for meaning:
# https://dev.twitter.com/docs/error-codes-responses
print "ERROR: ",; print status_code
return True
def on_timeout(self):
# If no post received for too long
return True
def on_limit(self, track):
# If too many posts match our filter criteria and only a subset is
# sent to us
return True
def filter(self, track_list):
while True:
try:
self.stream.filter(track=track_list)
except error.TweepError as e:
raise TweepError(e)
def go(self):
listener = CustomListener()
auth = OAuthHandler(consumer_key, consumer_secret)
self.stream = Stream(auth,listener,timeout=3600)
listener.filter(['LOL'])
if __name__ == '__main__':
go(CustomListener)
For anyone who happens to have the same issue, I should have added this line after auth was initialized:
auth.set_access_token(access_token, access_token_secret)
I can use the streaming API just fine when I don't include the count parameter in filter() call, but when I try to specify how many tweets from my history I want to receive, my stream object returns None.
import tweepy
from tweepy.streaming import StreamListener, Stream
class Listener (StreamListener):
def on_status(self, status):
print '-' * 20
print status.text
return
def get_tweets(request):
# if request.is_ajax():
# All keys and secrets are declared here, but were removed for security reasons.
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
listener = Listener()
stream = Stream(auth, listener)
stream.filter(follow=("14739093",), count=-5)
I also tried the following, to see what it was returning.
>>> something = stream.filter(follow=("14739093",), count=-5)
>>> print something
None
Thanks for your help!
Stream.filter always returns None, its job is just to pass the data on to the StreamListener.
Your problem is that Twitter only allows the count parameter for certain "roles".
Firehose, Links, Birddog and Shadow clients interested in capturing all statuses should maintain a current estimate of the number of statuses received per second and note the time that the last status was received. Upon a reconnect, the client can then estimate the appropriate backlog to request. Note that the count parameter is not allowed elsewhere, including track, sample and on the default access role.
This is the reason you're getting a 413 error when you try to use the count parameter -- you're on the "default access" role.
I've been looking for a way to update my Twitter status from a Python client. As this client only needs to access one Twitter account, it should be possible to do this with a pre-generated oauth_token and secret, according to http://dev.twitter.com/pages/oauth_single_token
However the sample code does not seem to work, I'm getting 'could not authenticate you' or 'incorrect signature'..
As there are a bunch of different python-twitter library out there (and not all of them are up-to-date) I'd really appreciate if anybody could point me a library that's currently working for POST requests, or post some sample code!
Update:
I've tried Pavel's solution, and it works as long as the new message is only one word long, but as soon as it contains spaces, i get this error:
status = api.PostUpdate('hello world')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 2459, in PostUpdate
self._CheckForTwitterError(data)
File "C:\Python26\lib\site-packages\python_twitter\twitter.py", line 3394, in _CheckForTwitterErro
r
raise TwitterError(data['error'])
python_twitter.twitter.TwitterError: Incorrect signature
If however the update is just one word, it works:
status = api.PostUpdate('helloworld')
{'status': 'helloworld'}
Any idea why this might be happening?
Thanks a lot in advance,
Hoff
You might be interested in this http://code.google.com/p/python-twitter/
Unfortunately the docs don't exist to be fair and last 'release' was in 2009.
I've used code from the hg:
wget http://python-twitter.googlecode.com/hg/get_access_token.py
wget http://python-twitter.googlecode.com/hg/twitter.py
After (long) app registration process ( http://dev.twitter.com/pages/auth#register ) you should have the Consumer key and secret. They are unique for an app.
Next you need to connect the app with your account, edit the get_access_token.py according to instructions in source (sic!) and run. You should have now the Twitter Access Token key and secret.
>>> import twitter
>>> api = twitter.Api(consumer_key='consumer_key',
consumer_secret='consumer_secret', access_token_key='access_token',
access_token_secret='access_token_secret')
>>> status = api.PostUpdate('I love python-twitter!')
>>> print status.text
I love python-twitter!
And it works for me http://twitter.com/#!/pawelprazak/status/16504039403425792 (not sure if it's visible to everyone)
That said I must add that I don't like the code, so if I would gonna use it I'd rewrite it.
EDIT: I've made the example more clear.
I've been able to solve this problem using another library - so I'll post my solution here for reference:
import tweepy
# http://dev.twitter.com/apps/myappid
CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
# http://dev.twitter.com/apps/myappid/my_token
ACCESS_TOKEN_KEY= 'my access token key'
ACCESS_TOKEN_SECRET= 'my access token secret'
def tweet(status):
'''
updates the status of my twitter account
requires tweepy (https://github.com/joshthecoder/tweepy)
'''
if len(status) > 140:
raise Exception('status message is too long!')
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
result = api.update_status(status)
return result
The most recent location for Python-Twitter documentation is now on GitHub (which the google code page points you at.)
You now no longer need to use the command line tool that comes with python-twitter to get the full set of access tokens and secrets, https://dev.twitter.com will let you request them when you register your app.
Once you have the four different credential values, the first thing you want to do is test them by making an API test:
api = twitter.Api(consumer_key='consumer_key',
consumer_secret='consumer_secret',
access_token_key='access_token',
access_token_secret='access_token_secret')
print api.VerifyCredentials()
This will show you if your credentials are working or not. If you get an error the next step is to pass in debugHTTP=True to the Api() call - this will cause all of the HTTP conversation to be printed so you can see the Twitter error message.
Once the credentials are working then you can try to call PostUpdate() or even just GetTimeline()
I Have coded some thing related to this question.
import tweepy
consumer_key = Your_consumer_key
consumer_secret = Your_consumer_secret
access_token = Your_access_token
access_token_secret = Your_access_token_secret_key
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
single_tweet = 'hello world'
api.update_status(single_tweet)
print "successfully Updated"