401 error when trying to stream tweets with Tweepy - python

import tweepy
import time
# Credentials (INSERT YOUR KEYS AND TOKENS IN THE STRINGS BELOW)
api_key = "XXX"
api_secret = "XXX"
bearer_token = r"XXX"
access_token = "XXXX"
access_token_secret = "XXXX"
# Gainaing access and connecting to Twitter API using Credentials
client = tweepy.Client(bearer_token, api_key, api_secret, access_token, access_token_secret)
auth = tweepy.OAuth1UserHandler(api_key, api_secret, access_token, access_token_secret)
#api = tweepy.API(auth)
search_terms = ["mahomes", "NFL"]
# Bot searches for tweets containing certain keywords
class MyStream(tweepy.StreamingClient):
# This function gets called when the stream is working
def on_connect(self):
print("Connected")
# This function gets called when a tweet passes the stream
def on_tweet(self, tweet):
# Displaying tweet in console
if tweet.referenced_tweets == None:
print(tweet.text)
client.like(tweet.id)
# Delay between tweets
#time.sleep(30)
# Creating Stream object
stream = MyStream(bearer_token=bearer_token)
# Adding terms to search rules
# It's important to know that these rules don't get deleted when you stop the
# program, so you'd need to use stream.get_rules() and stream.delete_rules()
# to change them, or you can use the optional parameter to stream.add_rules()
# called dry_run (set it to True, and the rules will get deleted after the bot
# stopped running).
for term in search_terms:
stream.add_rules(tweepy.StreamRule(term))
# Starting stream
stream.filter(tweet_fields=["referenced_tweets"])
Prints out the first tweet then gives the error:
Stream encountered an exception
Traceback (most recent call last):
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\streaming.py", line 94, in _connect
self.on_data(line)
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\streaming.py", line 936, in on_data
self.on_tweet(tweet)
File "<ipython-input-13-9febcb625821>", line 34, in on_tweet
client.like(tweet.id)
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 691, in like
return self._make_request(
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 129, in _make_request
response = self.request(method, route, params=request_params,
File "C:\Users\Eric\anaconda3\lib\site-packages\tweepy\client.py", line 98, in request
raise Unauthorized(response)
tweepy.errors.Unauthorized: 401 Unauthorized
Unauthorized
Giants postpone Carlos Correa’s intro news conference over unresolved medical results: Reports
#Jersey #MLB #NFL #NBA #NHL #NCAA #baseball #Americanfootball #baseballjersey #Americanfootballjersey #basketball #basketballJersey

Related

Authentication error with twitter like bot in 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')

Tweepy, upload media error API from The art institute of chicago = Invalid argument

Trying to have fun with a twitter bot.
The idea is : according to the art institute of chicago API, posting a Tweet with the informations (Artist, Date, Place...) And the media (picture).
I can't upload a media here, bellow you can see the traceback that I am trying to fix.
I will appreciate !
B
import tweepy
import requests
import random
import time
import io
############################# My logs ######################################
def twitter_api():
consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
return api
############################# My fonctions #################################
############################# The Loop ######################################
while True:
get_number()
r = requests.get(f"https://api.artic.edu/api/v1/artworks/{get_number()}")
a = r.json()
get_Titre(),get_Artist(),get_Date(),get_Place(),get_Im()
requests2 = (f"https://www.artic.edu/iiif/2/{get_Im()}/full/843,/0/default.jpg")
print("Imge ok:....................", requests2)
print(type(requests2))
message = (get_Titre()+ get_Artist()+str(get_Date())+get_Place())
print("La tête du tweet sera:", message)
twitter_api().update_status_with_media(message,requests2)
time.sleep(14400)
Here is the Traceback :
Traceback (most recent call last):
File "C:\PycharmProjects\TwitterBot\main.py", line 76, in <module>
twitter_api().update_status_with_media(message,requests2)
File "C:\PycharmProjects\TwitterBot\venv\lib\site-packages\tweepy\api.py", line 46, in wrapper
return method(*args, **kwargs)
File "C:\PycharmProjects\TwitterBot\venv\lib\site-packages\tweepy\api.py", line 1181, in update_status_with_media
files = {'media[]': stack.enter_context(open(filename, 'rb'))}
OSError: [Errno 22] Invalid argument: 'https://www.artic.edu/iiif/2/904ea189-c852-5f84-c614-a26a851f9b74/full/843,/0/default.jpg'
See documentation for update_status_with_media - second argument has to be filename.
update_status_with_media(text, filename, file, ...)
But third argument can be file-like object and this means object which has function .read().
If you would use urllib.request then it gives object which has .read() and it works.
BTW: you have to use any text as second argument - can be fake filename but function needs it.
import os
import urllib.request
import tweepy
url = "https://www.iheartradio.ca/image/policy:1.15731844:1627581512/rick.jpg?f=default&$p$f=20c1bb3"
text = "Testing module tweepy"
# --- create file_like_object ---
file_like_object = urllib.request.urlopen(url)
# --- send tweet ---
consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
access_token = os.getenv('TWITTER_ACCESS_TOKEN')
access_token_secret = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter_api = tweepy.API(auth)
# use any filename as second argument, and file-like object as third argument
twitter_api.update_status_with_media(text, 'fake_name.jpg', file=file_like_object)
With requests you have to use io.BytesIO to create file-like object
import os
import io
import requests
import tweepy
url = "https://www.iheartradio.ca/image/policy:1.15731844:1627581512/rick.jpg?f=default&$p$f=20c1bb3"
text = "Testing module tweepy"
# --- create file_like_object ---
response = requests.get(url)
file_like_object = io.BytesIO(response.content)
# --- send tweet ---
consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
access_token = os.getenv('TWITTER_ACCESS_TOKEN')
access_token_secret = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter_api = tweepy.API(auth)
# use any filename as second argument, and file-like object as third argument
twitter_api.update_status_with_media(text, 'fake_name.jpg', file=file_like_object)
EDIT:
Eventually you can use stream=True and then response.raw gives file-like object but this is not so popular.
# --- create file_like_object ---
response = requests.get(url, stream=True)
file_like_object = response.raw

Why do I get an authentication error with SMTP?

Every time I run this program, it runs the first time, but the second time it gives this error in terminal:
Traceback (most recent call last):
File "main.py", line 30, in <module>
timenow = datetime.now()
File "main.py", line 27, in temperature
moApparent = regexApparentTemp.search(str(json_object))
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 888, in append_row
return self.spreadsheet.values_append(self.title, params, body)
File "/usr/local/lib/python3.7/dist-packages/gspread/models.py", line 119, in values_append
r = self.client.request('post', url, params=params, json=body)
File "/usr/local/lib/python3.7/dist-packages/gspread/client.py", line 79, in request
raise APIError(response)
gspread.exceptions.APIError: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
The code is:
import requests, pprint, re, gspread, time
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
def temperature():
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Singapore-Weather-84def2be176a.json', scope)
gc = gspread.authorize(credentials)
wks = gc.open('Singapore Weather').sheet1
r = requests.get('https://api.darksky.net/forecast/b02b5107a2c9c27deaa3bc1876bcee81/1.312914,%20103.780257')
json_object = r.text
regexCurrentTemp = re.compile(r'"temperature":(\d\d.\d\d)')
moTemp = regexCurrentTemp.search(str(json_object))
temperature = moTemp.group(1)
regexApparentTemp = re.compile(r'"apparentTemperature":(\d\d.\d\d)')
moApparent = regexApparentTemp.search(str(json_object))
apparent = moApparent.group(1)
timenow = datetime.now()
wks.append_row([str(timenow), temperature, apparent])
while True:
temperature()
time.sleep(3597)
I put the autentication within the function in the loop so it would work, but it didn't. What is the problem?
As you can see on Github googleapis/oauth2client is deprecated
I would suggest you to try official Gmail API Python example:
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string(
))}
If you struggle with an example above try the Gmail API Quickstart Python tutorial

