I want to show the current playing song in Spotify on a 16x2 LCD.
I was thinking of connecting the LCD with my Arduino and then making a Python script that sends the current playing song of Spotify to the Arduino.
To get to the point, I'm looking for a way to get Spotify's current playing song in Python. (I'm using Windows 8.) I found some ways like dbus, but they were either for Linux or for Mac.
Thanks in advance! (And sorry for bad English grammar.)
I encountered the same issue, so I wrote a library to solve this issue. The library can be found at github: https://github.com/XanderMJ/spotilib. Keep in mind that this is still work in progress.
Just copy the file and place it in your Python/Lib directory.
import spotilib
spotilib.artist() #returns the artist of the current playing song
spotilib.song() #returns the song title of the current playing song
spotilib.artist() returns only the first artist. I started working on an other library spotimeta.py to solve this issue. However, this is not working at 100% yet.
import spotimeta
spotimeta.artists() #returns a list of all the collaborating artists of the track
If an error occurs, spotimeta.artists() will return only the first artist (found with spotilib.artist())
Hope this will help you (if still needed)!
The easiest way would probably be to scrobble the currently playing tracks from the Spotify client to a last.fm account and then use python to get it from there.
Last.fm allows you to get scrobbled tracks via their api with user.getRecentTracks which provides the nowplaying="true" attribute if a song is playing. It also provides some other useful things you may want for an external display like a link to the album art and last.fm page for the song.
Here's a quick example that takes a username and api key as cmd line arguments and fetches what is currently playing for that user using the requests library.
from time import sleep
import requests
import json
from pprint import pprint
import sys
def get_playing():
base_url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='
user = sys.argv[1]
key = sys.argv[2]
r = requests.get(base_url+user+'&api_key='+key+'&format=json')
data = json.loads(r.text)
latest_track = data['recenttracks']['track'][0]
try:
if latest_track['#attr']['nowplaying'] == 'true':
artist = latest_track['artist']['#text']
song = latest_track['name']
album = latest_track['album']['#text']
print "\nNow Playing: {0} - {1}, from the album {2}.\n".format(artist, song, album)
except KeyError:
print '\nNothing playing...\n'
def main():
if len(sys.argv)<3:
print "\nError: Please provide a username and api key in the format of: 'scrobble.py username api_key\n"
else:
get_playing()
if __name__ == '__main__':
main()
In a quick test it does seem to take a minute or so to realize the track is no longer playing after pausing or exiting the Spotify client however.
Is there more than one pytify ?
This worked for me until today:
https://code.google.com/p/pytify/
Spotify has been updated, now song is not shown in windows title anymore.
They will bring the "feature" back:
https://community.spotify.com/t5/ideas/v2/ideapage/blog-id/ideaexchange/article-id/73238/page/2#comments
while True:
print("Welcome to the project, " + user_name['display_name'])
print("0 - Exit the console")
print("1 - Search for a Song")
user_input = int(input("Enter Your Choice: "))
if user_input == 1:
search_song = input("Enter the song name: ")
results = spotifyObject.search(search_song, 1, 0, "track")
songs_dict = results['tracks']
song_items = songs_dict['items']
song = song_items[0]['external_urls']['spotify']
webbrowser.open(song)
print('Song has opened in your browser.')
elif user_input == 0:
print("Good Bye, Have a great day!")
break
else:
print("Please enter valid user-input.")
Related
Hello so I don't stream right but wanted to make a video on peoples reactions when they are suddenly hit with a lot of people (this would be accompanied by a chat bot too and ill tell them what it was as well as ask for use permissions). So I thought it would be fun to look at view bots for twitch and found one online (code below). so I ran in installed streamlink via Pip and windows executable and it seems to run "found matching plugin twitch for URL "Stream link"" but it doesn't actually increase viewership and I can only assume this is because its not actually opening the Vlc instances, so here I am wondering what I need to do I have the latest version of python and git isnt trying to download and install anything so im assuming streamlink is all I need but im kind confused why it woudnt be opening the VLC instance any help is most appreciated.
Edit: oh and I do have the proxies and using a small amount to try and get it to work first, and will buy more later but after I get this to work!
import concurrent.futures, time, random, os
#desired channel url
channel_url = 'https://www.twitch.tv/StreamerName'
#number of viewer bots
botcount = 10
#path to proxies.txt file
proxypath = "C:\Proxy\proxy.txt"
#path to vlc
playerpath = r'"C:\Program Files\VideoLAN\VLC\vlc.exe"'
#takes proxies from proxies.txt and returns to list
def create_proxy_list(proxyfile, shared_list):
with open(proxyfile, 'r') as file:
proxies = [line.strip() for line in file]
for i in proxies:
shared_list.append((i))
return shared_list
#takes random proxies from the proxies list and adds them to another list
def randproxy(proxylist, botcount):
randomproxylist = list()
for _ in range(botcount):
proxy = random.choice(proxylist)
randomproxylist.append(proxy)
proxylist.remove(proxy)
return (randomproxylist)
#launches a viewer bot after a short delay
def launchbots(proxy):
time.sleep(random.randint(5, 10))
os.system(f'streamlink --player={playerpath} --player-no-close --player-http --hls-segment-timeout 30 --hls-segment-attempts 3 --retry-open 1 --retry-streams 1 --retry-max 1 --http-stream-timeout 3600 --http-proxy {proxy} {channel_url} worst')
#calls the launchbots function asynchronously
def main(randomproxylist):
with concurrent.futures.ThreadPoolExecutor() as executer:
executer.map(launchbots, randomproxylist)
if __name__ == "__main__":
main(randproxy(create_proxy_list(proxypath, shared_list=list()), botcount))
I am working on a project that finds if a user is available or not on Instagram, (Basically that's only one of the functions.)
To do that I use this code from requests:
def start():
clear() # Clears the previous input through the OS module
print(inp + cut + "Stress them is booting...") # Inp + Cut are optional strings
use = input("Who do you want to attack? Enter here: >> ") # We take the input from here (Specifically the user)
response = requests.get("https://www.instagram.com/"+xuse+"/") # Check if the user exists, this does not work if you put # in the beginning.
if response.status_code == 404 :
PrintFatalError("User could not be found, try again.") # The user wasn't found
# Here the program stops and returns to the main program / input where I ask the user for a command.
elif response.status_code == 200 :
PrintFatalError("User " + use + " has been detected ! Proceed with the tool? ") # The user was found
f = input(" ") # This is the point
if f in "y":
print ("Beginning")
else:
print("Not a valid option, aborting.") # I abort since I don't want a loop in this phase.
Some other info that might help:
The program is fully CLI, I don't use a GUI.
This program uses while loops instead of for loops, for many reasons.
NOTE: PrintFatalError is a variable I created to display messages in red / green color. It still does not work with the classic print("string") way through.
I am very new to coding and web development. I am a Systems Engineer and looking to get into the Web Development side of things. I took some python tutorials and pieced together a (probably very) rough python application. I would now like to take that application and put it on a website I have created so that I can allow others in the office to use the utility as well.
To that end, I installed transcrypt with the goal of converting the python code to javascript. When running transcrypt I get the following output:
Error while compiling (offending file last):
File 'c:/Scripting/Transcrypt/Meraki.py', line 1, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/requests/init.py', line 43, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/urllib3/init.py', line 8, namely:
Attempt to import module: connectionpool
Can't find any of:
c:/Scripting/Transcrypt/connectionpool.py
c:/Scripting/Transcrypt/javascript/connectionpool.mod.js
The error goes on to list about 10 other files that it needs to run. I am not sure how to fix this issue and would appreciate any help anyone can give me.
Here is my code:
import requests
import json
from meraki import meraki
base_url = "https://dashboard.meraki.com/api/v0/"
def List_Orgs(apikey): #A FUNCTION FOR LISTING ORGANIZATION ADMINS
myOrgs = meraki.myorgaccess(apikey)
for orgs in myOrgs:
print(orgs)
def List_Admins(URL_admin, headers):
x = requests.get(URL_admin, headers = headers)
myAdmins = x.json()
for admins in myAdmins:
print(admins)
def Add_Admin(URL, admin_data, headers): #FUNCTION FOR ADDING NEW ADMIN
TO AN ORGANIZATION
r = requests.request("POST", URL, data = admin_data, headers = headers)
print(r.status_code)
if (r.status_code) == 201:
print()
print()
print("Administrator successfully added!")
print()
else:
print()
print("Administrator was NOT successfully added. Please try again!")
print()
def Del_Admin(URL_del, headers): #FUNCTION FOR DELETING AN ADMIN FROM AN
ORGANIZATION
r = requests.request("DELETE", URL_del, headers = headers)
print(r.status_code)
if (r.status_code) == 204:
print()
print()
print("Administrator successfully deleted!")
print()
else:
print()
print("Administrator was NOT successfully deleted. Please try again!")
print()
apikey = input("What is your Meraki API key? ")
print()
print("******************************************")
print()
print("Here is a list of your Organizations. You will need the ID to answer
the next set of questions.")
print()
print()
List_Orgs(apikey)
print()
print()
headers = {
'X-Cisco-Meraki-API-Key': apikey,
'Content-Type': "application/json"
}
add_or_del = input("Would you like to add or delete an admin? ")
if add_or_del == ("add" or "Add" or "ADD"):
orgid = input("Which Organization would you like to add an admin to? ")
admin_name = input("What is the new Admin's First and Last name? ")
admin_email = input("What is " + admin_name + "'s email address? ")
admin_access = input("What level of access would you like " + admin_name +
" to have? (full or read-only) ")
admin_data = '{\n\t\"name\":\"' + admin_name + '\",\n\t\"email\":\"' +
admin_email + '\",\n\t\"orgAccess\":\"' + admin_access + '\"}'
URL = (base_url + 'organizations/' + orgid + '/admins')
Add_Admin(URL, admin_data, headers)
elif add_or_del == ("delete" or "Delete" or "DELETE"):
orgid = input("Which Organization would you like to delete an admin from?
")
URL_admin = (base_url + 'organizations/' + orgid + '/admins/')
print()
print("Here is a list of Admins in this Organization. You will need to
admin ID to answer the next question.")
print()
print()
List_Admins(URL_admin, headers)
print()
print()
adminid = input ("What is the admin's Meraki portal ID? ")
URL_del = (base_url + 'organizations/' + orgid + '/admins/' + adminid)
Del_Admin(URL_del, headers)
else:
print("Please type add or delete and try again.")'
Thanks!
David
The problem lies with the imports:
import requests
import json
from meraki import meraki
A module like requests is a standard Python module that isn't supported by Transcrypt, since it uses code written in C, that doesn't run in a browser.
For json there's a JavaScript counterpart that can be used directly from Transcrypt without problems.
Module meraki I don't know, so can't judge about.
Although a growing number of standard modules is supplied in the Transcrypt distribution, in general it makes use of JavaScript modules, since these are specially geared toward functionality that makes sense in a browser.
E.g. local file access is generally prohibited in a browser, so any module using that cannot do it's 'thing'.
See also:
http://www.transcrypt.org/docs/html/what_why.html#the-ecosystem-different-batteries
So in Transcrypt you program in Python, but the libs you use are mainly JavaScript. The exception are very common libs like math, cmath, random (partially), time, datetime, itertools, re etc.
To get an impression of how to use JavaScript libs from Transcrypt, take a look at:
http://www.transcrypt.org/examples
and also at:
http://www.transcrypt.org/docs/html/integration_javascript.html#mixed-examples
[EDIT]
I've taken another good look at your application, and I notice that it's a typical console application, using things like input and print. While these are supported in Transcrypt in a limited way, see
http://www.transcrypt.org/docs/html/integration_javascript.html#example-using-input-and-print-in-a-dom-terminal-element-in-your-browser
in general web applications work somewhat differently.
In general they are event driven, meaning that a number of GUI elements are pieced together, sometimes in HTML, sometimes in a script. These GUI elements then trigger events, that in turn trigger certain pieces of code (event handlers) to be run.
So a good next step may be to study this way of working. A nice, simple example in Transcrypt, of HTML/DOM and a script cooperating in this way is this one:
http://www.transcrypt.org/docs/html/installation_use.html#your-first-transcrypt-program
In many cases with a web application there's also interaction with a webserver, so part of the processing is done on the server.
You can e.g. use Bottle or Django for that, as is demoed at:
https://github.com/Michael-F-Ellis/NearlyPurePythonWebAppDemo
Fairly new to python, I learn by doing, so I thought I'd give this project a shot. Trying to create a script which finds the google analytics request for a certain website parses the request payload and does something with it.
Here are the requirements:
Ask user for 2 urls ( for comparing the payloads from 2 diff. HAR payloads)
Use selenium to open the two urls, use browsermobproxy/phantomJS to
get all HAR
Store the HAR as a list
From the list of all HAR files, find the google analytics request, including the payload
If Google Analytics tag found, then do things....like parse the payload, etc. compare the payload, etc.
Issue: Sometimes for a website that I know has google analytics, i.e. nytimes.com - the HAR that I get is incomplete, i.e. my prog. will say "GA Not found" but that's only because the complete HAR was not captured so when the regex ran to find the matching HAR it wasn't there. This issue in intermittent and does not happen all the time. Any ideas?
I'm thinking that due to some dependency or latency, the script moved on and that the complete HAR didn't get captured. I tried the "wait for traffic to stop" but maybe I didn't do something right.
Also, as a bonus, I would appreciate any help you can provide on how to make this script run fast, its fairly slow. As I mentioned, I'm new to python so go easy :)
This is what I've got thus far.
import browsermobproxy as mob
from selenium import webdriver
import re
import sys
import urlparse
import time
from datetime import datetime
def cleanup():
s.stop()
driver.quit()
proxy_path = '/Users/bob/Downloads/browsermob-proxy-2.1.4-bin/browsermob-proxy-2.1.4/bin/browsermob-proxy'
s = mob.Server(proxy_path)
s.start()
proxy = s.create_proxy()
proxy_address = "--proxy=127.0.0.1:%s" % proxy.port
service_args = [proxy_address, '--ignore-ssl-errors=yes', '--ssl-protocol=any'] # so that i can do https connections
driver = webdriver.PhantomJS(executable_path='/Users/bob/Downloads/phantomjs-2.1.1-windows/phantomjs-2.1.1-windows/bin/phantomjs', service_args=service_args)
driver.set_window_size(1400, 1050)
urlLists = []
collectTags = []
gaCollect = 0
varList = []
for x in range(0,2): # I want to ask the user for 2 inputs
url = raw_input("Enter a website to find GA on: ")
time.sleep(2.0)
urlLists.append(url)
if not url:
print "You need to type something in...here"
sys.exit()
#gets the two user url and stores in list
for urlList in urlLists:
print urlList, 'start 2nd loop' #printing for debug purpose, no need for this
if not urlList:
print 'Your Url list is empty'
sys.exit()
proxy.new_har()
driver.get(urlList)
#proxy.wait_for_traffic_to_stop(15, 30) #<-- tried this but did not do anything
for ent in proxy.har['log']['entries']:
gaCollect = (ent['request']['url'])
print gaCollect
if re.search(r'google-analytics.com/r\b', gaCollect):
print 'Found GA'
collectTags.append(gaCollect)
time.sleep(2.0)
break
else:
print 'No GA Found - Ending Prog.'
cleanup()
sys.exit()
cleanup()
This might be a stale question, but I found an answer that worked for me.
You need to change two things:
1 - Remove sys.exit() -- this causes your programme to stop after the first iteration through the ent list, so if what you want is not the first thing, it won't be found
2 - call new_har with the captureContent option enabled to get the payload of requests:
proxy.new_har(options={'captureHeaders':True, 'captureContent': True})
See if that helps.
I am just creating a chatbot in Python. It's working well but I want to add pyttsx to this chatbot so that it could speak its output.
My code is
import aiml
import sys
import pyttsx
engine = pyttsx.init()
# Create a Kernel object.
kern = aiml.Kernel()
brainLoaded = False
forceReload = False
while not brainLoaded:
if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"):
kern.bootstrap(learnFiles="std-startup.xml", commands="load aiml b")
brainLoaded = True
kern.saveBrain("standard.brn")
else:
try:
kern.bootstrap(brainFile = "standard.brn")
brainLoaded = True
except:
forceReload = True
print "\nINTERACTIVE MODE (ctrl-c to exit)"
while(True):
hea = kern.respond(raw_input("> "))
print hea
engine.say (hea)
engine.runAndWait()
When I am running this code I am not hearing any voice but I can see chat on terminal. I want it to speak the response, too. What am I doing wrong?
engine.runAndWait is outside the while(True): loop, so it's unlikely to be played until the loop is interrupted.
If you move it into the loop, and and the sound is choppy, test the code below:
import pyttsx
engine = pyttsx.init()
engine.say("Oh, hello!")
My experience with pyttsx is that it needs to be fed short amounts of text, otherwise the text is interrupted. I'm not sure exactly why that is, but truncating the sentences yourself and saying several phrases should suit your purpose:
engine.say("It's nice to meet you.")
engine.say("I hope you are doing well.")
engine.say("Would you like to join us ")
engine.say ("tomorrow at eight for dinner?")
But you'd need to parse the text and truncate it in a way that would keep the message intact.