diff --git a/modules/rest_api.py b/modules/rest_api.py new file mode 100644 index 00000000..39200148 --- /dev/null +++ b/modules/rest_api.py @@ -0,0 +1,51 @@ +import http.server, json, threading, urllib.parse +import flask + +_bot = None +_events = None +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + _bot.lock.acquire() + parsed = urllib.parse.urlparse(self.path) + query = parsed.query + get_params = urllib.parse.parse_qs(query) + + response = "" + code = 404 + + if parsed.path.startswith("/api/"): + _, _, endpoint = parsed.path[1:].partition("/") + response = _events.on("api").on(endpoint).call_for_result( + params=get_params) + + if response: + response = json.dumps(response, sort_keys=True, indent=4) + code = 200 + + self.send_response(code) + self.send_header("Content-type", "application/json") + self.end_headers() + try: + self.wfile.write(response.encode("utf8")) + except: + pass + _bot.lock.release() + +class Module(object): + def __init__(self, bot, events, exports): + self.bot = bot + global _bot + _bot = bot + + self.events = events + global _events + _events = events + + if bot.get_setting("rest-api", False): + self.httpd = http.server.HTTPServer(("", 5000), Handler) + self.thread = threading.Thread(target=self.httpd.serve_forever) + self.thread.daemon = True + self.thread.start() + + def unload(self): + self.httpd.shutdown() diff --git a/modules/stats.py b/modules/stats.py index 38cb8cd3..f9a35d13 100644 --- a/modules/stats.py +++ b/modules/stats.py @@ -2,27 +2,34 @@ import time from src import ModuleManager, utils class Module(ModuleManager.BaseModule): + def _uptime(self): + return utils.to_pretty_time(int(time.time()-self.bot.start_time)) + @utils.hook("received.command.uptime") def uptime(self, event): """ :help: Show my uptime """ - seconds = int(time.time()-self.bot.start_time) - event["stdout"].write("Uptime: %s" % utils.to_pretty_time( - seconds)) + event["stdout"].write("Uptime: %s" % self._uptime()) + @utils.hook("api.uptime") + def uptime_api(self, event): + return self._uptime() - @utils.hook("received.command.stats") - def stats(self, event): - """ - :help: Show my network/channel/user stats - """ + def _stats(self): networks = len(self.bot.servers) channels = 0 users = 0 for server in self.bot.servers.values(): channels += len(server.channels) users += len(server.users) + return [networks, channels, users] + @utils.hook("received.command.stats") + def stats(self, event): + """ + :help: Show my network/channel/user stats + """ + networks, channels, users = self._stats() response = "I currently have %d network" % networks if networks > 1: @@ -35,3 +42,8 @@ class Module(ModuleManager.BaseModule): response += "s" event["stdout"].write(response) + + @utils.hook("api.stats") + def stats_api(self, event): + networks, channels, users = self._stats() + return {"networks": networks, "channels": channels, "users": users}