1
0
Fork 0
nemubot/modules/jsonbot.py

59 lines
1.6 KiB
Python
Raw Normal View History

2015-06-14 14:17:48 +00:00
from nemubot.hooks import hook
from nemubot.exception import IMException
2015-06-14 14:17:48 +00:00
from nemubot.tools import web
from nemubot.module.more import Response
2015-06-14 14:17:48 +00:00
import json
nemubotversion = 3.4
def help_full():
return "Retrieves data from json"
2015-07-02 21:49:17 +00:00
def getRequestedTags(tags, data):
response = ""
if isinstance(data, list):
for element in data:
repdata = getRequestedTags(tags, element)
2015-07-02 23:05:01 +00:00
if response:
response = response + "\n" + repdata
else:
response = repdata
2015-07-02 21:49:17 +00:00
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()
2015-06-14 14:17:48 +00:00
2015-11-02 19:19:12 +00:00
@hook.command("json")
2015-07-02 21:49:17 +00:00
def get_json_info(msg):
2015-07-10 21:09:54 +00:00
if not len(msg.args):
raise IMException("Please specify a url and a list of JSON keys.")
2015-06-14 14:17:48 +00:00
2015-07-10 21:09:54 +00:00
request_data = web.getURLContent(msg.args[0].replace(' ', "%20"))
2015-06-14 14:17:48 +00:00
if not request_data:
raise IMException("Please specify a valid url.")
2015-06-14 14:17:48 +00:00
json_data = json.loads(request_data)
2015-07-10 21:09:54 +00:00
if len(msg.args) == 1:
raise IMException("Please specify the keys to return (%s)" % ", ".join(getJsonKeys(json_data)))
2015-06-14 14:17:48 +00:00
2015-07-10 21:09:54 +00:00
tags = ','.join(msg.args[1:]).split(',')
2015-07-02 21:49:17 +00:00
response = getRequestedTags(tags, json_data)
2015-06-14 14:17:48 +00:00
return Response(response, channel=msg.channel, nomore="No more content", count=" (%d more lines)")