Skip to content

Commit

Permalink
Merge pull request #85 from MinatoAquaCrews/dev-v0.4.x
Browse files Browse the repository at this point in the history
🐛 fix: 修复 pre-commit hooks 导致 `import` 顺序改变
  • Loading branch information
KafCoppelia authored Jun 12, 2023
2 parents ff8c244 + 46b48ea commit a65e122
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 54 deletions.
7 changes: 4 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ repos:
- id: isort
stages: [commit]

- repo: https://github.com/pre-commit/mirrors-autopep8
rev: v2.0.2
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: autopep8
- id: black
stages: [commit]

- repo: https://github.com/pre-commit/mirrors-prettier
Expand All @@ -34,3 +34,4 @@ repos:
- id: check-added-large-files
- id: mixed-line-ending
- id: check-json
- id: check-toml
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ _🙏 今日运势 🙏_
<img src="https://img.shields.io/badge/nonebot2-2.0.0rc4+-green">
</a>

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

Expand All @@ -35,7 +35,7 @@ _🙏 今日运势 🙏_

## 版本

[v0.4.11](https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.11)
[v0.4.11.post1](https://github.com/MinatoAquaCrews/nonebot_plugin_fortune/releases/tag/v0.4.11.post1)

⚠️ 适配nonebot2-2.0.0rc4+

Expand Down
34 changes: 18 additions & 16 deletions nonebot_plugin_fortune/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
from nonebot_plugin_apscheduler import scheduler
from typing import Annotated

from nonebot import on_command, on_fullmatch, on_regex, require
from nonebot.adapters.onebot.v11 import (GROUP, GROUP_ADMIN, GROUP_OWNER,
GroupMessageEvent, Message,
MessageSegment)
from nonebot.adapters.onebot.v11 import (
GROUP,
GROUP_ADMIN,
GROUP_OWNER,
GroupMessageEvent,
Message,
MessageSegment,
)
from nonebot.log import logger
from nonebot.matcher import Matcher
from nonebot.params import CommandArg, Depends, RegexStr
Expand All @@ -15,8 +19,9 @@
from .data_source import FortuneManager, fortune_manager

require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler # isort:skip

__fortune_version__ = "v0.4.11"
__fortune_version__ = "v0.4.11.post1"
__fortune_usages__ = f"""
[今日运势/抽签/运势] 一般抽签
[xx抽签] 指定主题抽签
Expand All @@ -36,8 +41,7 @@
},
)

general_divine = on_command(
"今日运势", aliases={"抽签", "运势"}, permission=GROUP, priority=8)
general_divine = on_command("今日运势", aliases={"抽签", "运势"}, permission=GROUP, priority=8)
specific_divine = on_regex(r"^[^/]\S+抽签$", permission=GROUP, priority=8)
limit_setting = on_regex(r"^指定(.*?)签$", permission=GROUP, priority=8)
change_theme = on_regex(
Expand Down Expand Up @@ -89,8 +93,7 @@ async def _(event: GroupMessageEvent, args: Annotated[Message, CommandArg()]):
)
else:
logger.info(f"User {uid} | Group {gid} 占卜了今日运势")
msg = MessageSegment.text("✨今日运势✨\n") + \
MessageSegment.image(image_file)
msg = MessageSegment.text("✨今日运势✨\n") + MessageSegment.image(image_file)

await general_divine.finish(msg, at_sender=True)

Expand All @@ -111,8 +114,7 @@ async def _(
gid: str = str(event.group_id)
uid: str = str(event.user_id)

is_first, image_file = fortune_manager.divine(
gid, uid, theme, None)
is_first, image_file = fortune_manager.divine(gid, uid, theme, None)
if image_file is None:
await specific_divine.finish("今日运势生成出错……")

Expand Down Expand Up @@ -140,7 +142,9 @@ async def get_user_arg(matcher: Matcher, args: Annotated[str, RegexStr()]) -> st


@change_theme.handle()
async def _(event: GroupMessageEvent, user_theme: Annotated[str, Depends(get_user_arg)]):
async def _(
event: GroupMessageEvent, user_theme: Annotated[str, Depends(get_user_arg)]
):
gid: str = str(event.group_id)

for theme in FortuneThemesDict:
Expand Down Expand Up @@ -169,8 +173,7 @@ async def _(event: GroupMessageEvent, limit: Annotated[str, Depends(get_user_arg
if not spec_path:
await limit_setting.finish("还不可以指定这种签哦,请确认该签底对应主题开启或图片路径存在~")
else:
is_first, image_file = fortune_manager.divine(
gid, uid, None, spec_path)
is_first, image_file = fortune_manager.divine(gid, uid, None, spec_path)
if image_file is None:
await limit_setting.finish("今日运势生成出错……")

Expand All @@ -180,8 +183,7 @@ async def _(event: GroupMessageEvent, limit: Annotated[str, Depends(get_user_arg
)
else:
logger.info(f"User {uid} | Group {gid} 占卜了今日运势")
msg = MessageSegment.text("✨今日运势✨\n") + \
MessageSegment.image(image_file)
msg = MessageSegment.text("✨今日运势✨\n") + MessageSegment.image(image_file)

await limit_setting.finish(msg, at_sender=True)

Expand Down
33 changes: 12 additions & 21 deletions nonebot_plugin_fortune/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ def default(self, obj) -> Union[str, Any]:

driver = get_driver()
fortune_config: PluginConfig = PluginConfig.parse_obj(driver.config.dict())
themes_flag_config: ThemesFlagConfig = ThemesFlagConfig.parse_obj(
driver.config.dict())
themes_flag_config: ThemesFlagConfig = ThemesFlagConfig.parse_obj(driver.config.dict())


@driver.on_startup
Expand Down Expand Up @@ -129,8 +128,7 @@ async def fortune_check() -> None:

ret = await download_resource(copywriting_path, "copywriting.json", "fortune")
if not ret and not copywriting_path.exists():
raise ResourceError(
"Resource copywriting.json is missing! Please check!")
raise ResourceError("Resource copywriting.json is missing! Please check!")

"""
Check rules and data files
Expand All @@ -141,8 +139,7 @@ async def fortune_check() -> None:
specific_rules_path: Path = fortune_config.fortune_path / "specific_rules.json"

if not fortune_data_path.exists():
logger.warning(
"Resource fortune_data.json is missing, initialized one...")
logger.warning("Resource fortune_data.json is missing, initialized one...")

with fortune_data_path.open("w", encoding="utf-8") as f:
json.dump(dict(), f, ensure_ascii=False, indent=4)
Expand Down Expand Up @@ -181,18 +178,17 @@ async def fortune_check() -> None:

try:
is_divined: bool = _data[gid][uid].pop(
"is_divined") # type: ignore
"is_divined"
) # type: ignore
if is_divined:
_data[gid][uid].update(
{"last_sign_date": date.today()})
_data[gid][uid].update({"last_sign_date": date.today()})
else:
_data[gid][uid].update({"last_sign_date": 0})
except KeyError:
pass

with open(fortune_data_path, "w", encoding="utf-8") as f:
json.dump(_data, f, ensure_ascii=False,
indent=4, cls=DateTimeEncoder)
json.dump(_data, f, ensure_ascii=False, indent=4, cls=DateTimeEncoder)

_flag: bool = False
if not group_rules_path.exists():
Expand All @@ -201,31 +197,27 @@ async def fortune_check() -> None:
# Try to transfer from the old setting json
ret = group_rules_transfer(fortune_setting_path, group_rules_path)
if ret:
logger.info(
"旧版 fortune_setting.json 文件中群聊抽签主题设置已更新至 group_rules.json")
logger.info("旧版 fortune_setting.json 文件中群聊抽签主题设置已更新至 group_rules.json")
_flag = True

if not _flag:
# If failed or fortune_setting_path doesn't exist, initialize group_rules.json instead
with group_rules_path.open("w", encoding="utf-8") as f:
json.dump(dict(), f, ensure_ascii=False, indent=4)

logger.info(
"旧版 fortune_setting.json 文件中群聊抽签主题设置不存在,初始化 group_rules.json")
logger.info("旧版 fortune_setting.json 文件中群聊抽签主题设置不存在,初始化 group_rules.json")

_flag = False
if not specific_rules_path.exists():
# In version 0.4.9 and 0.4.10, data transfering will be done automatically if specific_rules.json doesn't exist
if fortune_setting_path.exists():
# Try to transfer from the old setting json
ret = specific_rules_transfer(
fortune_setting_path, specific_rules_path)
ret = specific_rules_transfer(fortune_setting_path, specific_rules_path)
if ret:
# Delete the old fortune_setting json if the transfer is OK
fortune_setting_path.unlink()

logger.info(
"旧版 fortune_setting.json 文件中签底指定规则已更新至 specific_rules.json")
logger.info("旧版 fortune_setting.json 文件中签底指定规则已更新至 specific_rules.json")
logger.warning("指定签底抽签功能将在 v0.5.0 弃用")
_flag = True

Expand Down Expand Up @@ -272,8 +264,7 @@ def specific_rules_transfer(
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
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:
Expand Down
9 changes: 4 additions & 5 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, int, date]]]] = 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 All @@ -32,7 +31,8 @@ def _multi_divine_check(self, gid: str, uid: str, nowtime: date) -> bool:

last_sign_date: datetime = datetime.strptime(
# type: ignore
self._user_data[gid][uid]["last_sign_date"], "%Y-%m-%d"
self._user_data[gid][uid]["last_sign_date"],
"%Y-%m-%d",
)

return last_sign_date.date() == nowtime
Expand Down Expand Up @@ -84,8 +84,7 @@ def divine(
self._end_data_handle(gid, uid, now_time)
return True, img_path
else:
img_path: Path = fortune_config.fortune_path / \
"out" / f"{gid}_{uid}.png"
img_path: Path = fortune_config.fortune_path / "out" / f"{gid}_{uid}.png"
return False, img_path

@staticmethod
Expand Down
3 changes: 1 addition & 2 deletions nonebot_plugin_fortune/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ async def download_url(url: str) -> Optional[Dict[str, Any]]:
return resp.json()

except Exception:
logger.warning(
f"Error occurred when downloading {url}, retry: {i+1}/3")
logger.warning(f"Error occurred when downloading {url}, retry: {i+1}/3")

logger.warning("Abort downloading")
return None
Expand Down
8 changes: 4 additions & 4 deletions nonebot_plugin_fortune/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,21 +135,21 @@ def decrement(text: str) -> Tuple[int, List[str]]:
fillIn = space * int(9 - length / 2)
return col_num, [
text[: int(length / 2)] + fillIn,
fillIn + text[int(length / 2):],
fillIn + text[int(length / 2) :],
]
else:
# odd number
fillIn = space * int(9 - (length + 1) / 2)
return col_num, [
text[: int((length + 1) / 2)] + fillIn,
fillIn + space + text[int((length + 1) / 2):],
fillIn + space + text[int((length + 1) / 2) :],
]

for i in range(col_num):
if i == col_num - 1 or col_num == 1:
result.append(text[i * cardinality:])
result.append(text[i * cardinality :])
else:
result.append(text[i * cardinality: (i + 1) * cardinality])
result.append(text[i * cardinality : (i + 1) * cardinality])

return col_num, result

Expand Down
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.11"
version = "0.4.11.post1"
description = "Fortune divination!"
authors = ["KafCoppelia <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit a65e122

Please sign in to comment.