Skip to content

Commit

Permalink
✨ add help tips
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Dec 8, 2023
1 parent a91bd0b commit 39fc9ad
Show file tree
Hide file tree
Showing 15 changed files with 121 additions and 78 deletions.
16 changes: 15 additions & 1 deletion app/image.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from base64 import b64encode
from datetime import datetime
from pathlib import Path

Expand All @@ -8,6 +9,7 @@
from yarl import URL

font_path = Path(__file__).parent.parent / "assets" / "fonts"
image_path = Path(__file__).parent.parent / "assets" / "image"

font_mime_map = {
"collection": "font/collection",
Expand All @@ -19,6 +21,13 @@
}


with (image_path / "qqapi.png").open("rb") as f:
b64 = b64encode(f.read()).decode()

# with (image_path / "qq-guild.png").open("rb") as f:
# b641 = b64encode(f.read()).decode()


async def fill_font(route: Route, request: Request):
url = URL(request.url)
if (font_path / url.name).exists():
Expand All @@ -34,7 +43,12 @@ async def fill_font(route: Route, request: Request):
"<style>.footer{box-sizing:border-box;position:absolute;left:0;width:100%;background:#eee;"
"padding:30px 40px;margin-top:50px;font-size:1rem;color:#6b6b6b;}"
".footer p{margin:5px auto;}</style>"
f'<div class="footer"><p>由 RaianBot 生成</p><p>{datetime.now().strftime("%Y/%m/%d %p %I:%M:%S")}</p></div>'
'<div class="footer">'
f'<img align="right" src="data:image/png;base64,{b64}" />'
'<p>由 RaianBot 生成</p>'
'<br/>'
f'<p>{datetime.now().strftime("%Y/%m/%d %p %I:%M:%S")}</p>'
f'</div>'
)

