From f80b43465ff168b8d12480dfb927f4e955320634 Mon Sep 17 00:00:00 2001
From: KafCoppelia <740677208@qq.com>
Date: Tue, 10 Jan 2023 13:16:29 +0800
Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20v0.4.10a2:=20remove=20useless=20?=
=?UTF-8?q?key=20in=20json?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
README.md | 8 +--
nonebot_plugin_fortune/__init__.py | 10 ++--
nonebot_plugin_fortune/config.py | 77 +++++++++++++++------------
nonebot_plugin_fortune/data_source.py | 17 +++---
nonebot_plugin_fortune/download.py | 2 +-
nonebot_plugin_fortune/utils.py | 39 +++++---------
pyproject.toml | 2 +-
7 files changed, 73 insertions(+), 82 deletions(-)
diff --git a/README.md b/README.md
index 27eedc1..1d2be09 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ _🙏 今日运势 🙏_
-
+
@@ -34,13 +34,13 @@ _🙏 今日运势 🙏_
## 版本
-v0.4.10a1
+v0.4.10a2
⚠️ 适配nonebot2-2.0.0rc1+
👉 [如何添加自己的抽签主题资源?欢迎贡献!🙏](https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/blob/beta/How-to-add-new-theme.md)
-[更新日志](https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.10a1)
+[更新日志](https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.10a2)
## 安装
@@ -56,7 +56,7 @@ v0.4.10a1
FORTUNE_PATH="your-path-to-resource" # For example, "./my-data/fortune",其下有img、font、fortune文件夹等资源
```
- ⚠️️ 插件启动时,将自动检查资源是否缺失(**除字体与图片**资源),会尝试从repo中下载
+ ⚠️️ 插件启动时,将自动检查资源是否缺失(**除字体与图片**资源)
3. 在`env`下设置`xxx_FLAG`以启用或关闭抽签随机主题(默认全部开启),例如:
diff --git a/nonebot_plugin_fortune/__init__.py b/nonebot_plugin_fortune/__init__.py
index fddea13..3eebd86 100644
--- a/nonebot_plugin_fortune/__init__.py
+++ b/nonebot_plugin_fortune/__init__.py
@@ -12,7 +12,7 @@
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler
-__fortune_version__ = "v0.4.10a1"
+__fortune_version__ = "v0.4.10a2"
__fortune_usages__ = f'''
[今日运势/抽签/运势] 一般抽签
[xx抽签] 指定主题抽签
@@ -65,7 +65,7 @@ async def _(event: GroupMessageEvent, args: Message = CommandArg()):
uid: str = str(event.user_id)
is_first, image_file = fortune_manager.divine(gid, uid, None, None)
- if not image_file:
+ if image_file is None:
await general_divine.finish("今日运势生成出错……")
if not is_first:
@@ -99,7 +99,7 @@ async def _(event: GroupMessageEvent, user_theme: str = Depends(get_user_theme))
is_first, image_file = fortune_manager.divine(
gid, uid, theme, None)
- if not image_file:
+ if image_file is None:
await specific_divine.finish("今日运势生成出错……")
if not is_first:
@@ -145,7 +145,7 @@ async def _(event: GroupMessageEvent, limit: str = Depends(get_user_arg)):
if limit == "随机":
is_first, image_file = fortune_manager.divine(gid, uid, None, None)
- if not image_file:
+ if image_file is None:
await limit_setting.finish("今日运势生成出错……")
else:
spec_path = fortune_manager.specific_check(limit)
@@ -154,7 +154,7 @@ async def _(event: GroupMessageEvent, limit: str = Depends(get_user_arg)):
else:
is_first, image_file = fortune_manager.divine(
gid, uid, None, spec_path)
- if not image_file:
+ if image_file is None:
await limit_setting.finish("今日运势生成出错……")
if not is_first:
diff --git a/nonebot_plugin_fortune/config.py b/nonebot_plugin_fortune/config.py
index 61ac12f..3e81730 100644
--- a/nonebot_plugin_fortune/config.py
+++ b/nonebot_plugin_fortune/config.py
@@ -91,7 +91,7 @@ async def fortune_check() -> None:
fortune_config.fortune_path.mkdir(parents=True, exist_ok=True)
'''
- Check whether all themes are disable.
+ Check whether all themes are DISABLE.
'''
content = themes_flag_config.dict()
_flag: bool = False
@@ -103,7 +103,10 @@ async def fortune_check() -> None:
if not _flag:
raise ResourceError("Fortune themes ALL disabled! Please check!")
- # Save fortune themes config
+ '''
+ Save fortune themes config.
+ Currently, the fortune_config.json is useless.
+ '''
flags_config_path: Path = fortune_config.fortune_path / "fortune_config.json"
with flags_config_path.open("w", encoding="utf-8") as f:
json.dump(content, f, ensure_ascii=False, indent=4)
@@ -116,18 +119,10 @@ async def fortune_check() -> None:
fonts_path.mkdir(parents=True, exist_ok=True)
if not (fonts_path / "Mamelon.otf").exists():
- # ret = await download_resource((fonts_path / "Mamelon.otf"), "Mamelon.otf", "font")
- # if ret:
- # logger.info(f"Downloaded Mamelon.otf from repo")
- # else:
- raise ResourceError(f"Resource Mamelon.otf is missing! Please check!")
+ raise ResourceError("Resource Mamelon.otf is missing! Please check!")
if not (fonts_path / "sakura.ttf").exists():
- # ret = await download_resource((fonts_path / "sakura.ttf"), "sakura.ttf", "font")
- # if ret:
- # logger.info(f"Downloaded sakura.ttf from repo")
- # else:
- raise ResourceError(f"Resource sakura.ttf is missing! Please check!")
+ raise ResourceError("Resource sakura.ttf is missing! Please check!")
'''
Try to get the latest copywriting from the repository.
@@ -157,7 +152,7 @@ async def fortune_check() -> None:
else:
'''
In version 0.4.10, the format of fortune_data.json is changed from v0.4.9 and older.
- 1. Remove useless key "nickname"
+ 1. Remove useless keys "gid", "uid" and "nickname"
2. Transfer the key "is_divined" to "last_sign_date"
'''
with open(fortune_data_path, 'r', encoding='utf-8') as f:
@@ -175,6 +170,16 @@ async def fortune_check() -> None:
except KeyError:
pass
+ try:
+ _data[gid][uid].pop("gid")
+ except KeyError:
+ pass
+
+ try:
+ _data[gid][uid].pop("uid")
+ except KeyError:
+ pass
+
try:
is_divined: bool = _data[gid][uid].pop("is_divined")
if is_divined:
@@ -236,31 +241,33 @@ def group_rules_transfer(fortune_setting_dir: Path, group_rules_dir: Path) -> bo
'''
Transfer the group_rule in fortune_setting.json to group_rules.json
'''
- with open(fortune_setting_dir, 'r', encoding='utf-8') as fs:
- _setting: Dict[str, Dict[str, Union[str, List[str]]]] = json.load(fs)
- group_rules = _setting.get("group_rule", None) # Old key is group_rule
-
- with open(group_rules_dir, 'w', encoding='utf-8') as fr:
- if group_rules is None:
- json.dump(dict(), fr, ensure_ascii=False, indent=4)
- return False
- else:
- json.dump(group_rules, fr, ensure_ascii=False, indent=4)
- return True
+ with open(fortune_setting_dir, 'r', encoding='utf-8') as f:
+ _setting: Dict[str, Dict[str, Union[str, List[str]]]] = json.load(f)
+
+ group_rules = _setting.get("group_rule", None) # Old key is group_rule
+
+ with open(group_rules_dir, 'w', encoding='utf-8') as f:
+ if group_rules is None:
+ json.dump(dict(), f, ensure_ascii=False, indent=4)
+ return False
+ else:
+ json.dump(group_rules, f, ensure_ascii=False, indent=4)
+ return True
def specific_rules_transfer(fortune_setting_dir: Path, specific_rules_dir: Path) -> bool:
'''
Transfer the specific_rule in fortune_setting.json to specific_rules.json
'''
- with open(fortune_setting_dir, 'r', encoding='utf-8') as fs:
- _setting: Dict[str, Dict[str, Union[str, List[str]]]] = json.load(fs)
- specific_rules = _setting.get("specific_rule", None) # Old key is specific_rule
-
- with open(specific_rules_dir, 'w', encoding='utf-8') as fr:
- if not specific_rules:
- json.dump(dict(), fr, ensure_ascii=False, indent=4)
- return False
- else:
- json.dump(specific_rules, fr, ensure_ascii=False, indent=4)
- return True
+ with open(fortune_setting_dir, 'r', encoding='utf-8') as f:
+ _setting: Dict[str, Dict[str, Union[str, List[str]]]] = json.load(f)
+
+ specific_rules = _setting.get("specific_rule", None) # Old key is specific_rule
+
+ with open(specific_rules_dir, 'w', encoding='utf-8') as f:
+ if not specific_rules:
+ json.dump(dict(), f, ensure_ascii=False, indent=4)
+ return False
+ else:
+ json.dump(specific_rules, f, ensure_ascii=False, indent=4)
+ return True
diff --git a/nonebot_plugin_fortune/data_source.py b/nonebot_plugin_fortune/data_source.py
index 6042d0f..b38474c 100644
--- a/nonebot_plugin_fortune/data_source.py
+++ b/nonebot_plugin_fortune/data_source.py
@@ -10,8 +10,7 @@
class FortuneManager:
def __init__(self):
- self._user_data: Dict[str, Dict[str,
- Dict[str, Union[str, bool, int]]]] = dict()
+ self._user_data: Dict[str, Dict[str, Dict[str, Union[str, int, date]]]] = dict()
self._group_rules: Dict[str, str] = dict()
self._specific_rules: Dict[str, List[str]] = dict()
self._user_data_file: Path = fortune_config.fortune_path / "fortune_data.json"
@@ -66,17 +65,16 @@ def divine(self, gid: str, uid: str, _theme: Optional[str] = None, spec_path: Op
if not self._multi_divine_check(gid, uid, now_time):
try:
- image_file = drawing(gid, uid, theme, spec_path)
+ img_path = drawing(gid, uid, theme, spec_path)
except Exception:
return True, None
# Record the sign-in time
self._end_data_handle(gid, uid, now_time)
- return True, image_file
+ return True, img_path
else:
- image_file: Path = fortune_config.fortune_path / \
- "out" / f"{gid}_{uid}.png"
- return False, image_file
+ img_path: Path = fortune_config.fortune_path / "out" / f"{gid}_{uid}.png"
+ return False, img_path
def clean_out_pics(self) -> None:
'''
@@ -104,10 +102,7 @@ def _init_user_data(self, gid: str, uid: str) -> None:
if uid not in self._user_data[gid]:
self._user_data[gid][uid] = {
- "gid": gid,
- "uid": uid,
- # Last sign-in date. YY-MM-DD
- "last_sign_date": 0
+ "last_sign_date": 0 # Last sign-in date. YY-MM-DD
}
self._save_data()
diff --git a/nonebot_plugin_fortune/download.py b/nonebot_plugin_fortune/download.py
index 189b24b..cf5c02a 100644
--- a/nonebot_plugin_fortune/download.py
+++ b/nonebot_plugin_fortune/download.py
@@ -33,7 +33,7 @@ async def download_resource(resource_dir: Path, name: str, _type: Optional[str]
Try to download resources, including fonts, fortune copywriting, but not images.
For fonts & copywriting, download and save into files when missing. Otherwise, raise ResourceError
'''
- base_url: str = "https://raw.fastgit.org/MinatoAquaCrews/nonebot_plugin_fortune/beta/nonebot_plugin_fortune/resource"
+ base_url: str = "https://raw.fastgit.org/MinatoAquaCrews/nonebot_plugin_fortune/master/nonebot_plugin_fortune/resource"
if isinstance(_type, str):
url: str = base_url + "/" + _type + "/" + name
diff --git a/nonebot_plugin_fortune/utils.py b/nonebot_plugin_fortune/utils.py
index 57c62e0..21343c5 100644
--- a/nonebot_plugin_fortune/utils.py
+++ b/nonebot_plugin_fortune/utils.py
@@ -1,9 +1,9 @@
from PIL import Image, ImageDraw, ImageFont
-from typing import Optional, Tuple, Dict, List
+from typing import Optional, Tuple, List
from pathlib import Path
import random
import json
-from .config import fortune_config
+from .config import fortune_config, themes_flag_config
def get_copywriting() -> Tuple[str, str]:
@@ -23,7 +23,7 @@ def get_copywriting() -> Tuple[str, str]:
return title, text
-def randomBasemap(theme: str, spec_path: Optional[str] = None) -> Path:
+def random_basemap(theme: str, spec_path: Optional[str] = None) -> Path:
if isinstance(spec_path, str):
p: Path = fortune_config.fortune_path / "img" / spec_path
return p
@@ -31,9 +31,8 @@ def randomBasemap(theme: str, spec_path: Optional[str] = None) -> Path:
if theme == "random":
__p: Path = fortune_config.fortune_path / "img"
- # Each dir is a theme, remember add _flag after the names of themes
- themes: List[str] = [f.name for f in __p.iterdir(
- ) if f.is_dir() and themes_flag_check(f.name)]
+ # Each dir is a theme. Add "_flag" after the names of themes
+ themes: List[str] = [f.name for f in __p.iterdir() if f.is_dir() and themes_flag_check(f.name + "_flag")]
picked: str = random.choice(themes)
_p: Path = __p / picked
@@ -51,7 +50,7 @@ def randomBasemap(theme: str, spec_path: Optional[str] = None) -> Path:
def drawing(gid: str, uid: str, theme: str, spec_path: Optional[str] = None) -> Path:
# 1. Random choice a base image
- imgPath: Path = randomBasemap(theme, spec_path)
+ imgPath: Path = random_basemap(theme, spec_path)
img: Image.Image = Image.open(imgPath)
draw = ImageDraw.Draw(img)
@@ -98,18 +97,13 @@ def drawing(gid: str, uid: str, theme: str, spec_path: Optional[str] = None) ->
draw.text((x, y), textVertical, fill=color, font=ttfront)
# Save
- outPath: Path = exportFilePath(imgPath, gid, uid)
- img.save(outPath)
- return outPath
-
-
-def exportFilePath(originalFilePath: Path, gid: str, uid: str) -> Path:
- dirPath: Path = fortune_config.fortune_path / "out"
- if not dirPath.exists():
- dirPath.mkdir(exist_ok=True, parents=True)
+ outDir: Path = fortune_config.fortune_path / "out"
+ if not outDir.exists():
+ outDir.mkdir(exist_ok=True, parents=True)
+
+ outPath = outDir / f"{gid}_{uid}.png"
- outPath: Path = originalFilePath.parent.parent.parent / \
- "out" / f"{gid}_{uid}.png"
+ img.save(outPath)
return outPath
@@ -154,11 +148,6 @@ def decrement(text: str) -> Tuple[int, List[str]]:
def themes_flag_check(theme: str) -> bool:
'''
- Read the config json, return the status of a theme
+ check wether a theme is enabled in themes_flag_config
'''
- flags_config_path: Path = fortune_config.fortune_path / "fortune_config.json"
-
- with flags_config_path.open("r", encoding="utf-8") as f:
- data: Dict[str, bool] = json.load(f)
-
- return data.get((theme + "_flag"), False)
+ return themes_flag_config.dict().get(theme, False)
diff --git a/pyproject.toml b/pyproject.toml
index 7b6f219..f6e8156 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot_plugin_fortune"
-version = "0.4.10a1"
+version = "0.4.10a2"
description = "Fortune divination!"
authors = ["KafCoppelia "]
license = "MIT"