Authentication error with twitter like bot in python - python

Hi Im trying to create a twitter like bot, that likes post with specific hashtags.
But I am getting unauthenticated error even though I am using the right keys.
raise Unauthorized(response) tweepy.errors.Unauthorized: 401 Unauthorized Unauthorized
This is the code I am using:
# Importing Tweepy and time
import tweepy
import time
# Credentials (INSERT YOUR CREDENTIALS BELOW)
all_keys = open("twitterkeys.txt", "r").read().splitlines()
api_key = all_keys[0]
api_key_secret = all_keys[1]
access_token = all_keys[2]
access_token_secret = all_keys[3]
# Gainaing access and connecting to Twitter API using Credentials
client = tweepy.Client(bearer_token, api_key, api_key_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret)
api = tweepy.API(auth)
# Bot searches for tweets containing certain keywords
class MyStream(tweepy.StreamingClient):
# This function gets called when a tweet passes the stream
def on_tweet(self, tweet):
#Liking the tweet
try:
client.like(tweet.id)
print(tweet.text)
except Exception as error:
print(error)
# delay between tweets
time.sleep(1)
# Creating Stream object
stream = MyStream(bearer_token=bearer_token)
# Adding terms to search rules
stream.add_rules(tweepy.StreamRule("(#Python OR #programming) (-is:retweet -is:reply)"))
# Starting stream
stream.filter()
Does anyone know why Im getting unauthenticated error?
Perhaps is because I am using OAuth 1.0a?
Thanks!

import tweepy
import time
all_keys = open("twitterkeys.txt", "r").read().splitlines()
api_key = all_keys[0]
api_key_secret = all_keys[1]
access_token = all_keys[2]
access_token_secret = all_keys[3]
auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret)
api = tweepy.API(auth)
class MyStream(tweepy.Stream):
def on_status(self, status):
try:
api.create_favorite(status.id)
print(status.text)
except Exception as error:
print(error)
time.sleep(1)
stream = MyStream(auth, listener=MyStream())
stream.filter(track=["#Python", "#programming"], filter_level='medium')

Related

Receiving "Stream encountered HTTP error: 409" when using Twitter API. What is causing this error and how can I fix it?

import tweepy
import time
api_key = ""
api_secret = ""
bearer_token = r""
access_token = ""
access_token_secret = ""
client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(bearer_token, api_key, api_secret, access_token, access_token_secret)
api = tweepy.API(auth)
class MyStream(tweepy.StreamingClient):
def on_tweet(self, tweet):
try:
print(tweet.text)
client.like(tweet.id)
except Exception as error:
print(error)
time.sleep(5)
stream = MyStream(bearer_token=bearer_token)
stream.add_rules(tweepy.StreamRule("#Python OR #programming -is:retweet -is:reply"), dry_run=True)
stream.filter()
Really unsure what is happening due to me following this youtube video to a T.
https://www.youtube.com/watch?v=tC9GnD0aU2c
Because you actually don't apply any rules to the stream, you have 2 choices:
Remove the dry_run so the add_rules() will send the data to Twitter and apply your rule
or
Add stream.sample() before filter()

401 error code being returned when trying to stream live Tweets from a specific account with Tweepy

Anyone have any idea what could be causing the error? All my keys and tokens should be correct. I made sure to double check them. I followed the steps on how to set up the stream pretty arcuately I thought.
import time
import tweepy
import praw
#Variables that contains the credentials to access Twitter API and REDDIT
USERNAME = ""
PASSWORD = "!"
CLIENT_ID = ''
CLIENT_SECRET = ''
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, consumer_key)
api = tweepy.API(auth, wait_on_rate_limit=True)
class MyStreamListener(tweepy.Stream):
def on_status(self, status):
print("ID: {}".format(status.id))
print(status.full_text)
def streamtweets():
myStreamListener = MyStreamListener(consumer_key, consumer_secret,access_token, consumer_key)
myStream = tweepy.Stream(consumer_key, consumer_secret,access_token, consumer_key)
myStream.filter(follow = [''])
streamtweets()
You're passing your consumer_key as the access token secret.

Why is my Twitter bot not authenticating?

I have been following a tutorial directly, as well as cross referencing with tweepy documentation and my code is still not authorizing to Twitters' API. I have quadruple checked my key, secrets, and tokens. I've even changed the which variables go where. Anytime I try to use the authentication methods found in the #graveyard it tells me the authentication failed. Where am I going wrong?
import tweepy
import time
consumer_key = 'xxx'
consumer_secret = 'xxx'
#bearertoken = "xxx"
access_token = 'xxx'
access_token_secret = 'xxx'
#authenticate to twitter
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
#create api object
api = tweepy.API(auth, wait_on_rate_limit=True)
##create tweet
#api.update_status('test run good')
#GRAVEYARD
#if api.verify_credentials():
# print("Success")
#else:
# print("authentication failed")
#try:
# api.verify_credentials()
# print("authentication ok")
#except:
# print("authentication failed")

Python Twitter Streaming Timeline

