Skip to content

Commit

Permalink
some edits
Browse files Browse the repository at this point in the history
  • Loading branch information
lgc2333 committed Dec 11, 2023
1 parent 4e7a525 commit 59c1330
Show file tree
Hide file tree
Showing 6 changed files with 186 additions and 176 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ plugins = [

## 🎉 使用

指令:`train 车次`
使用指令 `train -h` 查看帮助

### 效果图

Expand Down
6 changes: 3 additions & 3 deletions nonebot_plugin_cnrail/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
require("nonebot_plugin_alconna")
require("nonebot_plugin_htmlrender")

from .__main__ import usage # noqa: E402
from . import __main__ as __main__ # noqa: E402
from .config import ConfigModel # noqa: E402

__version__ = "0.1.2"
__version__ = "0.1.2.post1"
__plugin_meta__ = PluginMetadata(
name="CNRail",
description="查询 12306 列车时刻表",
usage=usage,
usage="使用指令 train -h 查看帮助",
type="application",
homepage="https://github.com/lgc-NB2Dev/nonebot-plugin-cnrail",
config=ConfigModel,
Expand Down
52 changes: 27 additions & 25 deletions nonebot_plugin_cnrail/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import datetime
import string
from contextlib import suppress
from datetime import date, datetime
from typing import Optional

from arclet.alconna import Alconna, Args, CommandMeta
Expand All @@ -9,32 +11,34 @@

from .data_source import MultipleTrainFoundError, query_train_info, render_train_info

usage = "指令:train 车次"

def parse_date(date_str: str) -> date:
for x in string.whitespace:
date_str = date_str.replace(x, "")
today = datetime.today()

def parse_date(date_str: str) -> datetime.date:
today = datetime.datetime.today()
for df in ("%Y/%m/%d", "%Y-%m-%d", "%Y年%m月%d日", "%m/%d", "%m-%d", "%m月%d日"):
try:
parsed_date = datetime.datetime.strptime(date_str, df)
except ValueError:
continue
parsed_date = parsed_date.replace(year=today.year)
if parsed_date < today:
parsed_date = parsed_date.replace(year=today.year + 1)
return parsed_date.date() # 忘了是不是这个
def parse(df: str) -> Optional[date]:
with suppress(ValueError):
parsed = datetime.strptime(date_str, df).replace(year=today.year)
if parsed < today:
parsed = parsed.replace(year=today.year + 1)
return parsed.date()
return None

date_formats = ("%m/%d", "%m-%d", "%m月%d日", "%m月%d号", "%m月%d")
if r := next((parse(x) for x in date_formats if parse(x)), None):
return r
raise ValueError


# search_train_info = on_command("train", aliases={"列车信息"})
search_train_info = on_alconna(
Alconna(
"train",
Args["train", str]["date?", str],
meta=CommandMeta(
description="查询列车信息",
usage="train 车次 [日期]",
example="train G1 2023-12-10",
usage="train <车次> [日期(只包含月和日)]",
example="train G1 12-10",
),
),
aliases={"列车信息", "查询列车"},
Expand All @@ -52,16 +56,13 @@ async def _(
train_no: str = train_no_query.result
train_date: Optional[str] = date_query.result

if train_date:
try:
train_date = parse_date(train_date).isoformat()
except ValueError:
await matcher.finish("日期格式不正确")
else:
train_date = datetime.date.today().isoformat()
try:
date_obj = parse_date(train_date) if train_date else date.today()
except ValueError:
await matcher.finish("日期格式不正确")

try:
train_info = await query_train_info(train_no, train_date)
train_info = await query_train_info(train_no, date_obj.isoformat())
except MultipleTrainFoundError as e:
much_text = "\n结果过多,仅显示前五个" if len(e.trains) > 5 else ""
info_text = "\n".join(x.word for x in e.trains[:5])
Expand All @@ -73,7 +74,8 @@ async def _(
await matcher.finish("查询信息时出现错误,请检查后台输出")

if not train_info:
await matcher.finish("未查询到车次,可能是当日未开行,请检查您的车次是否正确\n(可查询日期范围为前二日 ~ 后十四日)")
with_date_tip = "\n(可查询日期范围一般为前二日 ~ 后十四日)" if train_date else ""
await matcher.finish(f"未查询到车次,可能是当日未开行,请检查您的车次是否正确{with_date_tip}")

try:
img_bytes = await render_train_info(train_info)
Expand Down
5 changes: 0 additions & 5 deletions nonebot_plugin_cnrail/config.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
from nonebot import get_driver
from pydantic import BaseModel

# from pydantic.fields import Field
# from pydantic.networks import AnyHttpUrl


class ConfigModel(BaseModel):
# cnrail_max_suggestions: int = 5
# cnrail_moerail_base_url: AnyHttpUrl = Field("https://rail.re")
pass


Expand Down
7 changes: 2 additions & 5 deletions nonebot_plugin_cnrail/data_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

TEMPLATE_PATH = Path(__file__).parent / "templates" / "template.html.jinja"

ROUTE_BASE_URL = "https://rail.re/"
ROUTE_BASE_URL = "https://cnrail.nonebot/"
ROUTE_IMAGE_URL = f"{ROUTE_BASE_URL}image"


Expand All @@ -27,10 +27,7 @@ def __init__(self, trains: List[TrainSummary]) -> None:
super().__init__(trains)


async def query_train_info(
train_code: str,
train_date: str,
) -> Optional[TrainInfo]:
async def query_train_info(train_code: str, train_date: str) -> Optional[TrainInfo]:
train_code = train_code.upper()

async with httpx.AsyncClient(follow_redirects=True) as client:
Expand Down
Loading

0 comments on commit 59c1330

Please sign in to comment.