Skip to content

Commit

Permalink
Merge pull request #351 from SunshineboyZj/patch-1
Browse files Browse the repository at this point in the history
Update settings.md
  • Loading branch information
SK-415 authored Apr 22, 2023
2 parents 48565c3 + 8bbf87c commit 015d1d1
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 42 deletions.
2 changes: 1 addition & 1 deletion docs/usage/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ HARUKA_DIR="./data/"
在群里使用命令前是否需要 @机器人。设置为 `False` 则可以直接触发指令。

```json
Haruka_TO_ME=False
HARUKA_TO_ME=False
```

## HARUKA_LIVE_OFF_NOTIFY
Expand Down
5 changes: 0 additions & 5 deletions haruka_bot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
from nonebot import get_driver
from nonebot.plugin.manager import PluginLoader

from .config import Config

if isinstance(globals()["__loader__"], PluginLoader):
global_config = get_driver().config
config = Config.parse_obj(global_config)
from .utils import on_startup

on_startup()
Expand Down
7 changes: 6 additions & 1 deletion haruka_bot/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import List, Optional

from nonebot import get_driver
from pydantic import BaseSettings, validator
from pydantic.fields import ModelField

Expand All @@ -16,7 +17,7 @@ class Config(BaseSettings):
haruka_dynamic_interval: int = 0
haruka_dynamic_at: bool = False
haruka_screenshot_style: str = "mobile"
haruka_dynamic_timeout: int = 10
haruka_dynamic_timeout: int = 30
haruka_dynamic_font_source: str = "system"
haruka_dynamic_font: Optional[str] = "Noto Sans CJK SC"
haruka_command_prefix: str = ""
Expand All @@ -32,3 +33,7 @@ def non_negative(cls, v: int, field: ModelField):

class Config:
extra = "ignore"


global_config = get_driver().config
plugin_config = Config.parse_obj(global_config)
6 changes: 5 additions & 1 deletion haruka_bot/database/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ async def init(cls):
await cls.migrate()
await cls.update_uid_list()

@classmethod
async def close(cls):
await connections.close_all()

@classmethod
async def get_user(cls, **kwargs):
"""获取 UP 主信息"""
Expand Down Expand Up @@ -314,4 +318,4 @@ async def update_login(cls, tokens):


get_driver().on_startup(DB.init)
get_driver().on_shutdown(connections.close_all)
get_driver().on_shutdown(DB.close)
4 changes: 2 additions & 2 deletions haruka_bot/plugins/at/at_off.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from nonebot.permission import SUPERUSER
from nonebot_plugin_guild_patch import GuildMessageEvent

