Bad Request at Authorization Code Flow Spotify - python

I am trying to built a script that creates a playlist on a user's spotify profile. To learn spotipy I decided to try the examples they have on the documentation page.
The code I run is:
import sys
import spotipy
import spotipy.util as util
token = util.prompt_for_user_token('idxxx',
'user-library-read',
client_id='axxx',
client_secret='Bxxx',
redirect_uri='http://localhost')
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print("Usage: %s username" % (sys.argv[0],))
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print(track['name'] + ' - ' + track['artists'][0]['name'])
else:
print("Can't get token for", username)
The problem occurs when i run the code. I get redirected on my redirect uri and after i paste it back on the terminal i get this:
Traceback (most recent call last):
File "spot01.py", line 9, in <module>
redirect_uri='http://localhost')
File "/home/user/.local/lib/python3.6/site-packages/spotipy/util.py", line 92, in prompt_for_user_token
token = sp_oauth.get_access_token(code, as_dict=False)
File "/home/user/.local/lib/python3.6/site-packages/spotipy/oauth2.py", line 434, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
I tried to access the oauth2.py from the File Manager and the terminal but it says that this repository does not exist. Also i tried to install spotipy through the github page they have where the neccessary files exist but still nothing.
Any ideas?
Thanks a lot.

I solved the problem by downloading the required files from here https://github.com/plamere/spotipy/tree/master/spotipy
Then I changed some things inside of each .py file and i run every code I wanted to inside there. It must be another more fancy solution but this one worked for me.
Oh before running any command I typed this set of commands on the terminal:
$ bash
$ export SPOTIPY_CLIENT_ID='xxx'
$ export SPOTIPY_CLIENT_SECRET='xxx'
$ export SPOTIPY_REDIRECT_URI='http://localhost/'
where xxx you put your credentials and at the refirect uri your localhost or your github profile link.

Related

Create a Spotify playlist using spotipy

I am trying to create a playlist using the spotipy library. I followed the instructions on their website alongside this solved question Spotipy invalid username? . When running the code provided in this question (fitted to my Spotify developer account) everything works fine. However when trying another scope corresponding to my object of creating a playlist I get the same username error as mentioned in the linked question:
Traceback (most recent call last):
File "C:\Users\d92167\Spotify\Create_Favorites.py", line 23, in <module>
sp.user_playlist_create(cred.user_name, name=playlist_name)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 784, in user_playlist_create
return self._post("users/%s/playlists" % (user,), payload=data)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 302, in _post
return self._internal_call("POST", url, payload, kwargs)
File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 267, in _internal_call
raise SpotifyException(
SpotifyException: https://api.spotify.com/v1/users/*My Username*/playlists:
Invalid username
My code:
import spotipy
import cred
scope = 'playlist-modify-public'
token = spotipy.util.prompt_for_user_token(cred.user_name,scope,client_id=cred.client_id,client_secret=cred.client_secret,redirect_uri=cred.redirect_url)
sp = spotipy.Spotify(auth=token)
playlist_name = 'Test'
sp.user_playlist_create(cred.user_name, name=playlist_name)
I am using Python 3.8 and Spotipy version 2.20.0
I have 2 possible solutions:
1: You forgot to type user=
sp.user_playlist_create(user=cred.user_name, name=playlist_name)
2: Maybe the user_name in the cred file is wrong. You can get the username with this code:
sp_user = sp.current_user()
user_name = sp_user['uri'].split(":")[2]

Instabot API for Python raises error after running code for the 2nd time

I am currently working with the Instabot API for python and I ran across the following issue:
I wrote a small program:
from instabot import Bot
bot = Bot()
bot.login(username = "[my username]", password = "[my passowrd]")
bot.follow("lego")
which worked fine after running it for the very first time. However, after running the program for a second time, this time following another account, it raised an error ("KeyError: ds_user").
This error can be fixed by deleting the config folder inside the project folder. Unfortunately, this isn't a very sustainable solution, as it makes working on the code really arduous. I therefore would like to know if there is any solution for getting the program to run multiple times without having to delete the config folder over and over again.
I am receiving the following traceback (code is running in an anaconda environment called "Instagram Automation"):
Traceback (most recent call last):
File "e:/Programme/OneDrive/Dokumente/Projekte/Instagram Automation/main.py", line 4, in <module>
bot.login(username = "[my username]", password = "[my password]")
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\bot\bot.py", line 443, in login
if self.api.login(**args) is False:
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 240, in login
self.load_uuid_and_cookie(load_cookie=use_cookie, load_uuid=use_uuid)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api.py", line 199, in load_uuid_and_cookie
return load_uuid_and_cookie(self, load_uuid=load_uuid, load_cookie=load_cookie)
File "E:\Programme\Anaconda\envs\Instagram Automation\lib\site-packages\instabot\api\api_login.py", line 352, in load_uuid_and_cookie
cookie_username = self.cookie_dict["ds_user"]
KeyError: 'ds_user'
As far as I can see, the only way on your side to fight the symptoms is to always delete the JSON file in the config folder, e.g:
import os
if os.path.isfile("path/to/config/file.json"):
os.remove("path/to/config/file.json")
import instabot
# rest of your code goes here
The developers of instabot should fix the source of the problem, for example by using self.cookie_dict.get("ds_user", "some default value") instead of self.cookie_dict["ds_user"]

Why is pyperclip "not found", even though it is clearly installed?

I'm doing a basic coding project for class. It's the password locker from "Automate the Boring Stuff".
I have everything coded properly, compiled without errors and I've made the bat file and it's in the right spot.
This is the code (minus the dashes in front of the hashtags)
#! python3
#pw.py This is an insecure Password Locker.
PASSWORDS = {'yahooEmail':'12345', 'googleEmail':'23456','facebook':'34567', 'luggage':'45678'}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: py pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[acount])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account +'.')
So it should, of course, just allow me to type in the key to see the value, and copy/past new values as needed.
But when I run it I get this:
Traceback (most recent call last):
File "C:\Users\shawn\Desktop\Python homework\pw.py", line 6, in <module>
import sys, pyperclip
ModuleNotFoundError: No module named 'pyperclip'

