Migrating to Twitter API version 1.1 (?) [duplicated] - python

I am quite new to Twitter API. I have updated Tweepy. I don't know what is wrong with this code and how to fix it to make it work for new version of Twitter API:
import oauth, tweepy
from time import sleep
#stars is confident information
username = "*******"
password = "***********"
auth = tweepy.BasicAuthHandler(username, password)
api = tweepy.API(auth)
api.update_status('hello from tweepy!')
Terminal is showing me this:
$ python py/twi.py
Traceback (most recent call last):
File "py/twi.py", line 11, in <module>
api.update_status('hello from tweepy!')
File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 179, in _call
return method.execute()
File "/usr/lib/python2.7/dist-packages/tweepy/binder.py", line 162, in execute
raise TweepError(error_msg, resp)
tweepy.error.TweepError: [{'message': 'The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.', 'code': 68}]
Please help.

According to this google groups post, tweepy is supposed to support the 1.1 API. Your error message reports that tweepy is trying to use the 1.0 API. I suspect your update failed. Try uninstalling and reinstalling tweepy. What version of tweepy are you using? tweepy.__version__ should be 2.0

You are using basic authentication with user name and password. However, Twitter API 1.1 only supports OAuth. Here is how you authenticate with OAuth and Tweepy:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(key, secret)
according to this page.

Related

Why I get forbidden error for only reading home timeline?

My code is as simple as this, but it gave me 403 error:
def init_api():
api = json.load(open('secret.json'))['twitterapi']
consumer_key = api['api_token']
consumer_secret = api['api_secret']
access_token = api["access_token"]
access_token_secret = api["access_secret"]
bearer_token = api["bearer_token"]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#Step 2 - Retrieve Tweets
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
if __name__ == "__main__":
init_api()
Traceback (most recent call last):
File "path/to/project/config.py", line 45, in <module>
init_api()
File "path/to/project/config.py", line 39, in init_api
public_tweets = api.home_timeline()
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 33, in wrapper
return method(*args, **kwargs)
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 46, in wrapper
return method(*args, **kwargs)
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 488, in home_timeline
return self.request(
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 259, in request
raise Forbidden(resp)
tweepy.errors.Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve
(venv)
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
​​​​​​​​​​​​​​​​​​​​​​​​​
​​​​​​​​​​​​​​​​​​​​​​​​​​​​
From the error message:
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only.
So, you are only allowed to use v2 endpoints, but api.home_timeline() is a v1.1 API, so the v2 endpoint for reading the timeline is:
GET /2/users/:id/tweets
Or, since you are using tweepy, use their v2 API
Client.get_users_tweets(id, *, end_time=None, exclude=None, expansions=None, max_results=None,
media_fields=None, pagination_token=None, place_fields=None, poll_fields=None,
since_id=None, start_time=None, tweet_fields=None, until_id=None,
user_fields=None, user_auth=False)
Request the elevated v1.1 access. It generally gets accepted either instantly or very quickly. May not solve your issue though, because since they folded StreamListener into Stream, I can't seem to figure it out myself.

Post tweets using tweepy and Twitter API V2

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.

Tweepy unauthorized 401 error when Retweeting

I'm building a Twitter bot using Tweepy. When I'm testing it, I try to Retweet a test mention that I did, but I get an unauthorized 401 error. When getting timeline informations or just printing the mention ID/content, everything is fine, but when I try to retweet it, it raises 401:
I also changed my app permissions to write and read the first time I got the error.
import tweepy
consumer_key = '##########'
consumer_secret = '#######'
acess_token = '##'
acess_token_secret = '#'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(acess_token, acess_token_secret)
api = tweepy.API(auth)
mentions = api.mentions_timeline()
for mention in mentions:
api.retweet(mention.id)
Traceback (most recent call last):
File "C:\Users\Lorenzo\desktop\twitter-bot\open-source-divulgator-bot\app.py", line 15, in <module>
api.retweet(mention.id)
File "C:\Users\Lorenzo\Desktop\twitter-bot\open-source-divulgator-bot\venv\lib\site-packages\tweepy\api.py", line 46, in wrapper
return method(*args, **kwargs)
File "C:\Users\Lorenzo\Desktop\twitter-bot\open-source-divulgator-bot\venv\lib\site-packages\tweepy\api.py", line 993, in retweet
return self.request(
File "C:\Users\Lorenzo\Desktop\twitter-bot\open-source-divulgator-bot\venv\lib\site-packages\tweepy\api.py", line 257, in request
raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized
Doing what #Harmon758 said, I was able to run the code doing a simple regeneration on my credentials in the twitter developers site.
Since this is a common question and the solution is usually to grant the write permission and regenerate and use new credentials, like in this case, I've added an FAQ to Tweepy's documentation with a section answering this question.
To expand on the answers above and provide additional guidance.
Step 1 - First verify that you are using OAuthHandler and not AppAuthHandler.
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
Step 2 - Within Twitter's Developer portal navigate to your project and verify that the App's permissions are set to either Read and write or Read and write and Direct message as displayed in the image below.
Step 3 - You must regenerate new API Key and Secret and Access Token and Secret. Once the new keys are generated, make sure to update it either in your settings or code.
Additional References
Tweepy FAQ - Why am I encountering a 401 Unauthorized error?
Twitter Apps - App Permissions

Twitter API returned a 401 (Unauthorized), Invalid or expired token

I am using the below code to post a Tweet. This is a pretty standard authentication procedure but for some reason I cannot authenticate. The error I am getting is Twitter API returned a 401 (Unauthorized), Invalid or expired token.
from twython import Twython, TwythonError
import requests
APP_KEY = 'rpOzpgp2FZNJqsq0' #fake key
APP_SECRET = 'FKBJWXOJwXTblhi1xBl4PtKgPemNFvumH' #fake secret
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
oauth_verifier_url = auth['auth_url']
oauth_verifier = requests.get(oauth_verifier_url)
# Getting the FINAL authentication tokens
final_step = twitter.get_authorized_tokens(oauth_verifier)
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status='Yo')
Here is the full error message:
Traceback (most recent call last):
File "test.py", line 20, in <module>
final_step = twitter.get_authorized_tokens(oauth_verifier)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/twython/api.py", line 380, in get_authorized_tokens
ken'), error_code=response.status_code)
twython.exceptions.TwythonError: Twitter API returned a 401 (Unauthorized), Invalid / expired To ken
Why could I be getting this error and what can I do to fix it?
I have tried regenerating my keys multiple times. I have even deleted my app and created new ones multiple times but I still keep getting this error.
Under Application Settings my access level is set to read and write:
Screenshot of app page
I am not behind a firewall.
I have read other solutions concerning Twython authentication on this site but they all seem to provide the above code as the solution but this itself is not working for me.
I was facing the same problem, but after regeneration of keys the problem got solved.
You need to send four arguments not only 2
Objtwython = Twython(APP_KEY,APP_SECRET,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
last ones the same way you get the others, getting from twitter directly.
Seems that you're using the Twitter API too often. Due to security reasons, Twitter has rate limiting on the usage of their Twitter API from an arbitrary app. Twitter says in their post how their Twitter API rate-limiting works. You can make a maximum of 15 GET requests under 15 minutes from a specific set of authorization keys of that particular app. After 15 minutes, you are free to make the next 15 requests available.

Twitter API: simple status update (Python)

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"

Categories