Skip to content

Commit

Permalink
🔥 v0.4.10a2: remove useless key in json
Browse files Browse the repository at this point in the history
  • Loading branch information
KafCoppelia committed Jan 10, 2023
1 parent 4056835 commit f80b434
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 82 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ _🙏 今日运势 🙏_
<img src="https://img.shields.io/badge/nonebot2-2.0.0rc1+-green">
</a>

<a href="https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.10a1">
<a href="https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.10a2">
<img src="https://img.shields.io/github/v/release/MinatoAquaCrews/nonebot_plugin_fortune?color=orange">
</a>

Expand All @@ -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)

## 安装

Expand All @@ -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`以启用或关闭抽签随机主题(默认全部开启),例如:

Expand Down
10 changes: 5 additions & 5 deletions nonebot_plugin_fortune/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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抽签] 指定主题抽签
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
77 changes: 42 additions & 35 deletions nonebot_plugin_fortune/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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
17 changes: 6 additions & 11 deletions nonebot_plugin_fortune/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
'''
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_fortune/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 14 additions & 25 deletions nonebot_plugin_fortune/utils.py
Original file line number Diff line number Diff line change
@@ -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]:
Expand All @@ -23,17 +23,16 @@ 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

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
Expand All @@ -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)

Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot_plugin_fortune"
version = "0.4.10a1"
version = "0.4.10a2"
description = "Fortune divination!"
authors = ["KafCoppelia <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit f80b434

Please sign in to comment.