great change

This commit is contained in:
felinae98 2021-04-26 22:35:05 +08:00
parent 63fa370823
commit 81e402c783
No known key found for this signature in database
GPG Key ID: 00C8B010587FF610
9 changed files with 84 additions and 34 deletions

View File

@ -7,12 +7,16 @@ from nonebot.rule import to_me
from nonebot.typing import T_State from nonebot.typing import T_State
from .config import Config, NoSuchSubscribeException from .config import Config, NoSuchSubscribeException
from .platform import platform_manager from .platform import platform_manager, check_sub_target
from .platform.utils import check_sub_target
from .send import send_msgs from .send import send_msgs
from .utils import parse_text from .utils import parse_text
from .types import Target from .types import Target
common_platform = [p.platform_name for p in \
filter(lambda platform: platform.enabled and platform.is_common,
platform_manager.values())
]
help_match = on_command('help', rule=to_me(), priority=5) help_match = on_command('help', rule=to_me(), priority=5)
@help_match.handle() @help_match.handle()
async def send_help(bot: Bot, event: Event, state: T_State): async def send_help(bot: Bot, event: Event, state: T_State):
@ -20,7 +24,32 @@ async def send_help(bot: Bot, event: Event, state: T_State):
await help_match.finish(Message(await parse_text(message))) await help_match.finish(Message(await parse_text(message)))
add_sub = on_command("添加订阅", rule=to_me(), permission=GROUP_ADMIN | GROUP_OWNER | SUPERUSER, priority=5) add_sub = on_command("添加订阅", rule=to_me(), permission=GROUP_ADMIN | GROUP_OWNER | SUPERUSER, priority=5)
@add_sub.got('platform', '请输入想要订阅的平台,目前支持:{}'.format(', '.join(platform_manager.keys()))) @add_sub.handle()
async def add_sub_handle_platform(bot: Bot, event: Event, state: T_State):
if 'platform' in state:
return
await bot.send(event=event, message='请输入想要订阅的平台,目前支持:\n' +
''.join(['{}{}\n'.format(platform_name, platform_manager[platform_name].name) \
for platform_name in common_platform]) +
'要查看全部平台请输入:“全部”'
)
await add_sub.pause()
@add_sub.handle()
async def add_sub_parse_platform(bot: Bot, event: Event, state: T_State):
if 'platform' in state:
return
platform = str(event.get_message()).strip()
if platform == '全部':
message = '全部平台' + \
'\n'.join(['{}{}'.format(platform_name, platform.name) \
for platform_name, platform in platform_manager.items()])
await add_sub.reject(message)
elif platform in platform_manager:
state['platform'] = platform
else:
await add_sub.reject('平台输入错误')
# @add_sub.got('platform', '请输入想要订阅的平台,目前支持:{}'.format(', '.join(platform_manager.keys())))
# @add_sub.got('id', '请输入订阅用户的id详情查阅https://github.com/felinae98/nonebot-hk-reporter') # @add_sub.got('id', '请输入订阅用户的id详情查阅https://github.com/felinae98/nonebot-hk-reporter')
@add_sub.handle() @add_sub.handle()
async def add_sub_handle_id(bot: Bot, event: Event, state: T_State): async def add_sub_handle_id(bot: Bot, event: Event, state: T_State):

View File

@ -2,6 +2,7 @@ from .bilibili import Bilibili
from .rss import Rss from .rss import Rss
from .weibo import Weibo from .weibo import Weibo
from .wechat import Wechat from .wechat import Wechat
from .utils import check_sub_target from .utils import check_sub_target, fetch_and_send
from .platform import PlatformNoTarget from .platform import PlatformNoTarget
from .utils import platform_manager from .utils import platform_manager

View File

@ -19,6 +19,10 @@ class Bilibili(Platform):
} }
platform_name = 'bilibili' platform_name = 'bilibili'
enable_tag = False enable_tag = False
enabled = True
is_common = True
schedule_interval = 10
name = 'B站'
@staticmethod @staticmethod
async def get_account_name(target: Target) -> Optional[str]: async def get_account_name(target: Target) -> Optional[str]:

View File

