Tweepy Python returns: 401 Unauthorized - python

So, I was trying to like a Tweet using Tweepy, but this error is occurring:
Traceback (most recent call last):
File "c:/Users/User/Desktop/VScode/Python/FibraBot_home/bottwitter2.py", line 32, in <module>
tweet.favorite()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy\models.py", line 371, in favorite
return self._api.create_favorite(self.id)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy\api.py", line 46, in wrapper
return method(*args, **kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy\api.py", line 913, in create_favorite
), id=id, **kwargs
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\tweepy\api.py", line 257, in request
raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized
PS C:\Users\User\Desktop\VScode\Python\FibraBot_home>
Any ideas?

If you’re using a method that performs an action on behalf of the authenticating user, e.g. API.update_status(), make sure your app has the write permission.
After giving it the write permission, make sure to regenerate and use new credentials to utilize it.
https://tweepy.readthedocs.io/en/v4.8.0/faq.html#why-am-i-encountering-a-401-unauthorized-error-with-api-or-403-forbidden-error-with-client

Related

google cloud logging not working while working with python

python code.
import google.cloud.logging
client = google.cloud.logging.Client.from_service_account_json("file.config")
client.setup_logging()
import logging
loggin.info("error")
traceback:
Traceback (most recent call last):
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/grpc/_channel.py", line 923, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/grpc/_channel.py", line 826, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.PERMISSION_DENIED
details = "The caller does not have permission"
debug_error_string = "{"created":"#1612798593.245379000","description":"Error received from peer ipv4:142.250.71.42:443","file":"src/core/lib/surface/call.cc","file_line":1062,"grpc_message":"The caller does not have permission","grpc_status":7}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/handlers/transports/background_thread.py", line 123, in _safely_commit_batch
batch.commit()
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/logger.py", line 383, in commit
client.logging_api.write_entries(entries, **kwargs)
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging/_gapic.py", line 121, in write_entries
self._gapic_api.write_log_entries(
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/cloud/logging_v2/gapic/logging_service_v2_client.py", line 476, in write_log_entries
return self._inner_api_calls["write_log_entries"](
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/retry.py", line 281, in retry_wrapped_func
return retry_target(
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/Users/soubhagyapradhan/Desktop/upwork/baby/data-science/env/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission
Here i am trying to use google logging, But i am getting above error.
Please take a look
I am doing this using python. Is there any issue on generating service account creation
As John said, have you checked if the Service Account has the proper role assigned? As the official documentation says: "Using Cloud Logging library for Python requires the IAM Logs Writer role on Google Cloud. Most Google Cloud environments provide this role by default".
On the other hand, I am bit curious you used the "google-cloud-storage" tag, however you are not mention something related to it. Have you checked if the issue is because you do not have the enough permissions (As Storage Admin) to access your bucket?
I was using :
client = google.cloud.logging.Client()
(not ".from_service_account_json")
and I was getting the exact same error message. I also had the proper role roles/logging.logWriter. I am using using cloud-logging 2.6.0
I found that when I ran the code above in Vertex AI training job, if I don't create a client using my project_id in the following way:
client = google.cloud.logging.Client(project=<user project number>)
then google.cloud.logging use some kind of dummy project_id i.e "i285ca2410679d8f1p-tp" which don't have the necessay access. Putting my project_id and all the error messages are then gone.

Getting error when using praw to login to reddit

I've seen a couple of questions that already asked this but there were no responses, so I'll give it a try. When I use the following code:
import praw, time
r = praw.Reddit(user_agent="Bot experiment by redacted")
r.login('redacted', 'redacted')
I get a connection error that has the following traceback:
Traceback (most recent call last):
File "redacted", line 5, in <module>
r.login('redacted', 'redacted')
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/praw/__init__.py", line 1263, in login
self.request_json(self.config['login'], data=data)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/praw/decorators.py", line 161, in wrapped
return_value = function(reddit_session, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/praw/__init__.py", line 519, in request_json
response = self._request(url, params, data)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/praw/__init__.py", line 383, in _request
_raise_response_exceptions(response)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/praw/internal.py", line 172, in _raise_response_exceptions
response.raise_for_status()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 831, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden
I have tried this from python 3.4 and 2.7, I've tried running from IDLE and from the terminal. I've tried leaving my username and password out and logging in when prompted. I've tried from my Mac in my hotel room and a Windows machine from work and I get the same error everytime. I've tried from my bot account that I just made and my normal account. Does anyone have any ideas?
The issue was that I had the word 'bot' in my user_agent string. After it was removed, there were no problems.

python twitter api getting status

I am trying to get a recent status of a twitter user. I type in the following:
>>> from twitter import *
>>> t = Twitter(auth=OAuth(...))
>>> t.statuses.friends_timeline(id="StephenAtHome")
I get the following error at the last line:
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
t.statuses.friends_timeline(id="StephenAtHome")
File "twitter\api.py", line 204, in __call__
return self._handle_response(req, uri, arg_data, _timeout)
File "twitter\api.py", line 235, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
TwitterHTTPError: Twitter sent status 404 for URL: 1.1/statuses/friends_timeline/StephenAtHome.json using parameters (oauth_consumer_key=i1xQ3YKmmUI9pKlYDmSPeA&oauth_nonce=12051576929978547960&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1371245218&oauth_token=1517563807-75iFGXWHxMvzzsqrIs5W4tCb4OwFG4eisnDYRst&oauth_version=1.0&oauth_signature=m0LDp%2FdkJLMr3sHPnFQkLKlDTrE%3D)
details: {"errors":[{"message":"Sorry, that page does not exist","code":34}]}
How do I fix this error. I know that the page exists
The problem is that twitter API was upgraded to 1.1 version and friends_timeline was deprecated (see docs). Use home_timeline instead (user_timeline should work but doesn't):
t.statuses.home_timeline(user_id="gvanrossum")
Hope that helps.

prestapyt error on edit

I'm using the prestashop API prestapyt
I add a category by hand in my site, but when I'm trying to edit via the API, it fails.
Even the most simple thing, does not work:
ps = PrestaShopWebServiceDict(config.DOMAIN, config.KEY)
xml = ps.get('categories', 35)
ps.edit('categories',35,xml)
The xml (type DICT) loads ok, but the .edit() fails.
Here is the response
Traceback (most recent call last):
File "C:\Users\noukeys\Documents\psapi\main.py", line 31, in <module>
ps.edit('categories',35,xml)
File "C:\Python27\lib\site-packages\prestapyt\prestapyt.py", line 333, in edit
return self.edit_with_url(full_url, content)
File "C:\Python27\lib\site-packages\prestapyt\prestapyt.py", line 452, in edit_with_url
return super(PrestaShopWebServiceDict, self).edit_with_url(url, xml_content)
File "C:\Python27\lib\site-packages\prestapyt\prestapyt.py", line 344, in edit_with_url
return self._parse(self._execute(url, 'PUT', body=unicode_encode.encode(content), add_headers=headers)[2])
File "C:\Python27\lib\site-packages\prestapyt\prestapyt.py", line 171, in _execute
self._check_status_code(status_code)
File "C:\Python27\lib\site-packages\prestapyt\prestapyt.py", line 125, in _check_status_code
% (status_code, message_by_code[status_code]), status_code)
prestapyt.prestapyt.PrestaShopWebServiceError: 'This call to PrestaShop Web Services failed and returned an HTTP status of 400. That means: Bad Request.'
I'm having issues with edits also, but I am getting a 501 error. Turns out my host does not allow PUT requests.
You can turn on debugging in the api.
prestashop.debug = True
And then turn on display_errors in config.inc.php for your shop. This helped me debug why the request was bad. The error messages are pretty clear.

Unable to upgrade YouTube session token without logging into Google Accounts user API

I am having trouble upgrading my session token in google app engine if my user is not logged into my application using the google accounts user api. If the user is currently logged in then it functions perfectly.
If not then i am getting this error:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/5th-anniversary/1.341853888797531127/main.py", line 78, in get
u.upgradeToken(self)
File "/base/data/home/apps/5th-anniversary/1.341853888797531127/upload.py", line 47, in upgradeToken
client.UpgradeToSessionToken()
File "/base/data/home/apps/5th-anniversary/1.341853888797531127/gdata/service.py", line 903, in UpgradeToSessionToken
raise NonAuthSubToken
NonAuthSubToken
What are my best options here? I do not want the user to have to log into the google accounts api and then the youtube site to upload a video.
here is my method for updating the token:
def upgradeToken(data,self):
get = self.request.GET
authsub_token = get['token']
gdata.alt.appengine.run_on_appengine(client)
client.SetAuthSubToken(authsub_token)
client.UpgradeToSessionToken()
client is simply client = gdata.youtube.service.YouTubeService()
pretty sure i'm missing something on the authentication side but i can't seem to see what, thanks!
I solved this by using:
client.UpgradeToSessionToken(gdata.auth.extract_auth_sub_token_from_url(self.request.url))
but this raised another issue when building the upload form with
GetFormUploadToken
i receive:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 513, in __call__
handler.post(*groups)
File "/base/data/home/apps/5th-anniversary/1.341859541699944556/upload.py", line 106, in post
form = u.getUploadForm(self,title,description,keywords)
File "/base/data/home/apps/5th-anniversary/1.341859541699944556/upload.py", line 65, in getUploadForm
response = client.GetFormUploadToken(video_entry,'http://gdata.youtube.com/action/GetUploadToken')
File "/base/data/home/apps/5th-anniversary/1.341859541699944556/gdata/youtube/service.py", line 716, in GetFormUploadToken
raise YouTubeError(e.args[0])
YouTubeError: {'status': 401L, 'body': '<HTML>\n<HEAD>\n<TITLE>User authentication required.</TITLE>\n</HEAD>\n<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n<H1>User authentication required.</H1>\n<H2>Error 401</H2>\n</BODY>\n</HTML>\n', 'reason': ''}
Try this:
new_token = client.UpgradeToOAuthAccessToken(
gdata.auth.extract_auth_sub_token_from_url(self.request.url)
client.SetOAuthToken(new_token)
client.GetFormUploadToken(my_video_entry)

Categories