Upgraded lastfm to use SQL

This commit is contained in:
neersighted 2012-02-28 07:58:34 +08:00 committed by lukeroge
parent dad1c0873e
commit 1905f68037

View file

@ -1,20 +1,28 @@
from util import hook, http from util import hook, http
api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
@hook.command @hook.command
def lastfm(inp, nick='', say=None, bot=None): def lastfm(inp, nick='', say=None, db=None, bot=None):
if inp: db.execute("create table if not exists lastfm(nick primary key, acc)")
user = inp sql = db.execute("select acc from lastfm where nick=lower(?)", (nick,)).fetchone();
else: api_url = "http://ws.audioscrobbler.com/2.0/?format=json"
user = nick api_key = bot.config.get("api_keys", {}).get("lastfm")
api_key = bot.config.get("api_keys", {}).get("lastfm", None)
if api_key is None: if api_key is None:
return "error: no api key set" return "error: no api key set"
if sql:
if not inp: user = sql[0]
else:
user = inp
db.execute("insert or replace into lastfm(nick,acc) values(?,?)",(nick.lower(), user))
db.commit()
else:
if not inp: user = nick
else:
user = inp
db.execute("insert or replace into lastfm(nick,acc) values(?,?)",(nick.lower(), user))
db.commit()
response = http.get_json(api_url, method="user.getrecenttracks", response = http.get_json(api_url, method="user.getrecenttracks",
api_key=api_key, user=user, limit=1) api_key=api_key, user=user, limit=1)
@ -22,12 +30,12 @@ def lastfm(inp, nick='', say=None, bot=None):
if inp: # specified a user name if inp: # specified a user name
return "error: %s" % response["message"] return "error: %s" % response["message"]
else: else:
return "Your nick is not a LastFM account. Try '.lastfm username'." return "your nick is not a LastFM account. try '.lastfm username'."
tracks = response["recenttracks"]["track"] tracks = response["recenttracks"]["track"]
if len(tracks) == 0: if len(tracks) == 0:
return "No recent tracks for user %r found." % user return "no recent tracks for user %r found" % user
if type(tracks) == list: if type(tracks) == list:
# if the user is listening to something, the tracks entry is a list # if the user is listening to something, the tracks entry is a list
@ -40,7 +48,7 @@ def lastfm(inp, nick='', say=None, bot=None):
track = tracks track = tracks
status = 'last track' status = 'last track'
else: else:
return "Error parsing track listing" return "error parsing track listing"
title = track["name"] title = track["name"]
album = track["album"]["#text"] album = track["album"]["#text"]
@ -53,3 +61,4 @@ def lastfm(inp, nick='', say=None, bot=None):
ret += " on \x02%s\x0f" % album ret += " on \x02%s\x0f" % album
say(ret) say(ret)