tweepy bad authentication data - python

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 set\n")
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

import tweepy
Importing this way improves code readability especially when using it.
eg tweepy.API()
client.home_timeline()
The brackets after home_timeline shouldn't be there.
should be
for status in Cursor(client.home_timeline).items(4):
print(status.text)
.
import tweepy
auth = tweepy.OAuthHandler(<consumer_key>, <consumer_secret>)
auth.set_access_token(<access_token>, <access_secret>)
client = tweepy.API(auth)
for status in tweepy.Cursor(client.user_timeline).items(200):
process_status(status.text)

You may solve this problem by importing load dotenv, which will get .env variables.
import os
import sys
from tweepy import API
from tweepy import OAuthHandler
from dotenv import load_dotenv
def get_twitter_auth():
"""Setup twitter authentication
Return: tweepy.OAuthHandler object
"""
try:
consumer_key = os.getenv('CONSUMER_KEY')
consumer_secret = os.getenv('CONSUMER_SECRET')
access_token = os.getenv('ACCESS_TOKEN')
access_secret = os.getenv('TWITTER_ACCESS_SECRET')
except KeyError:
sys.stderr.write("TWITTER_* environment variable not set\n")
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
from tweepy import Cursor
if __name__ == '__main__':
client = get_twitter_client()
for status in Cursor(client.home_timeline()).items(4):
print(status.text)

Related

I am trying to make a Twitter bot using Tweepy and Python, but I get Error 215?

I am trying to create a Twitter bot that follows the people that follow me. However I am getting Error 215: Bad Authentication data. Im pretty sure it is twitter not authorizing my credentials, but i am not sure, and i dont know how to fix it.
here is my config file:
import tweepy
import logging
import os
logger=logging.getLogger()
def create_api():
consumer_key= os.getenv("CONSUMER_KEY")
consumer_secret= os.getenv("CONSUMER_SECRET")
access_token= os.getenv("ACCESS_TOKEN")
access_token_secret= os.getenv("ACCESS_TOKEN_SECRET")
auth= tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api= tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
#api=tweepy.API(auth)
try:
api.verify_credentials()
except Exception as e:
logger.error("Error in creating API", exc_info=True)
raise e
logger.info("API created")
return api
here is my following follower file
import tweepy
import logging
from config import create_api
import time
logging.basicConfig(level=logging.INFO)
logger=logging.getLogger()
def follow_followers(api):
logger.info("Retrieving and following followers")
for follower in tweepy.Cursor(api.followers).items():
if not follower.following:
logger.info(f"Following {follower.name}")
follower.follow()
def main():
api= create_api()
while True:
follow_followers(api)
logger.info("Waiting...")
time.sleep(60)
if __name__ == "__main__":
main()
I then use my windows terminal to set CONSUMER_KEY="XXX" etc and i het a tweep.error.TweepError [{'code': 215, 'message': 'Bad Authentication data.'}]
any suggestions to fix?

Tweepy StreamListener: Tweet when a specified account Tweets

I have a Twitter bot that is following one specific account.
When that account Tweets, I want my bot to Tweet.
So far I have the below code:
import tweepy
import time
import sys
import inspect
consumer_key = 'xxxxxxx'
consumer_secret = 'xxxxxxxx'
access_token = 'xxxxxxx'
access_token_secret = 'xxxxxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
auth.secure = True
print "Test Message"
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
if status.user.screen_name.encode('UTF-8').lower() == 'xxxxxx': #account I am following
api.update_status('Test Tweet') # tweet that is sent from my bot
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=MyStreamListener())
myStream.filter(track=['xxxxxx'])
However, when I run this code from the command line, it runs without a problem but does not react to any Tweets from the specified account.
It seems like the if statement within your on_status method isn't properly indented.
If that's not the case, to properly debug this, you need to add an on_error method to your MyStreamListener class so that you're able to determine what, if any, error/status code is being returned by Twitter's API.
See the Handling Errors section of the Streaming With Tweepy documentation.

How to get access token secret for StockTwit API?

I've already got the consumer key, consumer secret, and access token, but I don't know how to get the access token secret. This code works but I just need the access token secret. Thanks in Advance!
#!/usr/bin/python
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access stocktwits API
consumer_key = "something"
consumer_secret = "something"
access_token = "something"
#access_token_secret = ""
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords
stream.filter(track=['Hillary Clinton', '#Hillary', 'Donald Trump', '#Trump'])
StockTwits does not provide an access_token_secret. Once you have an access token, that token can be used on all requests to the API. You'll want to see of your OAuthHandler class allows only setting an access_token. It should.

Getting whole user timeline of a Twitter user

I want to get the all of a user tweets from one Twitter user and so far this is what I came up with:
import twitter
import json
import sys
import tweepy
from tweepy.auth import OAuthHandler
CONSUMER_KEY = ''
CONSUMER_SECRET= ''
OAUTH_TOKEN=''
OAUTH_TOKEN_SECRET = ''
auth = twitter.OAuth(OAUTH_TOKEN,OAUTH_TOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET)
twitter_api =twitter.Twitter(auth=auth)
print twitter_api
statuses = twitter_api.statuses.user_timeline(screen_name='#realDonaldTrump')
print [status['text'] for status in statuses]
Please ignore the unnecessary imports. One problem is that this only gets a user's recent tweets (or the first 20 tweets). Is it possible to get all of a users tweet? To my knowledge, the GEt_user_timeline (?) only allows a limit of 3200. Is there a way to get at least 3200 tweets? What am I doing wrong?
There's a few issues with your code, including some superfluous imports. Particularly, you don't need to import twitter and import tweepy - tweepy can handle everything you need. The particular issue you are running into is one of pagination, which can be handled in tweepy using a Cursor object like so:
import tweepy
# Consumer keys and access tokens, used for OAuth
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
for status in tweepy.Cursor(api.user_timeline, screen_name='#realDonaldTrump', tweet_mode="extended").items():
print(status.full_text)

How to get last update Twitter API

How to get time last status update on Twitter ? use python and tweepy
help please
These are the commands that I used to read tweets from my personal Twitter account using Python. I hope you can use the same to read the last status update from Twitter.
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "ENTER YOUR ACCESS TOKEN"
access_token_secret = "ENTER YOUR ACCESS TOKEN SECRET"
consumer_key = "ENTER YOUR API KEY"
consumer_secret = "ENTER YOUR API SECRET"
#This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
print data
return True
def on_error(self, status):
print status
if __name__ == '__main__':
#This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
#This line filter Twitter Streams to capture data by the keywords: 'python'
stream.filter(track=['python'])

Categories