Skip to content

Commit

Permalink
Merge pull request #78 from Cypas/dev_cypas
Browse files Browse the repository at this point in the history
perf:qq c2c聊天兼容,减少终端日志输出,等一系列优化
  • Loading branch information
Cypas authored Aug 6, 2024
2 parents 08886ca + b08b267 commit 02be5e1
Show file tree
Hide file tree
Showing 21 changed files with 519 additions and 139 deletions.
19 changes: 16 additions & 3 deletions nonebot_plugin_splatoon3_nso/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from nonebot.message import event_preprocessor
from nonebot.plugin import PluginMetadata
from nonebot.rule import is_type, to_me

from .config import driver, plugin_config, Config
from .data.db_sqlite import init_db
Expand All @@ -24,15 +25,18 @@
)


@on_startswith(("/", "、"), priority=99).handle()
async def unknown_command(bot: Bot, event: Event):
@on_message(rule=to_me(), priority=97, block=True).handle()
@on_startswith(("/", "、"), priority=99, block=True).handle()
async def unknown_command(bot: Bot, event: Event, matcher: Matcher):
logger.info(f'unknown_command from {event.get_event_name()}')
msg = ""
if plugin_config.splatoon3_unknown_command_fallback_reply:
if isinstance(bot, Tg_Bot):
msg = "Sorry, I didn't understand that command. /help"
elif isinstance(bot, QQ_Bot):
msg = "无效指令,请发送 /help 查看帮助\n或在消息框输入/后,手动选择bot命令"
elif isinstance(bot, All_BOT):
msg = "无效指令,发送 /help 查看帮助"
msg = "无效指令,请发送 /help 查看帮助"
kook_black_list = plugin_config.splatoon3_unknown_command_fallback_reply_kook_black_list
if len(kook_black_list) > 0:
if isinstance(bot, Kook_Bot):
Expand All @@ -44,6 +48,15 @@ async def unknown_command(bot: Bot, event: Event):
logger.info("kook指定兜底黑名单服务器,不进行兜底消息提示")
if msg:
await bot.send(event, message=msg)
await matcher.finish()


@on_message(rule=is_type(QQ_C2CME), priority=98, block=True).handle()
async def c2c_unknown_command(bot: Bot, event: Event, matcher: Matcher):
"""为qq c2c任何未匹配文本进行兜底"""
logger.info(f'unknown_command from {event.get_event_name()}')
msg = "无效指令,请发送/help 查看帮助\n或在消息框输入/后,手动选择bot命令"
await matcher.finish(msg)


@on_command("help", aliases={"h", "帮助", "说明", "文档"}, priority=10).handle()
Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_splatoon3_nso/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ class Config(BaseModel):

driver = get_driver()
global_config = driver.config
plugin_config = get_plugin_config(Config)
plugin_config = get_plugin_config(Config)
24 changes: 22 additions & 2 deletions nonebot_plugin_splatoon3_nso/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
from .db_sqlite import DBSession, TempImageTable, DIR_TEMP_IMAGE
from ..utils import init_path, get_file_url

# 插件数据全部变量提供静态读写
plugin_data = {}


class GlobalUserInfo:
"""全局公用用户类"""
Expand Down Expand Up @@ -52,8 +55,7 @@ async def model_get_or_set_temp_image(_type, name: str, link=None) -> TempImageT
image_data = await get_file_url(link)
file_name = ""
# 1024 bytes长度 = 1k
lens = len(image_data)
if lens > 200:
if image_data and len(image_data) > 200:
# 创建文件夹
init_path(f"{DIR_TEMP_IMAGE}")
init_path(f"{DIR_TEMP_IMAGE}/{_type}")
Expand Down Expand Up @@ -100,3 +102,21 @@ def get_insert_or_update_obj(cls, filter_dict, **kw):
setattr(res, k, v)
session.close()
return res


async def get_or_set_plugin_data(key, value=None):
"""获取或设置插件数据"""
from nonebot import require
require("nonebot_plugin_datastore")
from nonebot_plugin_datastore import get_plugin_data