from ... import config
from ...config import plugin_config
from ...database import DB as db
from ...utils import (
GUILD_ADMIN,
Expand Down Expand Up @@ -43,6 +43,6 @@ async def _(
assert user is not None
await at_off.finish(
f"已关闭 {user.name}{user.uid})"
f"{'直播推送' if not config.haruka_dynamic_at else ''}的@全体"
f"{'直播推送' if not plugin_config.haruka_dynamic_at else ''}的@全体"
)
await at_off.finish(f"UID({uid})未关注,请先关注后再操作")
4 changes: 2 additions & 2 deletions haruka_bot/plugins/at/at_on.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from nonebot.permission import SUPERUSER
from nonebot_plugin_guild_patch import GuildMessageEvent

from ... import config
from ...config import plugin_config
from ...database import DB as db
from ...utils import (
GUILD_ADMIN,
Expand Down Expand Up @@ -43,6 +43,6 @@ async def _(
assert user is not None
await at_on.finish(
f"已开启 {user.name}{user.uid})"
f"{'直播推送' if not config.haruka_dynamic_at else ''}的@全体"
f"{'直播推送' if not plugin_config.haruka_dynamic_at else ''}的@全体"
)
await at_on.finish(f"UID({uid})未关注,请先关注后再操作")
15 changes: 10 additions & 5 deletions haruka_bot/plugins/pusher/dynamic_pusher.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from nonebot.adapters.onebot.v11.message import MessageSegment
from nonebot.log import logger

from ... import config
from ...config import plugin_config
from ...database import DB as db
from ...database import dynamic_offset as offset
from ...utils import get_dynamic_screenshot, safe_send, scheduler
Expand All @@ -36,7 +36,9 @@ async def dy_sched():
# 获取 UP 最新动态列表
dynamics = (
await grpc_get_user_dynamics(
uid, timeout=config.haruka_dynamic_timeout, proxy=config.haruka_proxy
uid,
timeout=plugin_config.haruka_dynamic_timeout,
proxy=plugin_config.haruka_proxy,
)
).list
except AioRpcError as e:
Expand Down Expand Up @@ -96,7 +98,7 @@ async def dy_sched():
send_type=sets.type,
type_id=sets.type_id,
message=message,
at=bool(sets.at) and config.haruka_dynamic_at,
at=bool(sets.at) and plugin_config.haruka_dynamic_at,
)

offset[uid] = dynamic_id
Expand All @@ -115,7 +117,7 @@ def dynamic_lisener(event):
)


if config.haruka_dynamic_interval == 0:
if plugin_config.haruka_dynamic_interval == 0:
scheduler.add_listener(
dynamic_lisener,
EVENT_JOB_EXECUTED
Expand All @@ -125,5 +127,8 @@ def dynamic_lisener(event):
)
else:
scheduler.add_job(
dy_sched, "interval", seconds=config.haruka_dynamic_interval, id="dynamic_sched"
dy_sched,
"interval",
seconds=plugin_config.haruka_dynamic_interval,
id="dynamic_sched",
)
6 changes: 3 additions & 3 deletions haruka_bot/plugins/pusher/live_pusher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
from nonebot.adapters.onebot.v11.message import MessageSegment
from nonebot.log import logger

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

status = {}


@scheduler.scheduled_job(
"interval", seconds=config.haruka_live_interval, id="live_sched"
"interval", seconds=plugin_config.haruka_live_interval, id="live_sched"
)
async def live_sched():
"""直播推送"""
Expand Down Expand Up @@ -47,7 +47,7 @@ async def live_sched():
)
else: # 下播
logger.info(f"检测到下播:{name}{uid})")
if not config.haruka_live_off_notify: # 没开下播推送
if not plugin_config.haruka_live_off_notify: # 没开下播推送
continue
live_msg = f"{name} 下播了"

Expand Down
20 changes: 10 additions & 10 deletions haruka_bot/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@
from nonebot.rule import Rule
from nonebot_plugin_guild_patch import ChannelDestroyedNoticeEvent, GuildMessageEvent

from .. import config
from ..config import plugin_config


def get_path(*other):
"""获取数据文件绝对路径"""
if config.haruka_dir:
dir_path = Path(config.haruka_dir).resolve()
if plugin_config.haruka_dir:
dir_path = Path(plugin_config.haruka_dir).resolve()
else:
dir_path = Path.cwd().joinpath("data")
# dir_path = Path.cwd().joinpath('data', 'haruka_bot')
Expand Down Expand Up @@ -66,7 +66,7 @@ async def _guild_admin(bot: Bot, event: GuildMessageEvent):
)
)["roles"]
)
return bool(roles & set(config.haruka_guild_admin_roles))
return bool(roles & set(plugin_config.haruka_guild_admin_roles))


