优化原神日历

This commit is contained in:
CMHopeSunshine 2022-05-29 12:45:41 +08:00
parent b5323fd378
commit 40a62dc123
3 changed files with 95 additions and 118 deletions

View File

@ -1,12 +1,10 @@
import logging from nonebot import require, get_bot, on_command, logger
from typing import Union
from nonebot import require, get_bot, on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent, Bot, Message, MessageSegment, ActionFailed from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent, Bot, Message, MessageSegment, ActionFailed
from nonebot.params import CommandArg from nonebot.params import CommandArg
from ..utils.config import config from utils.config import config
from ..utils.file_handler import load_json, save_json from utils.file_handler import load_json, save_json
from utils.message_util import MessageBuild, get_message_id
from .generate import * from .generate import *
import re import re
@ -22,16 +20,25 @@ calendar = on_command('原神日历', aliases={"原神日历", 'ysrl', '原神
scheduler = require('nonebot_plugin_apscheduler').scheduler scheduler = require('nonebot_plugin_apscheduler').scheduler
async def send_calendar(group_id, group_data): async def send_calendar(push_id, push_data):
for server in group_data[str(group_id)]['server_list']: try:
im = await generate_day_schedule(server) if push_data['type'] == 'private':
base64_str = im2base64str(im) api = 'send_private_msg'
if 'cardimage' not in group_data or not group_data['cardimage']: data = {'user_id': push_id}
msg = MessageSegment.image(base64_str) elif push_data['type'] == 'guild':
api = 'send_guild_channel_msg'
data = {'guild_id': push_id, 'channel_id': push_data['channel_id']}
else: else:
msg = f'[CQ:cardimage,file={base64_str}]' api = 'send_group_msg'
data = {'group_id': push_id}
await get_bot().send_group_msg(group_id=int(group_id), message=msg) for server in push_data['server_list']:
im = await generate_day_schedule(server)
data['message'] = MessageBuild.Image(im)
await get_bot().call_api(api, **data)
logger.info(f'{push_data["type"]}{push_id}的原神日历推送成功')
except Exception as e:
logger.exception(f'{push_data["type"]}{push_id}的原神日历推送失败:{e}')
def update_group_schedule(group_id, group_data): def update_group_schedule(group_id, group_data):
@ -52,109 +59,74 @@ def update_group_schedule(group_id, group_data):
@calendar.handle() @calendar.handle()
async def _(bot: Bot, event: Union[GroupMessageEvent, MessageEvent], msg: Message = CommandArg()): async def _(event: MessageEvent, msg: Message = CommandArg()):
if event.message_type == 'private':
await calendar.finish('仅支持群聊模式下使用本指令')
group_id = str(event.group_id)
group_data = load_json('calender_push.json')
server = 'cn' server = 'cn'
fun = str(msg).strip() msg = msg.extract_plain_text().strip()
action = re.search(r'(?P<action>on|off|time|status|test)', fun)
if group_id not in config.paimon_calender_group or int(group_id) not in config.paimon_calender_group: if not msg:
await calendar.finish(f"尚未在群 {group_id} 开启本功能!", at_sender=True)
if not fun:
im = await generate_day_schedule(server) im = await generate_day_schedule(server)
base64_str = im2base64str(im) await calendar.finish(MessageBuild.Image(im))
group_data = load_json('calender_push.json') else:
push_data = load_json('calender_push.json')
if msg.startswith(('开启', 'on', '打开')):
# 添加定时推送任务
time_str = re.search(r'(\d{1,2}):(\d{2})', msg)
if time_str:
push_id = str(get_message_id(event))
push_data[push_id] = {
'server_list': [
str(server)
],
'hour': int(time_str.group(1)),
'minute': int(time_str.group(2)),
'type': event.message_type
}
if event.message_type == 'guild':
push_data[push_id]['guild_id'] = event.guild_id
if scheduler.get_job('genshin_calendar_' + push_id):
scheduler.remove_job("genshin_calendar_" + push_id)
try: save_json(push_data, 'calender_push.json')
if group_id not in group_data or 'cardimage' not in group_data[group_id] or not group_data[group_id]['cardimage']:
await calendar.finish(MessageSegment.image(base64_str)) scheduler.add_job(
func=send_calendar,
trigger='cron',
hour=int(time_str.group(1)),
minute=int(time_str.group(2)),
id="genshin_calendar_" + push_id,
args=(push_id, push_data[push_id]),
misfire_grace_time=10
)
await calendar.finish('原神日程推送已开启', at_sender=True)
else: else:
await calendar.finish(f'[CQ:cardimage,file={base64_str}]') await calendar.finish('请给出正确的时间格式为12:00', at_sender=True)
except ActionFailed as e:
await logging.ERROR(e)
elif action:
# 添加定时推送任务
if action.group('action') == 'on':
group_data[group_id] = {
'server_list': [
str(server)
],
'hour': 8,
'minute': 0,
'cardimage': False
}
if event.message_type == 'guild':
await calendar.finish("暂不支持频道内推送~")
if scheduler.get_job('genshin_calendar_' + group_id):
scheduler.remove_job("genshin_calendar_" + group_id)
save_json(group_data, 'calender_push.json')
scheduler.add_job(
func=send_calendar,
trigger='cron',
hour=8,
minute=0,
id="genshin_calendar_" + group_id,
args=(group_id, group_data[group_id]),
misfire_grace_time=10
)
await calendar.finish('原神日程推送已开启')
# 关闭推送功能 # 关闭推送功能
elif action.group('action') == 'off': elif msg.startswith(('关闭', 'off', 'close')):
del group_data[group_id] del push_data[str(get_message_id(event))]
if scheduler.get_job("genshin_calendar_" + group_id): if scheduler.get_job("genshin_calendar_" + str(get_message_id(event))):
scheduler.remove_job("genshin_calendar_" + group_id) scheduler.remove_job("genshin_calendar_" + str(get_message_id(event)))
await calendar.finish('原神日程推送已关闭') save_json('calender_push.json')
await calendar.finish('原神日程推送已关闭', at_sender=True)
# 设置推送时间 elif msg.startswith(('状态', 'status', 'setting')):
elif action.group('action') == 'time': if str(get_message_id(event)) not in push_data:
match = str(msg).split(" ") await calendar.finish('当前会话未开启原神日历订阅', at_sender=True)
time = re.search(r'(\d{1,2}):(\d{2})', match[1])
if re.match(r'(\d{1,2}):(\d{2})', match[1]):
if not time or len(time.groups()) < 2:
await calendar.finish("请指定推送时间")
else:
group_data[group_id]['hour'] = int(time.group(1))
group_data[group_id]['minute'] = int(time.group(2))
save_json(group_data, 'calender_push.json')
update_group_schedule(group_id, group_data)
await calendar.finish(
f"推送时间已设置为: {group_data[group_id]['hour']}:{group_data[group_id]['minute']:02d}")
else: else:
await calendar.finish("请给出正确的时间格式为12:00", at_sender=True) reply_msg = f'原神日历订阅:\n'
# DEBUG reply_msg += f'推送时间: {push_data[str(get_message_id(event))]["hour"]}:{push_data[str(get_message_id(event))]["minute"]:02d}\n'
elif action.group('action') == 'test': reply_msg += f'服务器: {" ".join(push_data[str(get_message_id(event))]["server_list"])}'
return
# 查询订阅推送状态
elif action.group('action') == "status":
message = f"订阅日历: {group_data[group_id]['server_list']}"
message += f"\n推送时间: {group_data[group_id]['hour']}:{group_data[group_id]['minute']:02d}"
await calendar.finish(message)
else: else:
await calendar.finish('指令错误') await calendar.finish('指令错误')
# 自动推送任务 # 自动推送任务
for group_id, group_data in load_json('calender_push.json').items(): for push_id, push_data in load_json('calender_push.json').items():
scheduler.add_job( scheduler.add_job(
func=send_calendar, func=send_calendar,
trigger='cron', trigger='cron',
hour=group_data['hour'], hour=push_data['hour'],
minute=group_data['minute'], minute=push_data['minute'],
id="genshin_calendar_" + group_id, id="genshin_calendar_" + push_data,
args=(group_id, group_data), args=(push_id, push_data),
misfire_grace_time=10 misfire_grace_time=10
) )

View File

@ -1,7 +1,7 @@
import re import re
from nonebot import on_command, require, get_bot, logger from nonebot import on_command, require, get_bot, logger
from nonebot.params import CommandArg from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import MessageEvent, MessageSegment from nonebot.adapters.onebot.v11 import MessageEvent, MessageSegment, Message
from utils import aiorequests from utils import aiorequests
from utils.file_handler import load_json, save_json from utils.file_handler import load_json, save_json
from utils.message_util import get_message_id from utils.message_util import get_message_id
@ -12,14 +12,14 @@ scheduler = require('nonebot_plugin_apscheduler').scheduler
@news60s_pic.handle() @news60s_pic.handle()
async def news60s_pic_handler(event: MessageEvent, msg=CommandArg()): async def news60s_pic_handler(event: MessageEvent, msg: Message = CommandArg()):
msg = str(msg).strip() msg = msg.extract_plain_text().strip()
if not msg: if not msg:
url = 'https://api.iyk0.com/60s/' url = 'https://api.iyk0.com/60s/'
res = await aiorequests.get(url=url) res = await aiorequests.get(url=url)
res = res.json() res = res.json()
await news60s_pic.finish(MessageSegment.image(file=res['imageUrl'])) await news60s_pic.finish(MessageSegment.image(file=res['imageUrl']))
elif msg.startswith('开启推送'): elif msg.startswith(('开启', 'on', '打开')):
# 匹配msg中的xx:xx时间 # 匹配msg中的xx:xx时间
time_str = re.search(r'(\d{1,2}):(\d{2})', msg) time_str = re.search(r'(\d{1,2}):(\d{2})', msg)
if time_str: if time_str:
@ -41,13 +41,14 @@ async def news60s_pic_handler(event: MessageEvent, msg=CommandArg()):
minute=int(time_str.group(2)), minute=int(time_str.group(2)),
id='60sNews' + str(get_message_id(event)), id='60sNews' + str(get_message_id(event)),
args=(str(get_message_id(event)), args=(str(get_message_id(event)),
push_data[str(get_message_id(event))]) push_data[str(get_message_id(event))]),
misfire_grace_time=10
) )
save_json(push_data, 'news60s_push.json') save_json(push_data, 'news60s_push.json')
await news60s_pic.finish('开启60s读世界推送成功', at_sender=True) await news60s_pic.finish('开启60s读世界推送成功', at_sender=True)
else: else:
await news60s_pic.finish('请给出正确的时间格式为12:00', at_sender=True) await news60s_pic.finish('请给出正确的时间格式为12:00', at_sender=True)
elif msg.startswith('关闭推送'): elif msg.startswith(('关闭', 'off', 'close')):
push_data = load_json('news60s_push.json') push_data = load_json('news60s_push.json')
del push_data[str(get_message_id(event))] del push_data[str(get_message_id(event))]
if scheduler.get_job('60sNews' + str(get_message_id(event))): if scheduler.get_job('60sNews' + str(get_message_id(event))):
@ -61,13 +62,16 @@ async def news60s_push_task(push_id, push_data: dict):
url = 'https://api.iyk0.com/60s/' url = 'https://api.iyk0.com/60s/'
res = await aiorequests.get(url=url) res = await aiorequests.get(url=url)
res = res.json() res = res.json()
if push_data['type'] == 'group': if push_data['type'] == 'private':
await get_bot().send_group_msg(group_id=push_id, message=MessageSegment.image(file=res['imageUrl'])) api = 'send_private_msg'
elif push_data['type'] == 'private': data = {'user_id': push_id, 'message': MessageSegment.image(file=res['imageUrl'])}
await get_bot().send_private_msg(user_id=push_id, message=MessageSegment.image(file=res['imageUrl']))
elif push_data['type'] == 'guild': elif push_data['type'] == 'guild':
await get_bot().send_guild_channel_msg(guild_id=push_data['guild_id'], channel_id=push_id, api = 'send_guild_channel_msg'
message=MessageSegment.image(file=res['imageUrl'])) data = {'guild_id': push_id, 'channel_id': push_data['channel_id'], 'message': MessageSegment.image(file=res['imageUrl'])}
else:
api = 'send_group_msg'
data = {'group_id': push_id, 'message': MessageSegment.image(file=res['imageUrl'])}
await get_bot().call_api(api, **data)
logger.info(f'{push_data["type"]}{push_id}的60秒读世界推送成功') logger.info(f'{push_data["type"]}{push_id}的60秒读世界推送成功')
except Exception as e: except Exception as e:
logger.exception(f'{push_data["type"]}{push_id}的60秒读世界推送失败{e}') logger.exception(f'{push_data["type"]}{push_id}的60秒读世界推送失败{e}')
@ -81,5 +85,6 @@ for push_id, push_data in load_json('news60s_push.json').items():
minute=push_data['minute'], minute=push_data['minute'],
id='60sNews' + push_id, id='60sNews' + push_id,
args=(push_id, args=(push_id,
push_data) push_data),
misfire_grace_time=10
) )