****I am trying to obtain information from the twitter timeline of a specific user and I am trying to print the output in Json format, however I am getting an AttributeError: 'str' object has no attribute '_json'. I am new to python so I'm having troubles trying to resolve this so any help would be greatly appreciated. ****
Below shows the code that I have at the moment:
from __future__ import absolute_import, print_function
import tweepy
import twitter
def oauth_login():
# credentials for OAuth
CONSUMER_KEY = 'woIIbsmhE0LJhGjn7GyeSkeDiU'
CONSUMER_SECRET = 'H2xSc6E3sGqiHhbNJjZCig5KFYj0UaLy22M6WjhM5gwth7HsWmi'
OAUTH_TOKEN = '306848945-Kmh3xZDbfhMc7wMHgnBmuRLtmMzs6RN7d62o3x6i8'
OAUTH_TOKEN_SECRET = 'qpaqkvXQtfrqPkJKnBf09b48TkuTufLwTV02vyTW1kFGunu'
# Creating the authentication
auth = twitter.oauth.OAuth( OAUTH_TOKEN,
OAUTH_TOKEN_SECRET,
CONSUMER_KEY,
CONSUMER_SECRET )
# Twitter instance
twitter_api = twitter.Twitter(auth=auth)
return twitter_api
# LogIn
twitter_api = oauth_login()
# Get statuses
statuses = twitter_api.statuses.user_timeline(screen_name='#ladygaga')
# Print text
for status in statuses:
print (status['text']._json)
You seem to be mixing up tweepy with twitter, and are possibly getting a bit confused with methods as a result. The auth process for tweepy, from your code, should go as follows:
import tweepy
def oauth_login():
# credentials for OAuth
consumer_key = 'YOUR_KEY'
consumer_secret = 'YOUR_KEY'
access_token = 'YOUR_KEY'
access_token_secret = 'YOUR_KEY'
# Creating the authentication
auth = tweepy.OAuthHandler(consumer_key,
consumer_secret)
# Twitter instance
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
# LogIn
twitter_api = oauth_login()
# Get statuses
statuses = twitter_api.user_timeline(screen_name='#ladygaga')
# Print text
for status in statuses:
print (status._json['text'])
If, as previously mentioned, you want to create a list of tweets, you could do the following rather than everything after # Print text
# Create a list
statuses_list = [status._json['text'] for status in statuses]
And, as mentioned in the comments, you shouldn't every give out your keys publicly. Twitter lets you reset them, which I'd recommend you do as soon as possible - editing your post isn't enough as people can still read your edit history.

401 Error when retrieving Twitter data using Tweepy

I am trying to retrieve Twitter data using Tweepy, using that below code, but I'm returning 401 error, and I regenerate the access and secret tokens, and the same error appeared.
#imports
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
#setting up the keys
consumer_key = 'xxxxxxx'
consumer_secret = 'xxxxxxxx'
access_token = 'xxxxxxxxxx'
access_secret = 'xxxxxxxxxxxxx'
class TweetListener(StreamListener):
# A listener handles tweets are the received from the stream.
#This is a basic listener that just prints received tweets to standard output
def on_data(self, data):
print (data)
return True
def on_error(self, status):
print (status)
#printing all the tweets to the standard output
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
stream = Stream(auth, TweetListener())
t = u"#سوريا"
stream.filter(track=[t])
Just reset your system's clock.
If an API request to authenticate comes from a server that claims it is a time that is outside of 15 minutes of Twitter time, it will fail with a 401 error.
ThankYou
You might just have made a mistake in copying the Access Token from the apps.twitter.com page.
You need to copy the entire thing that's given as Access Token, not just the string after the -.
For example, copy and paste the entire string like 74376347-jkghdui456hjkbjhgbm45gj, not just jkghdui456hjkbjhgbm45gj.
[Note the above string is just something I typed randomly for demonstration purpose. Your actual Access token will also look like this though, i.e,
"a string of number-an alphanumeric string"]
you just have to show your keys into the double quote
and you don't have to define your keys in last twitter authentication.
#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 = 'X3YIzD'
access_token_secret = 'PiwPirr'
consumer_key = 'ekaOmyGn'
consumer_secret = 'RkFXRIOf83r'
#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',
'javascript', 'ruby'
stream.filter(track=['python', 'javascript', 'ruby'])
I had the same issue - nothing here fixed it. The trick for me was that Streaming tweets with Tweepy apparently requires 1A authentication, not 2A (see - https://github.com/tweepy/tweepy/issues/1346). This means you need to use an access token as well as the consumer tokens in the authentication object.
import tweepy
# user credentials
access_token = '...'
access_token_secret = '...'
consumer_key = '...'
consumer_secret = '...'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# this is the main difference
auth.set_access_token(access_token, access_token_secret)
stream = tweepy.Stream(auth, tweepy.StreamListener)
In my case the error occurred because I was using AppAuthHandler rather than OAuthHandler. Switching to OAuthHandler resolved the issue.
In my case, I had this problem but it did not have to do with time.
My app had a "read only" permission.
I had to change it to a "read and write" permission for the error to cease.
You can do this by going to "user authentication" in the app settings page.
After changing your read only permission, you have to regenerate your access token, then put it into your code. Thanks for the help!

Categories

Resources