GUILD_ADMIN: Permission = Permission(_guild_admin)
Expand Down Expand Up @@ -102,7 +102,7 @@ async def group_only(


def to_me():
if config.haruka_to_me:
if plugin_config.haruka_to_me:
from nonebot.rule import to_me

return to_me()
Expand Down Expand Up @@ -200,12 +200,12 @@ async def get_type_id(event: Union[MessageEvent, ChannelDestroyedNoticeEvent]):

def check_proxy():
"""检查代理是否有效"""
if config.haruka_proxy:
if plugin_config.haruka_proxy:
logger.info("检查代理是否有效")
try:
httpx.get(
"https://icanhazip.com/",
proxies={"all://": config.haruka_proxy},
proxies={"all://": plugin_config.haruka_proxy},
timeout=2,
)
except Exception:
Expand All @@ -214,7 +214,7 @@ def check_proxy():

def on_startup():
"""安装依赖并检查当前环境是否满足运行条件"""
if config.fastapi_reload and sys.platform == "win32":
if plugin_config.fastapi_reload and sys.platform == "win32":
raise ImportError("加载失败,Windows 必须设置 FASTAPI_RELOAD=false 才能正常运行 HarukaBot")
try: # 如果开启 realod 只在第一次运行
asyncio.get_running_loop()
Expand All @@ -230,10 +230,10 @@ def on_startup():


def on_command(cmd, *args, **kwargs):
return _on_command(config.haruka_command_prefix + cmd, *args, **kwargs)
return _on_command(plugin_config.haruka_command_prefix + cmd, *args, **kwargs)


PROXIES = {"all://": config.haruka_proxy}
PROXIES = {"all://": plugin_config.haruka_proxy}

require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler # noqa
Expand Down
28 changes: 16 additions & 12 deletions haruka_bot/utils/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
from playwright.__main__ import main
from playwright.async_api import Browser, async_playwright

from .. import config
from ..config import plugin_config
from .fonts_provider import fill_font

_browser: Optional[Browser] = None
mobile_js = Path(__file__).parent.joinpath("mobile.js")


async def init_browser(proxy=config.haruka_proxy, **kwargs) -> Browser:
async def init_browser(proxy=plugin_config.haruka_proxy, **kwargs) -> Browser:
if proxy:
kwargs["proxy"] = {"server": proxy}
global _browser
Expand All @@ -32,7 +32,9 @@ async def get_browser() -> Browser:
return _browser


async def get_dynamic_screenshot(dynamic_id, style=config.haruka_screenshot_style):
async def get_dynamic_screenshot(
dynamic_id, style=plugin_config.haruka_screenshot_style
):
"""获取动态截图"""
if style.lower() == "mobile":
return await get_dynamic_screenshot_mobile(dynamic_id)
Expand All @@ -57,7 +59,7 @@ async def get_dynamic_screenshot_mobile(dynamic_id):
await page.goto(
url,
wait_until="networkidle",
timeout=config.haruka_dynamic_timeout * 1000,
timeout=plugin_config.haruka_dynamic_timeout * 1000,
)
# 动态被删除或者进审核了
if page.url == "https://m.bilibili.com/404":
Expand All @@ -76,9 +78,9 @@ async def get_dynamic_screenshot_mobile(dynamic_id):
await page.add_script_tag(path=mobile_js)

await page.evaluate(
f'setFont("{config.haruka_dynamic_font}", '
f'"{config.haruka_dynamic_font_source}")'
if config.haruka_dynamic_font
f'setFont("{plugin_config.haruka_dynamic_font}", '
f'"{plugin_config.haruka_dynamic_font_source}")'
if plugin_config.haruka_dynamic_font
else "setFont()"
)
await page.wait_for_function("getMobileStyle()")
Expand All @@ -87,7 +89,7 @@ async def get_dynamic_screenshot_mobile(dynamic_id):
await page.wait_for_load_state("domcontentloaded")

await page.wait_for_timeout(
200 if config.haruka_dynamic_font_source == "remote" else 50
200 if plugin_config.haruka_dynamic_font_source == "remote" else 50
)

# 判断字体是否加载完成
Expand Down Expand Up @@ -129,7 +131,9 @@ async def get_dynamic_screenshot_pc(dynamic_id):
page = await context.new_page()
try:
await page.goto(
url, wait_until="networkidle", timeout=config.haruka_dynamic_timeout * 1000
url,
wait_until="networkidle",
timeout=plugin_config.haruka_dynamic_timeout * 1000,
)
# 动态被删除或者进审核了
if page.url == "https://www.bilibili.com/404":
Expand All @@ -156,16 +160,16 @@ def install():

def restore_env():
del os.environ["PLAYWRIGHT_DOWNLOAD_HOST"]
if config.haruka_proxy:
if plugin_config.haruka_proxy:
del os.environ["HTTPS_PROXY"]
if original_proxy is not None:
os.environ["HTTPS_PROXY"] = original_proxy

logger.info("检查 Chromium 更新")
sys.argv = ["", "install", "chromium"]
original_proxy = os.environ.get("HTTPS_PROXY")
if config.haruka_proxy:
os.environ["HTTPS_PROXY"] = config.haruka_proxy
if plugin_config.haruka_proxy:
os.environ["HTTPS_PROXY"] = plugin_config.haruka_proxy
os.environ["PLAYWRIGHT_DOWNLOAD_HOST"] = "https://npmmirror.com/mirrors/playwright/"
success = False
try:
Expand Down

0 comments on commit 015d1d1

Please sign in to comment.