View File

@ -80,7 +80,7 @@
+ 5.25 + 5.25
- `ys、ysc、ysa、sy`等和`wiki`模块指令可以对话式查询 - `ys、ysc、ysa、sy`等和`wiki`模块指令可以对话式查询
+ 5.27 + 5.27
- 新增`原神日历`[@nicklly](https://github.com/nicklly),需在`.env.*`配置`paimon_calender_group=[开启群号]` - 新增`原神日历`[@nicklly](https://github.com/nicklly)
+ 5.28 + 5.28
- `Paimon_Chat`聊天新增`学习群友发言`(魔改自[Pallas-Bot](https://github.com/InvoluteHell/Pallas-Bot/tree/master/src/plugins/repeater)),需安装`jieba_fast、pymongo、pypinyin依赖库`、`mongodb数据库`且在`.env.*`配置文件中添加mongodb连接参数`paimon_mongodb_url`,例如`paimon_mongodb_url=mongodb://localhost:27017/` - `Paimon_Chat`聊天新增`学习群友发言`(魔改自[Pallas-Bot](https://github.com/InvoluteHell/Pallas-Bot/tree/master/src/plugins/repeater)),需安装`jieba_fast、pymongo、pypinyin依赖库`、`mongodb数据库`且在`.env.*`配置文件中添加mongodb连接参数`paimon_mongodb_url`,例如`paimon_mongodb_url=mongodb://localhost:27017/`