Geoffrey-Django/api/views.py

92 lines
2.6 KiB
Python
Raw Normal View History

from django.views.generic import View
from django.http import JsonResponse
2018-12-02 02:17:19 +00:00
from django.conf import settings
import traceback
import sys
import GeoffreyApp.api.commands as commands
2018-12-17 16:02:43 +00:00
from GeoffreyApp.errors import *
from GeoffreyApp.models import APIToken
def check_token(request, **kwargs):
if "api" in request:
key = request["api"]
if APIToken.objects.filter(key=key, **kwargs).exists():
return True
return False
def run_command(request, command, req_type):
command = command.lower()
try:
if command in commands.command_dict[req_type]:
params = request.dict()
params.pop("api")
response = commands.command_dict[req_type][command]["func"](**params)
else:
raise CommandNotFound
except Exception as e:
response = {"error": e.__class__.__name__, "error_message": str(e)}
2019-01-31 23:10:28 +00:00
if getattr(settings, "DEBUG", False):
traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)
return JsonResponse(response, safe=False)
def get_commands():
command_list = []
for request in commands.command_dict:
for c in commands.command_dict[request]:
command_list.append({"command": c, "help": commands.command_dict[request][c]["help"]})
return command_list
class CommandAPI(View):
def get(self, request, command):
get = request.GET
if check_token(get, commands_perm=True):
if command.lower() == "commands":
return JsonResponse(get_commands(), safe=False)
else:
return run_command(get, command, "GET")
2018-12-08 21:37:00 +00:00
else:
return JsonResponse({})
def post(self, request, command):
post = request.POST
if check_token(post, commands_perm=True):
return run_command(post, command, "POST")
else:
return JsonResponse({})
def delete(self, request, command):
delete = request.DELETE
if check_token(delete, commands_perm=True):
return run_command(delete, command, "DELETE")
else:
return JsonResponse({})
2018-12-02 02:17:19 +00:00
class SettingsAPI(View):
2018-12-08 21:37:00 +00:00
def get(self, request):
if check_token(request.GET, commands_perm=True):
2019-01-01 16:18:15 +00:00
response = {
"BOT_PREFIX": getattr(settings, 'GEOFFREY_BOT_PREFIX', '?'),
"ERROR_USERS": getattr(settings, 'GEOFFREY_BOT_ERROR_USERS', []),
2019-01-01 16:18:15 +00:00
"MOD_RANKS": getattr(settings, 'GEOFFREY_BOT_MOD_RANK', []),
"STATUS": getattr(settings, 'GEOFFREY_BOT_STATUS', 'sed')
}
else:
response = {}
2018-12-02 02:17:19 +00:00
return JsonResponse(response)