Skip to content

Commit

Permalink
✨ 添加 Theme 功能
Browse files Browse the repository at this point in the history
  • Loading branch information
AzideCupric authored and felinae98 committed Feb 12, 2024
1 parent 2973eae commit 8767d83
Show file tree
Hide file tree
Showing 57 changed files with 1,617 additions and 711 deletions.
3 changes: 2 additions & 1 deletion nonebot_bison/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import nonebot_plugin_saa

from .plugin_config import PlugConfig, plugin_config
from . import post, send, types, utils, config, platform, bootstrap, scheduler, admin_page, sub_manager
from . import post, send, theme, types, utils, config, platform, bootstrap, scheduler, admin_page, sub_manager

__help__version__ = "0.8.2"
nonebot_plugin_saa.enable_auto_select_bot()
Expand Down Expand Up @@ -43,4 +43,5 @@
"platform",
"types",
"utils",
"theme",
]
160 changes: 89 additions & 71 deletions nonebot_bison/platform/arknights.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,56 @@
from typing import Any
from pathlib import Path
from functools import partial

from httpx import AsyncClient
from nonebot.plugin import require
from bs4 import BeautifulSoup as bs
from pydantic import Field, BaseModel

from ..post import Post
from ..types import Target, RawPost, Category
from .platform import NewMessage, StatusChange
from ..utils.scheduler_config import SchedulerConfig
from .platform import NewMessage, StatusChange, CategoryNotRecognize


class ArkResponseBase(BaseModel):
code: int
msg: str


class BulletinListItem(BaseModel):
cid: str
title: str
category: int
display_time: str = Field(alias="displayTime")
updated_at: int = Field(alias="updatedAt")
sticky: bool


class BulletinList(BaseModel):
list: list[BulletinListItem]

class Config:
extra = "ignore"


class BulletinData(BaseModel):
cid: str
display_type: int = Field(alias="displayType")
title: str
category: int
header: str
content: str
jump_link: str = Field(alias="jumpLink")
banner_image_url: str = Field(alias="bannerImageUrl")
display_time: str = Field(alias="displayTime")
updated_at: int = Field(alias="updatedAt")


class ArkBulletinListResponse(ArkResponseBase):
data: BulletinList


class ArkBulletinResponse(ArkResponseBase):
data: BulletinData


class ArknightsSchedConf(SchedulerConfig):
Expand All @@ -26,74 +68,52 @@ class Arknights(NewMessage):
is_common = False
scheduler = ArknightsSchedConf
has_target = False
default_theme = "arknights"

@classmethod
async def get_target_name(cls, client: AsyncClient, target: Target) -> str | None:
return "明日方舟游戏信息"

async def get_sub_list(self, _) -> list[RawPost]:
async def get_sub_list(self, _) -> list[BulletinListItem]:
raw_data = await self.client.get("https://ak-webview.hypergryph.com/api/game/bulletinList?target=IOS")
return raw_data.json()["data"]["list"]
return ArkBulletinListResponse.parse_obj(raw_data.json()).data.list

def get_id(self, post: RawPost) -> Any:
return post["cid"]
def get_id(self, post: BulletinListItem) -> Any:
return post.cid

def get_date(self, _: RawPost) -> Any:
return None
def get_date(self, post: BulletinListItem) -> Any:
return post.updated_at

def get_category(self, _) -> Category:
return Category(1)

async def parse(self, raw_post: RawPost) -> Post:
async def parse(self, raw_post: BulletinListItem) -> Post:
raw_data = await self.client.get(
f"https://ak-webview.hypergryph.com/api/game/bulletin/{self.get_id(post=raw_post)}"
)
raw_data = raw_data.json()["data"]

announce_title = raw_data.get("header") if raw_data.get("header") != "" else raw_data.get("title")
text = ""

pics = []
if raw_data["bannerImageUrl"]:
pics.append(raw_post["bannerImageUrl"])

elif raw_data["content"]:
require("nonebot_plugin_htmlrender")
from nonebot_plugin_htmlrender import template_to_pic

template_path = str(Path(__file__).parent.parent / "post/templates/ark_announce")
pic_data = await template_to_pic(
template_path=template_path,
template_name="index.html",
templates={
"bannerImageUrl": raw_data["bannerImageUrl"],
"announce_title": announce_title,
"content": raw_data["content"],
},
pages={
"viewport": {"width": 400, "height": 100},
"base_url": f"file://{template_path}",
},
)
# render = Render()
# viewport = {"width": 320, "height": 6400, "deviceScaleFactor": 3}
# pic_data = await render.render(
# announce_url, viewport=viewport, target="div.main"
# )
if pic_data:
pics.append(pic_data)
else:
text = "图片渲染失败"
data = ArkBulletinResponse.parse_obj(raw_data.json()).data

