XChat MPD Song Display

XChat MPD (Music Player Daemon) Song Display for Xchat,

python script to display song information in channel.

Dependencies: python-mpd – Python MPD client library

Ubuntu: sudo apt-get install python-mpd

__module_version__ = "2.0" 
__module_description__ = "MPD Xchat Plugin"

import xchat
import mpd
import os
import time

HOSTNAME = "localhost"
PORT = "6600"

client = mpd.MPDClient()

def mpd_connect():

	try:
		client.connect(HOSTNAME,PORT) 
	except:
		print "Failed to connect to MPD: %s:%s" % (HOSTNAME,PORT)
	
	return client

def mpd_disconnect(client):
	client.close()                     # send the close command
	client.disconnect()                # disconnect from the server
	return

def mpdshow_cb(word, word_eol, userdata):

	client = mpd_connect()
	current_song = client.currentsong()
	current_status = client.status()
	song_filename = os.path.basename(current_song["file"])
	(song_shortname, song_extension) = os.path.splitext(song_filename)
	song_extension = song_extension[1:]
	ratestr = "%s kbps" % current_status["bitrate"]
	(freqhz,bit,chan) = current_status["audio"].split(":")
	(song_pos,song_length) = current_status["time"].split(":")

	song_pos = time.strftime('%M:%S', time.gmtime(float(song_pos)))
	song_length = time.strftime('%M:%S', time.gmtime(float(song_length)))
	
#	song_position = current_status["songid"]
#	playlist_length = current_status["playlistlength"]

	# show filename if /mpdshow is given any parameters
	if len(word) > 1:
		msg = "ME playing: %s (%s) (%s kHz) (%s/%s) [%s]" % (song_shortname, ratestr,freqhz,song_pos,song_length,song_extension) 
	else: 
		msg = "ME playing: %s - %s - %s (%s) (%s/%s) [%s]" % (current_song["artist"], current_song["album"], current_song["title"],ratestr,song_pos,song_length,song_extension) 

	xchat.command(msg)
	mpd_disconnect(client)
	return xchat.EAT_ALL

def mpdplaypause_cb(word, word_eol, userdata):
	client = mpd_connect()
	client.pause()                   
	mpd_disconnect(client)	
	return xchat.EAT_ALL

def mpdprev_cb(word, word_eol, userdata):
	client = mpd_connect()
	client.previous()                   
	mpd_disconnect(client)	
	return xchat.EAT_ALL

def mpdnext_cb(word, word_eol, userdata):
	client = mpd_connect()
	client.next()                   
	mpd_disconnect(client)	
	return xchat.EAT_ALL

xchat.hook_command("MPDPLAY", mpdplaypause_cb, help="/mpdplay play/pause song")
xchat.hook_command("MPDNEXT", mpdnext_cb, help="/mpdnext change to next song")
xchat.hook_command("MPDPREV", mpdprev_cb, help="/mpdprev change to previous song")
xchat.hook_command("MPDSHOW", mpdshow_cb, help="/mpdshow shows song information to channel, /mpdshow 1 - shows filename instead of artist + album")
More Reading