Skip to content

Commit

Permalink
0.1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
lgc2333 committed Jan 10, 2024
1 parent 17998c6 commit 1986ffa
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 24 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,6 @@ Telegram:[@lgc2333](https://t.me/lgc2333)

## 📝 更新日志

芝士刚刚发布的插件,还没有更新日志的说 qwq~
### 0.1.1

- 优化部分逻辑
2 changes: 1 addition & 1 deletion nonebot_plugin_pingti/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from . import __main__ as __main__ # noqa: E402
from .config import ConfigModel # noqa: E402

__version__ = "0.1.0.post1"
__version__ = "0.1.1"
__plugin_meta__ = PluginMetadata(
name="最佳平替",
description="用更低价的搜索词购物",
Expand Down
8 changes: 6 additions & 2 deletions nonebot_plugin_pingti/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,12 @@ async def _(matcher: AlconnaMatcher, kw: str):

if not (val := await query_from_db(kw)):
async with recall(await UniMessage("正在寻找平替……").send()):
val = await get_alternative_put_queue(kw)
try:
val = await get_alternative_put_queue(kw)
except Exception:
await matcher.finish("出现了一些问题,请稍后再试吧 >_<")

if val:
await matcher.finish(f"{kw} 的平替是:{val}")
await matcher.finish("出现了一些问题,请稍后再试吧 >_<")
# 有可能返回值为空,不知道是什么情况
await matcher.finish("好像并没有找到平替呢")
53 changes: 33 additions & 20 deletions nonebot_plugin_pingti/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Awaitable, Callable, Optional
from typing import Any, Awaitable, Callable, Dict, Optional, Union, cast

from httpx import AsyncClient
from nonebot import get_driver, logger
Expand All @@ -18,12 +18,19 @@
DATA_DIR.mkdir(parents=True)
if not DATA_FILE.exists():
DATA_FILE.write_text("{}", "u8")
else:
_d: Dict[str, str] = json.loads(DATA_FILE.read_text("u8"))
if any((not v) for v in _d.values()):
DATA_FILE.write_text(
json.dumps({k: v for k, v in _d.items() if v}, ensure_ascii=False),
encoding="u8",
)


async def query_from_db(kw: str) -> Optional[str]:
kw = kw.lower()
try:
data = json.loads(DATA_FILE.read_text("u8"))
data: Dict[str, str] = json.loads(DATA_FILE.read_text("u8"))
except Exception:
logger.exception("Error when querying database")
else:
Expand All @@ -35,9 +42,9 @@ async def query_from_db(kw: str) -> Optional[str]:
async def save_to_db(kw: str, resp: str) -> None:
kw = kw.lower()
try:
data = json.loads(DATA_FILE.read_text("u8"))
data: Dict[str, str] = json.loads(DATA_FILE.read_text("u8"))
data[kw] = resp
DATA_FILE.write_text(json.dumps(data, ensure_ascii=False), "u8")
DATA_FILE.write_text(json.dumps(data, ensure_ascii=False), encoding="u8")
except Exception:
logger.exception("Error when committing database")

Expand All @@ -50,7 +57,7 @@ async def save_to_db(kw: str, resp: str) -> None:
@dataclass
class QueueItem:
kw: str
callback: Callable[[Optional[str]], Awaitable[Any]]
callback: Callable[[Union[str, Exception]], Awaitable[Any]]


queue = asyncio.Queue[QueueItem]()
Expand Down Expand Up @@ -79,22 +86,27 @@ async def request_alternative(kw: str) -> str:


async def get_alternative_put_queue(kw: str) -> str:
val = ...
async def wait():
val = ...

async def callback(resp: Optional[str]) -> None:
nonlocal val
val = resp
if resp is None:
return
async def callback(r: Union[str, Exception]) -> None:
nonlocal val
val = r

await queue.put(QueueItem(kw, callback))

await queue.put(QueueItem(kw, callback))
while val is ...:
await asyncio.sleep(0)
return val
while val is ...:
await asyncio.sleep(0)
return cast(Union[str, Exception], val)

resp = await asyncio.wait_for(wait(), timeout=config.pingti_request_timeout + 1)
if isinstance(resp, Exception):
raise resp
return resp


async def handle_queue():
async def call(it: QueueItem, val: Optional[str]) -> None:
async def call(it: QueueItem, val: Union[str, Exception]) -> None:
try:
await it.callback(val)
except Exception:
Expand All @@ -109,20 +121,21 @@ async def once():

try:
val = await request_alternative(it.kw)
except Exception:
except Exception as e:
logger.exception("Error when doing request")
await call(it, None)
await call(it, e)
else:
if val:
await save_to_db(it.kw, val)
await call(it, val)
await save_to_db(it.kw, val)
queue.task_done()
await asyncio.sleep(2)

while True:
try:
await once()
except Exception:
logger.exception("Error when handling queue")
logger.exception("Unexpected error when handling queue")


driver = get_driver()
Expand Down

0 comments on commit 1986ffa

Please sign in to comment.