Tweepy API v2 "NoneType" - python

import tweepy
client = tweepy.Client(consumer_key='REPLACE_ME',
consumer_secret='REPLACE_ME',
access_token='REPLACE_ME',
access_token_secret='REPLACE_ME')
# Replace the text with whatever you want to Tweet about
response = client.create_tweet(text='hello world')
print(response)
I am currently trying to work with this template code, but this is the error that I am currently getting:
TypeError: Consumer key must be string or bytes, not NoneType
I'm not sure how this counts as a NoneType error, the Consumer Key, Consumer Secret, Access Token, and Access Token Secret are all in quotations so they should be a string.
Thank you!

You can try something like this if you want to post a tweet.
import tweepy
consumerKey = 'REPLACE_ME'
consumerSecret = 'REPLACE_ME'
accessToken = 'REPLACE_ME'
accessTokenSecret = 'REPLACE_ME'
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
status = api.update_status(status="Hello world!")

I replicated your code on my machine (I am using Twitter API v2). I get an Unauthorized 401 error. The first argument to tweepy.Client() should be the bearer token, in addition to the 4 other keys of course.
After that, you may face Forbidden: 403 issues with Client.create_tweet() if you have not given your app write permissions. See how you can address this issue in the answer to this post.

Related

Tweepy + api v1 + keys

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")

Can't register webhook for Twitter Account Activity API [python3]

I'm trying to set up a Twitter app using the Account Activity API, to replace my old set up which used the user streaming endpoint. I want to be able to get DM messages to one user sent to a particular URL in real time.
Following these migration instructions, I've set up a webhook endpoint on my site, as described here. I've checked that process is working, by making sure that when I open https://example.com/webhook_endpoint?crc_token=foo in my browser, I get a token in response.
Now I'm trying and failing to register my webhook. I'm using the following code, and getting a 403 response.
from requests_oauthlib import OAuth1Session
import urllib
CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
ACCESS_TOKEN = 'my access token'
ACCESS_SECRET = 'my access secret'
twitter = OAuth1Session(CONSUMER_KEY,
client_secret=CONSUMER_SECRET,
resource_owner_key=ACCESS_TOKEN,
resource_owner_secret=ACCESS_SECRET)
webhook_endpoint = urllib.parse.quote_plus('https://example.com/webhook/')
url = 'https://api.twitter.com/1.1/account_activity/all/env-beta/'
'webhooks.json?url={}'.format(webhook_endpoint)
r = twitter.post(url)
403 response content: {"errors":[{"code":200,"message":"Forbidden."}]}
I can successfully post a status using the same session object and
r = twitter.post('https://api.twitter.com/1.1/statuses/update.json?status=Test')
What am I doing wrong here?
This turned out to be due to a combination of:
Not having created an environment here: https://developer.twitter.com/en/account/environments as described here: https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/getting-started-with-webhooks
using the wrong consumer secret in the function that created the token returned at the /webhook endpoint

Tweepy streaming returns 401 Authorization Required

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.

tweepy error response status code 400

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.

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