Authenticate to linkedin

I am trying to write a code that get some user's linkedin profile and just print it
this is my code
from linkedin import linkedin
CONSUMER_KEY = "XXXXX"
CONSUMER_SECRET = "XXXXX"
RETURN_URL = r"http://localhost:8000"
authentication = linkedin.LinkedInAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(authentication)
a = application.get_profile(member_url=my_url)
print(a)
I get the following error
Traceback (most recent call last):
File "C:/Users/Linkedin/main.py", line 28, in <module>
a = application.get_profile(member_url=my_url)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-4.2-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'NoneType' object has no attribute 'access_token'
What do I do wrong?
Not tested. Try this
As per the documentation. Access token must be generated to grand access to the application.
authentication = linkedin.LinkedInAuthentication(API_KEY, API_SECRET, RETURN_URL, linkedin.PERMISSIONS.enums.values())
application = linkedin.LinkedInApplication(token=authentication.get_access_token())
print authentication.authorization_url
When you grant access to the application, you will be redirected to the return url with the following query strings appended to your RETURN_URL:
"http://localhost:8000/?code=AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8&state=ea34a04b91c72863c82878d2b8f1836c"
Copy the code manually and set like
authentication.authorization_code = 'AQTXrv3Pe1iWS0EQvLg0NJA8ju_XuiadXACqHennhWih7iRyDSzAm5jaf3R7I8'
authentication.get_access_token() #AQTFtPILQkJzXHrHtyQ0rjLe3W0I
application = linkedin.LinkedInApplication(token='AQTFtPILQkJzXHrHtyQ0rjLe3W0I')

Python Dropbox API error: 'The provided token does not allow this operation' [duplicate]

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories

Resources