def title_escape(text: str) -> str:
return text.replace("\n", " - ")

# gen title, content
if data.header:
# header是title的更详细版本
# header会和content一起出现
title = data.header
else:
raise CategoryNotRecognize("未找到可渲染部分")
# 只有一张图片
title = title_escape(data.title)

return Post(
"arknights",
text=text,
url="",
target_name="明日方舟游戏内公告",
pics=pics,
self,
content=data.content,
title=title,
nickname="明日方舟游戏内公告",
images=[data.banner_image_url] if data.banner_image_url else None,
url=data.jump_link or None,
timestamp=data.updated_at,
compress=True,
override_use_pic=False,
)


Expand All @@ -106,6 +126,7 @@ class AkVersion(StatusChange):
is_common = False
scheduler = ArknightsSchedConf
has_target = False
default_theme = "brief"

@classmethod
async def get_target_name(cls, client: AsyncClient, target: Target) -> str | None:
Expand All @@ -122,18 +143,15 @@ async def get_status(self, _):

def compare_status(self, _, old_status, new_status):
res = []
ArkUpdatePost = partial(Post, self, "", nickname="明日方舟更新信息")
if old_status.get("preAnnounceType") == 2 and new_status.get("preAnnounceType") == 0:
res.append(
Post("arknights", text="登录界面维护公告上线(大概是开始维护了)", target_name="明日方舟更新信息")
)
res.append(ArkUpdatePost(title="登录界面维护公告上线(大概是开始维护了)"))
elif old_status.get("preAnnounceType") == 0 and new_status.get("preAnnounceType") == 2:
res.append(
Post("arknights", text="登录界面维护公告下线(大概是开服了,冲!)", target_name="明日方舟更新信息")
)
res.append(ArkUpdatePost(title="登录界面维护公告下线(大概是开服了,冲!)"))
if old_status.get("clientVersion") != new_status.get("clientVersion"):
res.append(Post("arknights", text="游戏本体更新(大更新)", target_name="明日方舟更新信息"))
res.append(ArkUpdatePost(title="游戏本体更新(大更新)"))
if old_status.get("resVersion") != new_status.get("resVersion"):
res.append(Post("arknights", text="游戏资源更新(小更新)", target_name="明日方舟更新信息"))
res.append(ArkUpdatePost(title="游戏资源更新(小更新)"))
return res

def get_category(self, _):
Expand Down Expand Up @@ -180,13 +198,12 @@ async def parse(self, raw_post: RawPost) -> Post:
imgs = [x["src"] for x in soup("img")]
text = f'{raw_post["title"]}\n{soup.text.strip()}'
return Post(
"monster-siren",
text=text,
pics=imgs,
self,
text,
images=imgs,
url=url,
target_name="塞壬唱片新闻",
nickname="塞壬唱片新闻",
compress=True,
override_use_pic=False,
)


Expand All @@ -199,6 +216,7 @@ class TerraHistoricusComic(NewMessage):
is_common = False
scheduler = ArknightsSchedConf
has_target = False
default_theme = "brief"

@classmethod
async def get_target_name(cls, client: AsyncClient, target: Target) -> str | None:
Expand All @@ -220,11 +238,11 @@ def get_category(self, _) -> Category:
async def parse(self, raw_post: RawPost) -> Post:
url = f'https://terra-historicus.hypergryph.com/comic/{raw_post["comicCid"]}/episode/{raw_post["episodeCid"]}'
return Post(
"terra-historicus",
text=f'{raw_post["title"]} - {raw_post["episodeShortTitle"]}',
pics=[raw_post["coverUrl"]],
self,
raw_post["subtitle"],
title=f'{raw_post["title"]} - {raw_post["episodeShortTitle"]}',
images=[raw_post["coverUrl"]],
url=url,
target_name="泰拉记事社漫画",
nickname="泰拉记事社漫画",
compress=True,
override_use_pic=False,
)
27 changes: 16 additions & 11 deletions nonebot_bison/platform/bilibili.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ async def parse(self, raw_post: RawPost) -> Post:
text += orig_text
else:
raise CategoryNotSupport(post_type)
return Post("bilibili", text=text, url=url, pics=pic, target_name=target_name)
return Post(self, text, url=url, images=pic, nickname=target_name)


