Skip to content

Commit

Permalink
Merge pull request #400 from SK-415/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
djkcyl authored Jun 29, 2023
2 parents 1fce7b7 + 3b33663 commit be68521
Show file tree
Hide file tree
Showing 13 changed files with 451 additions and 212 deletions.
34 changes: 33 additions & 1 deletion docs/usage/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,36 @@ HARUKA_LIVE_INTERVAL=20
HARUKA_DYNAMIC_AT=True
```

## HARUKA_SCREENSHOT_STYLE
<!-- ## HARUKA_SCREENSHOT_STYLE
默认值:mobile
截图样式,可选值:mobile(手机)、pc(电脑)。
```yml
HARUKA_SCREENSHOT_STYLE=pc
``` -->

## HARUKA_CAPTCHA_ADDRESS

默认值:<https://captcha-cd.ngworks.cn>

验证码地址,用于解决动态截图验证码问题。
(如果你不知道这是什么,请忽略)

```yml
HARUKA_CAPTCHA_ADDRESS=https://captcha-cd.ngworks.cn
```

## HARUKA_BROWSER_UA

默认值:""

自定义浏览器 UA
(如果你不知道这是什么,请忽略)

```yml
HARUKA_BROWSER_UA="Mozilla/5.0 (Linux; Android 10; Redmi K30 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.210 Mobile Safari/537.36"
```

## HARUKA_DYNAMIC_TIMEOUT
Expand All @@ -138,6 +160,16 @@ HARUKA_DYNAMIC_TIMEOUT=30
HARUKA_DYNAMIC_FONT="Microsoft YaHei"
```

## HARUKA_DYNAMIC_BIG_IMAGE

默认值:False

是否使用大图模式,大图模式下会将动态图片扩展至页宽。

```json
HARUKA_DYNAMIC_BIG_IMAGE=True
```

## HARUKA_COMMAND_PREFIX

默认值:""
Expand Down
13 changes: 10 additions & 3 deletions haruka_bot/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import List, Optional

from loguru import logger
from nonebot import get_driver
from pydantic import BaseSettings, validator
from pydantic.fields import ModelField
Expand All @@ -18,19 +19,25 @@ class Config(BaseSettings):
haruka_dynamic_at: bool = False
haruka_screenshot_style: str = "mobile"
haruka_captcha_address: str = "https://captcha-cd.ngworks.cn"
haruka_browser_ua: Optional[str] = None
haruka_dynamic_timeout: int = 30
haruka_dynamic_font_source: str = "system"
haruka_dynamic_font: Optional[str] = "Noto Sans CJK SC"
haruka_dynamic_big_image: bool = False
haruka_command_prefix: str = ""
# 频道管理员身份组
haruka_guild_admin_roles: List[str] = ["频道主", "超级管理员"]

@validator("haruka_interval", "haruka_live_interval", "haruka_dynamic_interval")
def non_negative(cls, v: int, field: ModelField):
"""定时器为负返回默认值"""
if v < 1:
return field.default
return v
return field.default if v < 1 else v

@validator("haruka_screenshot_style")
def screenshot_style(cls, v: str):
if v != "mobile":
logger.warning("截图样式目前只支持 mobile,pc 样式现已被弃用")
return "mobile"

class Config:
extra = "ignore"
Expand Down
2 changes: 1 addition & 1 deletion haruka_bot/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from . import help # noqa: F401
from .at import at_off, at_on # noqa: F401
from .dynamic import dynamic_off, dynamic_on # noqa: F401
from .live import live_off, live_on # noqa: F401
from .permission import permission_off, permission_on # noqa: F401
from .pusher import dynamic_pusher, live_pusher # noqa: F401
from .live import live_off, live_on, live_now # noqa: F401
from .sub import add_sub, delete_sub, sub_list # noqa: F401
23 changes: 23 additions & 0 deletions haruka_bot/plugins/live/live_now.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from nonebot.adapters.onebot.v11.event import MessageEvent

from ...database import DB as db
from ...utils import get_type_id, on_command, permission_check, to_me

from ..pusher.live_pusher import status

live_now = on_command("已开播", rule=to_me(), priority=5)
live_now.__doc__ = """已开播"""

live_now.handle()(permission_check)


@live_now.handle()
async def _(event: MessageEvent):
"""返回已开播的直播间"""
subs = await db.get_sub_list(event.message_type, await get_type_id(event))
if now_live := [sub for sub in subs if status.get(str(sub.uid)) == 1]:
await live_now.finish(
f"共有{len(now_live)}个主播正在直播:\n\n"
+ "\n".join([f"{await db.get_name(sub.uid)}{sub.uid})" for sub in now_live])
)
await live_now.finish("当前没有正在直播的主播")
23 changes: 13 additions & 10 deletions haruka_bot/plugins/pusher/dynamic_pusher.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async def dy_sched():
).list
except AioRpcError as e:
if e.code() == StatusCode.DEADLINE_EXCEEDED:
logger.error("爬取动态超时,将在下个轮询中重试")
logger.error(f"爬取动态超时,将在下个轮询中重试{e.code()} {e.details()}")
return
raise

Expand All @@ -70,13 +70,19 @@ async def dy_sched():
dynamic_id = int(dynamic.extend.dyn_id_str)
if dynamic_id > offset[uid]:
logger.info(f"检测到新动态({dynamic_id}):{name}{uid})")
image, err = await get_dynamic_screenshot(dynamic_id)
url = f"https://t.bilibili.com/{dynamic_id}"
image = await get_dynamic_screenshot(dynamic_id)
if image is None:
logger.debug(f"动态不存在,已跳过:{url}")
return
elif dynamic.card_type == DynamicType.live_rcmd:
logger.debug(f"直播推荐动态,已跳过:{url}")
elif dynamic.card_type in [
DynamicType.live_rcmd,
DynamicType.live,
DynamicType.ad,
DynamicType.banner,
]:
logger.debug(f"无需推送的动态 {dynamic.card_type},已跳过:{url}")
offset[uid] = dynamic_id
return

type_msg = {
Expand All @@ -90,8 +96,8 @@ async def dy_sched():
}
message = (
f"{name} {type_msg.get(dynamic.card_type, type_msg[0])}\n"
+ MessageSegment.image(image)
+ f"\n{url}"
f"{f'动态图片可能截图异常:{err}' if err else ''}\n"
f"{MessageSegment.image(image)}\n{url}"
)

push_list = await db.get_push_list(uid, "dynamic")
Expand Down Expand Up @@ -123,10 +129,7 @@ def dynamic_lisener(event):
if plugin_config.haruka_dynamic_interval == 0:
scheduler.add_listener(
dynamic_lisener,
EVENT_JOB_EXECUTED
| EVENT_JOB_ERROR
| EVENT_JOB_MISSED
| EVENT_SCHEDULER_STARTED,
EVENT_JOB_EXECUTED | EVENT_JOB_ERROR | EVENT_JOB_MISSED | EVENT_SCHEDULER_STARTED,
)
else:
scheduler.add_job(
Expand Down
27 changes: 18 additions & 9 deletions haruka_bot/plugins/pusher/live_pusher.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import time

from bilireq.live import get_rooms_info_by_uids
from nonebot.adapters.onebot.v11.message import MessageSegment
from nonebot.log import logger

from ...config import plugin_config
from ...database import DB as db
from ...utils import PROXIES, safe_send, scheduler
from ...utils import PROXIES, safe_send, scheduler, calc_time_total

status = {}
live_time = {}


@scheduler.scheduled_job(
Expand Down Expand Up @@ -34,22 +37,28 @@ async def live_sched():

name = info["uname"]
if new_status: # 开播
room_id = info["short_id"] if info["short_id"] else info["room_id"]
url = "https://live.bilibili.com/" + str(room_id)
live_time[uid] = info["live_time"]
room_id = info["short_id"] or info["room_id"]
url = f"https://live.bilibili.com/{room_id}"
title = info["title"]
cover = (
info["cover_from_user"] if info["cover_from_user"] else info["keyframe"]
)
cover = info["cover_from_user"] or info["keyframe"]
area_parent = info["area_v2_parent_name"]
area = info["area_v2_name"]
room_area = f"{area_parent} / {area}"
logger.info(f"检测到开播:{name}{uid})")

live_msg = (
f"{name} 正在直播:\n{title}\n" + MessageSegment.image(cover) + f"\n{url}"
f"{name} 开播啦!\n分区:{room_area}\n标题:{title}\n{MessageSegment.image(cover)}\n{url}"
)
else: # 下播
logger.info(f"检测到下播:{name}{uid})")
if not plugin_config.haruka_live_off_notify: # 没开下播推送
continue
live_msg = f"{name} 下播了"
live_time_msg = (
f",本次直播时长 {calc_time_total(time.time() - live_time[uid])}。"
if live_time[uid]
else "。"
)
live_msg = f"{name} 下播了{live_time_msg}"

# 推送
push_list = await db.get_push_list(uid, "live")
Expand Down
2 changes: 1 addition & 1 deletion haruka_bot/plugins/sub/add_sub.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async def _(event: MessageEvent, uid: str = ArgPlainText("uid")):
try:
name = (await get_user_info(uid, reqtype="web", proxies=PROXIES))["name"]
except ResponseCodeError as e:
if e.code == -400 or e.code == -404:
if e.code in [-400, -404]:
await add_sub.finish("UID不存在,注意UID不是房间号")
elif e.code == -412:
await add_sub.finish("操作过于频繁IP暂时被风控,请半小时后再尝试")
Expand Down
Loading

0 comments on commit be68521

Please sign in to comment.