New hack: mpd_random_playlist.c
[mpd-hacks.git] / mpdnp.py
blob0283547a83491be5f98c241c218d0971241a70d7
1 """
2 :Author: Henning Hasemann <hhasemann [at] web [dot] de>
4 :What it does:
5 This plugin lets you inform all users in the current
6 channel about the song which music-player-daemon (MPD)
7 is currently playing.
9 :Usage:
10 /mpdnp - Display file mpd is playing to current channel.
12 :Configuration Variables:
13 ============= ==========================================
14 Variable name Meaning
15 ============= ==========================================
16 host The host where your mpd runs
17 port The port to connect to mpd (usually 6600)
18 format How this script should display
19 whats going on.
20 You may use the following variables here:
21 $artist, $title_or_file,
22 $length_min, $length_sec, $pct,
23 $pos_min, $pos_sec
25 Released under GPL licence.
26 """
28 todo = """
29 - maybe support sending commands to mpd.
30 - maybe make condional display
31 (displaying some characters only
32 if preceding or trailing variables are set)
33 """
35 import weechat as wc
36 import mpdclient as mpd
37 import re
38 from os.path import basename, splitext
40 default_fmt = "/me 's MPD plays: $artist - $title_or_file ($length_min:$length_sec)"
42 wc.register("mpdnp", "0.3", "", "np for mpd")
44 def subst(text, values):
45 out = ""
46 n = 0
47 for match in re.finditer(findvar, text):
48 if match is None: continue
49 else:
50 l, r = match.span()
51 nam = match.group(1)
52 out += text[n:l+1] + values.get(nam, "") #"$" + nam)
53 n = r
54 return out + text[n:]
56 def np(server, args):
57 """
58 Send information about the currently
59 played song to the channel.
60 """
61 host = wc.get_plugin_config("host")
62 port = int(wc.get_plugin_config("port"))
63 cont = mpd.MpdController(host=host, port=port)
64 song = cont.getCurrentSong()
65 pos, length, pct = cont.getSongPosition()
67 # insert artist, title, album, track, path
68 d = song.__dict__
69 d.update({
70 "title_or_file": song.title or splitext(basename(song.path))[0],
71 "pos_sec": "%02d" % (pos / 60),
72 "pos_min": str(pos / 60),
73 "length_sec": "%02d" % (length % 60),
74 "length_min": str(length / 60),
75 "pct": "%2.0f" % pct,
78 wc.command(subst(wc.get_plugin_config("format"), d))
79 return 0
81 def dbgnp(server, args):
82 try:
83 return np(server, args)
84 except Exception, e:
85 print e
87 wc.add_command_handler("mpdnp", "np", "", "", np.__doc__)
89 findvar = re.compile(r'[^\\]\$([a-z_]+)(\b|[^a-z_])')
91 default = {
92 "host": "localhost",
93 "port": "6600",
94 "format": default_fmt,
97 for k, v in default.items():
98 if not wc.get_plugin_config(k):
99 wc.set_plugin_config(k, v)