Skip to content

Instantly share code, notes, and snippets.

@jamesmcdonald
Last active November 2, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmcdonald/bdb2c4c51eda435afa2617513cbd1b62 to your computer and use it in GitHub Desktop.
Save jamesmcdonald/bdb2c4c51eda435afa2617513cbd1b62 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Wrap i3status to add things to your i3bar
You need to have dbus-python installed.
Right now this will prepend
* Spotify status that looks like "Artist > Song".
The > will be replaced with an _ if Spotify is paused.
Your ~/.i3status.conf should contain:
general {
output_format = "i3bar"
}
And in ~/.i3/config you should have something like:
bar {
status_command "i3status | ~/bin/statuswrap.py"
}
"""
from __future__ import print_function
import sys
import json
import dbus
class SpotifyStatus(object):
"""Get Spotify status via DBus"""
def __init__(self, interface=None):
self.interface = interface
@staticmethod
def getinterface():
"""Get an interface to Spotify via the session bus
Returns None if it can't find the object."""
try:
session_bus = dbus.SessionBus()
spotify = session_bus.get_object('org.mpris.MediaPlayer2.spotify',
'/org/mpris/MediaPlayer2')
interface = dbus.Interface(spotify, dbus_interface='org.freedesktop.DBus.Properties')
except dbus.DBusException:
return None
return interface
def playing(self):
"""Return a string showing what is playing and whether it is paused"""
if self.interface is None:
self.interface = self.getinterface()
if self.interface is None:
return '[Spotify not running]'
try:
metadata = self.interface.Get('org.mpris.MediaPlayer2.Player', 'Metadata')
play = self.interface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus')
play = '>' if play == 'Playing' else '_'
except dbus.DBusException:
self.interface = None
return '[Spotify went away]'
artist = ', '.join(metadata['xesam:artist'])
title = metadata['xesam:title']
return '{} {} {}'.format(artist, play, title)
def read_line():
"""Read a line from stdin"""
try:
line = sys.stdin.readline().strip()
if not line:
sys.exit(3)
return line
except KeyboardInterrupt:
sys.exit()
def print_line(line):
"""Print a line to stdout"""
sys.stdout.write(line + '\n')
sys.stdout.flush()
def main():
"""A function to shut pylint up"""
spotify = SpotifyStatus()
print_line(read_line())
print_line(read_line())
while True:
line, prefix = read_line(), ''
if line.startswith(','):
line, prefix = line[1:], ','
j = json.loads(line)
j.insert(0, {'full_text': '%s' % spotify.playing(), 'name': 'spotify'})
print_line(prefix+json.dumps(j))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment