Skip to content

Commit

Permalink
Merge pull request #33 from MinatoAquaCrews/dev
Browse files Browse the repository at this point in the history
🐛 bugfix: update download url and chores
  • Loading branch information
KafCoppelia authored Mar 28, 2023
2 parents a9b14f7 + 2461f9a commit 0e49713
Show file tree
Hide file tree
Showing 10 changed files with 185 additions and 163 deletions.
4 changes: 4 additions & 0 deletions .github/release-drafter.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
categories:
- title: 💥 Breaking changes
labels:
- breaking-change
- title: "🚀 Features"
labels:
- "feature"
Expand All @@ -10,6 +13,7 @@ categories:
- "bug"
- title: "🧰 Maintenance"
label: "chore"

change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks.
version-resolver:
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

version: 2
updates:
- package-ecosystem: "pip" # See documentation for possible values
directory: "/" # Location of package manifests
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
interval: "daily"

target-branch: "master"
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,4 @@ dmypy.json
# Pyre type checker
.pyre/

*.zip
*.zip
10 changes: 10 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,13 @@ repos:
- id: prettier
types_or: [markdown, yaml, json]
stages: [commit]

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: mixed-line-ending
- id: check-json
19 changes: 10 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ _🔮 塔罗牌 🔮_
</div>

<p align="center">

<a href="https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/MinatoAquaCrews/nonebot_plugin_tarot?color=blue">
</a>

<a href="https://github.com/nonebot/nonebot2">
<img src="https://img.shields.io/badge/nonebot2-2.0.0b3+-green">
</a>
<a href="https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/releases/tag/v0.4.0.post1">

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

Expand All @@ -31,7 +31,7 @@ _🔮 塔罗牌 🔮_
<a href="https://results.pre-commit.ci/latest/github/MinatoAquaCrews/nonebot_plugin_tarot/master">
<img src="https://results.pre-commit.ci/badge/github/MinatoAquaCrews/nonebot_plugin_tarot/master.svg" alt="pre-commit.ci status">
</a>

</p>

##
Expand All @@ -40,7 +40,7 @@ _“许多傻瓜对千奇百怪的迷信说法深信不疑:象牙、护身符

## 版本

💥 [v0.4.0.post1](https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/releases/tag/v0.4.0.post1)
💥 [v0.4.0.post2](https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/releases/tag/v0.4.0.post2)

⚠ 适配nonebot2-2.0.0b3+

Expand All @@ -50,11 +50,12 @@ _“许多傻瓜对千奇百怪的迷信说法深信不疑:象牙、护身符

1. 通过 `pip``nb` 安装。pypi无法发行过大安装包,由此安装的插件不包含 `./resource`**所有塔罗牌主题资源**。请在[v0.4.0 release](https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/releases/tag/v0.4.0)页面下载各主题资源,部署至本地后修改 `TAROT_PATH` 配置即可;

2. `env` 下设置 `TAROT_PATH` 以更改资源路径`CHAIN_REPLY` 设置全局群聊转发模式(避免刷屏),亦可通过命令修改。例如:
2. `env` 下设置 `TAROT_PATH` 以更改资源路径`CHAIN_REPLY` 设置全局群聊转发模式(避免刷屏),亦可通过命令修改`TAROT_AUTO_UPDATE` 开启则插件将在启动时自动检查更新(默认关闭)。例如:

```python
TAROT_PATH="~/data/path-to-your-resource"
TAROT_PATH="path-to-your-resource"
CHAIN_REPLY=false
TAROT_AUTO_UPDATE=false
```

⚠ 请为塔罗牌资源分配单独的目录存放!即某一目录下仅有塔罗牌的所有资源。[#26](https://github.com/MinatoAquaCrews/nonebot_plugin_tarot/issues/26)
Expand All @@ -63,7 +64,7 @@ _“许多傻瓜对千奇百怪的迷信说法深信不疑:象牙、护身符

4. 图片资源可选择**不部署在本地**,插件会自动尝试从repo中下载缓存。

⚠ 使用 `raw.fastgit.org` 进行下载,不确保次次成功
⚠ 使用 `raw.fgit.ml` 进行下载,不确保次次成功

## 命令

Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_tarot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from .data_source import tarot_manager

__tarot_version__ = "v0.4.0.post1"
__tarot_version__ = "v0.4.0.post2"
__tarot_usages__ = f'''
塔罗牌 {__tarot_version__}
[占卜] 随机选取牌阵进行占卜
Expand Down
82 changes: 41 additions & 41 deletions nonebot_plugin_tarot/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import List, Set, Union
from typing import Any, Dict, List, Set, Union

import httpx
import nonebot
Expand All @@ -19,6 +19,7 @@ class PluginConfig(BaseModel, extra=Extra.ignore):
'''
tarot_path: Path = Path(__file__).parent / "resource"
chain_reply: bool = True
tarot_auto_update: bool = False
nickname: Set[str] = {"Bot"}

'''
Expand Down Expand Up @@ -47,19 +48,21 @@ def __str__(self):
__repr__ = __str__


class EventsNotSupport(Exception):
class EventNotSupport(Exception):
pass


async def download_url(url: str) -> Union[httpx.Response, None]:
async def download_url(name: str, is_json: bool = False) -> Union[Dict[str, Any], bytes, None]:
url: str = "https://raw.fgit.ml/MinatoAquaCrews/nonebot_plugin_tarot/master/nonebot_plugin_tarot/" + name

async with httpx.AsyncClient() as client:
for i in range(3):
try:
response = await client.get(url)
response: httpx.Response = await client.get(url)
if response.status_code != 200:
continue

return response
return response.json() if is_json else response.content()

except Exception:
logger.warning(
Expand All @@ -77,36 +80,36 @@ async def tarot_version_check() -> None:
if not tarot_config.tarot_path.exists():
tarot_config.tarot_path.mkdir(parents=True, exist_ok=True)

tarot_json_path = Path(__file__).parent / "tarot.json"

cur_version = 0
if tarot_json_path.exists():
with tarot_json_path.open("r", encoding="utf-8") as f:
data = json.load(f)
cur_version = data.get("version", 0)

url: str = "https://raw.fastgit.org/MinatoAquaCrews/nonebot_plugin_tarot/master/nonebot_plugin_tarot/tarot.json"
response = await download_url(url)

if response is None:
if not tarot_json_path.exists():
logger.warning("Tarot text resource missing! Please check!")
raise ResourceError("Missing necessary resource: tarot.json!")
else:
docs = response.json()
try:
version = docs.get("version")
except KeyError:
logger.warning(
"Tarot text resource downloaded incompletely! Please check!")
raise DownloadError

# Update when there is a newer version
if version > cur_version:
with tarot_json_path.open("w", encoding="utf-8") as f:
json.dump(docs, f, ensure_ascii=False, indent=4)
logger.info(
f"Updated tarot.json, version: {cur_version} -> {version}")
tarot_json_path: Path = Path(__file__).parent / "tarot.json"

# Auto update check on startup when tarot_auto_update is True
if tarot_config.tarot_auto_update:
cur_version: float = 0
if tarot_json_path.exists():
with tarot_json_path.open("r", encoding="utf-8") as f:
data = json.load(f)
cur_version = data.get("version", 0)

response: Dict[str, Any] = await download_url("tarot.json", is_json=True)

if response is None:
if not tarot_json_path.exists():
logger.warning("Tarot text resource missing! Please check!")
raise ResourceError("Missing necessary resource: tarot.json!")
else:
try:
version: float = response.get("version", 0)
except KeyError:
logger.warning(
"Tarot text resource downloaded incompletely! Please check!")
raise DownloadError

# Update when there is a newer version
if version > cur_version:
with tarot_json_path.open("w", encoding="utf-8") as f:
json.dump(response, f, ensure_ascii=False, indent=4)
logger.info(
f"Updated tarot.json, version: {cur_version} -> {version}")


@cached(ttl=180)
Expand All @@ -118,14 +121,11 @@ async def get_tarot(_theme: str, _type: str, _name: str) -> Union[bytes, None]:
logger.info(
f"Downloading tarot image {_theme}/{_type}/{_name} from repo")

url: str = "https://raw.fastgit.org/MinatoAquaCrews/nonebot_plugin_tarot/master/nonebot_plugin_tarot/resource/" + \
f"{_theme}/{_type}/{_name}"

data = await download_url(url)
resource: str = "resource/" + f"{_theme}/{_type}/{_name}"
data = await download_url(resource)

if data is None:
logger.warning(
f"Downloading tarot image {_theme}/{_type}/{_name} failed!")
return None

return data.content
return data
4 changes: 2 additions & 2 deletions nonebot_plugin_tarot/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from nonebot.matcher import Matcher
from PIL import Image

from .config import EventsNotSupport, ResourceError, get_tarot, tarot_config
from .config import EventNotSupport, ResourceError, get_tarot, tarot_config

try:
import ujson as json
Expand Down Expand Up @@ -132,7 +132,7 @@ async def divine(self, bot: Bot, matcher: Matcher, event: MessageEvent) -> None:
else:
await matcher.finish(msg_header + msg_body)
else:
raise EventsNotSupport
raise EventNotSupport

if self.is_chain_reply:
await bot.send_group_forward_msg(group_id=event.group_id, messages=chain)
Expand Down
Loading

0 comments on commit 0e49713

Please sign in to comment.