Skip to content

Commit

Permalink
v2.6.20 (#448)
Browse files Browse the repository at this point in the history
* feat: 新增配置项 `telegram_admin_ids` `telegram_bot_token` 用于接收 QQ bot 离线通知

* chore(release): v2.6.20
  • Loading branch information
NekoAria authored Jul 5, 2023
1 parent 38a660c commit 09e73f2
Show file tree
Hide file tree
Showing 10 changed files with 67 additions and 22 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "ELF_RSS"
version = "2.6.19"
version = "2.6.20"
description = "QQ机器人 RSS订阅 插件,订阅源建议选择 RSSHub"
authors = ["Quan666 <[email protected]>"]
license = "GPL-3.0-only"
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/ELF_RSS2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .rss_class import Rss
from .utils import send_message_to_admin

VERSION = "2.6.19"
VERSION = "2.6.20"

__plugin_meta__ = PluginMetadata(
name="ELF_RSS",
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/ELF_RSS2/command/upload_group_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ async def handle_first_receive(
url=target[0],
group_ids=[str(event.group_id)],
name="手动上传",
proxy=get_proxy(True),
proxy=get_proxy(),
)
3 changes: 3 additions & 0 deletions src/plugins/ELF_RSS2/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ class Config:
# pikpak 离线保存的目录, 默认是根目录,示例: ELF_RSS/Downloads ,目录不存在会自动创建, 不能/结尾
pikpak_download_path: str = ""

telegram_admin_ids: List[int] = [] # Telegram 管理员 ID 列表,用于接收离线通知和管理机器人
telegram_bot_token: Optional[str] = None # Telegram 机器人的 token


config = ELFConfig(**get_driver().config.dict())
logger.debug(f"RSS Config loaded: {config!r}")
7 changes: 4 additions & 3 deletions src/plugins/ELF_RSS2/parsing/download_torrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from typing import Any, Dict, List, Optional

import aiohttp
from nonebot import get_bot
from nonebot.adapters.onebot.v11 import Bot
from nonebot.log import logger

Expand All @@ -11,7 +10,7 @@
from ..pikpak_offline import pikpak_offline_download
from ..qbittorrent_download import start_down
from ..rss_class import Rss
from ..utils import convert_size, get_torrent_b16_hash, send_msg
from ..utils import convert_size, get_bot, get_torrent_b16_hash, send_msg


async def down_torrent(
Expand All @@ -20,7 +19,9 @@ async def down_torrent(
"""
创建下载种子任务
"""
bot: Bot = get_bot() # type: ignore
bot: Bot = await get_bot() # type: ignore
if bot is None:
raise ValueError("There are not bots to get.")
hash_list = []
for tmp in item["links"]:
if (
Expand Down
7 changes: 3 additions & 4 deletions src/plugins/ELF_RSS2/parsing/send_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
from typing import Any, Callable, Coroutine, DefaultDict, Dict, List, Tuple, Union

import arrow
from nonebot import get_bot
from nonebot.adapters.onebot.v11 import Bot, Message, MessageSegment
from nonebot.adapters.onebot.v11.exception import NetworkError
from nonebot.log import logger

from ..config import config
from ..rss_class import Rss
from ..utils import get_bot
from .cache_manage import insert_into_cache_db, write_item

sending_lock: DefaultDict[Tuple[Union[int, str], str], asyncio.Lock] = defaultdict(
Expand All @@ -22,9 +22,8 @@
async def send_msg(
rss: Rss, messages: List[str], items: List[Dict[str, Any]], header_message: str
) -> bool:
try:
bot: Bot = get_bot() # type: ignore
except ValueError:
bot: Bot = await get_bot() # type: ignore
if bot is None:
return False
if not messages:
return False
Expand Down
2 changes: 1 addition & 1 deletion src/plugins/ELF_RSS2/parsing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


# 代理
def get_proxy(open_proxy: bool) -> Optional[str]:
def get_proxy(open_proxy: bool = True) -> Optional[str]:
if not open_proxy or not config.rss_proxy:
return None
return f"http://{config.rss_proxy}"
Expand Down
12 changes: 6 additions & 6 deletions src/plugins/ELF_RSS2/qbittorrent_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
import aiohttp
import arrow
from apscheduler.triggers.interval import IntervalTrigger
from nonebot import get_bot
from nonebot.adapters.onebot.v11 import ActionFailed, Bot, NetworkError
from nonebot.log import logger
from qbittorrent import Client

from .config import config
from .utils import (
convert_size,
get_bot,
get_bot_group_list,
get_torrent_b16_hash,
scheduler,
Expand Down Expand Up @@ -68,23 +68,21 @@ async def get_qb_client() -> Optional[Client]:
else:
qb.login()
except Exception:
bot: Bot = get_bot() # type: ignore
msg = (
"❌ 无法连接到 qbittorrent ,请检查:\n"
"1. 是否启动程序\n"
"2. 是否勾选了“Web用户界面(远程控制)”\n"
"3. 连接地址、端口是否正确"
)
logger.exception(msg)
await send_message_to_admin(msg, bot)
await send_message_to_admin(msg)
return None
try:
qb.get_default_save_path()
except Exception:
bot: Bot = get_bot() # type: ignore
msg = "❌ 无法连登录到 qbittorrent ,请检查相关配置是否正确"
logger.exception(msg)
await send_message_to_admin(msg, bot)
await send_message_to_admin(msg)
return None
return qb

Expand Down Expand Up @@ -253,5 +251,7 @@ async def rss_trigger(bot: Bot, hash_str: str, group_ids: List[str], name: str)
misfire_grace_time=60, # 允许的误差时间,建议不要省略
job_defaults=job_defaults,
)
bot: Bot = get_bot() # type: ignore
bot: Bot = await get_bot() # type: ignore
if bot is None:
return
await send_msg(bot, f"👏 {name}\nHash:{hash_str}\n下载任务添加成功!", group_ids)
6 changes: 4 additions & 2 deletions src/plugins/ELF_RSS2/rss_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import aiohttp
import feedparser
from nonebot import get_bot
from nonebot.adapters.onebot.v11 import Bot
from nonebot.log import logger
from tinydb import TinyDB
Expand All @@ -19,6 +18,7 @@
filter_valid_group_id_list,
filter_valid_guild_channel_id_list,
filter_valid_user_id_list,
get_bot,
get_http_caching_headers,
send_message_to_admin,
)
Expand Down Expand Up @@ -69,7 +69,9 @@ async def save_first_time_fetch(rss: Rss, new_rss: Dict[str, Any]) -> None:

# 抓取 feed,读取缓存,检查更新,对更新进行处理
async def start(rss: Rss) -> None:
bot: Bot = get_bot() # type: ignore
bot: Bot = await get_bot() # type: ignore
if bot is None:
return

# 先检查订阅者是否合法
rss = await filter_and_validate_rss(rss, bot)
Expand Down
46 changes: 43 additions & 3 deletions src/plugins/ELF_RSS2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
from contextlib import suppress
from typing import Any, Dict, Generator, List, Mapping, Optional

from aiohttp import ClientSession
from cachetools import TTLCache
from cachetools.keys import hashkey
from nonebot import get_bot, require
from nonebot import get_bot as _get_bot
from nonebot import require
from nonebot.adapters.onebot.v11 import Bot
from nonebot.log import logger

Expand All @@ -19,6 +21,9 @@
from nonebot_plugin_guild_patch.permission import GUILD_ADMIN, GUILD_OWNER # noqa

from .config import config
from .parsing.utils import get_proxy

bot_offline = False


def get_http_caching_headers(
Expand Down Expand Up @@ -113,7 +118,11 @@ def get_torrent_b16_hash(content: bytes) -> str:
return str(b16_hash, "utf-8")


async def send_message_to_admin(message: str, bot: Bot) -> None:
async def send_message_to_admin(message: str, bot: Optional[Bot] = None) -> None:
if bot is None:
bot: Bot = await get_bot() # type: ignore
if bot is None:
return
await bot.send_private_msg(user_id=int(list(config.superusers)[0]), message=message)


Expand All @@ -129,7 +138,9 @@ async def send_msg(
发送消息到私聊或群聊
"""
bot: Bot = get_bot() # type: ignore
bot: Bot = await get_bot() # type: ignore
if bot is None:
raise ValueError("There are not bots to get.")
msg_id = []
if group_ids:
for group_id in group_ids:
Expand Down Expand Up @@ -208,3 +219,32 @@ def partition_list(
) -> Generator[List[Any], None, None]:
for i in range(0, len(input_list), partition_size):
yield input_list[i : i + partition_size]


async def send_message_to_telegram_admin(message: str) -> None:
try:
async with ClientSession(raise_for_status=True) as session:
await session.post(
f"https://api.telegram.org/bot{config.telegram_bot_token}/sendMessage",
json={
"chat_id": config.telegram_admin_ids[0],
"text": message,
},
proxy=get_proxy(),
)
except Exception as e:
logger.error(f"发送到 Telegram 失败:\n {e}")


async def get_bot() -> Optional[Bot]:
global bot_offline
bot: Optional[Bot] = None
try:
bot = _get_bot() # type: ignore
bot_offline = False
except ValueError:
if not bot_offline and config.telegram_admin_id and config.telegram_bot_token:
await send_message_to_telegram_admin("QQ Bot 已离线!")
logger.warning("Bot 已离线!")
bot_offline = True
return bot

0 comments on commit 09e73f2

Please sign in to comment.