How to initialize Python Slackbot module?

I'm new to Slack bots (familiar with Discord.py). I am using the Slackbot package (https://github.com/lins05/slackbot) to create my Python slack bot.
Followed the example on their page, installed the package using pip install slackbot, went to the path of the installation, created a slackbot_settings.py (with specified tags they mentioned) and run.py in the main directory and mybot.py (with example commands they showed on their page to test), but I can't initialize the bot. I tried to run the bot using python run.py but get the following error:
Traceback (most recent call last):
File "run.py", line 23, in
main()
File "run.py", line 20, in main
bot.run()
File "/Users/xxx/anaconda3/lib/python3.5/site-packages/slackbot/bot.py", line 32, in run
self._plugins.init_plugins()
File "/Users/xxx/anaconda3/lib/python3.5/site-packages/slackbot/manager.py", line 31, in init_plugins
self._load_plugins(plugin)
File "/Users/xxx/anaconda3/lib/python3.5/site-packages/slackbot/manager.py", line 47, in _load_plugins
path_name = importlib_find(plugin)
File "/Users/xxx/anaconda3/lib/python3.5/importlib/util.py", line 89, in find_spec
return _find_spec(fullname, parent.path)
AttributeError: module 'mybot' has no attribute 'path'
mybot.py has the following lines:
from slackbot.bot import respond_to
from slackbot.bot import listen_to
import re
#respond_to('hi', re.IGNORECASE)
def hi(message):
message.reply('I can understand hi or HI!')
# react with thumb up emoji
message.react('+1')
#respond_to('I love you')
def love(message):
message.reply('I love you too!')
#listen_to('Can someone help me?')
def help(message):
# Message is replied to the sender (prefixed with #user)
message.reply('Yes, I can!')
# Message is sent on the channel
message.send('I can help everybody!')
# Start a thread on the original message
message.reply("Here's a threaded reply", in_thread=True)
Where am I going wrong? I've tried asking the developer but got no answer.
The bot apparently can not find your mybot plugin. Assuming mybot.py is in the same folder than run.py change the entry in PLUGINS to 'mybot'. Then it should work.
Full example of slackbot_settings.py:
DEFAULT_REPLY = "Sorry but I didn't understand you"
PLUGINS = [
'mybot'
]

Cracking a PDF File using Python 3

I'm currently completing an assignment which requires me to create a script to crack a password from a PDF file, I already have a list which contains the password within, I am having issues when prompt to enter the path to the file and met with an Name not define error, please mind I am a novice to coding.
file = raw_input('Path: ')
wordlist = 'wordlist.txt'
word =open(wordlist, 'r')
allpass = word.readlines()
word.close()
for password in allpass:
password = password.strip()
print ("Testing password: "+password)
instance = dispatch('pdf.Application')
try:
instance.Workbooks.Open(file, False, True, None, password)
print ("Password Cracked: "+password)
break
except:
pass
When the program is running, it attempts the first password from the list then proceeds to crash.
python Comsec.py
Path: /home/hall/Desktop/comsec121/examAnswers.pdf
Testing password: 123456
Traceback (most recent call last):
File "Comsec.py", line 11, in <module>
instance = dispatch(&apos;pdf.Application&apos;)
NameError: name &apos;dispatch&apos; is not defined
Please excuse my formatting on this website, I am trying my best to help you understand my issue!
Thanks in advance!
This error means that inside your Python script there is no object or function with the name dispatch. You would get that same error if you tried:
instance = this_is_a_function_that_has_not_been_defined('pdf.Application')
Typically, this function should be defined in a Python module. To access it, at the top of your code you should have some import statement like this:
from aBeautifulModuleForPDFs import dispatch
That module will be providing you the missing dispatch function. Checking in Google, I suggest you to try with module pywin32. Install it (run pip install pywin32 in a terminal) and add this line at the beginning of the code:
from win32com.client import Dispatch as dispatch

Categories

Resources