Add basics of (by-default disabled) REST API

This commit is contained in:
jesopo 2018-10-04 16:01:13 +01:00
parent f2d9ff9d3b
commit 82b40cc8b2
2 changed files with 71 additions and 8 deletions

51
modules/rest_api.py Normal file
View file

@ -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()

View file

@ -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}