html_render = HTMLRenderer(
Expand Down
2 changes: 1 addition & 1 deletion library/tencentcloud/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ async def send_email(
addr: str,
target: list[str],
subject: str,
template_id: str,
template_id: int,
template_data: dict[str, str],
name: str | None = None,
):
Expand Down
20 changes: 7 additions & 13 deletions library/weibo/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ async def __aenter__(self):
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()

async def _call(self, params: dict, timeout: int = 10) -> dict[str, Any] | None:
async def _call(self, params: dict, timeout: int = 10) -> dict[str, Any]:
base_url = "https://m.weibo.cn/api/container/getIndex?"
headers = {
"Host": "m.weibo.cn",
Expand All @@ -54,7 +54,6 @@ async def _call(self, params: dict, timeout: int = 10) -> dict[str, Any] | None:
try:
data = await resp.json(loads=ujson.loads)
except aiohttp.ContentTypeError as e:
print(await resp.text(), e)
raise RespDataError(f"Error: {await resp.text()}\n{params}") from e
if not data or data.get("ok") != 1:
raise RespDataError(f"Error: {data}\n{params}")
Expand All @@ -73,14 +72,11 @@ async def get_profile(
uid: int,
save: bool = False,
cache: bool = True,
) -> WeiboUser | None:
) -> WeiboUser:
if cache and str(uid) in self.data.followers:
return self.data.followers[str(uid)]
params = {"type": "uid", "value": uid}
try:
d_data = await self._call(params)
except (WeiboError, asyncio.TimeoutError):
return
d_data = await self._call(params)
user = WeiboUser(
id=uid,
name=d_data["userInfo"]["screen_name"],
Expand All @@ -105,7 +101,7 @@ async def get_profile_by_name(
index: int = 0,
save: bool = False,
cache: bool = True,
) -> WeiboUser | None:
) -> WeiboUser:
index = max(index, 0)
return await self.get_profile((await self.search_users(name))[index], save, cache)

Expand All @@ -117,7 +113,7 @@ async def get_profiles(self, name: str) -> list[WeiboUser]:
return res

def _handler_dynamic(self, data: dict) -> WeiboDynamic:
text: str = Query(data["text"]).text(squash_space=False) + "\n"
text: str = Query(data["text"]).text(squash_space=False) + "\n" # type: ignore
dynamic = WeiboDynamic(bid=data["bid"], text=text)
if len(data["pic_ids"]) > 0:
pics = data["pics"]
Expand All @@ -138,11 +134,9 @@ async def get_dynamic(
page: int = 1,
save: bool = False,
cache: bool = False,
) -> WeiboDynamic | None:
) -> WeiboDynamic:
if not isinstance(target, WeiboUser):
target = await self.get_profile(target, save, cache)
if not target:
return
params = {
"type": "uid",
"value": target.id,
Expand All @@ -151,7 +145,7 @@ async def get_dynamic(
}
d_data = await self._call(params)
if index > len(d_data["cards"]) - 1:
return
raise WeiboError("Index out of range")
if index < 0:
if len(d_data["cards"]) > 1:
ids = [int(i["mblog"]["id"]) for i in d_data["cards"] if i["card_type"] == 9]
Expand Down
8 changes: 4 additions & 4 deletions migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
import ujson
from loguru import logger

from app.config import SqliteDatabaseConfig, load_config
from app.database import Base, Group, User, get_engine_url
from app.config import load_config
from app.database import Base, Group, User
from app.database.manager import DatabaseManager
from app.logger import setup_logger
from plugins.coc.model import CocRule
Expand All @@ -29,11 +29,11 @@
setup_logger(config.log_level)


if isinstance(config.database, SqliteDatabaseConfig):
if config.database.type == "sqlite":
config.database.name = f"/{config.data_dir}/{config.database.name}"
if not config.database.name.endswith(".db"):
config.database.name = f"{config.database.name}.db"
db = DatabaseManager(get_engine_url(**config.database.dict()), {"echo": None, "pool_pre_ping": True})
db = DatabaseManager(config.database.url, {"echo": None, "pool_pre_ping": True})


async def main():
Expand Down
45 changes: 23 additions & 22 deletions plugins/admin/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,42 +51,43 @@ async def report(event: ExceptionThrown, avilla: Avilla):
with StringIO() as fp:
traceback.print_tb(event.exception.__traceback__, file=fp)
tb = fp.getvalue()
msg = f"""\
data = {
"event": str(event.event.__repr__()),
"exctype": str(type(event.exception)),
"exc": str(event.exception),
"traceback": tb,
}
masters = {conf.master_id for conf in bot.config.bots}
if api:
masters = {f"{conf.master_id}@qq.com" for conf in bot.config.bots}
with suppress(Exception):
await api.send_email(
"[email protected]",
[f"{master}@qq.com" for master in masters],
"Exception Occur",
27228,
data,
)
template = """\
## 异常事件:
`{str(event.event.__repr__())}`
`{event}`
## 异常类型:
`{type(event.exception)}`
`{exctype}`
## 异常内容:
{str(event.exception)}
{exc}
## 异常追踪:
```py
{tb}
{traceback}
```
"""
masters = {conf.master_id for conf in bot.config.bots}
if api:
masters = {f"{conf.master_id}@qq.com" for conf in bot.config.bots}
with suppress(Exception):
await api.send_email(
"[email protected]",
[f"{master}@qq.com" for master in masters],
"Exception Occur",
"27228",
{
"event": str(event.event.__repr__()),
"exctype": str(type(event.exception)),
"exc": str(event.exception),
"traceback": tb,
},
)
img = await md2img(msg, 1500)
img = await md2img(template.format_map(data), 1500)
if not (accounts := avilla.get_accounts(account_type=ElizabethAccount)):
return
for account in accounts:
Expand Down
2 changes: 1 addition & 1 deletion plugins/coc/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ async def setcoc_handle(
if not rule.available:
async with db.get_session() as session:
coc_rule = (await session.scalars(select(CocRule).where(CocRule.id == ctx.scene.last_value))).one_or_none()
rule = coc_rule.rule if coc_rule else 0
rule.result = coc_rule.rule if coc_rule else 0
return await ctx.scene.send_message(f"当前房规为 {rule}")
if rule.result > 6 or rule.result < 0:
return await ctx.scene.send_message("规则错误,规则只能为0-6")
Expand Down
2 changes: 1 addition & 1 deletion plugins/gacha/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async def get_sim_gacha(per: int = 2, status: int = 0):

cmd = Alconna(
"抽卡",
Args["count", int, Field(10, completion=lambda: "试试输入 300")],
Args["count", int, Field(10, completion=lambda: "试试输入 300", unmatch_tips=lambda x: f"预期参数为数字,而不是 {x}\n例如:/抽卡 100")],
Option("更新", help_text="卡池更新"),
meta=CommandMeta("模拟方舟寻访", example="$抽卡 300", extra={"supports": {"mirai", "qqapi"}}),
)
Expand Down
1 change: 1 addition & 0 deletions plugins/help/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
Field(
-1,
completion=lambda: f"试试 {random.randint(0, len(command_manager.get_commands()))}",
unmatch_tips=lambda x: f"预期输入为某个命令的id或者名称,而不是 {x}\n例如:/帮助 0"
),
],
meta=CommandMeta("查看帮助", extra={"supports": {"mirai", "qqapi"}}),
Expand Down
4 changes: 2 additions & 2 deletions plugins/music/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@

music = Alconna(
"点歌",
Args["name", str, Field(completion=lambda: "比如说, 以父之名")],
Args["singer?", str, Field(completion=lambda: "比如说, ‘周杰伦’")],
Args["name", str, Field(completion=lambda: "比如说, 以父之名")],
Args["singer?", str, Field(completion=lambda: "比如说, 'Talyer Swift'")],
meta=CommandMeta(
"在网易云点歌",
usage="可以指定歌手, 与歌名用空格分开",
Expand Down
9 changes: 6 additions & 3 deletions plugins/query_record/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pathlib import Path
from secrets import token_hex

from arclet.alconna import Alconna, Arg, Args, Arparma, CommandMeta, Option
from arclet.alconna import Alconna, Arg, Args, Arparma, CommandMeta, Option, Field
from arclet.alconna.graia import Match, alcommand, assign
from arknights_toolkit.images import update_operators
from arknights_toolkit.record import ArkRecord
Expand All @@ -17,7 +17,7 @@
alc = Alconna(
"抽卡查询",
Args["count#最近x抽", int, -1],
Option("绑定", Args[Arg("token", str, seps="\n")], compact=True),
Option("绑定", Args[Arg("token", str, Field(unmatch_tips=lambda x: f"请输入您的凭证,而不是{x}"), seps="\n")], compact=True),
Option("更新", Args["name?#卡池名", str]["limit", bool, True]),
meta=CommandMeta(
"明日方舟抽卡数据查询,数据来源为方舟官网",
Expand Down Expand Up @@ -121,7 +121,10 @@ async def update(ctx: Context, arp: Arparma):
@accessable
async def bind(ctx: Context, token: Match[str]):
if "content" in token.result:
token.result = re.match('.*content(")?:(")?(?P<token>[^{}"]+).*', token.result)["token"]
mat = re.match('.*content(")?:(")?(?P<token>[^{}"]+).*', token.result)
if not mat:
return await ctx.scene.send_message("凭据输入格式有误!")
token.result = mat["token"]
try:
res = querier.user_token_save(token.result, f"{ctx.client.last_value}")
except RuntimeError as e:
Expand Down
4 changes: 2 additions & 2 deletions plugins/random_operator/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
@alcommand(
Alconna(
"测试干员",
Args["name?#你的代号", [str, Notice], Field(completion=lambda: "你的代号是?")],
Args["name?#你的代号", [str, Notice], Field(completion=lambda: "你的代号是?", unmatch_tips=lambda x: f"输入的应该是名字或者 @提及某人,而不是 {x}")],
meta=CommandMeta(
"依据名字测试你会是什么干员",
example="$测试干员 海猫",
Expand All @@ -39,7 +39,7 @@ async def ro(ctx: Context, name: Match[Union[str, Notice]], bot: RaianBotService
text = RandomOperator().generate(_name.display or (await ctx.client.pull(Nick)).nickname)
else:
if is_qqapi_group(ctx):
await ctx.scene.send_message("请输入测试干员的名称:")
await ctx.scene.send_message("请输入测试干员的名称:\n如 [回复机器人] XXX")

async def waiter(waiter_ctx: Context, message: MessageChain):
ans = str(message.exclude(Notice)).lstrip()
Expand Down
4 changes: 2 additions & 2 deletions plugins/recruitment/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

cmd = Alconna(
"公招",
Args["tags", MultiVar(str, "*"), Field(completion=lambda: "高资")],
Args["tags", MultiVar(str, "*"), Field(completion=lambda: "高资", unmatch_tips=lambda x: f"输入的应该是公招标签,而不是{x}\n例如:/公招 高资")],
meta=CommandMeta(
"自助访问 prts 的公招计算器并截图",
usage="标签之间用空格分隔",
Expand All @@ -28,7 +28,7 @@
@accessable
async def recruit(ctx: Context, res: Arparma, pw: PlaywrightService, bot: RaianBotService):
if not res.all_matched_args.get("tags"):
return await ctx.scene.send_message("缺失标签\n试试比如 公招 高资")
return await ctx.scene.send_message("缺失标签\n试试比如 /公招 高资")
tags: tuple[str, ...] = res.all_matched_args["tags"]
await ctx.scene.send_message("正在获取中,请稍等。。。")
# Click html
Expand Down
11 changes: 7 additions & 4 deletions plugins/sk_autosign/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from datetime import datetime
from secrets import token_hex

from arclet.alconna import Alconna, Args, CommandMeta, Option
from arclet.alconna import Alconna, Args, CommandMeta, Option, Field
from arclet.alconna.graia import Match, alcommand, assign
from avilla.core import ActionFailed, Avilla, Context, Picture, RawResource
from avilla.elizabeth.account import ElizabethAccount
Expand All @@ -20,9 +20,9 @@

alc = Alconna(
"森空岛签到",
Option("绑定", Args["token", str], compact=True),
Option("绑定", Args["token", str, Field(unmatch_tips=lambda x: f"请输入你的凭据,而不是{x}")], compact=True),
Option("解除", compact=True),
Option("查询", Args["uid?", str], compact=True),
Option("查询", Args["uid?", str, Field(unmatch_tips=lambda x: f"请输入角色uid,而不是{x}")], compact=True),
Option("方法"),
meta=CommandMeta(
"森空岛方舟自动签到",
Expand Down Expand Up @@ -98,7 +98,10 @@ async def notice(ctx: Context, db: DatabaseService):
async def reg(ctx: Context, token: Match[str], db: DatabaseService):
sender = ctx.client.last_value
if "content" in token.result:
token.result = re.match('.*content(")?:(")?(?P<token>[^{}"]+).*', token.result)["token"]
mat = re.match('.*content(")?:(")?(?P<token>[^{}"]+).*', token.result)
if not mat:
return await ctx.scene.send_message("输入格式有误!")
token.result = mat["token"]
try:
await bind(token.result)
except RuntimeError as e:
Expand Down
Loading

0 comments on commit 39fc9ad

Please sign in to comment.