[jsonbot] now supports json lists

This commit is contained in:
Max 2015-07-02 22:49:17 +01:00 committed by nemunaire
parent 0c960e984a
commit ea05b3014c

View File

@ -11,9 +11,39 @@ nemubotversion = 3.4
def help_full(): def help_full():
return "Retrieves data from json" return "Retrieves data from json"
def getRequestedTags(tags, data):
response = ""
if isinstance(data, list):
for element in data:
repdata = getRequestedTags(tags, element)
if repdata:
if response:
response = response + "\n" + repdata
else:
response = repdata
else:
for tag in tags:
if tag in data.keys():
if response:
response += ", " + tag + ": " + str(data[tag])
else:
response = tag + ": " + str(data[tag])
return response
def getJsonKeys(data):
if isinstance(data, list):
pkeys = []
for element in data:
keys = getJsonKeys(element)
for key in keys:
if not key in pkeys:
pkeys.append(key)
return pkeys
else:
return data.keys()
@hook("cmd_hook", "json") @hook("cmd_hook", "json")
def get_hn_info(msg): def get_json_info(msg):
if len(msg.cmds) < 2: if len(msg.cmds) < 2:
raise IRCException("Please specify a url and a list of JSON keys.") raise IRCException("Please specify a url and a list of JSON keys.")
@ -23,13 +53,9 @@ def get_hn_info(msg):
json_data = json.loads(request_data) json_data = json.loads(request_data)
if len(msg.cmds) == 2: if len(msg.cmds) == 2:
raise IRCException("Please specify the keys to return (%s)" % ", ".join(json_data.keys())) raise IRCException("Please specify the keys to return (%s)" % ", ".join(getJsonKeys(json_data)))
tags = msg.cmds[2].split(',') tags = msg.cmds[2].split(',')
response = "" response = getRequestedTags(tags, json_data)
for tag in tags:
if not tag in json_data.keys():
raise IRCException("The key '%s' was not found in the JSON retrieved." % tag)
response += tag + ": " + str(json_data[tag]) + "\n"
return Response(response, channel=msg.channel, nomore="No more content", count=" (%d more lines)") return Response(response, channel=msg.channel, nomore="No more content", count=" (%d more lines)")