update v0.0.5.0

This commit is contained in:
HibiKier
2021-10-03 14:24:07 +08:00
parent 87ed445a58
commit 00658cf165
182 changed files with 6439 additions and 3845 deletions
+3
View File
@@ -0,0 +1,3 @@
import nonebot
nonebot.load_plugins("plugins/genshin")
+37 -24
View File
@@ -1,25 +1,44 @@
from .alc import get_almanac_base64_str, load_data
import os
from utils.utils import get_bot, scheduler
from nonebot import on_command
from models.level_user import LevelUser
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, MessageEvent
from utils.message_builder import image
from services.log import logger
from models.group_remind import GroupRemind
from configs.path_config import IMAGE_PATH
from .data_source import get_alc_image
from utils.manager import group_manager
from pathlib import Path
FILE_PATH = os.path.dirname(__file__)
__zx_plugin_name__ = "原神老黄历"
__plugin_usage__ = """
usage:
有时候也该迷信一回!特别是运气方面
指令:
原神黄历
""".strip()
__plugin_des__ = "有时候也该迷信一回!特别是运气方面"
__plugin_cmd__ = ["原神黄历"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神黄历", "原神老黄历"],
}
__plugin_task__ = {"genshin_alc": "原神黄历提醒"}
almanac = on_command("原神黄历", priority=5, block=True)
reload = on_command("重载原神黄历数据", priority=5, block=True)
ALC_PATH = Path(IMAGE_PATH) / "genshin" / "alc"
ALC_PATH.mkdir(parents=True, exist_ok=True)
@almanac.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
almanac_base64 = get_almanac_base64_str()
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
alc_img = await get_alc_image(ALC_PATH)
mes = alc_img + "\n ※ 黄历数据来源于 genshin.pub"
await almanac.send(mes)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
@@ -27,13 +46,6 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
)
@reload.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
if await LevelUser.check_level(event.user_id, event.group_id, 5):
load_data()
await reload.send("重载成功")
@scheduler.scheduled_job(
"cron",
hour=10,
@@ -42,10 +54,11 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
async def _():
# 每日提醒
bot = get_bot()
gl = await bot.get_group_list(self_id=bot.self_id)
gl = [g["group_id"] for g in gl]
almanac_base64 = get_almanac_base64_str()
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
for gid in gl:
if await GroupRemind.get_status(gid, "almanac"):
await bot.send_group_msg(group_id=int(gid), message=mes)
if bot:
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
alc_img = await get_alc_image(ALC_PATH)
mes = alc_img + "\n ※ 黄历数据来源于 genshin.pub"
for gid in gl:
if await group_manager.check_group_task_status(gid, "genshin_alc"):
await bot.send_group_msg(group_id=int(gid), message=mes)
-123
View File
@@ -1,123 +0,0 @@
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import os
import json
import random
import base64
import time
FILE_PATH = os.path.dirname(__file__)
FONT_PATH = os.path.join(FILE_PATH, "汉仪文黑.ttf")
data = {} # configs.json里的数据
almanac_data = {
# 生成的黄历base64字符串和黄历更新日期
"date": "",
"almanac_base64_str": ""
}
chinese = {"0": "", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六", "7": "七", "8": "八", "9": "九"}
def month_to_chinese(month: str):
# 把日期数字转成中文数字
m = int(month)
if m < 10:
return chinese[month[-1]]
elif m < 20:
return "十" + chinese[month[-1]]
else:
return chinese[month[0]] + "十" + chinese[month[-1]]
def load_data():
# 载入config.json文件的数据
global data
with open(os.path.join(FILE_PATH, 'config.json'), 'r', encoding='UTF-8') as f:
data = json.load(f)
almanac_data["date"] = ""
almanac_data["almanac_base64_str"] = ""
load_data()
def seed_random_list(seed: str, l: list):
# 使用随机种子随机选择列表中的元素,相同的种子和列表将返回同样的输出
seed = seed + str(l)
random.seed(seed)
index = random.random() * len(l)
return l[int(index)]
def generate_almanac():
# 生成黄历图片,然后转换成base64保存到 almanac_data["almanac_base64_str"]
seed = time.strftime("%Y-%m-%d")
offset = 1
today_luck = []
l = list(data.keys())
while len(today_luck) < 6:
# 随机6个不同的运势放到 today_luck
r = seed_random_list(str(offset) + seed, l)
if r in today_luck:
offset += 1
else:
today_luck.append(r)
back = Image.open(os.path.join(FILE_PATH, "back.png"))
year = time.strftime("%Y")
month = month_to_chinese(time.strftime("%m")) + "月"
day = month_to_chinese(time.strftime("%d")) + "日"
draw = ImageDraw.Draw(back)
draw.text((118, 165), year, fill="#8d7650ff", font=ImageFont.truetype(FONT_PATH, size=30), anchor="mm",
align="center")
draw.text((260, 165), day, fill="#f7f8f2ff", font=ImageFont.truetype(FONT_PATH, size=35), anchor="mm",
align="center")
draw.text((410, 165), month, fill="#8d7650ff", font=ImageFont.truetype(FONT_PATH, size=30), anchor="mm",
align="center")
buff = Image.new("RGBA", (325, 160))
debuff = Image.new("RGBA", (325, 160))
buff_draw = ImageDraw.Draw(buff)
debuff_draw = ImageDraw.Draw(debuff)
for i in range(3):
buff_name = today_luck[i]
debuff_name = today_luck[(i + 3)]
buff_effect = seed_random_list(seed, data[buff_name]["buff"])
debuff_effect = seed_random_list(seed, data[debuff_name]["debuff"])
buff_draw.text((0, i * 53), buff_name, fill="#756141ff", font=ImageFont.truetype(FONT_PATH, size=25))
debuff_draw.text((0, i * 53), debuff_name, fill="#756141ff", font=ImageFont.truetype(FONT_PATH, size=25))
buff_draw.text((0, i * 53 + 28), buff_effect, fill="#b5b3acff", font=ImageFont.truetype(FONT_PATH, size=19))
debuff_draw.text((0, i * 53 + 28), debuff_effect, fill="#b5b3acff", font=ImageFont.truetype(FONT_PATH, size=19))
back.paste(buff, (150, 230), buff)
back.paste(debuff, (150, 400), debuff)
bio = BytesIO()
back.save(bio, format='PNG')
base64_str = base64.b64encode(bio.getvalue()).decode()
almanac_data["date"] = time.strftime("%Y-%m-%d")
almanac_data["almanac_base64_str"] = 'base64://' + base64_str
def get_almanac_base64_str():
# if almanac_data["date"] == time.strftime("%Y-%m-%d"):
# return almanac_data["almanac_base64_str"]
# else:
# generate_almanac()
# return almanac_data["almanac_base64_str"]
generate_almanac()
return almanac_data["almanac_base64_str"]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

-70
View File
@@ -1,70 +0,0 @@
{
"抽卡":{
"buff": ["欧气满满,十连出金","出金不歪"],
"debuff": ["武器大师","保底出金","金色会是痛苦大剑"]
},
"刷世界boss":{
"buff": ["双攻双爆角斗士"],
"debuff": ["只有保底材料","贪生怕死角斗士"]
},
"刷风本":{
"buff": ["会有极品猎人套","会掉真正的少女心","治疗加成少女头"],
"debuff": ["勇往直前少女心","少女飘摇的杀意","少女暴怒的容颜"]
},
"刷火本":{
"buff": ["魔女帽子火伤杯","暴伤魔女帽!","火伤魔女心!"],
"debuff": ["幡 然 醒 悟","这么阴间的地方真的会有魔女套吗?","不务正业火魔女","会匹配到3个卢姥爷"]
},
"刷岩本":{
"buff": ["悠久的磐岩伴你左右","岩神的庇护常在"],
"debuff": ["防御流星杯,你值得拥有"]
},
"刷宗室":{
"buff": ["物理伤害骑士道,元素精通宗室套"],
"debuff": ["贪生怕死骑士道,物理伤害宗室杯"]
},
"刷冰本":{
"buff": ["双暴词条概率up"],
"debuff": ["防御力船帽,无人可及"]
},
"刷雷本":{
"buff": ["愿雷鸟伴你左右"],
"debuff": ["来表演一个只掉平雷套的绝活","风神忽悠雷凶兆"]
},
"锄大地":{
"buff": ["会掉一大堆紫色材料"],
"debuff": ["深渊法师爱你哟","会被冰水法控到死"]
},
"挖矿":{
"buff": ["开矿出双材料"],
"debuff": ["去别人世界会被拒"]
},
"刷天赋本":{
"buff": ["金色!我看到了金色的书!"],
"debuff": ["2蓝2绿不会变"]
},
"刷突破材料":{
"buff": ["金色!我看到了金色的材料!"],
"debuff": ["2蓝2绿不会变"]
},
"升级圣遗物":{
"buff": ["稀有词条跳跳跳","会双爆拉满"],
"debuff": ["女 仆 狂 喜","无中生有防御力","生命拉满","完美避开双爆"]
},
"打风魔龙":{
"buff": ["看我一箭一个风魔鸡","今天特瓦林可以给想要的突破材料","5金加原胚!"],
"debuff": ["会不小心掉下平台","不小心被地板烫死了"]
},
"打狼王":{
"buff": ["今天安德琉斯的心情不错,可以py一下","5金加原胚!"],
"debuff": ["狼尾巴*1"]
},
"打公子":{
"buff": ["今天可以和公子py想要的突破材料","5金加原胚!"],
"debuff": ["要角没有!要命一条!"]
}
}
+43
View File
@@ -0,0 +1,43 @@
from utils.browser import get_browser
from utils.message_builder import image
from datetime import datetime
from services.log import logger
from pathlib import Path
import os
url = "https://genshin.pub"
async def get_alc_image(path: Path):
date = datetime.now().date()
for file in os.listdir(path):
if f'{date}.png' != file:
file = path / file
file.unlink()
if f'{date}.png' in os.listdir(path):
return image(f'{date}.png', 'genshin/alc')
page = None
try:
browser = await get_browser()
page = await browser.new_page()
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
card = await page.query_selector('.GSAlmanacs_gs_almanacs__3qT_A')
await card.screenshot(path=path / f'{date}.png', timeout=100000)
except Exception as e:
logger.error(f'获取原神黄历发生错误..{type(e)}: {e}')
finally:
if page:
await page.close()
return image(f'{date}.png', 'genshin/alc')
Binary file not shown.
+78 -34
View File
@@ -12,14 +12,39 @@ from nonebot.permission import SUPERUSER
from typing import List
import os
import asyncio
import time
__zx_plugin_name__ = "原神今日素材"
__plugin_usage__ = """
usage:
看看原神今天要刷什么
指令:
今日素材/今天素材
""".strip()
__plugin_superuser_usage__ = """
usage:
更新原神今日素材
指令:
更新原神今日素材
""".strip()
__plugin_des__ = "看看原神今天要刷什么"
__plugin_cmd__ = ["今日素材/今天素材", "更新原神今日素材 [_superuser]"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["今日素材", "今天素材"],
}
driver: Driver = nonebot.get_driver()
material = on_command('今日素材', aliases={'今日材料', '今天素材', '今天材料'}, priority=5, block=True)
material = on_command("今日素材", aliases={"今日材料", "今天素材", "今天材料"}, priority=5, block=True)
super_cmd = on_command('更新原神今日素材', permission=SUPERUSER, priority=1, block=True)
super_cmd = on_command("更新原神今日素材", permission=SUPERUSER, priority=1, block=True)
@material.handle()
@@ -27,49 +52,62 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
if time.strftime("%w") == "0":
await material.send("今天是周日,所有材料副本都开放了。")
return
await material.send(Message(image('daily_material.png', 'genshin/material') + '\n※ 每日素材数据来源于 genshin.pub'))
await material.send(
Message(
image("daily_material.png", "genshin/material")
+ "\n※ 每日素材数据来源于 genshin.pub"
)
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
f" 发送查看今日素材")
f" 发送查看今日素材"
)
@super_cmd.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
if await update_image():
await super_cmd.send('更新成功...')
logger.info(f'更新每日天赋素材成功...')
await super_cmd.send("更新成功...")
logger.info(f"更新每日天赋素材成功...")
else:
await super_cmd.send(f'更新失败...')
await super_cmd.send(f"更新失败...")
@driver.on_startup
async def update_image():
page = None
try:
if not os.path.exists(f'{IMAGE_PATH}/genshin/material'):
os.mkdir(f'{IMAGE_PATH}/genshin/material')
for file in os.listdir(f'{IMAGE_PATH}/genshin/material'):
os.remove(f'{IMAGE_PATH}/genshin/material/{file}')
if not os.path.exists(f"{IMAGE_PATH}/genshin/material"):
os.mkdir(f"{IMAGE_PATH}/genshin/material")
for file in os.listdir(f"{IMAGE_PATH}/genshin/material"):
os.remove(f"{IMAGE_PATH}/genshin/material/{file}")
browser = await get_browser()
if not browser:
logger.warning('获取 browser 失败,请部署至 linux 环境....')
logger.warning("获取 browser 失败,请部署至 linux 环境....")
return False
url = 'https://genshin.pub/daily'
url = "https://genshin.pub/daily"
page = await browser.new_page()
await page.goto(url, wait_until='networkidle', timeout=10000)
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
await page.evaluate("""
await page.evaluate(
"""
document.getElementsByClassName('GSTitleBar_gs_titlebar__2IJqy')[0].remove();
e = document.getElementsByClassName('GSContainer_gs_container__2FbUz')[0];
e.setAttribute("style", "height:880px");
""")
"""
)
await page.click("button")
div = await page.query_selector(".GSContainer_content_box__1sIXz")
for i, card in enumerate(await page.query_selector_all(".GSTraitCotainer_trait_section__1f3bc")):
for i, card in enumerate(
await page.query_selector_all(".GSTraitCotainer_trait_section__1f3bc")
):
index = 0
type_ = 'char' if not i else 'weapons'
type_ = "char" if not i else "weapons"
for x in await card.query_selector_all("xpath=child::*"):
await x.screenshot(path=f'{IMAGE_PATH}/genshin/material/{type_}_{index}.png', timeout=100000)
await x.screenshot(
path=f"{IMAGE_PATH}/genshin/material/{type_}_{index}.png",
timeout=100000,
)
# 下滑两次
for _ in range(3):
await div.press("PageDown")
@@ -77,13 +115,23 @@ async def update_image():
# 结束后上滑至顶
for _ in range(index * 3):
await div.press("PageUp")
file_list = os.listdir(f'{IMAGE_PATH}/genshin/material')
char_imgs = [f'{IMAGE_PATH}/genshin/material/{x}' for x in file_list if x.startswith('char')]
weapons_imgs = [f'{IMAGE_PATH}/genshin/material/{x}' for x in file_list if x.startswith('weapons')]
file_list = os.listdir(f"{IMAGE_PATH}/genshin/material")
char_imgs = [
f"{IMAGE_PATH}/genshin/material/{x}"
for x in file_list
if x.startswith("char")
]
weapons_imgs = [
f"{IMAGE_PATH}/genshin/material/{x}"
for x in file_list
if x.startswith("weapons")
]
char_imgs.sort()
weapons_imgs.sort()
height = await asyncio.get_event_loop().run_in_executor(None, get_background_height, weapons_imgs)
background_img = CreateImg(1200, height + 100, color='#f6f2ee')
height = await asyncio.get_event_loop().run_in_executor(
None, get_background_height, weapons_imgs
)
background_img = CreateImg(1200, height + 100, color="#f6f2ee")
current_width = 50
for imgs in [char_imgs, weapons_imgs]:
current_height = 20
@@ -92,11 +140,11 @@ async def update_image():
background_img.paste(x, (current_width, current_height))
current_height += x.size[1]
current_width += 600
background_img.save(f'{IMAGE_PATH}/genshin/material/daily_material.png')
background_img.save(f"{IMAGE_PATH}/genshin/material/daily_material.png")
await page.close()
return True
except Exception as e:
logger.error(f'原神每日素材更新出错... {type(e)}: {e}')
logger.error(f"原神每日素材更新出错... {type(e)}: {e}")
if page:
await page.close()
return False
@@ -116,7 +164,7 @@ def get_background_height(weapons_imgs: List[str]) -> int:
@scheduler.scheduled_job(
'cron',
"cron",
hour=4,
minute=1,
)
@@ -124,11 +172,7 @@ async def _():
for _ in range(5):
try:
await update_image()
logger.info(f'更新每日天赋素材成功...')
logger.info(f"更新每日天赋素材成功...")
break
except Exception as e:
logger.error(f'更新每日天赋素材出错 e:{e}')
logger.error(f"更新每日天赋素材出错 e:{e}")
@@ -5,9 +5,24 @@ from nonebot import on_command
from utils.utils import get_message_text
from services.log import logger
__plugin_name__ = "丘丘语翻译"
__plugin_usage__ = "用法:丘丘翻译 [消息]"
__zx_plugin_name__ = "丘丘语翻译"
__plugin_usage__ = """
usage:
异世界旅游小助手,仅支持丘丘语翻译至中文
指令:
丘丘语翻译/丘丘一下 [文本]
""".strip()
__plugin_des__ = "其实我听得懂丘丘人讲话"
__plugin_cmd__ = ["丘丘语翻译/丘丘一下 [文本]"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["丘丘语翻译", "丘丘一下"],
}
qiuqiu = on_command("丘丘语翻译", aliases={"丘丘一下", "丘丘翻译"}, priority=5, block=True)
@@ -1,6 +1,5 @@
from nonebot import on_command, on_regex
from nonebot.rule import to_me
from .query_resource import get_resource_type_list, query_resource, init
from .query_resource import get_resource_type_list, query_resource, init, check_resource_exists
from utils.utils import get_message_text, scheduler
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.typing import T_State
@@ -14,28 +13,53 @@ try:
except ModuleNotFoundError:
import json
__plugin_name__ = "原神资源查询"
__zx_plugin_name__ = "原神资源查询"
__plugin_usage__ = """
usage:
不需要打开网页,就能帮你生成资源图片
指令:
原神资源查询 [资源名称]
原神资源列表
[资源名称]在哪
哪有[资源名称]
""".strip()
__plugin_superuser_usage__ = """
usage:
更新原神资源信息
指令:
更新原神资源信息
""".strip()
__plugin_des__ = "原神大地图资源速速查看"
__plugin_cmd__ = ["原神资源查询 [资源名称]", "原神资源列表", "[资源名称]在哪/哪有[资源名称]", "更新原神资源信息 [_superuser]"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神资源查询", "原神资源列表"],
}
__plugin_usage__ = (
"用法:\n" "\t原神资源查询 [消息]\n" "\t原神资源列表\n" "\t[消息]在哪\n" "\t哪有[消息]\n" "[消息] = 资源名称"
)
qr = on_command("原神资源查询", priority=5, block=True)
qr = on_command("原神资源查询", aliases={"原神资源查找"}, priority=5, block=True)
qr_lst = on_command("原神资源列表", priority=5, block=True)
rex_qr = on_regex(".*?(在哪|在哪里|哪有|哪里有).*?", rule=to_me(), priority=5, block=True)
update_info = on_command('更新原神资源信息', permission=SUPERUSER, priority=1, block=True)
rex_qr = on_regex(".*?(在哪|在哪里|哪有|哪里有).*?", priority=5, block=True)
update_info = on_command("更新原神资源信息", permission=SUPERUSER, priority=1, block=True)
@qr.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
resource_name = get_message_text(event.json())
await qr.send('正在生成位置....')
rst = await query_resource(resource_name)
await qr.send(Message(rst), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
if check_resource_exists(resource_name):
await qr.send("正在生成位置....")
resource = await query_resource(resource_name)
await qr.send(Message(resource), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
else:
await qr.send(f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称..")
@rex_qr.handle()
@@ -47,14 +71,15 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
else:
rs = re.search(".*?(哪有|哪里有)(.*)", msg)
resource_name = rs.group(2) if rs else ""
if resource_name:
await qr.send('正在生成位置....')
msg = await query_resource(resource_name)
await rex_qr.send(Message(msg), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
if check_resource_exists(resource_name):
await qr.send("正在生成位置....")
resource = await query_resource(resource_name)
if resource:
await rex_qr.send(Message(resource), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
@qr_lst.handle()
@@ -87,17 +112,17 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
@update_info.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
await init(True)
await update_info.send('更新原神资源信息完成...')
await update_info.send("更新原神资源信息完成...")
@scheduler.scheduled_job(
'cron',
"cron",
hour=5,
minute=1,
)
async def _():
try:
await init()
logger.info(f'每日更新原神材料信息成功!')
logger.info(f"每日更新原神材料信息成功!")
except Exception as e:
logger.error(f'每日更新原神材料信息错误:{e}')
logger.error(f"每日更新原神材料信息错误:{e}")
+3 -3
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from configs.path_config import IMAGE_PATH, TXT_PATH
from configs.path_config import IMAGE_PATH, TEXT_PATH
from utils.image_utils import CreateImg
from typing import Tuple, List
from math import sqrt, pow
@@ -12,8 +12,8 @@ except ModuleNotFoundError:
icon_path = Path(IMAGE_PATH) / "genshin" / "genshin_icon"
map_path = Path(IMAGE_PATH) / "genshin" / "map" / "map.png"
resource_label_file = Path(TXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TXT_PATH) / "genshin" / "resource_point_file.json"
resource_label_file = Path(TEXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TEXT_PATH) / "genshin" / "resource_point_file.json"
class Map:
@@ -1,5 +1,5 @@
from typing import Tuple, Optional, List
from configs.path_config import IMAGE_PATH, TXT_PATH
from configs.path_config import IMAGE_PATH, TEXT_PATH
from PIL.Image import UnidentifiedImageError
from utils.message_builder import image
from services.log import logger
@@ -30,9 +30,9 @@ MAP_URL = "https://api-static.mihoyo.com/common/map_user/ys_obc/v1/map/info?map_
icon_path = Path(IMAGE_PATH) / "genshin" / "genshin_icon"
map_path = Path(IMAGE_PATH) / "genshin" / "map"
resource_label_file = Path(TXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TXT_PATH) / "genshin" / "resource_point_file.json"
resource_type_file = Path(TXT_PATH) / "genshin" / "resource_type_file.json"
resource_label_file = Path(TEXT_PATH) / "genshin" / "resource_label_file.json"
resource_point_file = Path(TEXT_PATH) / "genshin" / "resource_point_file.json"
resource_type_file = Path(TEXT_PATH) / "genshin" / "resource_type_file.json"
# 地图中心坐标
CENTER_POINT: Optional[Tuple[int, int]] = None
@@ -50,7 +50,8 @@ async def query_resource(resource_name: str) -> str:
resource_name = resource_name[:-2].strip()
planning_route = True
if not resource_name or resource_name not in resource_name_list:
return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
# return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
return ''
map_ = Map(
resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO
)
@@ -81,23 +82,36 @@ def get_resource_type_list():
return mes
def check_resource_exists(resource: str) -> bool:
"""
检查资源是否存在
:param resource: 资源名称
"""
resource = resource.replace('路径', '').replace('路线', '')
return resource in resource_name_list
@driver.on_startup
async def init(flag: bool = False):
global CENTER_POINT, resource_name_list
semaphore = asyncio.Semaphore(10)
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
await download_map_init(session, semaphore, MAP_RATIO, flag)
await download_resource_data(session, semaphore)
await download_resource_type(session)
if not CENTER_POINT:
CENTER_POINT = json.load(open(resource_label_file, "r", encoding="utf8"))[
"CENTER_POINT"
]
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
try:
semaphore = asyncio.Semaphore(10)
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
await download_map_init(session, semaphore, MAP_RATIO, flag)
await download_resource_data(session, semaphore)
await download_resource_type(session)
if not CENTER_POINT:
CENTER_POINT = json.load(open(resource_label_file, "r", encoding="utf8"))[
"CENTER_POINT"
]
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
except TimeoutError:
logger.warning('原神资源查询信息初始化超时....')
pass
# 图标及位置资源