I'm trying to call the Spotify API using the Spotipy Python library. I'm getting a 'PermissionError: [Errno 13] Permission denied' error.
I'm using a GCP Compute Engine with Debian as the OS.
Error is below
Traceback (most recent call last):<br>
File "<stdin>", line 1, in <module><br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/client.py", line 1307, in current_use
r_recently_played<br>
before=before,<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/client.py", line 291, in _get<br>
return self._internal_call("GET", url, payload, kwargs)<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/client.py", line 221, in _internal_ca
ll<br>
headers = self._auth_headers()<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/client.py", line 212, in _auth_header
s<br>
token = self.auth_manager.get_access_token(as_dict=False)<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/oauth2.py", line 484, in get_access_t
oken<br>
"code": code or self.get_auth_response(),<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/oauth2.py", line 439, in get_auth_res
ponse<br>
return self._get_auth_response_local_server(redirect_port)<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/oauth2.py", line 405, in _get_auth_re
sponse_local_server<br>
server = start_local_http_server(redirect_port)<br>
File "/home/#####/.local/lib/python3.7/site-packages/spotipy/oauth2.py", line 1227, in start_local
_http_server<br>
server = HTTPServer(("127.0.0.1", port), handler)<br>
File "/usr/lib/python3.7/socketserver.py", line 452, in __init__<br>
self.server_bind()<br>
File "/usr/lib/python3.7/http/server.py", line 137, in server_bind<br>
socketserver.TCPServer.server_bind(self)<br>
File "/usr/lib/python3.7/socketserver.py", line 466, in server_bind<br>
self.socket.bind(self.server_address)<br>
PermissionError: [Errno 13] Permission denied<br>
Code example is
import spotipy
from spotipy.oauth2 import SpotifyOAuth
scope = 'user-read-recently-played'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
played = sp.current_user_recently_played()
I have done chmod 0775 -R on what I believe are the relevant directories but still getting stuck.
I would suggest trying using a different approach. Here's what I use for my Spotify pipeline:
import spotipy
import spotipy.util as util
import os
un = os.environ['un']
scope = 'user-read-recently-played'
cid = os.environ['cid']
csid = os.environ['csid']
redr = r'http://localhost:8888/callback/'
token = util.prompt_for_user_token(un,scope,cid,csid,redr)
sp = spotipy.Spotify(auth=token)
results = sp.current_user_recently_played()
Where un is my username, cid and csid are the key/secret key for my developer account, and redr is just a local webpage for redirects.
Related
I'm new to python, and I am trying to build a little Reddit bot to get some practice.
My bot works just fine (tested many times) but once I try to move the credentials to a .env file it fails.
I've ran pip3 install python-dotenv
This is my code, just one file, removing irrelevant stuff:
import os
import praw
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from dotenv import load_dotenv
load_dotenv()
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://makideat-6a-default-db.firebaseio.com'
})
db_ref = db.reference()
reddit = praw.Reddit(
client_id=os.getenv('CLIENT_ID'),
client_secret=os.getenv('CLIENT_SECRET'),
username=os.getenv('USERNAME'),
password=os.getenv('PASSWORD'),
user_agent=os.getenv('USER_AGENT')
)
def summoned_reply(comment):
DO SOME STUFF...
messages = reddit.inbox.stream() # creates an iterable for your inbox and streams it
for message in messages: # iterates through your messages
try:
if message in reddit.inbox.mentions() and message in reddit.inbox.unread():
summoned_reply(message)
message.mark_read()
except praw.exceptions.APIException:
print("probably a rate limit....")
And this is the error I'm getting (line 56 is for message in messages:):
Traceback (most recent call last):
File "C:\Users\Yanay\Documents\Coding\NiceAndPretty\main.py", line 56, in <module>
for message in messages: # iterates through your messages
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\util.py", line 195, in stream_generator
for item in reversed(list(function(limit=limit, **function_kwargs))):
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 63, in __next__
self._next_batch()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\models\listing\generator.py", line 89, in _next_batch
self._listing = self._reddit.get(self.url, params=self.params)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 634, in get
return self._objectify_request(method="GET", params=params, path=path)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 739, in _objectify_request
self.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\util\deprecate_args.py", line 43, in wrapped
return func(**dict(zip(_old_args, args)), **kwargs)
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\praw\reddit.py", line 941, in request
return self._core.request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 330, in request
return self._request_with_retries(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 228, in _request_with_retries
response, saved_exception = self._make_request(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 185, in _make_request
response = self._rate_limiter.call(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\rate_limit.py", line 33, in call
kwargs["headers"] = set_header_callback()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\sessions.py", line 283, in _set_header_callback
self._authorizer.refresh()
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 425, in refresh
self._request_token(
File "C:\Users\Yanay\.virtualenvs\NiceAndPretty\lib\site-packages\prawcore\auth.py", line 158, in _request_token
raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
Then, in the same directory I have a .env file in the following structure (changed characters for everything here of course, but haven't changed the structure or added or removed spaces from anywhere):
CLIENT_ID=gGATUW-Ea507LoQ
CLIENT_SECRET=_b6vCCHKBCqVHzlJin3sEQ
USERNAME=Maddeeat
PASSWORD=!Neatat!
USER_AGENT=Maddeeat:1.0.0 (by u/Maddeeat)
I've been wanting to start a small spotify-based project and I'm currently trying to utilize python to create a playlist using the spotipy library as such:
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
import spotipy.util as util
scope = 'playlist-modify-public'
username = 'aaronang_'
token = SpotifyOAuth(scope=scope,username=username)
spotifyObject = spotipy.Spotify(auth_manager = token)
playlist_name = input("Enter a playlistname:")
playlist_description = input("Enter a playlist description:")
spotifyObject.user_playlist_create(user=username,name=playlist_name,public=True,description=playlist_description)
I set my client id,client secret and redirect uri in terminal's virtual environment(venv) yet using:
set CLIENT_ID=c3032b421ce94......9a05abcb623da
set CLIENT_SECRET=32a9c32611......5b69cf643f7c33e
set CLIENT_REDIRECT_URI=http://127.0.0.1:8080/
I end up getting this error:
Traceback (most recent call last):
File "C:\Users\Aaron\spotifyPlaylist.py", line 17, in <module>
spotifyObject.user_playlist_create(user=username,name=playlist_name,public=True,description=playlist_description)
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\client.py", line 784, in user_playlist_create
return self._post("users/%s/playlists" % (user,), payload=data)
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\client.py", line 302, in _post
return self._internal_call("POST", url, payload, kwargs)
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\client.py", line 221, in _internal_call
headers = self._auth_headers()
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\client.py", line 212, in _auth_headers
token = self.auth_manager.get_access_token(as_dict=False)
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\oauth2.py", line 525, in get_access_token
token_info = self.validate_token(self.cache_handler.get_cached_token())
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\oauth2.py", line 380, in validate_token
token_info = self.refresh_access_token(
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\oauth2.py", line 596, in refresh_access_token
self._handle_oauth_error(http_error)
File "C:\Users\Aaron\venv\lib\site-packages\spotipy\oauth2.py", line 146, in _handle_oauth_error
raise SpotifyOauthError(
spotipy.oauth2.SpotifyOauthError: error: invalid_client, error_description: Invalid client
I've seen this code work for others, yet my token won't validate. I've got a token from https://developer.spotify.com/console/put-playlist-tracks/ which worked.
Thanks.
I am using MongoDB atlas for my discord bot but recently ran into an error. On the hosting (Heroku) everything works without errors, I first updated all the modules, but the error has not disappeared.
I am using motor as a driver to work with MongoDB atlas.
Checked the database connection URL, everything is correct.
Python version 3.10(on Heroku too)
Traceback (most recent call last):
File "D:\Проекты\AkainuBot\main.py", line 23, in <module>
mongo = AsyncIOMotorClient(
File "D:\Python\lib\site-packages\motor\core.py", line 159, in __init__
delegate = self.__delegate_class__(*args, **kwargs)
File "D:\Python\lib\site-packages\pymongo\mongo_client.py", line 718, in __init__
self.__options = options = ClientOptions(
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 165, in __init__
self.__pool_options = _parse_pool_options(options)
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 132, in _parse_pool_options
ssl_context, ssl_match_hostname = _parse_ssl_options(options)
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 98, in _parse_ssl_options
ctx = get_ssl_context(
File "D:\Python\lib\site-packages\pymongo\ssl_support.py", line 159, in get_ssl_context
ctx.load_verify_locations(certifi.where())
File "D:\Python\lib\site-packages\pymongo\pyopenssl_context.py", line 276, in load_verify_locations
self._callback_data.trusted_ca_certs = _load_trusted_ca_certs(cafile)
File "D:\Python\lib\site-packages\pymongo\ocsp_support.py", line 79, in _load_trusted_ca_certs
_load_pem_x509_certificate(cert_data, backend))
File "D:\Python\lib\site-packages\cryptography\x509\base.py", line 436, in load_pem_x509_certificate
return rust_x509.load_pem_x509_certificate(data)
ValueError: error parsing asn1 value: ParseError { kind: InvalidValue, location: ["RawCertificate::tbs_cert", "TbsCertificate::serial"] }
I've solved my problem getting the parsing asn1 value error by adding the ssl_cert_reqs option on the MongoClient (and obviously importing ssl).
dbClient = pymongo.MongoClient(uri, ssl_cert_reqs=ssl.CERT_NONE)
I'm trying to access a public FTP in my work, but I'm getting an error.
That's is the code that I used in my house.
from ftplib import FTP
ftp = FTP('ftp.cetip.com.br')
ftp.login()
ftp.cwd('/MediaCDI')
ftp.quit()
It's work fine in my home, but in my work I get this error:
Traceback (most recent call last):
File "C:\Users\TBMEPYG\Desktop\stack.py", line 3, in <module>
ftp = FTP('ftp.cetip.com.br')
File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\ftplib.py", line 117, in __init__
self.connect(host)
File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\ftplib.py", line 152, in connect
source_address=self.source_address)
File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\socket.py", line 722, in create_connection
raise err
File "C:\Users\TBMEPYG\AppData\Local\Continuum\Anaconda3\lib\socket.py", line 713, in create_connection
sock.connect(sa)
[Finished in 21.3s]
When I was developing a scraper in a HTTP website, I solved this problem for http using HTTPProxyAuth and requests. Just to illustrate, that's was the code:
from requests.auth import HTTPProxyAuth
import requests
user = 'xxxx'
password = 'yyyy'
credenciais = HTTPProxyAuth(user, password)
params = {'Dt_Ref': data, 'TpInstFinanceiro': 'CRI', 'Tipo':'1','saida':'txt'}
proxy_access = {'http':'proxy.mywork/accelerated_pac_base.pac'}
url = 'http://www.anbima.com.br/reune/reune_down.asp'
r = requests.post(url, data = params, proxies = proxy_access , auth = credenciais)
Anyone has any idea about what can I do?
Thanks
I have this simple script that spits out the buckets in my GCS:
import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time
# URI scheme for Cloud Storage.
GOOGLE_STORAGE = 'gs'
# URI scheme for accessing local files.
LOCAL_FILE = 'file'
header_values = {"x-goog-project-id": "xxxxxxxxxxxx"}
uri = boto.storage_uri('', GOOGLE_STORAGE)
for bucket in uri.get_all_buckets(headers=header_values):
print bucket.name
The top of my ~/.boto file has the following (with real values for everything inside brackets):
# Google OAuth2 service account credentials (for "gs://" URIs):
gs_service_key_file = /home/pi/dev/camera/cl-camera-<id>.json
gs_service_client_id = '<user>#<id>.iam.gserviceaccount.com'
Everything works fine when running without sudo, but once I add sudo (I need access to GPIO pins since this is on a RPi), I get the following error:
Traceback (most recent call last):
File "gcs-test.py", line 24, in <module>
for bucket in uri.get_all_buckets(headers=header_values):
File "/usr/local/lib/python2.7/dist-packages/boto/storage_uri.py", line 584, in get_all_buckets
conn = self.connect()
File "/usr/local/lib/python2.7/dist-packages/boto/storage_uri.py", line 140, in connect
**connection_args)
File "/usr/local/lib/python2.7/dist-packages/boto/gs/connection.py", line 47, in __init__
suppress_consec_slashes=suppress_consec_slashes)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/connection.py", line 191, in __init__
validate_certs=validate_certs, profile_name=profile_name)
File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 569, in __init__
host, config, self.provider, self._required_auth_capability())
File "/usr/local/lib/python2.7/dist-packages/boto/auth.py", line 1021, in get_auth_handler
'Check your credentials' % (len(names), str(names)))
boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 3 handlers were checked. ['OAuth2Auth', 'OAuth2ServiceAccountAuth', 'HmacAuthV1Handler'] Check your credentials
Any ideas as to what's happening and why it's only when I run it with sudo?
I figure this one out. Since I'm running it as root now, it looks for the .boto file in a different place (/root/.boto instead of /home/pi/.boto), so I did the following to create a new config file and it worked:
$ sudo su
$ gsutil config -e