@ -9,21 +9,43 @@ from ..config import Config
from ..plugin_config import plugin_config from ..plugin_config import plugin_config
from ..post import Post from ..post import Post
from ..types import Category, RawPost, Tag, Target, User from ..types import Category, RawPost, Tag, Target, User
from ..utils import Singleton
class CategoryNotSupport(Exception): class CategoryNotSupport(Exception):
"raise in get_category, when post category is not supported" "raise in get_category, when post category is not supported"
pass
class PlatformProto(metaclass=Singleton):
class RegistryMeta(type):
def __new__(cls, name, bases, namespace, **kwargs):
if name not in ['PlatformProto', 'Platform', 'PlatformNoTarget'] and \
'platform_name' not in namespace:
raise TypeError('Platform has no `platform_name`')
return super().__new__(cls, name, bases, namespace, **kwargs)
def __init__(cls, name, bases, namespace, **kwargs):
if not hasattr(cls, 'registory'):
# this is the base class
cls.registory = []
elif name not in ['Platform', 'PlatformNoTarget']:
# this is the subclass
cls.registory.append(cls)
super().__init__(name, bases, namespace, **kwargs)
class PlatformProto(metaclass=RegistryMeta):
categories: dict[Category, str] categories: dict[Category, str]
reverse_category: dict[str, Category] reverse_category: dict[str, Category]
has_target: bool has_target: bool
platform_name: str platform_name: str
name: str
enable_tag: bool enable_tag: bool
cache: dict[Any, Post] cache: dict[Any, Post]
enabled: bool
is_common: bool
schedule_interval: int
async def fetch_new_post(self, target: Target, users: list[User]) -> list[tuple[User, list[Post]]]: async def fetch_new_post(self, target: Target, users: list[User]) -> list[tuple[User, list[Post]]]:
... ...

View File

@ -14,6 +14,10 @@ class Rss(Platform):
categories = {} categories = {}
enable_tag = False enable_tag = False
platform_name = 'rss' platform_name = 'rss'
name = "Rss"
enabled = True
is_common = True
schedule_interval = 30
@staticmethod @staticmethod
async def get_account_name(target: Target) -> Optional[str]: async def get_account_name(target: Target) -> Optional[str]:

View File

@ -2,10 +2,6 @@ import nonebot
from nonebot import logger from nonebot import logger
from collections import defaultdict from collections import defaultdict
from typing import Type from typing import Type
from .weibo import Weibo
from .bilibili import Bilibili
from .rss import Rss
from .wechat import Wechat
from .platform import PlatformProto from .platform import PlatformProto
from ..config import Config from ..config import Config
from ..post import Post from ..post import Post
@ -15,10 +11,8 @@ async def check_sub_target(target_type, target):
return await platform_manager[target_type].get_account_name(target) return await platform_manager[target_type].get_account_name(target)
platform_manager: dict[str, PlatformProto] = { platform_manager: dict[str, PlatformProto] = {
'bilibili': Bilibili(), obj.platform_name: obj() for obj in \
'weibo': Weibo(), filter(lambda platform: platform.enabled, PlatformProto.registory)
'rss': Rss(),
# 'wechat': Wechat(),
} }
async def fetch_and_send(target_type: str): async def fetch_and_send(target_type: str):

View File

@ -17,6 +17,9 @@ class Wechat(Platform):
categories = {} categories = {}
enable_tag = False enable_tag = False
platform_name = 'wechat' platform_name = 'wechat'
enabled = False
is_common = False
name = '微信公众号'
@classmethod @classmethod
def _get_query_url(cls, target: Target): def _get_query_url(cls, target: Target):

View File

@ -21,6 +21,10 @@ class Weibo(Platform):
} }
enable_tag = False enable_tag = False
platform_name = 'weibo' platform_name = 'weibo'
name = '新浪微博'
enabled = True
is_common = True
schedule_interval = 10
def __init__(self): def __init__(self):
self.top : dict[Target, RawPost] = dict() self.top : dict[Target, RawPost] = dict()

View File

@ -1,6 +1,6 @@
from nonebot import require, get_driver from nonebot import get_driver, logger
from .send import do_send_msgs from .send import do_send_msgs
from .platform.utils import fetch_and_send from .platform import fetch_and_send, platform_manager
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
scheduler = AsyncIOScheduler() scheduler = AsyncIOScheduler()
@ -11,23 +11,12 @@ async def _start():
get_driver().on_startup(_start) get_driver().on_startup(_start)
@scheduler.scheduled_job('interval', seconds=10) for platform_name, platform in platform_manager.items():
async def weibo_check(): if isinstance(platform.schedule_interval, int):
await fetch_and_send('weibo') logger.info(f'start scheduler for {platform_name} with interval {platform.schedule_interval}')
scheduler.add_job(
@scheduler.scheduled_job('interval', seconds=10) fetch_and_send, 'interval', seconds=platform.schedule_interval,
async def bilibili_check(): args=(platform_name,))
await fetch_and_send('bilibili')
@scheduler.scheduled_job('interval', seconds=30)
async def rss_check():
await fetch_and_send('rss')
# @scheduler.scheduled_job('interval', seconds=30)
# async def wechat_check():
# await fetch_and_send('wechat')
@scheduler.scheduled_job('interval', seconds=1) @scheduler.scheduled_job('interval', seconds=1)
async def _send_msgs(): async def _send_msgs():