class Bilibililive(StatusChange):
Expand All @@ -206,6 +206,7 @@ class Bilibililive(StatusChange):
name = "Bilibili直播"
has_target = True
use_batch = True
default_theme = "brief"

@unique
class LiveStatus(Enum):
Expand Down Expand Up @@ -334,11 +335,12 @@ async def parse(self, raw_post: Info) -> Post:
title = f"[{self.categories[raw_post.category].rstrip('提醒')}] {raw_post.title}"
target_name = f"{raw_post.uname} {raw_post.area_name}"
return Post(
self.name,
text=title,
self,
"",
title=title,
url=url,
pics=list(pic),
target_name=target_name,
images=list(pic),
nickname=target_name,
compress=True,
)

Expand All @@ -353,6 +355,7 @@ class BilibiliBangumi(StatusChange):
name = "Bilibili剧集"
has_target = True
parse_target_promot = "请输入剧集主页"
default_theme = "brief"

_url = "https://api.bilibili.com/pgc/review/user"

Expand Down Expand Up @@ -384,7 +387,7 @@ async def get_status(self, target: Target):
if res_dict["code"] == 0:
return {
"index": res_dict["result"]["media"]["new_ep"]["index"],
"index_show": res_dict["result"]["media"]["new_ep"]["index"],
"index_show": res_dict["result"]["media"]["new_ep"]["index_show"],
"season_id": res_dict["result"]["media"]["season_id"],
}
else:
Expand Down Expand Up @@ -412,13 +415,15 @@ async def parse(self, raw_post: RawPost) -> Post:
url = lastest_episode["link"]
pic: list[str] = [lastest_episode["cover"]]
target_name = detail_dict["result"]["season_title"]
text = lastest_episode["share_copy"]
content = raw_post["index_show"]
title = lastest_episode["share_copy"]
return Post(
self.name,
text=text,
self,
content,
title=title,
url=url,
pics=list(pic),
target_name=target_name,
images=list(pic),
nickname=target_name,
compress=True,
)

Expand Down
5 changes: 3 additions & 2 deletions nonebot_bison/platform/ff14.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def get_date(self, _: RawPost) -> None:
return None

async def parse(self, raw_post: RawPost) -> Post:
text = f'{raw_post["Title"]}\n{raw_post["Summary"]}'
title = raw_post["Title"]
text = raw_post["Summary"]
url = raw_post["Author"]
return Post("ff14", text=text, url=url, target_name="最终幻想XIV官方公告")
return Post(self, text, title=title, url=url, nickname="最终幻想XIV官方公告")
8 changes: 4 additions & 4 deletions nonebot_bison/platform/mcbbsnews.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ async def parse(self, post: RawPost) -> Post:
pics = await self._news_render(post_url, f"#{post_id}")

return Post(
self.name,
text="{}\n\n└由 {} 发表".format(post["title"], post["author"]),
self,
"{}\n\n└由 {} 发表".format(post["title"], post["author"]),
url=post_url,
pics=list(pics),
target_name=post["category"],
images=list(pics),
nickname=post["category"],
)

async def _news_render(self, url: str, selector: str) -> list[bytes]:
Expand Down
4 changes: 2 additions & 2 deletions nonebot_bison/platform/ncm.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async def parse(self, raw_post: RawPost) -> Post:
target_name = raw_post["artist"]["name"]
pics = [raw_post["picUrl"]]
url = "https://music.163.com/#/album?id={}".format(raw_post["id"])
return Post("ncm-artist", text=text, url=url, pics=pics, target_name=target_name)
return Post(self, text, url=url, images=pics, nickname=target_name)


class NcmRadio(NewMessage):
Expand Down Expand Up @@ -126,4 +126,4 @@ async def parse(self, raw_post: RawPost) -> Post:
target_name = raw_post["radio"]["name"]
pics = [raw_post["coverUrl"]]
url = "https://music.163.com/#/program/{}".format(raw_post["id"])
return Post("ncm-radio", text=text, url=url, pics=pics, target_name=target_name)
return Post(self, text, url=url, images=pics, nickname=target_name)
2 changes: 2 additions & 0 deletions nonebot_bison/platform/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ class Platform(metaclass=PlatformABCMeta, base=True):
client: AsyncClient
reverse_category: dict[str, Category]
use_batch: bool = False
# TODO: 限定可使用的theme名称
default_theme: str = "basic"

@classmethod
@abstractmethod
Expand Down
Loading

0 comments on commit 8767d83

Please sign in to comment.