Skip to content

Commit

Permalink
Merge pull request #77 from djkcyl/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
djkcyl authored Aug 3, 2023
2 parents 6cdf4d3 + a0d0865 commit 71f6ce5
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 79 deletions.
7 changes: 5 additions & 2 deletions aunly_bbot/function/command/content_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ async def main(
logger.info(f"开始生成视频信息图片:{aid}")
b23_url = await get_b23_url(f"https://www.bilibili.com/video/{bvid}")

image = await (await BiliVideoImage.from_view_rely(video_info, b23_url)).render(BotConfig.Bilibili.render_style)
image = await (await BiliVideoImage.from_view_rely(video_info, b23_url)).render(
BotConfig.Bilibili.render_style
)
info_message = await app.send_group_message(
group,
MessageChain(
Expand Down Expand Up @@ -108,7 +110,7 @@ async def openai_summarization():
summarise = ai_summary.response
archive_data.openai = summarise
else:
logger.warning(f"视频 {aid} 总结失败:{ai_summary.raw}")
logger.warning(f"视频 {aid} 总结失败:{ai_summary.raw or '总结内容为空'}")
return

if "no meaning" in summarise.lower() or len(summarise) < 20:
Expand Down Expand Up @@ -167,6 +169,7 @@ async def wordcloud():
)

except AbortError as e:
logger.exception(e)
logger.warning(f"视频 {aid} 总结失败:{e.message}")
return
archive_data.save()
Expand Down
2 changes: 1 addition & 1 deletion aunly_bbot/function/command/up/subscribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async def main(app: Ariadne, group: Group, at: ElementResult, anything: RegexRes
if not BOT_Status.check_status(Status.INITIALIZED):
return await app.send_group_message(
group,
MessageChain("正在初始化,请稍后..."),
MessageChain("正在初始化,请稍后再试..."),
)
message = anything.result.display # type: ignore
uid = await uid_extract(message, show_error=True)
Expand Down
40 changes: 10 additions & 30 deletions aunly_bbot/function/pusher/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,13 @@ async def init(app: Ariadne):
data = await bilibili_login.send_sms(BotConfig.Bilibili.username)
await app.send_friend_message(
BotConfig.master,
MessageChain(
f"[Bilibili推送] 用户名密码登录失败:{e.msg}\n正在使用验证码登录,请在 120 秒内发送验证码到此处"
),
MessageChain(f"[Bilibili推送] 用户名密码登录失败:{e.msg}\n正在使用验证码登录,请在 120 秒内发送验证码到此处"),
)
try:
code = await asyncio.wait_for(inc.wait(CodeWaiter()), timeout=120)
auth_data = await bilibili_login.sms_login(code)
logger.success("[BiliBili推送] 验证码登录完成")
await app.send_friend_message(
BotConfig.master, MessageChain("[BiliBili推送] 验证码登录完成")
)
await app.send_friend_message(BotConfig.master, MessageChain("[BiliBili推送] 验证码登录完成"))
break
except asyncio.TimeoutError:
logger.warning("[BiliBili推送] 等待输入验证码超时,如需重新登陆,请重启机器人")
Expand Down Expand Up @@ -159,18 +155,14 @@ async def init(app: Ariadne):
logger.error(f"[BiliBili推送] 二维码登录失败:{e.code}{e.msg},如需重新登陆,请重启机器人")
await app.send_friend_message(
BotConfig.master,
MessageChain(
f"[BiliBili推送] 二维码登录失败:{e.code}{e.msg},如需重新登陆,请重启机器人"
),
MessageChain(f"[BiliBili推送] 二维码登录失败:{e.code}{e.msg},如需重新登陆,请重启机器人"),
)
sys.exit(1)

if auth_data:
Bili_Auth.update(auth_data)
logger.debug(await Bili_Auth.get_info())
login_cache_file.write_text(
json.dumps(dict(Bili_Auth), indent=2, ensure_ascii=False)
)
login_cache_file.write_text(json.dumps(dict(Bili_Auth), indent=2, ensure_ascii=False))
logger.info("[Bilibili推送] 登录完成")
else:
logger.critical("[Bilibili推送] 登录状态异常,正在退出")
Expand All @@ -195,22 +187,16 @@ async def init(app: Ariadne):
followed_list = resp.items

if Path("data").joinpath(".lock").exists():
if Path("data").joinpath(".lock").read_text(encoding="utf-8") != str(
BotConfig.Bilibili.username
):
logger.critical(
"[Bilibili推送] 检测到上次登录的账号与当前账号不一致,如需继续使用,请先手动删除数据库(data/data.db)和 data/.lock 文件"
)
if Path("data").joinpath(".lock").read_text(encoding="utf-8") != str(BotConfig.Bilibili.username):
logger.critical("[Bilibili推送] 检测到上次登录的账号与当前账号不一致,如需继续使用,请先手动删除数据库(data/data.db)和 data/.lock 文件")
sys.exit(1)

elif (f := len(followed_list)) != 0:
if cache["ignore_sub"]:
logger.warning(f"[Bilibili推送] 该账号已关注 {f} 个用户,正在尝试自动处理")
Path("data").joinpath(".lock").write_text(str(BotConfig.Bilibili.username))
else:
logger.critical(
f"[Bilibili推送] 该账号已关注 {f} 个用户,为避免产生问题,已停止运行,请先手动取消关注或添加启动参数 --ignore-sub,这将取关所有已关注的用户"
)
logger.critical(f"[Bilibili推送] 该账号已关注 {f} 个用户,为避免产生问题,已停止运行,请先手动取消关注或添加启动参数 --ignore-sub,这将取关所有已关注的用户")
sys.exit(1)
else:
Path("data").joinpath(".lock").write_text(str(BotConfig.Bilibili.username))
Expand All @@ -219,23 +205,17 @@ async def init(app: Ariadne):
if followed_list:
for uid in followed_list:
if str(uid.uid) not in subid_list:
logger.warning(
f"[BiliBili推送] {uid.name}{uid.uid})在 BliBili 关注列表中,但不在数据库中,正在从 BliBili 取消关注"
)
logger.warning(f"[BiliBili推送] {uid.name}{uid.uid})在 BliBili 关注列表中,但不在数据库中,正在从 BliBili 取消关注")
resp = await delete_uid(uid.uid)
if resp:
await app.send_friend_message(
BotConfig.master,
MessageChain(
f"[BiliBili推送] {uid.name}{uid.uid})在 BliBili 关注列表中,但不在数据库中,正在从 BliBili 取消关注"
),
MessageChain(f"[BiliBili推送] {uid.name}{uid.uid})在 BliBili 关注列表中,但不在数据库中,正在从 BliBili 取消关注"),
)
await asyncio.sleep(1)
continue
else:
logger.error(
f"[BiliBili推送] {uid.name}{uid.uid})从 BliBili 取消关注失败,请检查后重启 Bot"
)
logger.error(f"[BiliBili推送] {uid.name}{uid.uid})从 BliBili 取消关注失败,请检查后重启 Bot")
sys.exit(1)

# 顺便检测直播状态
Expand Down
52 changes: 13 additions & 39 deletions aunly_bbot/function/pusher/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,17 @@

@channel.use(SchedulerSchema(every_custom_seconds(BotConfig.Bilibili.dynamic_interval)))
async def main(app: Ariadne):
sub_list = get_all_uid()
sub_sum = len(sub_list)

if (
not BOT_Status.is_all_statuses_true(
Status.INITIALIZED, Status.ACCOUNT_CONNECTED, Status.STARTED, Status.SUBSCRIBE_IDLE
)
or BOT_Status.is_all_statuses_true(
Status.INITIALIZED, Status.ACCOUNT_CONNECTED, Status.STARTED, Status.SUBSCRIBE_IDLE
)
and len(get_all_uid()) == 0
or sub_sum == 0
):
await asyncio.sleep(5)
return
sub_list = get_all_uid()

BOT_Status.set_status(Status.LIVE_IDLE, False)

for up in BOT_Status.living.copy():
Expand Down Expand Up @@ -73,9 +71,7 @@ async def main(app: Ariadne):
# 检测订阅配置里是否有该 up
if up_id in sub_list:
# 如果存在直播信息则为已开播
logger.debug(
f"[Live] {up_name}({up_id}) live_status: {live_data['live_status']}"
)
logger.debug(f"[Live] {up_name}({up_id}) live_status: {live_data['live_status']}")
if live_data["live_status"] == 1:
# 判断是否在正在直播列表中
if up_id in BOT_Status.living:
Expand Down Expand Up @@ -104,18 +100,11 @@ async def main(app: Ariadne):

# 发送推送消息
for data in get_sub_by_uid(up_id):
if ( # 判断是否处于 DEBUG 模式
BotConfig.Debug.enable
and int(data.group) not in BotConfig.Debug.groups
):
if BotConfig.Debug.enable and int(data.group) not in BotConfig.Debug.groups: # 判断是否处于 DEBUG 模式
continue
if data.live: # 判断该群是否开启直播推送
group = await app.get_group(int(data.group))
nick = (
f"*{up_nick} "
if (up_nick := data.nick)
else f"UP {up_name}{up_id})"
)
nick = f"*{up_nick} " if (up_nick := data.nick) else f"UP {up_name}{up_id})"
msg = [
f"{nick}{room_area} 区开播啦 !\n标题:{title}\n",
cover_img or "",
Expand All @@ -139,17 +128,13 @@ async def main(app: Ariadne):
)
except UnknownTarget:
delete = await delete_group(data.group)
logger.info(
f"[BiliBili推送] 推送失败,找不到该群 {data.group},已删除该群订阅的 {len(delete)} 个 UP"
)
logger.info(f"[BiliBili推送] 推送失败,找不到该群 {data.group},已删除该群订阅的 {len(delete)} 个 UP")
except AccountMuted:
group = f"{group.name}{group.id})" if group else data.group
logger.warning(f"[BiliBili推送] 推送失败,账号在 {group} 被禁言")
await asyncio.sleep(5)

insert_live_push(
up_id, True, len(get_sub_by_uid(up_id)), title, area_parent, area
)
insert_live_push(up_id, True, len(get_sub_by_uid(up_id)), title, area_parent, area)
elif up_id in BOT_Status.living:
logger.debug(f"[Live] {up} live_data: {live_data}")
live_time = (
Expand All @@ -161,27 +146,18 @@ async def main(app: Ariadne):
set_name(up_id, up_name)
logger.info(f"[BiliBili推送] {up_name} 已下播{live_time}")
for data in get_sub_by_uid(up_id):
if (
BotConfig.Debug.enable
and int(data.group) not in BotConfig.Debug.groups
):
if BotConfig.Debug.enable and int(data.group) not in BotConfig.Debug.groups:
continue
if data.live:
try:
nick = (
f"*{up_nick} "
if (up_nick := data.nick)
else f"UP {up_name}{up_id})"
)
nick = f"*{up_nick} " if (up_nick := data.nick) else f"UP {up_name}{up_id})"
await app.send_group_message(
int(data.group),
MessageChain(f"{nick}已下播{live_time}"),
)
except UnknownTarget:
delete = await delete_group(data.group)
logger.info(
f"[BiliBili推送] 推送失败,找不到该群 {data.group},已删除该群订阅的 {len(delete)} 个 UP"
)
logger.info(f"[BiliBili推送] 推送失败,找不到该群 {data.group},已删除该群订阅的 {len(delete)} 个 UP")
except AccountMuted:
group = await app.get_group(int(data.group))
group = f"{group.name}{group.id})" if group else data.group
Expand All @@ -191,9 +167,7 @@ async def main(app: Ariadne):
logger.error("[BiliBili推送] 推送失败,Bot 被限制发送群聊消息")
await app.send_friend_message(
BotConfig.master,
MessageChain(
"Bot 被限制发送群聊消息(46 代码),请尽快处理后发送 /init 重新开启推送进程"
),
MessageChain("Bot 被限制发送群聊消息(46 代码),请尽快处理后发送 /init 重新开启推送进程"),
)
BOT_Status.set_status(Status.LIVE_IDLE, True)
BOT_Status.set_status(Status.INITIALIZED, True)
Expand Down
2 changes: 1 addition & 1 deletion aunly_bbot/function/scheduler/refresh_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async def main(app: Ariadne):
if BotConfig.Bilibili.username and BotConfig.Bilibili.password and Bili_Auth.tokens:
BOT_Status.set_status(Status.INITIALIZED, False)

while BOT_Status.check_status(Status.LIVE_IDLE) or BOT_Status.check_status(
while not BOT_Status.check_status(Status.LIVE_IDLE) or not BOT_Status.check_status(
Status.DYNAMIC_IDLE
):
await asyncio.sleep(0.1)
Expand Down
22 changes: 17 additions & 5 deletions aunly_bbot/model/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ def can_use_login(cls, enable, values):
if values["groups"]:
return enable
raise KeyError
except KeyError as key_err:
raise ValueError("已启用 Debug 但未填入合法的群号") from key_err
except KeyError:
click.secho("已启用 Debug 但未填入合法的群号", fg="bright_red")
sys.exit()


class _Bilibili(BaseModel, extra=Extra.ignore):
Expand Down Expand Up @@ -80,8 +81,9 @@ def can_use_login(cls, use_login, values):
try:
if isinstance(values["username"], int) and isinstance(values["password"], str):
return use_login
except KeyError as key_err:
raise ValueError("已启用登录但未填入合法的用户名与密码") from key_err
except KeyError:
click.secho("已启用登录但未填入合法的用户名与密码", fg="bright_red")
sys.exit()

# 验证是否可以使用浏览器
@validator("use_browser")
Expand All @@ -105,18 +107,28 @@ def can_use_wordcloud(cls, use_wordcloud):
click.secho("已检测到开启词云", fg="bright_yellow")
try:
import wordcloud # noqa # type: ignore
import jieba # noqa # type: ignore

return use_wordcloud
except ImportError:
click.secho("未安装 wordcloud,如需使用词云,请安装 wordcloud", fg="bright_red")
sys.exit()

# 验证是否可以启用 openai
@validator("openai_api_token", always=True)
def valid_openai_api(cls, openai_api_token: str, values: dict):
if values.get("openai_summarization"):
if not openai_api_token or not openai_api_token.startswith("sk-"):
click.secho("openai_api_token 未填写的情况下无法开启 AI 视频总结", fg="bright_red")
sys.exit()
return openai_api_token

# 验证 openai promt version
@validator("openai_promot_version")
def valid_openai_promot_version(cls, openai_promot_version):
if openai_promot_version in [1, 2]:
return openai_promot_version
click.secho("openai_promot_version 只能为 1 或 2", fg="bright_yellow")
click.secho("openai_promot_version 只能为 1 或 2", fg="bright_red")
sys.exit()

# 验证 Bilibili gRPC 并发数
Expand Down
2 changes: 2 additions & 0 deletions aunly_bbot/utils/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ async def openai_req(
temperature: Optional[float] = None,
) -> OpenAI:
if not token:
logger.warning("未配置 OpenAI API Token,无法总结")
return OpenAI(error=True, message="未配置 OpenAI API Token")
async with httpx.AsyncClient(
proxies=BotConfig.Bilibili.openai_proxy,
Expand All @@ -139,6 +140,7 @@ async def openai_req(
"https://api.openai.com/v1/chat/completions", json=data
)
except Exception as e:
logger.exception(e)
return OpenAI(error=True, message=f"OpenAI 请求失败 {type(e)} {e}")
if req.status_code != 200:
return OpenAI(error=True, message=req.text, raw=req.json())
Expand Down
2 changes: 1 addition & 1 deletion release.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
with res.path(playwright, "driver") as playwright_package_path:
path = list(
playwright_package_path.joinpath("package", ".local-browsers").glob(
"chromium-*/chromium*"
"chromium-*/chrome*"
)
)[0]
chrome_relative_path = path.relative_to(pathlib.Path(playwright_package_path).parent)
Expand Down

0 comments on commit 71f6ce5

Please sign in to comment.