python twitter api getting status - python

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.

Related

Spotipy throws 404 when retrieving song data

EDIT 2: As #ximzend said, spotipy has moved to playlist_items instead of playlist_tracks
EDIT 1: In the process of moving to a curses interface, I changed the progress bar to a tqdm one (rather than rich), and that seemed to solve my problem. I did also upgrade spotipy (after it started working) but no change was needed in the API code ¯( ツ )/¯ so idk if rich was breaking the API req somehow or whatever
Thought I would put this here to help anyone in the future ツ
Spotipy throws this error when trying to retrieve data about tracks in a playlist
requests.exceptions.HTTPError: 404 Client Error: Not Found for url:
The error is thrown on the line below, specifically the self.sp.playlist_tracks(playlist_uri)['items'] part (The progress.track is a progress bar for the loop from rich)
for song in progress.track(self.sp.playlist_tracks(playlist_uri)['items'], description='Listing songs...'):
Full traceback is:
HTTP Error for GET to https://api.spotify.com/v1/playlists/4wi8hpuh4oyjtivbzk3k9n/tracks with Params: {'limit': 100, 'offset': 0, 'fields': None, 'market': None, 'additional_types': 'track'} returned 404 due to Not found.
Traceback (most recent call last):
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\spotipy\client.py", line 245, in _internal_call
response.raise_for_status()
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.spotify.com/v1/playlists/4wi8hpuh4oyjtivbzk3k9n/tracks?limit=100&offset=0&additional_types=track
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "t:\projects\youtusic\main.py", line 132, in <module>
main()
File "t:\projects\youtusic\main.py", line 119, in main
track_list = obj.sp_get_tracks(playlist_uri)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "t:\projects\youtusic\youtusic.py", line 104, in sp_get_tracks
for song in progress.track(self.sp.playlist_tracks(playlist_uri)['items'], description='Listing songs...'):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\spotipy\client.py", line 657, in playlist_tracks
return self.playlist_items(playlist_id, fields, limit, offset,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\spotipy\client.py", line 681, in playlist_items
return self._get(
^^^^^^^^^^
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\spotipy\client.py", line 297, in _get
return self._internal_call("GET", url, payload, kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "T:\projects\youtusic\youtusic-env\Lib\site-packages\spotipy\client.py", line 267, in _internal_call
raise SpotifyException(
spotipy.exceptions.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/playlists/4wi8hpuh4oyjtivbzk3k9n/tracks?limit=100&offset=0&additional_types=track:
Not found., reason: None
The code I was using was as follows:
def sp_get_tracks(self, playlist_link: str) -> list:
'''
Uses [spotipy](https://pypi.org/project/spotipy/) to retrieve
a list of songs in the playlist provided. Returns a list to be
used with `grab_yt_links`
'''
playlist_uri = playlist_link.split('/')[-1].split('?')[0]
song_titles = []
for song in progress.track(self.sp.playlist_tracks(playlist_uri)['items'], description='Listing songs...'):
track_name: str = song['track']['name']
artist_name: str = song['track']['artists'][0]['name']
track_name = track_name.replace(' ', '+')
artist_name = artist_name.replace(' ', '+')
song_titles.append(f'{artist_name}+{track_name}')
return song_titles
It should returns a list of all the songs (and artists) in the playlist. (The progress.track is a progress bar for the loop from rich). The 404 confuses me because my network connection is fine and I am able to perform Google searches etc
Additionally, the playlist only has 19 songs in so should be resticted by the limits I have read elsewhere
You get this error, because Spotify made a code breaking change to its API.
SpotiPy has fixed this issue by releasing an upgrade.
To install this upgrade, open a command prompt and run pip install spotipy --upgrade.
After the upgrade, you need to use playlist_items(playlist_id, fields=None, limit=100, offset=0, market=None, additional_types=('track', 'episode')). playlist_tracks is deprecated.

Tweepy Python returns: 401 Unauthorized

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

SSL required error for twython API call

I am trying to use twython to make API call for twitter and get the tweets. And I am receiving 403 error from twitter that says SSL is required. Can anyone help me how to finish this simply query?
Btw, I am using python 2.7. The OS is Windows 7.
from twython import Twython
tw = Twythonfrom twython import Twython(app_key=app_key, app_secret=app_secret, oauth_token=oauth_token, oauth_token_secret=oauth_token_secret)
search = tw.search(q = 'Sandra')
for result in search:
print result
And the error message
traceback (most recent call last):
File "C:\Users\local.admin\My Documents\LiClipse Workspace\test\TwythonTest.py", line 33, in <module>
search = tw.search(q = 'Sandra')
File "C:\Python27\lib\site-packages\twython\twython.py", line 133, in <lambda>
return lambda **kwargs: self._constructFunc(key, **kwargs)
File "C:\Python27\lib\site-packages\twython\twython.py", line 149, in _constructFunc
content = self._request(url, method=fn['method'], params=kwargs)
File "C:\Python27\lib\site-packages\twython\twython.py", line 218, in _request
retry_after=response.headers.get('retry-after'))
twython.twython.TwythonError: Twitter API returned a 403 (Forbidden), SSL is required

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