global plugin_data
if not value:
# 读取配置
value = await get_plugin_data().config.get(key)
plugin_data[key] = value
else:
# 存储配置
await get_plugin_data().config.set(key, value)
plugin_data[key] = value
return value
16 changes: 16 additions & 0 deletions nonebot_plugin_splatoon3_nso/handle/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from .send_msg import bot_send, notify_to_private
from ..data.data_source import dict_get_all_global_users, model_clean_db_cache, model_get_or_set_user, \
dict_get_or_set_user_info
from ..data.utils import get_or_set_plugin_data
from ..utils import get_msg_id
from ..utils.bot import *
from nonebot import logger
Expand Down Expand Up @@ -125,6 +126,7 @@ async def admin_cmd(bot: Bot, event: Event, args: Message = CommandArg()):
msg = "所有命令都需要加上/admin 前缀\n" \
"get_push 获取当前push统计\n" \
"close_push 关闭当前全部push\n" \
"set_bot_notice {公告消息} 设置公告消息\n" \
"get_x_player 获取x赛top\n" \
"get_event_top 获取活动top\n" \
"clean_cache 清理数据库缓存\n" \
Expand Down Expand Up @@ -154,6 +156,20 @@ async def admin_cmd(bot: Bot, event: Event, args: Message = CommandArg()):
else:
await bot_send(bot, event, message=f"无效命令, lens:{len(args)}")

if plain_text.startswith("set_bot_notice"):
"""设置公告消息
set_bot_notice {notice}
"""
notice = plain_text.replace("set_bot_notice", "").strip().replace("\n", "\r")
old_notice = await get_or_set_plugin_data("splatoon3_bot_notice")
await get_or_set_plugin_data("splatoon3_bot_notice", notice)
if not old_notice:
old_notice = "None"
if not notice:
notice = "None"
msg = "旧公告消息为:\n" + old_notice + "\n" + "新的公告消息为:\n" + notice
await bot_send(bot, event, message=msg)

if plain_text.startswith("copy_token"):
"""复制同平台其他用户token到自己账号,方便测试"""
args = plain_text.split(" ")
Expand Down
12 changes: 6 additions & 6 deletions nonebot_plugin_splatoon3_nso/handle/cron/event_top.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async def get_event_top():

db_user = model_get_newest_user()
if not db_user:
cron_logger.info(f"no user login.")
cron_logger.error(f"no user login.")
return
user = dict_get_or_set_user_info(db_user.platform, db_user.user_id)
splatoon = Splatoon(None, None, user)
Expand Down Expand Up @@ -47,13 +47,13 @@ async def get_event_top_player_task(splatoon):
for n in edges[::-1]:
in_ed = n['node']['leagueMatchRankingTimePeriodGroups']['edges']
for nn in in_ed[::-1]:
cron_logger.info(nn['node']['leagueMatchSetting']['leagueMatchEvent']['name'])
cron_logger.debug(nn['node']['leagueMatchSetting']['leagueMatchEvent']['name'])
for t in nn['node']['timePeriods']:
top_id = t['id']
top_type = base64.b64decode(top_id).decode('utf-8')
_, search_type = top_type.split('TimePeriod-')
count = model_get_top_all_count_by_top_type(search_type)
cron_logger.info(f'top_all.type search {search_type}, {count or 0}')
cron_logger.debug(f'top_all.type search {search_type}, {count or 0}')
if count:
continue
res = await splatoon.get_event_items(top_id, multiple=True)
Expand All @@ -63,16 +63,16 @@ async def get_event_top_player_task(splatoon):
def parse_league(league):
"""解析活动榜单并写入数据"""
if not league:
cron_logger.info('no league')
cron_logger.debug('no league')
return

play_time = league['data']['rankingPeriod']['endTime'].replace('T', ' ').replace('Z', '')
play_time = dt.strptime(play_time, '%Y-%m-%d %H:%M:%S')
league_name = league['data']['rankingPeriod']['leagueMatchSetting']['leagueMatchEvent']['name']
cron_logger.info(f'{play_time}, {league_name}')
cron_logger.debug(f'{play_time}, {league_name}')
for team in league['data']['rankingPeriod']['teams']:
top_id = team['id']
cron_logger.info(f'saving top_id: {top_id}')
cron_logger.debug(f'saving top_id: {top_id}')
model_delete_top_all(top_id)
top_type = base64.b64decode(top_id).decode('utf-8')
for n in team['details']['nodes']:
Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_splatoon3_nso/handle/cron/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ async def send_report_task():
if msg:
# 写日志
log_msg = msg.replace('\n', '')
report_logger.info(f"get {msg_id} report:{log_msg}")
report_logger.debug(f"get {msg_id} report:{log_msg}")
# # 通知到频道
# await report_notify_to_channel(user.platform, user.user_id, msg, _type='job')
# 通知到私信
Expand Down
Loading

0 comments on commit 02be5e1

Please sign in to comment.