Skip to content

Instantly share code, notes, and snippets.

Last active July 28, 2019 12:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tribela/d573fda522800af828949aca7c9c8f18 to your computer and use it in GitHub Desktop.
Mpris listener to change yeelight color
import gi.repository.GLib
from dbus.mainloop.glib import DBusGMainLoop
from io import BytesIO
from pprint import pprint
import colorthief
import mpris2
import requests
class LightManager():
API_KEY = '7fb78a81b20bee7cb6e8fad4cbcb3694'
API_URL = ''
YEELIGHT_URL = 'http://sakura.lan:31337/light'
def __init__(self):
player_uri = next(mpris2.get_players_uri())
self.player = mpris2.Player(dbus_interface_info={
'dbus_uri': player_uri})
self.player.PropertiesChanged = self.property_handler
self.last_song = None
def run(self):
mloop = gi.repository.GLib.MainLoop()
def handle_changed(self):
artist = str(self.player.Metadata['xesam:artist'][0])
album = str(self.player.Metadata['xesam:album'])
title = str(self.player.Metadata['xesam:title'])
if (artist, album, title) != self.last_song:
print(f'{artist} - {album} - {title}')
self.last_song = (artist, album, title)
cover = self.get_lastfm_cover(artist, album)
if not cover:
color = self.get_colorcode(cover)
def property_handler(self, *args, **kwargs):
data = args[1]
if 'Metadata' in data:
def change_color(self, color):
resp =, {
'rgb': color
def get_lastfm_cover(cls, artist, album):
res = requests.get(cls.API_URL, {
'method': 'album.getInfo',
'artist': artist,
'album': album,
'api_key': cls.API_KEY,
'format': 'json',
if 'error' in res:
return res['album']['image'][-1]['#text']
def get_colorcode(image_url):
resp = requests.get(image_url)
file = BytesIO(resp.content)
ct = colorthief.ColorThief(file)
r, g, b = ct.get_color()
print('Color: {:02x}{:02x}{:02x}'.format(r, g, b))
r //= 2
print('Color (Adjusted): {:02x}{:02x}{:02x}'.format(r, g, b))
return '{:02x}{:02x}{:02x}'.format(r, g, b)
lm = LightManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment