Skip to content

Commit

Permalink
<jx3>[feat]serendipity v3
Browse files Browse the repository at this point in the history
  • Loading branch information
HornCopper committed Sep 10, 2024
1 parent 6e455d4 commit 7cb390f
Show file tree
Hide file tree
Showing 127 changed files with 305 additions and 19 deletions.
3 changes: 2 additions & 1 deletion src/plugins/jx3/awesome/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment as ms
from nonebot.params import CommandArg

from src.tools.config import Config
from src.tools.utils.num import check_number
from src.tools.utils.file import get_content_local

Expand All @@ -12,7 +13,7 @@

@cheater.handle()
async def _(event: GroupMessageEvent, args: Message = CommandArg()):
if args.extract_plain_text() == "":
if args.extract_plain_text() == "" or not Config.jx3.api.enable:
return
uin = args.extract_plain_text()
if not check_number(uin):
Expand Down
42 changes: 36 additions & 6 deletions src/plugins/jx3/serendipity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment as ms

from src.tools.config import Config
from src.tools.utils.file import get_content_local
from src.tools.utils.request import get_content

from .v1 import *
from .v2 import *
from .v1 import serendipity_ as v1_serendipity, statistical_, global_serendipity, global_statistical, get_preposition
from .v2 import getImage_v2 as v2_serendipity
from .v3 import get_serendipity_image_v3 as v3_serendipity

jx3_cmd_serendipity = on_command("jx3_serendipity", aliases={"奇遇v1", "查询v1"}, force_whitespace=True, priority=5)

Expand All @@ -19,7 +21,7 @@ async def _(event: GroupMessageEvent, args: Message = CommandArg()):
Example:-奇遇 幽月轮 哭包猫@唯我独尊
"""
if args.extract_plain_text() == "":
if args.extract_plain_text() == "" or not Config.jx3.api.enable:
return
arg = args.extract_plain_text().split(" ")
if len(arg) not in [1, 2]:
Expand All @@ -30,7 +32,7 @@ async def _(event: GroupMessageEvent, args: Message = CommandArg()):
elif len(arg) == 2:
server = arg[0]
id = arg[1]
data = await serendipity_(server, id, group_id=str(event.group_id))
data = await v1_serendipity(server, id, group_id=str(event.group_id))
if isinstance(data, list):
await jx3_cmd_serendipity.finish(data[0])
else:
Expand Down Expand Up @@ -58,13 +60,41 @@ async def _(event: GroupMessageEvent, args: Message = CommandArg()):
elif len(arg) == 2:
server = arg[0]
id = arg[1]
data = await getImage_v2(server, id, str(event.group_id), True)
data = await v2_serendipity(server, id, str(event.group_id), True)
if isinstance(data, list):
await serendipity_v2.finish(data[0])
elif isinstance(data, str):
data = get_content_local(data)
await serendipity_v2.finish(ms.image(data))

serendipity_v3 = on_command("jx3_serendipity_v3", aliases={"奇遇v3", "查询v3"}, force_whitespace=True, priority=5)


@serendipity_v3.handle()
async def _(event: GroupMessageEvent, args: Message = CommandArg()):
"""
获取个人奇遇记录:
Example:-奇遇v3 幽月轮 哭包猫@唯我独尊
"""
if args.extract_plain_text() == "":
return
arg = args.extract_plain_text().split(" ")
if len(arg) not in [1, 2]:
await serendipity_v3.finish("唔……参数不正确哦,请检查后重试~")
if len(arg) == 1:
server = None
id = arg[0]
elif len(arg) == 2:
server = arg[0]
id = arg[1]
data = await v3_serendipity(server, id, str(event.group_id))
if isinstance(data, list):
await serendipity_v3.finish(data[0])
elif isinstance(data, str):
data = get_content_local(data)
await serendipity_v3.finish(ms.image(data))

pet_serendipity = on_command("jx3_pet_serendipity", aliases={"宠物奇遇"}, force_whitespace=True, priority=5)


Expand All @@ -86,7 +116,7 @@ async def _(event: GroupMessageEvent, args: Message = CommandArg()):
elif len(arg) == 2:
server = arg[0]
id = arg[1]
data = await getImage_v2(server, id, str(event.group_id), False)
data = await v2_serendipity(server, id, str(event.group_id), False)
if isinstance(data, list):
await pet_serendipity.finish(data[0])
elif isinstance(data, str):
Expand Down
7 changes: 5 additions & 2 deletions src/plugins/jx3/serendipity/v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
from src.tools.basic.server import server_mapping
from src.tools.utils.path import ASSETS, CACHE, VIEWS
from src.tools.generate import get_uuid, generate
from src.tools.utils.request import get_api
from src.tools.utils.time import convert_time
from src.tools.utils.file import read, write

from src.plugins.jx3.bind import get_player_local_data

from .without_jx3api import *
from .without_jx3api import JX3Serendipity

import os

Expand Down Expand Up @@ -44,21 +45,23 @@ async def getImage_v2(server: Optional[str], name: str, group_id: str, type: boo
return [PROMPT.PlayerNotExist]
if Config.jx3.api.enable:
serendipity_data = await get_api(f"{Config.jx3.api.url}/data/luck/adventure?server={server}&name={name}&ticket={ticket}&token={token}")
serendipity_data = serendipity_data["data"]
else:
serendipity_data = await Serendipity.integration(server, name)
data = serendipity_data
# 笔记:1 → 世界奇遇;2 → 绝世奇遇;3 → 宠物奇遇
# 注:暂时忽略宠物奇遇,不做统计
tables = []
current_time = int(datetime.now().timestamp())
type_map = ["common", "peerless", "pet"]
for i in data:
if type and i["level"] >= 3: # 绝世+普通
continue
if not type and i["level"] != 3: # 宠物
continue
serendity_name = i["name"]
flag = ASSETS + "/serendipity/vector/peerless.png" if i["level"] == 2 else ""
icon = ASSETS + "/serendipity/serendipity/" + serendity_name + ".png"
icon = ASSETS + "/serendipity/serendipity/" + type_map[i["level"]-1] + "/" + serendity_name + ".png"
if not os.path.exists(icon):
continue
if i["time"] != 0:
Expand Down
142 changes: 142 additions & 0 deletions src/plugins/jx3/serendipity/v3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, List
from jinja2 import Template

from src.tools.config import Config
from src.tools.basic.prompts import PROMPT
from src.tools.basic.server import server_mapping
from src.tools.utils.path import ASSETS, CACHE, VIEWS
from src.tools.generate import get_uuid, generate
from src.tools.utils.time import convert_time, get_relate_time, get_current_time
from src.tools.utils.file import read, write

from src.plugins.jx3.bind import get_player_local_data, Player

from .without_jx3api import JX3Serendipity

import os

template: str = """
<td class="element-column">
<div class="element-container">
<img class="{{ status }}-color" src="{{ image_path }}" alt="{{ name }}.png">
<div class="{{ status }}-serendipity">{{ msg }}</div>
</div>
</td>"""

class JX3Serendipities:
def __init__(self, data: list):
self.data = data


@property
def common(self):
new = []
for serendipity in self.data:
if serendipity["level"] == 1:
new.append(serendipity)
return new

@property
def pet(self):
new = []
for serendipity in self.data:
if serendipity["level"] == 3:
new.append(serendipity)
return new

@property
def peerless(self):
new = []
for serendipity in self.data:
if serendipity["level"] == 2:
new.append(serendipity)
return new

async def check_role(server: str, name: str) -> bool:
player_data: Player = await get_player_local_data(role_name=name, server_name=server)
if player_data.format_jx3api()["code"] != 200:
return False
return True

def generate_table(local_data, comparison_data, path_map, template):
table_list = []
cache_table = []

for serendipity in local_data:
status = serendipity["name"] in [item["name"] for item in comparison_data]
corresponding = {}
for item in comparison_data:
if item["name"] == serendipity["name"]:
corresponding = item

cache_table.append(
Template(template).render(
**{
"image_path": ASSETS + "/serendipity/serendipity/" + path_map[int(serendipity["level"]) - 1] + "/" + serendipity["name"] + ".png",
"name": serendipity["name"],
"status": "yes" if status else "no",
"msg": "尚未触发" if not status else "遗忘的时间" if corresponding["time"] == 0 else convert_time(corresponding["time"], "%Y-%m-%d %H:%M:%S") + "<br>" + get_relate_time(get_current_time(), corresponding["time"])
}
)
)

if len(cache_table) == 5:
table_list.append(
"<tr>\n" + "\n".join(cache_table) + "\n</tr>"
)
cache_table = []

if len(cache_table) != 0:
table_list.append(
"<tr>\n" + "\n".join(cache_table) + "\n</tr>"
)
return table_list

async def get_serendipity_image_v3(server: Optional[str], name: str, group_id: Optional[str] = ""):
server = server_mapping(server, group_id)
if not server:
return [PROMPT.ServerNotExist]
player_exist = await check_role(server, name)
if not player_exist:
return [PROMPT.PlayerNotExist]

data: list = await JX3Serendipity().integration(server, name)
data_obj = JX3Serendipities(data)

common: List[dict] = data_obj.common
peerless: List[dict] = data_obj.peerless
pet: List[dict] = data_obj.pet

local_common: List[dict] = [{"name": serendipity[:-4], "level": 1} for serendipity in os.listdir(ASSETS + "/serendipity/serendipity/common/")]
local_peerless: List[dict] = [{"name": serendipity[:-4], "level": 2} for serendipity in os.listdir(ASSETS + "/serendipity/serendipity/peerless/")]
local_pet: List[dict] = [{"name": serendipity[:-4], "level": 3} for serendipity in os.listdir(ASSETS + "/serendipity/serendipity/pet/")]

path_map: List[str] = ["common", "peerless", "pet"]

common_table = generate_table(local_common, common, path_map, template)
peerless_table = generate_table(local_peerless, peerless, path_map, template)
pet_table = generate_table(local_pet, pet, path_map, template)

font = ASSETS + "/font/custom.ttf"
html = read(VIEWS + "/jx3/serendipity/v3.html")
html = Template(html).render(
**{
"font": font,
"name": name,
"server": server,
"total": f"{len(data)}/{len(local_common + local_peerless + local_pet)}",
"peerless": len(peerless),
"pet": len(pet),
"table_content_peerless": "\n".join(peerless_table),
"table_content_common": "\n".join(common_table),
"table_content_pet": "\n".join(pet_table)
}
)
final_html = CACHE + "/" + get_uuid() + ".html"
write(final_html, html)
final_path = await generate(final_html, False, ".total", False)
if not isinstance(final_path, str):
return
return Path(final_path).as_uri()
7 changes: 5 additions & 2 deletions src/plugins/jx3/serendipity/without_jx3api.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
from src.tools.config import Config
from src.tools.utils.request import post_url, get_api, get_url
from src.tools.basic.jx3 import gen_ts, gen_xsk, format_body
from src.tools.utils.path import ASSETS

from src.plugins.jx3.bind import get_player_local_data, Player
from src.plugins.majsoul.koromo import sort_list_of_dicts

import json
import re
import os

ticket = Config.jx3.api.ticket
device_id = ticket.split("::")[-1]
Expand All @@ -29,7 +31,9 @@ def __init__(self):
def get_serendipity_level(self, serendipity_name: str) -> int:
if serendipity_name.find("宠物奇缘") != -1:
serendipity_level = 3
elif serendipity_name in ["昆吾余火", "浮光织梦", "塞外西风", "入蛟宫", "追魂骨", "千秋铸", "万灵当歌", "流年如虹", "侠行囧途", "争铸吴钩", "兔江湖", "济苍生", "塞外宝驹", "阴阳两界", "三尺青锋", "三山四海"]:
elif serendipity_name in [serendipity[:-4] for serendipity in os.listdir(ASSETS + "/serendipity/serendipity/pet")]:
serendipity_level = 3
elif serendipity_name in [serendipity[:-4] for serendipity in os.listdir(ASSETS + "/serendipity/serendipity/peerless")]:
serendipity_level = 2
else:
serendipity_level = 1
Expand Down Expand Up @@ -115,7 +119,6 @@ async def get_jx3pet_data(self, server: str, name: str):
}
)
self.jx3pet = serendipities
print(self.jx3pet)

async def integration(self, server: str, name: str):
await self.get_tuilan_data(server, name)
Expand Down
11 changes: 3 additions & 8 deletions src/tools/utils/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@
import time
import datetime

def convert_time(timestamp: int, format: str = "%Y年%m月%d日 %H:%M:%S") -> Union[str, bool]:
if check_number(timestamp):
try:
timestamp = int(timestamp)
except:
return False
def convert_time(timestamp: int, format: str = "%Y年%m月%d日 %H:%M:%S") -> str:
"""
时间转换,自适应时间长度。
"""
Expand All @@ -25,10 +20,10 @@ class TimeLengthError(OSError):
dt = time.strftime(format, time_local)
return dt

def get_current_time():
def get_current_time() -> int:
return int(datetime.datetime.now().timestamp())

def get_relate_time(current, goal):
def get_relate_time(current: int, goal: int) -> str:
current_time = int(current)
timeGet_int = int(goal)
datetime_1 = datetime.datetime.fromtimestamp(current_time)
Expand Down
Loading

0 comments on commit 7cb390f

Please sign in to comment.