I am trying to access twitter api via tweepy. And I get tweepy.error.TweepError: [{'code': 215, 'message': 'Bad Authentication data.'}]
error.
My API access is decribed in twitter_client.py
:
import os
import sys
from tweepy import API
from tweepy import OAuthHandler
def get_twitter_auth():
"""Setup twitter authentication
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']
access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_secret = os.environ['TWITTER_ACCESS_SECRET']
except KeyError:
sys.stderr.write("TWITTER_* environment variable not setn")
sys.exit(1)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
return auth
def get_twitter_client():
"""Setup twitter api client
Return: tweepy.API object
"""
auth = get_twitter_auth()
client = API(auth)
return client
Then I try to get my last 4 tweets:
from tweepy import Cursor
from twitter_client import get_twitter_client
if __name__ == '__main__':
client = get_twitter_client()
for status in Cursor(client.home_timeline()).items(4):
print(status.text)
And get that error. How do I fix it?
I am using python 3.6 and I’ve installed tweepy via pip whithout specifying a version, so it should be the last version of tweepy.
Upd: I found out that the problem is in environ variables. Somehow twitter api can’t get it. However, when I just print(consumer_key, consumer_secret, access_token, access_secret)
, everything is on it’s place
2
Answers
Importing this way improves code readability especially when using it.
eg tweepy.API()
The brackets after home_timeline shouldn’t be there.
should be
.
You may solve this problem by importing load dotenv, which will get .env variables.