示例#1
0
def api(req):
    httpresponse = None
    if req.method == "POST":
        tracker = req.GET.get("tracker")
        trackers = tracker.split(",")
        print("tracker:{}".format(tracker))
        if tracker:
            if "ffxiv-eureka" in trackers:
                instance = req.GET.get("instance")
                password = req.GET.get("password")
                print("ffxiv-eureka {}:{}".format(instance,password))
                if instance and password:
                    nm_name = req.POST.get("text")
                    if nm_name:
                        nm_id = get_nm_id("ffxiv-eureka", nm_name)
                        print("nm_name:{} id:{}".format(nm_name,nm_id))
                        if nm_id > 0:
                            print("nm_name:{} nm_id:{}".format(nm_name,nm_id))
                            # ws = create_connection("wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0")
                            ws = create_connection(
                                "wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0"
                            )
                            msg = '["1","1","instance:{}","phx_join",{{"password":"******"}}]'.format(
                                instance, password
                            )
                            # print(msg)
                            ws.send(msg)
                            msg = '["1","2","instance:{}","set_kill_time",{{"id":{},"time":{}}}]'.format(
                                instance, nm_id, int(time.time() * 1000)
                            )
                            # print(msg)
                            ws.send(msg)
                            ws.close()
                            httpresponse = HttpResponse("OK", status=200)
                    else:
                        print("no nm_name")
            if "ffxivsc" in trackers:
                key = req.GET.get("key")
                # print("ffxiv-eureka {}:{}".format(instance,password))
                if key:
                    nm_name = req.POST.get("text")
                    if nm_name:
                        nm_level_type = get_nm_id("ffxivsc", nm_name)
                        if int(nm_level_type["type"]) > 0:
                            url = (
                                "https://nps.ffxivsc.cn/lobby/addKillTime"
                            )
                            post_data = {
                                "killTime": strftime(
                                    "%Y-%m-%d %H:%M", time.localtime()
                                ),
                                "level": "{}".format(nm_level_type["level"]),
                                "key": key,
                                "type": "{}".format(nm_level_type["type"]),
                            }
                            r = requests.post(url=url, data=post_data)
                            httpresponse = HttpResponse(r)
                    else:
                        print("no nm_name")
            if "qq" in trackers:
                bot_qq = req.GET.get("bot_qq")
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                group_id = req.GET.get("group")
                print("bot: {} qq:{} token:{}".format(bot_qq, qq, token))
                if bot_qq and qq and token:
                    bot = None
                    qquser = None
                    group = None
                    api_rate_limit = True
                    try:
                        bot = QQBot.objects.get(user_id=bot_qq)
                    except QQBot.DoesNotExist:
                        print("bot {} does not exist".format(bot_qq))
                    try:
                        qquser = QQUser.objects.get(user_id=qq, bot_token=token)
                        if time.time() < qquser.last_api_time + qquser.api_interval:
                            api_rate_limit = False
                            print("qquser {} api rate limit exceed".format(qq))
                        qquser.last_api_time = int(time.time())
                        qquser.save(update_fields=["last_api_time"])
                    except QQUser.DoesNotExist:
                        print("qquser {}:{} auth fail".format(qq, token))
                        qquser = None
                    if bot and qquser and api_rate_limit:
                        channel_layer = get_channel_layer()
                        msg = req.POST.get("text")
                        reqbody = req.body
                        try:
                            if reqbody:
                                reqbody = reqbody.decode()
                                reqbody = json.loads(reqbody)
                                msg = msg or reqbody["content"]
                                msg = re.compile(
                                    "[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]"
                                ).sub(" ", msg)
                        except BaseException:
                            pass
                        print("body:{}".format(req.body.decode()))
                        if group_id:
                            try:
                                group = QQGroup.objects.get(group_id=group_id)
                                group_push_list = [
                                    user["user_id"]
                                    for user in json.loads(group.member_list)
                                    if (
                                        user["role"] == "owner"
                                        or user["role"] == "admin"
                                    )
                                ]
                                print("group push list:{}".format(group_push_list))
                            except QQGroup.DoesNotExist:
                                print("group:{} does not exist".format(group_id))
                        msg = handle_hunt_msg(msg)
                        if (
                            group
                            and group.api
                            and int(qquser.user_id) in group_push_list
                        ):
                            jdata = {
                                "action": "send_group_msg",
                                "params": {
                                    "group_id": group.group_id,
                                    "message": "Message from [CQ:at,qq={}]:\n{}".format(
                                        qquser.user_id, msg
                                    ),
                                },
                                "echo": "",
                            }
                        else:
                            jdata = {
                                "action": "send_private_msg",
                                "params": {"user_id": qquser.user_id, "message": msg},
                                "echo": "",
                            }
                        if not bot.api_post_url:
                            async_to_sync(channel_layer.send)(
                                bot.api_channel_name,
                                {"type": "send.event", "text": json.dumps(jdata)},
                            )
                        else:
                            url = os.path.join(bot.api_post_url, "{}?access_token={}".format(jdata["action"], bot.access_token))
                            headers = {'Content-Type': 'application/json'} 
                            r = requests.post(url=url, headers=headers, data=json.dumps(jdata["params"]))
                            if r.status_code!=200:
                                logging.error(r.text)
                        httpresponse = HttpResponse("OK", status=200)
            if "webapi" in trackers:
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                print("qq:{}\ntoken:{}".format(qq, token))
                if qq and token:
                    qquser = None
                    try:
                        qquser = QQUser.objects.get(user_id=qq, bot_token=token)
                    except QQUser.DoesNotExist:
                        res_dict = {
                            "response": "error",
                            "msg": "Invalid API token",
                            "rcode": "101",
                        }
                        return JsonResponse(res_dict)
                    if qquser:
                        res_dict = webapi(req)
                        return JsonResponse(res_dict)
                else:
                    res_dict = {
                        "response": "error",
                        "msg": "Invalid request",
                        "rcode": "100",
                    }
                    return JsonResponse(res_dict)
                return HttpResponse(status=500)
    return httpresponse if httpresponse else HttpResponse(status=404)
