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.
Related
I have python code that posts tweets to twitter using oauth2 and that works fine but I need to attach some images to tweets and it seems that has to be done with api v1.1
On the twitter dev portal under project settings, user authentication it says "oAuth 1.0a and OAuth 2.0 turned on" and the Oauth 1.0a settings app permissions are read and write. I'm confused about which keys I should be using for Oauth 1.0a as when I use the consumer keys like this
my_api_key="xxx"
my_api_secret="xxx"
auth = tw.OAuthHandler(my_api_key, my_api_secret)
api = tw.API(auth, wait_on_rate_limit=True)
tweet = api.update_status("Testing tweepy API v1")
I get the error 220 - Your credentials do not allow access to this resource.
If I copy the access keys from the OAuth2 code that works then I get this error
32 - Could not authenticate you.
The OAuth2 code that works looks like this:
api = tweepy.Client(bearer_token=keys.twitter_bearer,
access_token=keys.access_key,
access_token_secret=keys.access_secret,
consumer_key=keys.consumer_key,
consumer_secret=keys.consumer_secret_key)
api.create_tweet(text=str)
I'm not sure what I'm doing wrong.
edit - am elevated
Went back to basics and investigated the code as everything else sounds right.
Turns out I was just doing it wrong.
This works:
auth = tweepy.OAuth1UserHandler(
consumer_key, consumer_secret, access_token, access_token_secret
)
api = tweepy.API(auth)
image=".\dataframe.png"
media=api.media_upload(image)
try:
api.update_status("Test",media_ids=[media.media_id])
except Exception as e:
print(e.class)
print(f"Exception occured - {e}")
else:
print("Success")
I am trying to connect to the twitter stream api to fetch tweets in realtime. This piece of code was working till 5-6 ago. Suddenly I've started receiving 401 all the time. Strangely this is both happening in my local machine and on our production server which is located in cloud, so I think this is not a network related issue.
Here is the code:
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth.callback = 'https://localhost' #no effect commented/uncommented
stream = Stream(auth, l)
stream.filter(track=['twitter'], languages=["es"])
So far I've tried the following:
Generating new consumer key, consumer secret, access token and access token secret. I've used 4 different set of keys which was working previously.
Created a fresh new app from apps.twitter.com. Filled the callback url as some users reported that 401 "Authorization Required" is related with the callback URL field missing in the application page of twitter.
Synced my clock with an ntp server, both on my local and on production server. My clock is not off.
My application have the correct privileges and I received access token and secret after the configuration.
Here is the request:
'Content-Length': '22'
'Content-Type': 'application/x-www-form-urlencoded'
'Authorization': 'OAuth oauth_nonce="161484371946745487981492681844"
oauth_timestamp="1492681844"
oauth_version="1.0"
oauth_signature_method="HMAC-SHA1"
oauth_consumer_key="<oauth_consumer_key>"
oauth_token="<oauth_token>"
oauth_signature="tphQqFWaBvEo2byjZ%2BRqNAM30I0%3D"'
Method: 'POST'
URL: 'https://stream.twitter.com/1.1/statuses/filter.json?delimited=length'
Any help would be appreciated on why I am getting a 401 Unauthorized "Need Authorization" response.
Edit: I've also tried using Twython and I got the same response back from twitter.
Thanks
Maybe you can try using Twython OAuth2 to connect if you don't need to tweet back
Twython Auth
Or try using this code.
# Put the consumer keys
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
# Redirect user to Twitter to authorize
redirect_user(auth.get_authorization_url())
# Get access token
auth.get_access_token("verifier_value")
# Construct the API instance
api = tweepy.API(auth)
#Create the stream
streamClass= StdOutListener()
stream= tweepy.Stream(auth = api.auth, listener=streamClass)
This should work.
Maybe your bot is not authorised on the account and this may be the error. But I don't think it's the case.
Check out my BOT's auth if you want an example :
ED_Postcards BOT
(New version incoming with pretty code)
I was able to solve the issue after 2 weeks of troubleshooting. For tweepy you need to manually set the callback url of the auth object you use to authenticate with the twitter.
After this correction head to apps.twitter.com and uncheck the box "Allow this application to to be used to Sign in with Twitter". Twitter API is not concise at all with the error messages.
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.
I'm trying to write a simple twitter bot using python and tweepy. The code is as follows:
import tweepy
CONSUMER_KEY = 'xxxxxxxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxx'
ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxxxxxxx'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status('hi')
I get the following error:
TweepError: Twitter error response: status code = 400
I would like some info on how to avoid this error
This may be a bug that emerged in the 3.2.0 release of Tweepy. See this issue opened on GitHub. In that issue, TylerGlaiel notes that api.update_status fails if called thus:
api.update_status('Test')
But works if called like so:
api.update_status(status='Test')
I have also found this works. I imagine a fix will be out before long.
This sentence: api.update_status(status='Test') let you know if your API Key and Token is working well. So, if you see:
TweepError: Twitter error response: status code = 400
Possibly means that you need to regenerate your credentiales for any reason. Regenerate your API Key, API Secret Key and your Tokens and will work.
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"