示例#2
0
文件: api.py 项目: shana321/FFXIVBOT
def api(req):
    httpresponse = None
    if req.method == "POST":
        tracker = req.GET.get("tracker")
        trackers = tracker.split(",")
        print("tracker:{}".format(tracker))
        if tracker:
            if "ffxiv-eureka" in trackers:
                instance = req.GET.get("instance")
                password = req.GET.get("password")
                print("ffxiv-eureka {}:{}".format(instance, password))
                if instance and password:
                    nm_name = req.POST.get("text")
                    if nm_name:
                        nm_id = get_nm_id("ffxiv-eureka", nm_name)
                        print("nm_name:{} id:{}".format(nm_name, nm_id))
                        if nm_id > 0:
                            print("nm_name:{} nm_id:{}".format(nm_name, nm_id))
                            # ws = create_connection("wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0")
                            ws = create_connection(
                                "wss://ffxiv-eureka.com/socket/websocket?vsn=2.0.0"
                            )
                            msg = '["1","1","instance:{}","phx_join",{{"password":"******"}}]'.format(
                                instance, password)
                            # print(msg)
                            ws.send(msg)
                            msg = '["1","2","instance:{}","set_kill_time",{{"id":{},"time":{}}}]'.format(
                                instance, nm_id, int(time.time() * 1000))
                            # print(msg)
                            ws.send(msg)
                            ws.close()
                            httpresponse = HttpResponse("OK", status=200)
                    else:
                        print("no nm_name")
            if "ffxivsc" in trackers:
                key = req.GET.get("key")
                # print("ffxiv-eureka {}:{}".format(instance,password))
                if key:
                    nm_name = req.POST.get("text")
                    if nm_name:
                        nm_level_type = get_nm_id("ffxivsc", nm_name)
                        if int(nm_level_type["type"]) > 0:
                            url = ("https://nps.ffxivsc.cn/lobby/addKillTime")
                            post_data = {
                                "killTime":
                                strftime("%Y-%m-%d %H:%M", time.localtime()),
                                "level":
                                "{}".format(nm_level_type["level"]),
                                "key":
                                key,
                                "type":
                                "{}".format(nm_level_type["type"]),
                            }
                            r = requests.post(url=url, data=post_data)
                            httpresponse = HttpResponse(r)
                    else:
                        print("no nm_name")
            if "qq" in trackers:
                bot_qq = req.GET.get("bot_qq")
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                group_id = req.GET.get("group")
                print("bot: {} qq:{} token:{}".format(bot_qq, qq, token))
                if bot_qq and qq and token:
                    bot = None
                    qquser = None
                    group = None
                    api_rate_limit = True
                    try:
                        bot = QQBot.objects.get(user_id=bot_qq)
                    except QQBot.DoesNotExist:
                        print("bot {} does not exist".format(bot_qq))
                    try:
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                        if time.time(
                        ) < qquser.last_api_time + qquser.api_interval:
                            api_rate_limit = False
                            print("qquser {} api rate limit exceed".format(qq))
                        qquser.last_api_time = int(time.time())
                        qquser.save(update_fields=["last_api_time"])
                    except QQUser.DoesNotExist:
                        print("qquser {}:{} auth fail".format(qq, token))
                        httpresponse = HttpResponse(
                            "QQUser {}:{} auth fail".format(qq, token),
                            status=500)
                    if bot and qquser and api_rate_limit:
                        channel_layer = get_channel_layer()
                        msg = req.POST.get("text")
                        reqbody = req.body
                        try:
                            if reqbody:
                                reqbody = reqbody.decode()
                                reqbody = json.loads(reqbody)
                                msg = msg or reqbody.get("content")
                                msg = re.compile(
                                    "[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]").sub(
                                        " ", msg)
                        except BaseException:
                            pass
                        if not msg:
                            msg = github_webhook(req)
                        if not msg:
                            print("Can't get msg from request:{}:{}".format(
                                req, reqbody))
                            httpresponse = HttpResponse("Can't get message",
                                                        status=500)
                        else:
                            print("body:{}".format(req.body.decode()))
                            if group_id:
                                try:
                                    group = QQGroup.objects.get(
                                        group_id=group_id)
                                    group_push_list = [
                                        user["user_id"] for user in json.loads(
                                            group.member_list)
                                        if (user["role"] == "owner"
                                            or user["role"] == "admin")
                                    ]
                                    print("group push list:{}".format(
                                        group_push_list))
                                except QQGroup.DoesNotExist:
                                    print("group:{} does not exist".format(
                                        group_id))
                            msg = handle_hunt_msg(msg)
                            if (group and group.api and int(qquser.user_id)
                                    in group_push_list):
                                at_msg = "[CQ:at,qq={}]".format(
                                    qquser.user_id) if req.GET.get(
                                        "at", "true") == "true" else str(
                                            qquser.user_id)
                                jdata = {
                                    "action": "send_group_msg",
                                    "params": {
                                        "group_id":
                                        group.group_id,
                                        "message":
                                        "Message from {}:\n{}".format(
                                            at_msg, msg),
                                    },
                                    "echo": "",
                                }
                            else:
                                jdata = {
                                    "action": "send_private_msg",
                                    "params": {
                                        "user_id": qquser.user_id,
                                        "message": msg
                                    },
                                    "echo": "",
                                }
                            if not bot.api_post_url:
                                async_to_sync(channel_layer.send)(
                                    bot.api_channel_name,
                                    {
                                        "type": "send.event",
                                        "text": json.dumps(jdata)
                                    },
                                )
                            else:
                                url = os.path.join(
                                    bot.api_post_url,
                                    "{}?access_token={}".format(
                                        jdata["action"], bot.access_token))
                                headers = {'Content-Type': 'application/json'}
                                r = requests.post(url=url,
                                                  headers=headers,
                                                  data=json.dumps(
                                                      jdata["params"]))
                                if r.status_code != 200:
                                    logging.error(r.text)
                            httpresponse = HttpResponse("OK", status=200)
            if "hunt" in trackers:
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                group_id = req.GET.get("group")
                bot_qq = req.GET.get("bot_qq")
                print("qq:{} token:{}, group:{}".format(qq, token, group_id))
                if bot_qq and qq and token:
                    qquser = None
                    group = None
                    api_rate_limit = True
                    try:
                        bot = QQBot.objects.get(user_id=bot_qq)
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                        if time.time(
                        ) < qquser.last_api_time + qquser.api_interval:
                            api_rate_limit = False
                            print("qquser {} api rate limit exceed".format(qq))
                        httpresponse = HttpResponse(
                            "User API rate limit exceed", status=500)
                    except QQUser.DoesNotExist:
                        print("qquser {}:{} auth fail".format(qq, token))
                    except QQBot.DoesNotExist:
                        print("bot {} does not exist".format(bot_qq))
                    else:
                        channel_layer = get_channel_layer()
                        try:
                            reqbody = json.loads(req.body.decode())
                        except BaseException as e:
                            print(e)
                        else:
                            print("reqbody:{}".format(reqbody))
                            try:
                                hunt_group = HuntGroup.objects.get(
                                    group__group_id=group_id)
                                group = hunt_group.group
                                group_push_list = [
                                    user["user_id"]
                                    for user in json.loads(group.member_list)
                                ]
                                assert int(
                                    qquser.user_id
                                ) in group_push_list, "You're not in the group member list"
                                monster_name = reqbody["monster"]
                                zone_name = reqbody["zone"]
                                zone_name = zone_name.replace(
                                    chr(57521),
                                    "").replace(chr(57522),
                                                "2").replace(chr(57523), "3")
                                try:
                                    monster = Monster.objects.get(
                                        cn_name=monster_name)
                                except Monster.DoesNotExist:
                                    monster = Monster.objects.get(
                                        cn_name=re.sub("1|2|3", "",
                                                       monster_name))
                                world_name = reqbody.get("world", "None")
                                timestamp = int(reqbody["time"])
                                server = None
                                world_id = reqbody.get("worldid", -1)
                                servers = Server.objects.filter(
                                    worldId=world_id)
                                server = servers[0] if servers.exists(
                                ) else Server.objects.get(name=world_name)
                                success = False
                                # handle instances
                                if req.GET.get(
                                        "strict_zone", "true"
                                ) == "false" or str(
                                        monster.territory
                                ) in zone_name:  # "ZoneName2", "ZoneName"
                                    if str(monster.territory
                                           ) != zone_name:  # "ZoneName2"
                                        monster_name = zone_name.replace(
                                            str(monster.territory),
                                            monster_name
                                        )  # "ZoneName2" -> "MonsterName2"
                                        try:
                                            monster = Monster.objects.get(
                                                cn_name=monster_name)
                                        except Monster.DoesNotExist:
                                            monster = Monster.objects.get(
                                                cn_name=re.sub(
                                                    "1|2|3", "", monster_name))
                                    print(
                                        "Get HuntLog info:\nmonster:{}\nserver:{}"
                                        .format(monster, server))
                                    if HuntLog.objects.filter(
                                            monster=monster,
                                            server=server,
                                            hunt_group=hunt_group,
                                            log_type="kill",
                                            time__gt=timestamp - 60).exists():
                                        msg = "{}——\"{}\" 已在一分钟内记录上报,此次API调用被忽略".format(
                                            server, monster,
                                            time.strftime(
                                                "%Y-%m-%d %H:%M:%S",
                                                time.localtime(timestamp)))
                                        success = False
                                    else:
                                        hunt_log = HuntLog(
                                            monster=monster,
                                            hunt_group=hunt_group,
                                            server=server,
                                            log_type="kill",
                                            time=timestamp)
                                        hunt_log.save()
                                        msg = "{}——\"{}\" 击杀时间: {}".format(
                                            hunt_og.server, monster,
                                            time.strftime(
                                                "%Y-%m-%d %H:%M:%S",
                                                time.localtime(timestamp)))
                                        at_msg = "[CQ:at,qq={}]".format(
                                            qquser.user_id) if req.GET.get(
                                                "at",
                                                "true") == "true" else str(
                                                    qquser.user_id)
                                        msg = at_msg + "通过API更新了如下HuntLog:\n{}".format(
                                            msg)
                                        success = True
                                else:
                                    at_msg = "[CQ:at,qq={}]".format(
                                        qquser.user_id) if req.GET.get(
                                            "at", "true") == "true" else str(
                                                qquser.user_id)
                                    msg = at_msg + "上报 {} 失败,{} 与 {} 不兼容".format(
                                        monster, monster.territory, zone_name)
                                    success = False
                                if success or req.GET.get("verbose",
                                                          "false") == "true":
                                    jdata = {
                                        "action": "send_group_msg",
                                        "params": {
                                            "group_id":
                                            hunt_group.group.group_id,
                                            "message": msg,
                                        },
                                        "echo": "",
                                    }
                                    if not bot.api_post_url:
                                        async_to_sync(channel_layer.send)(
                                            bot.api_channel_name,
                                            {
                                                "type": "send.event",
                                                "text": json.dumps(jdata)
                                            },
                                        )
                                    else:
                                        url = os.path.join(
                                            bot.api_post_url,
                                            "{}?access_token={}".format(
                                                jdata["action"],
                                                bot.access_token))
                                        headers = {
                                            'Content-Type': 'application/json'
                                        }
                                        r = requests.post(url=url,
                                                          headers=headers,
                                                          data=json.dumps(
                                                              jdata["params"]))
                                        if r.status_code != 200:
                                            logging.error(r.text)
                                httpresponse = HttpResponse(status=200)
                            except HuntGroup.DoesNotExist:
                                print("HuntGroup:{} does not exist".format(
                                    group_id))
                                httpresponse = HttpResponse(
                                    "HuntGroup:{} does not exist".format(
                                        group_id),
                                    status=500)
                            except Monster.DoesNotExist:
                                print("Monster:{} does not exist".format(
                                    monster_name))
                                httpresponse = HttpResponse(
                                    "Monster:{} does not exist".format(
                                        monster_name),
                                    status=500)
                            except Server.DoesNotExist:
                                print("Server:{} does not exist".format(
                                    world_name))
                                httpresponse = HttpResponse(
                                    "Server:{} does not exist".format(
                                        world_name),
                                    status=500)
                            except AssertionError as e:
                                print(str(e))
                                httpresponse = HttpResponse(str(e), status=500)
                else:
                    httpresponse = HttpResponse("Missing URL parameters",
                                                status=500)
            if "webapi" in trackers:
                qq = req.GET.get("qq")
                token = req.GET.get("token")
                print("qq:{}\ntoken:{}".format(qq, token))
                if qq and token:
                    qquser = None
                    try:
                        qquser = QQUser.objects.get(user_id=qq,
                                                    bot_token=token)
                    except QQUser.DoesNotExist:
                        res_dict = {
                            "response": "error",
                            "msg": "Invalid API token",
                            "rcode": "101",
                        }
                        return JsonResponse(res_dict)
                    if qquser:
                        res_dict = webapi(req)
                        return JsonResponse(res_dict)
                else:
                    res_dict = {
                        "response": "error",
                        "msg": "Invalid request",
                        "rcode": "100",
                    }
                    return JsonResponse(res_dict)
                return HttpResponse("Default API Error, contact dev please",
                                    status=500)
    return httpresponse if httpresponse else HttpResponse(
        "Default API Error, contact dev please.", status=500)