mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2025-12-15 14:22:55 +08:00
Delete plugins directory
This commit is contained in:
parent
b4aef2bba6
commit
a9f2035041
@ -1,71 +0,0 @@
|
||||
import random
|
||||
from nonebot import on_keyword
|
||||
import os
|
||||
from util.init_result import image
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from nonebot import on_command
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, MessageEvent
|
||||
from nonebot.adapters.cqhttp.permission import GROUP
|
||||
from util.utils import FreqLimiter
|
||||
|
||||
|
||||
__plugin_name__ = '基本设置 [Hidden]'
|
||||
__plugin_usage__ = '用法: 基本'
|
||||
|
||||
|
||||
_flmt = FreqLimiter(300)
|
||||
|
||||
|
||||
config_playgame = on_keyword({'打游戏'}, permission=GROUP, priority=1, block=True)
|
||||
|
||||
|
||||
@config_playgame.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if not _flmt.check(event.group_id):
|
||||
return
|
||||
_flmt.start_cd(event.group_id)
|
||||
await config_playgame.finish(image(
|
||||
random.choice(os.listdir(IMAGE_PATH + "dayouxi/")
|
||||
), "dayouxi"))
|
||||
|
||||
|
||||
self_introduction = on_command("自我介绍", aliases={'介绍', '你是谁', '你叫什么'},
|
||||
rule=to_me(), priority=5, block=True)
|
||||
|
||||
|
||||
@self_introduction.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
result = "我叫绪山真寻\n" \
|
||||
"你们可以叫我真寻,小真寻,哪怕你们叫我小寻子我也能接受!\n" \
|
||||
"年龄的话我还是个**岁初中生(至少现在是)\n" \
|
||||
"身高保密!!!(也就比美波里(姐姐..(妹妹))矮一点)\n" \
|
||||
"我生日是在3月6号, 能记住的话我会很高兴的\n现在是自宅警备系的现役JC\n" \
|
||||
"最好的朋友是椛!\n"\
|
||||
+ image("zhenxun")
|
||||
await self_introduction.finish(result)
|
||||
|
||||
laopo = on_keyword({'老婆'}, rule=to_me(), priority=5, block=True)
|
||||
|
||||
|
||||
@laopo.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await laopo.finish(image('laopo.jpg', 'other'))
|
||||
|
||||
|
||||
# config_robot = on_keyword({"机器人"}, permission=GROUP, priority=5, block=True)
|
||||
# @config_robot.handle()
|
||||
# async def _(bot: Bot, event: Event, state: T_State):
|
||||
# if not _flmt.check(event.group_id) or event.group_id == 774261838:
|
||||
# return
|
||||
# _flmt.start_cd(event.group_id)
|
||||
# await config_robot.send("小真寻才不是机器人!")
|
||||
# result = "我叫绪山真寻\n" \
|
||||
# "你们可以叫我真寻,小真寻,哪怕你们叫我小寻子我也能接受!\n" \
|
||||
# "年龄的话我还是个**岁初中生(至少现在是)\n" \
|
||||
# "身高保密!!!(也就比美波里(姐姐..(妹妹))矮一点)\n" \
|
||||
# "我生日是在3月6号, 能记住的话我会很高兴的\n现在是自宅警备系的现役JC\n" \
|
||||
# "最好的朋友是椛!\n"\
|
||||
# + image("zhenxun", "")
|
||||
# await config_jieshao.finish(result)
|
||||
Binary file not shown.
Binary file not shown.
@ -1,88 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from util.utils import get_message_text, get_message_imgs, scheduler, get_bot
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
|
||||
from .data_source import set_group_status, custom_group_welcome, change_group_switch, \
|
||||
update_member_info, group_current_status
|
||||
from nonebot.adapters.cqhttp.permission import GROUP
|
||||
from services.log import logger
|
||||
from configs.config import plugins2name_dict
|
||||
from nonebot.plugin import export
|
||||
|
||||
__plugin_usage__ = '''自定义进群欢迎消息:
|
||||
自定义进群欢迎消息 xxxx(图片)
|
||||
示例:自定义进群欢迎消息 欢迎新人!(后面可以跟一张图片噢)'''
|
||||
|
||||
export = export()
|
||||
export.update_member_info = update_member_info
|
||||
|
||||
cmds = []
|
||||
for cmd_list in plugins2name_dict.values():
|
||||
for cmd in cmd_list:
|
||||
cmds.append(f'开启{cmd}')
|
||||
cmds.append(f'关闭{cmd}')
|
||||
cmds = set(cmds)
|
||||
|
||||
group_status = on_command('oc_reminds', aliases={'开启早晚安', '关闭早晚安',
|
||||
'开启进群欢迎', '关闭进群欢迎',
|
||||
'开启每日开箱重置提醒', '关闭每日开箱重置提醒',
|
||||
'开启b站转发解析', '关闭b站转发解析',
|
||||
'开启epic通知', '关闭epic通知',
|
||||
'开启丢人爬', '关闭丢人爬',
|
||||
'开启原神黄历提醒', '关闭原神黄历提醒',
|
||||
'开启全部通知', '开启所有通知', '关闭全部通知', '关闭所有通知',
|
||||
'群通知状态'}, permission=GROUP, priority=4, block=True)
|
||||
|
||||
switch_rule = on_command('switch_rule', aliases=cmds, permission=GROUP, priority=4, block=True)
|
||||
custom_welcome = on_command('自定义进群欢迎消息', aliases={'自定义欢迎消息', '自定义群欢迎消息'}, permission=GROUP, priority=5, block=True)
|
||||
refresh_member_group = on_command("更新群组成员列表", aliases={"更新群组成员信息"}, permission=GROUP, priority=5, block=True)
|
||||
|
||||
|
||||
@switch_rule.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
await switch_rule.send(await change_group_switch(state["_prefix"]["raw_command"].strip(), event.group_id))
|
||||
logger.info(f'USER {event.user_id} GROUP {event.group_id} 使用群功能管理命令 {state["_prefix"]["raw_command"]}')
|
||||
|
||||
|
||||
@group_status.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if state["_prefix"]["raw_command"] in ['群通知状态']:
|
||||
await group_status.finish(await group_current_status(event.group_id))
|
||||
await group_status.send(await set_group_status(state["_prefix"]["raw_command"], event.group_id),
|
||||
at_sender=True)
|
||||
logger.info(f'USER {event.user_id} GROUP {event.group_id} 使用群通知管理命令 {state["_prefix"]["raw_command"]}')
|
||||
|
||||
|
||||
@custom_welcome.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if str(event.get_message()) in ['帮助'] or str(event.get_message()) == '':
|
||||
await custom_welcome.finish(__plugin_usage__)
|
||||
msg = get_message_text(event.json())
|
||||
imgs = get_message_imgs(event.json())
|
||||
await custom_welcome.finish(await custom_group_welcome(msg, imgs, event.user_id, event.group_id), at_sender=True)
|
||||
|
||||
|
||||
@refresh_member_group.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if await update_member_info(event.group_id):
|
||||
await refresh_member_group.finish("更新群员信息成功!", at_sender=True)
|
||||
else:
|
||||
await refresh_member_group.finish("更新群员信息失败!", at_sender=True)
|
||||
|
||||
|
||||
# 自动更新群员信息
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=2,
|
||||
minute=1,
|
||||
)
|
||||
async def _():
|
||||
bot = get_bot()
|
||||
gl = await bot.get_group_list(self_id=bot.self_id)
|
||||
gl = [g['group_id'] for g in gl]
|
||||
for g in gl:
|
||||
try:
|
||||
await update_member_info(g)
|
||||
logger.info(f'更新群组 g:{g} 成功')
|
||||
except Exception as e:
|
||||
logger.error(f'更新群组错误 g:{g} e:{e}')
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,210 +0,0 @@
|
||||
from models.group_remind import GroupRemind
|
||||
from services.log import logger
|
||||
from configs.path_config import DATA_PATH
|
||||
import os
|
||||
import aiofiles
|
||||
import aiohttp
|
||||
from util.init_result import image
|
||||
from util.utils import get_local_proxy, get_bot
|
||||
from pathlib import Path
|
||||
from nonebot import require
|
||||
from configs.config import plugins2name_dict
|
||||
from models.group_member_info import GroupInfoUser
|
||||
import time
|
||||
from datetime import datetime
|
||||
from services.db_context import db
|
||||
from models.level_user import LevelUser
|
||||
from configs.config import ADMIN_DEFAULT_AUTH
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
export = require("nonebot_plugin_manager")
|
||||
|
||||
|
||||
command_dict = {
|
||||
'早晚安': 'zwa',
|
||||
'进群欢迎': 'hy',
|
||||
'每日开箱重置提醒': 'kxcz',
|
||||
'b站转发解析': 'blpar',
|
||||
'epic': 'epic',
|
||||
'丢人爬': 'pa',
|
||||
'原神黄历提醒': 'almanac',
|
||||
}
|
||||
command_list = list(command_dict.values())
|
||||
command_info_dt = {
|
||||
'早晚安': '将会在每晚11:59晚安,在6:01早安哦',
|
||||
'每日开箱重置提醒': '将会在每日00:01提示开箱重置!',
|
||||
'epic': '将会在每日中午12:01发送可白嫖的epic游戏',
|
||||
'原神黄历提醒': '将会在每日8:00发送当日的原神黄历',
|
||||
}
|
||||
|
||||
|
||||
async def remind_status(group: int, name: str, flag: bool) -> str:
|
||||
_name = ''
|
||||
if name in command_dict.values():
|
||||
_name = list(command_dict.keys())[list(command_dict.values()).index(name)]
|
||||
if flag:
|
||||
rst = '开启'
|
||||
if await GroupRemind.get_status(group, name):
|
||||
return f'该群已经{rst}过 {_name},请勿重复开启!'
|
||||
else:
|
||||
rst = '关闭'
|
||||
if not await GroupRemind.get_status(group, name):
|
||||
return f'该群已经{rst}过 {_name},请勿重复开启!'
|
||||
if await GroupRemind.set_status(group, name, flag):
|
||||
info = command_info_dt[_name] if command_info_dt.get(_name) else ''
|
||||
if info:
|
||||
info = '\n' + info
|
||||
return f'成功{rst} {_name}!0v0 {info}'
|
||||
else:
|
||||
return f'{rst} {_name} 失败了...'
|
||||
|
||||
|
||||
async def set_group_status(name: str, group_id: int):
|
||||
flag = None
|
||||
if name[:2] == '开启':
|
||||
flag = True
|
||||
elif name[:2] == '关闭':
|
||||
flag = False
|
||||
cmd = name[2:]
|
||||
if cmd in ['全部通知', '所有通知']:
|
||||
for command in command_list:
|
||||
await remind_status(group_id, command, flag)
|
||||
return f'已{name[:2]}所有通知!'
|
||||
return await remind_status(group_id, command_dict[cmd], flag)
|
||||
|
||||
|
||||
async def group_current_status(group_id: int):
|
||||
result = f'(被动技能)\n早晚安通知:{"√" if await GroupRemind.get_status(group_id, "zwa") else "×"}\n' \
|
||||
f'进群欢迎:{"√" if await GroupRemind.get_status(group_id, "hy") else "×"}\n' \
|
||||
f'每日开箱重置通知:{"√" if await GroupRemind.get_status(group_id, "kxcz") else "×"}\n' \
|
||||
f'b站转发解析:{"√" if await GroupRemind.get_status(group_id, "blpar") else "×"}\n' \
|
||||
f'丢人爬:{"√" if await GroupRemind.get_status(group_id, "pa") else "×"}\n' \
|
||||
f'epic免费游戏:{"√" if await GroupRemind.get_status(group_id, "epic") else "×"}\n' \
|
||||
f'原神黄历提醒:{"√" if await GroupRemind.get_status(group_id, "almanac") else "×"}'
|
||||
return result
|
||||
|
||||
|
||||
custom_welcome_msg_json = Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
|
||||
|
||||
|
||||
async def custom_group_welcome(msg, imgs, user_id, group_id):
|
||||
img_result = ''
|
||||
img = imgs[0] if imgs else ''
|
||||
result = ''
|
||||
if os.path.exists(DATA_PATH + f'custom_welcome_msg/{group_id}.jpg'):
|
||||
os.remove(DATA_PATH + f'custom_welcome_msg/{group_id}.jpg')
|
||||
# print(custom_welcome_msg_json)
|
||||
if not custom_welcome_msg_json.exists():
|
||||
custom_welcome_msg_json.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {}
|
||||
else:
|
||||
try:
|
||||
data = json.load(open(custom_welcome_msg_json, 'r'))
|
||||
except FileNotFoundError:
|
||||
data = {}
|
||||
try:
|
||||
if msg:
|
||||
data[str(group_id)] = str(msg)
|
||||
json.dump(data, open(custom_welcome_msg_json, 'w'), indent=4, ensure_ascii=False)
|
||||
logger.info(f'USER {user_id} GROUP {group_id} 更换群欢迎消息 {msg}')
|
||||
result += msg
|
||||
if img:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(img, proxy=get_local_proxy()) as response:
|
||||
async with aiofiles.open(DATA_PATH + f'custom_welcome_msg/{group_id}.jpg', 'wb') as f:
|
||||
await f.write(await response.read())
|
||||
img_result = image(abspath=DATA_PATH + f'custom_welcome_msg/{group_id}.jpg')
|
||||
logger.info(f'USER {user_id} GROUP {group_id} 更换群欢迎消息图片')
|
||||
except Exception as e:
|
||||
logger.error(f'GROUP {group_id} 替换群消息失败 e:{e}')
|
||||
return '替换群消息失败..'
|
||||
return f'替换群欢迎消息成功:\n{result}' + img_result
|
||||
|
||||
|
||||
async def change_group_switch(cmd: str, group_id: int):
|
||||
group_id = str(group_id)
|
||||
status = cmd[:2]
|
||||
cmd = cmd[2:]
|
||||
try:
|
||||
with open(DATA_PATH + 'manager/plugin_list.json', 'r', encoding='utf8') as f:
|
||||
plugin_list = json.load(f)
|
||||
except ValueError:
|
||||
pass
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
for plugin_cmd in plugins2name_dict.keys():
|
||||
if cmd in plugins2name_dict[plugin_cmd]:
|
||||
# print(plugin_list[plugin_cmd])
|
||||
if status == '开启':
|
||||
# if group_id in plugin_list[plugin_cmd]:
|
||||
if group_id not in plugin_list[plugin_cmd] or plugin_list[plugin_cmd][group_id]:
|
||||
return f'功能 {cmd} 正处于开启状态!不要重复开启.'
|
||||
export.unblock_plugin(group_id, plugin_cmd)
|
||||
else:
|
||||
if group_id in plugin_list[plugin_cmd]:
|
||||
if not plugin_list[plugin_cmd][group_id]:
|
||||
return f'功能 {cmd} 正处于关闭状态!不要重复关闭.'
|
||||
export.block_plugin(group_id, plugin_cmd)
|
||||
if os.path.exists(DATA_PATH + f'group_help/{group_id}.png'):
|
||||
os.remove(DATA_PATH + f'group_help/{group_id}.png')
|
||||
|
||||
return f'{status} {cmd} 功能!'
|
||||
return f'没有找到 {cmd} 功能喔'
|
||||
|
||||
|
||||
async def update_member_info(group_id: int) -> bool:
|
||||
bot = get_bot()
|
||||
_group_user_list = await bot.get_group_member_list(group_id=group_id)
|
||||
_error_member_list = []
|
||||
_exist_member_list = []
|
||||
# try:
|
||||
for user_info in _group_user_list:
|
||||
if user_info['card'] == "":
|
||||
nickname = user_info['nickname']
|
||||
else:
|
||||
nickname = user_info['card']
|
||||
async with db.transaction():
|
||||
# 更新权限
|
||||
if user_info['role'] in ['owner', 'admin'] and not await LevelUser.is_group_flag(user_info['user_id'], group_id):
|
||||
await LevelUser.set_level(user_info['user_id'], user_info['group_id'], ADMIN_DEFAULT_AUTH)
|
||||
if str(user_info['user_id']) in bot.config.superusers:
|
||||
await LevelUser.set_level(user_info['user_id'], user_info['group_id'], 9)
|
||||
user = await GroupInfoUser.select_member_info(user_info['user_id'], user_info['group_id'])
|
||||
if user:
|
||||
if user.user_name != nickname:
|
||||
await user.update(user_name=nickname).apply()
|
||||
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新群昵称成功")
|
||||
_exist_member_list.append(int(user_info['user_id']))
|
||||
continue
|
||||
join_time = datetime.strptime(
|
||||
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user_info['join_time'])), "%Y-%m-%d %H:%M:%S")
|
||||
if await GroupInfoUser.insert(
|
||||
user_info['user_id'],
|
||||
user_info['group_id'],
|
||||
nickname,
|
||||
join_time,):
|
||||
_exist_member_list.append(int(user_info['user_id']))
|
||||
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
|
||||
else:
|
||||
_error_member_list.append(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败\n")
|
||||
_del_member_list = list(set(_exist_member_list).difference(set(await GroupInfoUser.query_group_member_list(group_id))))
|
||||
if _del_member_list:
|
||||
for del_user in _del_member_list:
|
||||
if await GroupInfoUser.delete_member_info(del_user, group_id):
|
||||
logger.info(f"退群用户{del_user} 所属{group_id} 已删除")
|
||||
else:
|
||||
logger.info(f"退群用户{del_user} 所属{group_id} 删除失败")
|
||||
if _error_member_list:
|
||||
result = ""
|
||||
for error_user in _error_member_list:
|
||||
result += error_user
|
||||
await bot.send_private_msg(user_id=int(list(bot.config.superusers)[0]), message=result[:-1])
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,27 +0,0 @@
|
||||
from nonebot import on_notice
|
||||
from services.log import logger
|
||||
from nonebot.adapters.cqhttp import Bot, GroupAdminNoticeEvent
|
||||
from nonebot.typing import T_State
|
||||
from models.level_user import LevelUser
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from configs.config import ADMIN_DEFAULT_AUTH
|
||||
|
||||
|
||||
admin_notice = on_notice(priority=5)
|
||||
|
||||
|
||||
@admin_notice.handle()
|
||||
async def _(bot: Bot, event: GroupAdminNoticeEvent, state: T_State):
|
||||
try:
|
||||
nickname = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
|
||||
except AttributeError:
|
||||
nickname = event.user_id
|
||||
if event.sub_type == 'set':
|
||||
await LevelUser.set_level(event.user_id, event.group_id, ADMIN_DEFAULT_AUTH)
|
||||
logger.info(f'为新晋管理员 {nickname}({event.user_id}) 添加权限等级:{ADMIN_DEFAULT_AUTH}')
|
||||
if event.sub_type == 'unset':
|
||||
await LevelUser.delete_level(event.user_id, event.group_id)
|
||||
logger.info(f'将非管理员 {nickname}({event.user_id}) 取消权限等级')
|
||||
|
||||
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.adapters.cqhttp import GroupMessageEvent
|
||||
from util.img_utils import CreateImg
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from util.init_result import image
|
||||
|
||||
|
||||
__plugin_name__ = '管理帮助 [Hidden]'
|
||||
__plugin_usage__ = '''管理帮助(权限等级):
|
||||
1.更新群组成员列表(1)
|
||||
2.功能开关 --> 指令:开启/关闭xx功能(2)
|
||||
3.查看群被动技能 --> 指令:群通知状态(2)
|
||||
4.自定义群欢迎 --> 指令:自定义进群欢迎消息(2)
|
||||
5.将用户拉入真寻黑名单 --> .ban/.unban(5)
|
||||
6.刷屏禁言相关 --> 指令:刷屏检测设置/设置检测时间
|
||||
\t\t/设置检测次数/设置禁言时长(5)
|
||||
7.上传图片(6)
|
||||
8.移动图片(7)
|
||||
9.删除图片(7)
|
||||
对我说 “指令名 帮助” 获取对应详细帮助
|
||||
群主与管理员默认 5 级权限
|
||||
'''
|
||||
|
||||
passive_help = '''【被动技能开关(2):
|
||||
开启/关闭进群欢迎
|
||||
开启/关闭每日开箱重置提醒
|
||||
开启/关闭b站转发解析
|
||||
开启/关闭丢人爬
|
||||
开启/关闭epic通知
|
||||
开启/关闭全部通知
|
||||
开启/关闭原神黄历提醒】
|
||||
'''
|
||||
|
||||
admin_help = on_command("管理员帮助", aliases={"管理帮助"}, priority=5, block=True)
|
||||
|
||||
admin_help_img = CreateImg(1000, 600, font_size=24)
|
||||
admin_help_img.text((10, 10), __plugin_usage__)
|
||||
admin_help_img.paste(CreateImg(400, 600, font_size=24).text((0, 0), passive_help), (600, 50))
|
||||
admin_help_img.save(IMAGE_PATH + 'admin_help_img.png')
|
||||
|
||||
|
||||
@admin_help.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
await admin_help.send(image('admin_help_img.png'))
|
||||
Binary file not shown.
Binary file not shown.
@ -1,61 +0,0 @@
|
||||
from .data_source import get_qqbot_chat_result, hello, no_result
|
||||
from services.log import logger
|
||||
from nonebot import on_message
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent, PrivateMessageEvent
|
||||
from util.utils import get_message_text, get_message_imgs
|
||||
from models.friend_user import FriendUser
|
||||
from models.group_member_info import GroupInfoUser
|
||||
|
||||
__plugin_name__ = 'AI'
|
||||
|
||||
|
||||
ai = on_message(rule=to_me(), priority=8)
|
||||
|
||||
|
||||
@ai.handle()
|
||||
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
|
||||
msg = get_message_text(event.json())
|
||||
imgs = get_message_imgs(event.json())
|
||||
if str(event.get_message()).find('CQ:xml') != -1:
|
||||
return
|
||||
# 打招呼
|
||||
if not msg and not imgs:
|
||||
await ai.finish(hello())
|
||||
img = imgs[0] if imgs else ''
|
||||
nickname = await FriendUser.get_friend_nickname(event.user_id)
|
||||
if not nickname:
|
||||
nickname = await FriendUser.get_user_name(event.user_id)
|
||||
if not nickname:
|
||||
nickname = "你"
|
||||
result = await get_qqbot_chat_result(msg, img, event.user_id, nickname)
|
||||
logger.info(f"USER {event.user_id} 问题:{msg}\n回答:{result}")
|
||||
if result:
|
||||
await ai.finish(result)
|
||||
else:
|
||||
await ai.finish(no_result())
|
||||
|
||||
|
||||
@ai.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
# if await GroupRemind.get_status(event.group_id, 'ai'):
|
||||
msg = get_message_text(event.json())
|
||||
imgs = get_message_imgs(event.json())
|
||||
# 打招呼
|
||||
if not msg and not imgs:
|
||||
await ai.finish(hello())
|
||||
img = imgs[0] if imgs else ''
|
||||
nickname = await GroupInfoUser.get_group_member_nickname(event.user_id, event.group_id)
|
||||
if not nickname:
|
||||
try:
|
||||
nickname = (await GroupInfoUser.select_member_info(event.user_id, event.group_id)).user_name
|
||||
except AttributeError:
|
||||
nickname = "你"
|
||||
result = await get_qqbot_chat_result(msg, img, event.user_id, nickname)
|
||||
logger.info(f"问题:{msg}\n回答:{result}")
|
||||
if result:
|
||||
await ai.finish(result)
|
||||
else:
|
||||
await ai.finish(no_result())
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,142 +0,0 @@
|
||||
from configs.config import TL_KEY
|
||||
import aiohttp
|
||||
import random
|
||||
import os
|
||||
from configs.path_config import IMAGE_PATH, DATA_PATH
|
||||
from util.init_result import image
|
||||
from util.utils import get_bot
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
url = "http://openapi.tuling123.com/openapi/api/v2"
|
||||
|
||||
index = 0
|
||||
|
||||
anime_data = json.load(open(DATA_PATH + 'anime.json', 'r', encoding='utf8'))
|
||||
|
||||
|
||||
# 图灵AI
|
||||
async def get_qqbot_chat_result(text: str, img_url: str, user_id: int, user_name: str) -> str:
|
||||
global index
|
||||
if index == 5:
|
||||
index = 0
|
||||
if len(text) < 6 and random.random() < 0.6:
|
||||
keys = anime_data.keys()
|
||||
for key in keys:
|
||||
if text.find(key) != -1:
|
||||
return random.choice(anime_data[key]).replace('你', user_name)
|
||||
if text:
|
||||
req = {
|
||||
"perception":
|
||||
{
|
||||
"inputText":
|
||||
{
|
||||
"text": text
|
||||
},
|
||||
"selfInfo":
|
||||
{
|
||||
"location":
|
||||
{
|
||||
"city": "陨石坑",
|
||||
"province": "火星",
|
||||
"street": "第5坑位"
|
||||
}
|
||||
}
|
||||
},
|
||||
"userInfo":
|
||||
{
|
||||
"apiKey": TL_KEY[index],
|
||||
"userId": str(user_id)
|
||||
}
|
||||
}
|
||||
elif img_url:
|
||||
req = {
|
||||
"reqType": 1,
|
||||
"perception":
|
||||
{
|
||||
"inputImage": {
|
||||
"url": img_url
|
||||
},
|
||||
"selfInfo":
|
||||
{
|
||||
"location":
|
||||
{
|
||||
"city": "陨石坑",
|
||||
"province": "火星",
|
||||
"street": "第5坑位"
|
||||
}
|
||||
}
|
||||
},
|
||||
"userInfo":
|
||||
{
|
||||
"apiKey": TL_KEY[index],
|
||||
"userId": str(user_id)
|
||||
}
|
||||
}
|
||||
async with aiohttp.ClientSession() as sess:
|
||||
async with sess.post(url, json=req) as response:
|
||||
if response.status != 200:
|
||||
return ''
|
||||
resp_payload = json.loads(await response.text())
|
||||
if resp_payload['intent']:
|
||||
if resp_payload['intent']['code'] == 4003:
|
||||
index += 1
|
||||
# 该AI很屑!!!!!!!!!!!!
|
||||
async with sess.get(f'http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}') as res:
|
||||
data = json.loads(await res.text())
|
||||
if data['result'] == 0:
|
||||
content = data['content']
|
||||
if content.find('菲菲') != -1:
|
||||
content = content.replace('菲菲', list(get_bot().config.nickname)[0])
|
||||
if content.find('公众号') != -1:
|
||||
content = ''
|
||||
if content.find('{br}') != -1:
|
||||
content = content.replace('{br}', '\n')
|
||||
if content.find('提示') != -1:
|
||||
content = content[:content.find('提示')]
|
||||
return content
|
||||
if resp_payload['results']:
|
||||
for result in resp_payload['results']:
|
||||
if result['resultType'] == 'text':
|
||||
text = result['values']['text']
|
||||
if user_name:
|
||||
text = text.replace('小朋友', user_name)
|
||||
if len(user_name) < 5:
|
||||
if random.random() < 0.5:
|
||||
user_name = "~".join(user_name) + '~'
|
||||
if random.random() < 0.5:
|
||||
if user_name.find('大人') == -1:
|
||||
user_name += '大~人~'
|
||||
text = text.replace('小主人', user_name)
|
||||
return text
|
||||
|
||||
|
||||
def hello() -> str:
|
||||
result = random.choice((
|
||||
"哦豁?!",
|
||||
"你好!Ov<",
|
||||
f"库库库,呼唤{list(get_bot().config.nickname)[0]}做什么呢",
|
||||
"我在呢!",
|
||||
"呼呼,叫俺干嘛"
|
||||
))
|
||||
img = random.choice(os.listdir(IMAGE_PATH + "zai/"))
|
||||
if img[-4:] == ".gif":
|
||||
result += image(img, "zai")
|
||||
else:
|
||||
result += image(img, "zai")
|
||||
return result
|
||||
|
||||
|
||||
def no_result() -> str:
|
||||
return random.choice([
|
||||
'你在说啥子?',
|
||||
f'纯洁的{list(get_bot().config.nickname)[0]}没听懂',
|
||||
'下次再告诉你(下次一定)',
|
||||
'你觉得我听懂了吗?嗯?',
|
||||
'我!不!知!道!'
|
||||
]) + image(
|
||||
random.choice(os.listdir(IMAGE_PATH + "noresult/")
|
||||
), "noresult")
|
||||
@ -1,44 +0,0 @@
|
||||
from nonebot import on_request
|
||||
from nonebot.adapters.cqhttp import Bot, FriendRequestEvent, GroupRequestEvent
|
||||
from models.friend_user import FriendUser
|
||||
from datetime import datetime
|
||||
from configs.config import AUTO_ADD_FRIEND
|
||||
from nonebot.adapters.cqhttp.exception import ActionFailed
|
||||
|
||||
__plugin_name__ = '处理请求'
|
||||
|
||||
friend_req = on_request(priority=5)
|
||||
|
||||
|
||||
@friend_req.handle()
|
||||
async def _(bot: Bot, event: FriendRequestEvent, state: dict):
|
||||
if AUTO_ADD_FRIEND:
|
||||
nickname = ''
|
||||
for user in await bot.get_friend_list():
|
||||
if user['user_id'] == event.user_id:
|
||||
nickname = user['nickname']
|
||||
await FriendUser.add_friend_info(user['user_id'], user['nickname'])
|
||||
break
|
||||
await bot.send_private_msg(user_id=int(list(bot.config.superusers)[0]), message=f"{nickname}({event.user_id})"
|
||||
f" 添加小真寻好友(已自动同意)")
|
||||
await bot.set_friend_add_request(flag=event.flag, approve=True)
|
||||
|
||||
|
||||
group_req = on_request(priority=5, block=True)
|
||||
|
||||
|
||||
@group_req.handle()
|
||||
async def _(bot: Bot, event: GroupRequestEvent, state: dict):
|
||||
if event.sub_type == 'invite':
|
||||
nickname = await FriendUser.get_user_name(event.user_id)
|
||||
if str(event.user_id) in bot.config.superusers:
|
||||
try:
|
||||
await bot.set_group_add_request(flag=event.flag, sub_type='invite', approve=True)
|
||||
except ActionFailed:
|
||||
pass
|
||||
else:
|
||||
await bot.send_private_msg(user_id=int(list(bot.config.superusers)[0]),
|
||||
message=f"报告..\n{nickname}({event.user_id})"
|
||||
f" 希望邀请我加入 {event.group_id}\n邀请日期:{str(datetime.now()).split('.')[0]}")
|
||||
await bot.send_private_msg(user_id=event.user_id,
|
||||
message="想要邀请我偷偷入群嘛~~已经提醒管理员了\n等待管理员处理吧~")
|
||||
Binary file not shown.
Binary file not shown.
@ -1,82 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from models.ban_user import BanUser
|
||||
from models.level_user import LevelUser
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.adapters.cqhttp import GroupMessageEvent
|
||||
from nonebot.adapters.cqhttp.permission import GROUP
|
||||
from util.utils import get_message_at, get_message_text, is_number
|
||||
from services.log import logger
|
||||
from models.group_member_info import GroupInfoUser
|
||||
|
||||
|
||||
__plugin_name__ = 'Ban/unBan'
|
||||
__plugin_usage__ = f'用法: 封禁/解封用户(不是禁言!是针对bot是否处理封禁用户消息)\n' \
|
||||
'示例:.ban @djdsk\n' \
|
||||
'示例:.ban @djdsk 0(小时) 30(分钟)\n' \
|
||||
'示例:.ban @sdasf 4(小时)\n' \
|
||||
'示例:.unban @sdasf'
|
||||
|
||||
|
||||
ban = on_command(".ban", aliases={'.unban', '/ban', '/unban'}, priority=5, permission=GROUP, block=True)
|
||||
|
||||
|
||||
@ban.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if get_message_text(event.json()) in ['帮助'] or str(event.get_message()) == '':
|
||||
await ban.finish(__plugin_usage__)
|
||||
# try:
|
||||
result = ''
|
||||
qq = int(get_message_at(event.json())[0])
|
||||
if qq:
|
||||
nickname = await GroupInfoUser.get_group_member_nickname(qq, event.group_id)
|
||||
if not nickname:
|
||||
nickname = '用户'
|
||||
msg = get_message_text(event.json())
|
||||
if msg:
|
||||
msg = msg.split(" ")
|
||||
if len(msg) == 2:
|
||||
if not is_number(msg[0].strip()) or not is_number(msg[1].strip()):
|
||||
await ban.finish('参数必须是数字!', at_sender=True)
|
||||
time = int(msg[0]) * 60 * 60 + int(msg[1]) * 60
|
||||
else:
|
||||
if not is_number(msg[0].strip()):
|
||||
await ban.finish('参数必须是数字!', at_sender=True)
|
||||
time = int(msg[0]) * 60 * 60
|
||||
else:
|
||||
time = -1
|
||||
if state["_prefix"]["raw_command"] in [".ban", '/ban']:
|
||||
if await LevelUser.get_user_level(event.user_id, event.group_id) <= await \
|
||||
LevelUser.get_user_level(qq, event.group_id) and str(event.user_id) not in bot.config.superusers:
|
||||
await ban.finish(f"您的权限等级比对方低或相等, {list(bot.config.nickname)[0]}不能为您使用此功能!", at_sender=True)
|
||||
if await BanUser.ban(qq, await LevelUser.get_user_level(event.user_id, event.group_id), time):
|
||||
logger.info(f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 封禁 时长 {time/60} 分钟")
|
||||
result = f"已经将 {nickname} 加入{list(bot.config.nickname)[0]}的黑名单了!"
|
||||
if time != -1:
|
||||
result += f"将在 {time/60} 分钟后解封"
|
||||
else:
|
||||
time = await BanUser.check_ban_time(qq)
|
||||
if is_number(time):
|
||||
time = abs(time)
|
||||
if time < 60:
|
||||
time = str(int(time)) + ' 秒'
|
||||
else:
|
||||
time = str(int(time / 60)) + ' 分钟'
|
||||
else:
|
||||
time += ' 分钟'
|
||||
result = f"{nickname} 已在黑名单!预计 {time}后解封"
|
||||
else:
|
||||
if await BanUser.check_ban_level(qq, await LevelUser.get_user_level(event.user_id, event.group_id)) and\
|
||||
str(event.user_id) not in bot.config.superusers:
|
||||
await ban.finish(f"ban掉 {nickname} 的管理员权限比您高,无法进行unban", at_sender=True)
|
||||
if await BanUser.unban(qq):
|
||||
logger.info(f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 解禁")
|
||||
result = f"已经把 {nickname} 从黑名单中删除了!"
|
||||
else:
|
||||
result = f"{nickname} 不在黑名单!"
|
||||
else:
|
||||
await ban.finish('艾特人了吗??', at_sender=True)
|
||||
# except Exception as e:
|
||||
# result = 'ban/unban执行出错,确定艾特人了吗?'
|
||||
# logger.error(f'ban/unban执行出错 e:{e}')
|
||||
await ban.finish(result, at_sender=True)
|
||||
Binary file not shown.
Binary file not shown.
@ -1,44 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.permission import SUPERUSER
|
||||
import asyncio
|
||||
from util.utils import get_message_text, get_message_imgs
|
||||
from services.log import logger
|
||||
from models.group_remind import GroupRemind
|
||||
from util.init_result import image
|
||||
|
||||
broadcast = on_command("广播-", priority=1, permission=SUPERUSER, block=True)
|
||||
|
||||
|
||||
@broadcast.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
msg = get_message_text(event.json())
|
||||
imgs = get_message_imgs(event.json())
|
||||
rst = ''
|
||||
for img in imgs:
|
||||
rst += image(img)
|
||||
sid = bot.self_id
|
||||
gl = await bot.get_group_list(self_id=sid)
|
||||
gl = [g['group_id'] for g in gl]
|
||||
for g in gl:
|
||||
if await GroupRemind.get_status(g, 'gb'):
|
||||
await asyncio.sleep(0.5)
|
||||
try:
|
||||
await bot.send_group_msg(self_id=sid, group_id=g, message=msg+rst)
|
||||
logger.info(f'群{g} 投递广播成功')
|
||||
except Exception as e:
|
||||
logger.error(f'群{g} 投递广播失败:{type(e)}')
|
||||
try:
|
||||
await broadcast.send(f'群{g} 投递广播失败:{type(e)}')
|
||||
except Exception as e:
|
||||
logger.critical(f'向广播发起者进行错误回报时发生错误:{type(e)}')
|
||||
await broadcast.send(f'广播完成!')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -1,95 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from .data_source import get_bt_info
|
||||
from services.log import logger
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot
|
||||
from nonebot.adapters.cqhttp import PrivateMessageEvent
|
||||
from util.utils import get_message_text
|
||||
from nonebot.adapters.cqhttp.permission import PRIVATE
|
||||
from util.utils import UserExistLimiter
|
||||
|
||||
__plugin_name__ = '磁力搜索'
|
||||
__plugin_usage__ = r"""
|
||||
* 请各位使用后不要转发 *
|
||||
* 有时可能搜不到,再试一次就行了 *
|
||||
参数: -U(时间) -H(热度) -S(大小)
|
||||
-V(仅视频) -P(仅图片) -A(仅压缩包)
|
||||
-R (R18懂的都懂)
|
||||
num(页数, 如果不知道页数请不要填,并且是倒叙,比如页数总数是29,你想查看第一页的内容, 就使用 bt 29 xxx)
|
||||
-按相关度检索(默认)
|
||||
bt [关键词]
|
||||
-按更新时间检索(参数不区分大小写,但要注意空格)
|
||||
bt -U [关键词]
|
||||
-搜索第10页数
|
||||
bt 10(倒着) [关键词]
|
||||
""".strip()
|
||||
|
||||
_ulmt = UserExistLimiter()
|
||||
|
||||
bt = on_command('bt', permission=PRIVATE, priority=5, block=True)
|
||||
|
||||
|
||||
@bt.args_parser
|
||||
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
|
||||
if str(event.get_message()) in ['取消', '算了']:
|
||||
await bt.finish("已取消操作..", at_sender=True)
|
||||
msg = get_message_text(event.json())
|
||||
if not msg:
|
||||
await bt.reject('你想搜索什么呢?', at_sender=True)
|
||||
mp = msg.split(" ")
|
||||
if len(mp) > 1:
|
||||
args = ''
|
||||
for i in range(len(mp) - 1):
|
||||
args += mp[i] + ' '
|
||||
state['args'] = args
|
||||
state['bt'] = mp[1]
|
||||
else:
|
||||
state['bt'] = get_message_text(event.json())
|
||||
state['args'] = ''
|
||||
|
||||
|
||||
@bt.handle()
|
||||
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
|
||||
if get_message_text(event.json()) in ['帮助'] or str(event.get_message()) == '':
|
||||
await bt.finish(__plugin_usage__)
|
||||
if _ulmt.check(event.user_id):
|
||||
await bt.finish('您有bt任务正在进行,请等待结束.', at_sender=True)
|
||||
mp = get_message_text(event.json()).split(" ")
|
||||
if len(mp) > 1:
|
||||
args = ''
|
||||
for i in range(len(mp) - 1):
|
||||
args += mp[i] + ' '
|
||||
state['args'] = args.strip()
|
||||
state['bt'] = mp[-1]
|
||||
else:
|
||||
state['bt'] = get_message_text(event.json())
|
||||
state['args'] = ''
|
||||
|
||||
|
||||
@bt.got('bt', prompt='虚空磁力?查什么GKD')
|
||||
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
|
||||
_ulmt.set_True(event.user_id)
|
||||
keyword = state['bt']
|
||||
args = state['args']
|
||||
await bt.send('开始搜索....', at_sender=True)
|
||||
try:
|
||||
if args.find('-R') == -1 and args.find('-r') == -1:
|
||||
bt_report = await get_bt_info(keyword, args)
|
||||
else:
|
||||
bt_report = await get_bt_info(keyword, args, '0')
|
||||
if bt_report:
|
||||
if len(bt_report.split("\n")) < 2:
|
||||
await bt.finish(bt_report + '搜索失败了,再试一次也许能成', at_sender=True)
|
||||
else:
|
||||
await bt.send("如果有页数没资源请再试一次\n" + bt_report)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 搜索bt {args} {keyword}")
|
||||
else:
|
||||
logger.error("没查询到资源")
|
||||
await bt.send("没有查询到资源(也有可能是超时,再试一次?)", at_sender=True)
|
||||
_ulmt.set_False(event.user_id)
|
||||
except Exception as e:
|
||||
_ulmt.set_False(event.user_id)
|
||||
await bt.send("bt出错啦,再试一次?", at_sender=True)
|
||||
logger.info(f'bt {keyword} 出错 e:{e}')
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,96 +0,0 @@
|
||||
from util.user_agent import get_user_agent
|
||||
import aiohttp
|
||||
from lxml import etree
|
||||
from lxml.etree import Element
|
||||
from configs.config import MAXINFO_BT
|
||||
from urllib import parse
|
||||
from html import unescape
|
||||
from util.utils import get_local_proxy, is_number
|
||||
import time
|
||||
import platform
|
||||
if platform.system() == 'Windows':
|
||||
import asyncio
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
url = 'https://www.btmet.com/search.php'
|
||||
|
||||
|
||||
async def get_bt_info(keyword: str, args: str, r18: str = '1') -> str:
|
||||
cookiesDit = {
|
||||
'r18': r18
|
||||
}
|
||||
s_time = time.time()
|
||||
params = get_params(keyword, args)
|
||||
async with aiohttp.ClientSession(headers=get_user_agent(), cookies=cookiesDit) as session:
|
||||
async with session.get(url, proxy=get_local_proxy(), params=params, timeout=30) as response:
|
||||
html = etree.HTML(await response.text())
|
||||
print(response.url)
|
||||
num = html.xpath('//div[@id="wall"]//span/b/text()')[0]
|
||||
print(num)
|
||||
if num.find(",") != -1:
|
||||
num = num.split(',')[0]
|
||||
if num == '0':
|
||||
return "没有找到记录"
|
||||
|
||||
div_all = html.xpath('//div[@class="search-item"]')[1:]
|
||||
div_all = div_all[:MAXINFO_BT] if len(div_all) > MAXINFO_BT else div_all
|
||||
line_list = [await get_item_line(div) for div in div_all]
|
||||
clist = []
|
||||
for line in line_list:
|
||||
if line.strip() != '':
|
||||
clist.append(line)
|
||||
|
||||
return f"搜索 {keyword} 结果(共 {int(int(num.text) / 10) if int(num) % 10 == 0 else int(int(num) / 10) + 1} " \
|
||||
f"页)(耗时 {int(time.time() - s_time)} 秒):\n" + "\n\n".join(clist)
|
||||
|
||||
|
||||
async def get_item_line(div: Element) -> str:
|
||||
try:
|
||||
magent = div.xpath('./div[2]/a/@href')[0]
|
||||
size = div.xpath('./div[@class="f_left"]/div[@class="item-bar"]/span/b/font/text()')[0]
|
||||
type = div.xpath('./div[@class="f_left"]/div[@class="item-bar"]/span[@class="cpill blue-pill"]/text()')[0].strip()
|
||||
|
||||
title_doc = div.xpath('.//a[@class="smashTitle"]//text()')[0]
|
||||
title_code = title_doc[title_doc.find('("') + 2: title_doc.find('")')]
|
||||
title_xml_code = parse.unquote(title_code)
|
||||
title_xml = etree.HTML(unescape(title_xml_code))
|
||||
title = title_xml.xpath('string(.)')
|
||||
except Exception:
|
||||
return ''
|
||||
return "【{}】| {}\n【{}】| {}".format(type, title, size, magent)
|
||||
|
||||
|
||||
# https://www.btmet.com/search.php?q=%E9%92%A2%E9%93%81%E4%BE%A0&c=5&o=0&l=&p=2
|
||||
def get_params(keyword: str, args: str) -> dict:
|
||||
params = {
|
||||
'q': keyword,
|
||||
'c': '',
|
||||
'l': '',
|
||||
'o': 0,
|
||||
'p': ''
|
||||
}
|
||||
if not args:
|
||||
return params
|
||||
args = args.split(" ")
|
||||
for arg in args:
|
||||
if '-U' == arg.upper():
|
||||
params['o'] = 1
|
||||
if '-S' == arg.upper():
|
||||
params['o'] = 2
|
||||
if '-H' == arg.upper():
|
||||
params['o'] = 3
|
||||
if '-V' == arg.upper():
|
||||
params['c'] = 1
|
||||
if '-P' == arg.upper():
|
||||
params['c'] = 2
|
||||
if '-A' == arg.upper():
|
||||
params['c'] = 5
|
||||
if is_number(arg):
|
||||
params['p'] = arg
|
||||
return params
|
||||
|
||||
|
||||
# print(asyncio.get_event_loop().run_until_complete(get_bt_info('钢铁侠', '')))
|
||||
|
||||
|
||||
@ -1,20 +0,0 @@
|
||||
|
||||
from nonebot import on_command
|
||||
from .data_source import Check
|
||||
from nonebot.adapters.cqhttp import Bot, Event
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.permission import SUPERUSER
|
||||
|
||||
|
||||
__plugin_name__ = '自我检查'
|
||||
|
||||
check = Check()
|
||||
|
||||
|
||||
check_ = on_command('自检', aliases={'check'}, rule=to_me(), permission=SUPERUSER, block=True, priority=1)
|
||||
|
||||
|
||||
@check_.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
await check_.send(await check.show())
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,67 +0,0 @@
|
||||
import psutil
|
||||
import aiohttp
|
||||
import time
|
||||
from datetime import datetime
|
||||
from util.user_agent import get_user_agent
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from aiohttp.client_exceptions import ClientConnectorError
|
||||
from util.utils import get_local_proxy
|
||||
import asyncio
|
||||
from services.log import logger
|
||||
|
||||
|
||||
class Check:
|
||||
def __init__(self):
|
||||
self.cpu = None
|
||||
self.memory = None
|
||||
self.disk = None
|
||||
self.user = None
|
||||
self.baidu = 200
|
||||
self.google = 200
|
||||
|
||||
async def check_all(self):
|
||||
await self.check_network()
|
||||
await asyncio.sleep(0.1)
|
||||
self.check_system()
|
||||
self.check_user()
|
||||
|
||||
def check_system(self):
|
||||
self.cpu = psutil.cpu_percent()
|
||||
self.memory = psutil.virtual_memory().percent
|
||||
self.disk = psutil.disk_usage("/").percent
|
||||
|
||||
async def check_network(self):
|
||||
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
|
||||
try:
|
||||
async with session.get('https://www.baidu.com/', proxy=get_local_proxy(), timeout=3) as response:
|
||||
pass
|
||||
except (TimeoutError, ClientConnectorError) as e:
|
||||
logger.warning(f'访问BaiDu失败... e: {e}')
|
||||
self.baidu = 404
|
||||
try:
|
||||
async with session.get('https://www.google.com/', proxy=get_local_proxy(), timeout=3) as response:
|
||||
pass
|
||||
except (TimeoutError, ClientConnectorError) as e:
|
||||
logger.warning(f'访问Google失败... e: {e}')
|
||||
self.google = 404
|
||||
|
||||
def check_user(self):
|
||||
rst = ''
|
||||
for user in psutil.users():
|
||||
rst += f'[{user.name}] {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.started))}\n'
|
||||
self.user = rst[:-1]
|
||||
|
||||
async def show(self):
|
||||
await self.check_all()
|
||||
rst = f'[Time] {str(datetime.now()).split(".")[0]}\n' \
|
||||
f'-----System-----\n' \
|
||||
f'[CPU] {self.cpu}%\n' \
|
||||
f'[Memory] {self.memory}%\n' \
|
||||
f'[Disk] {self.disk}%\n' \
|
||||
f'-----Network-----\n' \
|
||||
f'[BaiDu] {self.baidu}\n' \
|
||||
f'[Google] {self.google}\n'
|
||||
if self.user:
|
||||
rst += '-----User-----\n' + self.user
|
||||
return rst
|
||||
|
||||
@ -1,39 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from util.utils import get_message_text
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from services.log import logger
|
||||
from util.init_result import image
|
||||
import requests
|
||||
|
||||
__plugin_usage_coser__ = '不得看看可爱的coser?发送‘coser’'
|
||||
|
||||
|
||||
coser = on_command('cos', aliases={'coser', '括丝'}, priority=5, block=True)
|
||||
|
||||
|
||||
url_2 = 'http://api.rosysun.cn/cos'
|
||||
|
||||
|
||||
@coser.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
if get_message_text(event.json()) in ['帮助']:
|
||||
await coser.finish(__plugin_usage_coser__)
|
||||
img_url = requests.get(url_2).text
|
||||
await coser.send(image(img_url))
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'}) 发送COSER")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -1,79 +0,0 @@
|
||||
from configs.path_config import IMAGE_PATH, TEMP_PATH
|
||||
import os
|
||||
from util.init_result import image
|
||||
from services.log import logger
|
||||
from nonebot import on_command
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from configs.config import IMAGE_DIR_LIST
|
||||
from util.utils import is_number, cn2py
|
||||
|
||||
__plugin_name__ = '删除图片'
|
||||
__plugin_usage__ = '删除图片帮助:\n\t' \
|
||||
'1.查看列表 --> 指令: 删除图片 列表/目录\n\t' \
|
||||
'2.删除图片 图库 id, 即在相应目录下删除图片\n\t\t示例: 删除图片 色图 1 '
|
||||
|
||||
|
||||
delete_img = on_command("删除图片", priority=5, rule=to_me(), block=True)
|
||||
|
||||
|
||||
@delete_img.args_parser
|
||||
async def parse(bot: Bot, event: Event, state: T_State):
|
||||
if str(event.get_message()) in ['取消', '算了']:
|
||||
await delete_img.finish("已取消操作..", at_sender=True)
|
||||
if state["_current_key"] in ['path']:
|
||||
if str(event.get_message()) not in IMAGE_DIR_LIST:
|
||||
await delete_img.reject("此目录不正确,请重新输入目录!")
|
||||
state[state["_current_key"]] = str(event.get_message())
|
||||
if state["_current_key"] == 'id':
|
||||
if not is_number(str(event.get_message())):
|
||||
await delete_img.reject("id不正确!请重新输入数字...")
|
||||
state[state["_current_key"]] = str(event.get_message())
|
||||
|
||||
|
||||
@delete_img.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
raw_arg = str(event.get_message()).strip()
|
||||
if raw_arg:
|
||||
args = raw_arg.split(" ")
|
||||
if args[0] in ['帮助']:
|
||||
await delete_img.finish(__plugin_usage__)
|
||||
if len(args) >= 2 and args[0] in IMAGE_DIR_LIST and is_number(args[1]):
|
||||
state['path'] = args[0]
|
||||
state['id'] = args[1]
|
||||
|
||||
|
||||
@delete_img.got("path", prompt="请输入要删除的目标图库?")
|
||||
@delete_img.got("id", prompt="请输入要删除的图片id?")
|
||||
async def arg_handle(bot: Bot, event: Event, state: T_State):
|
||||
path = cn2py(state['path'])
|
||||
img_id = state['id']
|
||||
path = IMAGE_PATH + path
|
||||
max_id = len(os.listdir(path)) - 1
|
||||
if int(img_id) > max_id or int(img_id) < 0:
|
||||
await delete_img.finish(f"Id超过上下限,上限:{max_id}", at_sender=True)
|
||||
try:
|
||||
if os.path.exists(IMAGE_PATH + TEMP_PATH + "delete.jpg"):
|
||||
os.remove(IMAGE_PATH + TEMP_PATH + "delete.jpg")
|
||||
logger.info("删除图片 delete.jpg 成功")
|
||||
except Exception as e:
|
||||
logger.warning(f"删除图片 delete.jpg 失败 e{e}")
|
||||
try:
|
||||
os.rename(path + img_id + ".jpg", IMAGE_PATH + TEMP_PATH + "delete.jpg")
|
||||
logger.info(f"移动 {path}{img_id}.jpg 移动成功")
|
||||
except Exception as e:
|
||||
logger.warning(f"{path}{img_id}.jpg --> 移动失败 e:{e}")
|
||||
if not os.path.exists(path + img_id + ".jpg"):
|
||||
try:
|
||||
if int(img_id) != max_id:
|
||||
os.rename(path + str(max_id) + ".jpg", path + img_id + ".jpg")
|
||||
except FileExistsError:
|
||||
logger.error(f"{path}{max_id}.jpg 替换 {path}{img_id}.jpg 失败 e:{e}")
|
||||
logger.info(f"{path}{max_id}.jpg 替换 {path}{img_id}.jpg 成功")
|
||||
logger.info(f"USER {event.user_id} GROUP {event.group_id if event.message_type != 'private' else 'private'}"
|
||||
f" -> id: {img_id} 删除成功")
|
||||
await delete_img.finish(f"id: {img_id} 删除成功" + image("delete.jpg", TEMP_PATH), at_sender=True)
|
||||
await delete_img.finish(f"id: {img_id} 删除失败!")
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -1,54 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.permission import SUPERUSER
|
||||
from util.utils import get_message_text, is_number
|
||||
from services.log import logger
|
||||
from util.init_result import at
|
||||
|
||||
|
||||
__plugin_name__ = '联系管理员'
|
||||
__plugin_usage__ = '滴滴滴- 后接内容 联系管理员'
|
||||
|
||||
|
||||
dialogue = on_command("[滴滴滴]", aliases={"滴滴滴-"}, priority=1, block=True)
|
||||
reply = on_command("/t", priority=1, permission=SUPERUSER, block=True)
|
||||
|
||||
|
||||
@dialogue.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
uid = event.user_id
|
||||
coffee = int(list(bot.config.superusers)[0])
|
||||
text = get_message_text(event.json())
|
||||
if not text or text in ['帮助']:
|
||||
await dialogue.send("请发送[滴滴滴]+您要说的内容~", at_sender=True)
|
||||
else:
|
||||
if event.get_event_name() == "message.private.friend":
|
||||
group_id = ""
|
||||
else:
|
||||
group_id = event.group_id
|
||||
await bot.send_private_msg(user_id=coffee, message=f'Q{uid}@群{group_id}\n{text}')
|
||||
await dialogue.send(f'您的话已发送至管理员!\n======\n{text}', at_sender=True)
|
||||
logger.info(f"Q{uid}@群{group_id} 联系管理员:{coffee} text:{text}")
|
||||
|
||||
|
||||
@reply.handle()
|
||||
async def _(bot: Bot, event: Event, state: T_State):
|
||||
if get_message_text(event.json()) in ['帮助']:
|
||||
await reply.finish(f'/t qq group text')
|
||||
msg = get_message_text(event.json()).split(" ")
|
||||
user_id = int(msg[0])
|
||||
if is_number(msg[1]) and len(msg[1]) > 5:
|
||||
group_id = int(msg[1])
|
||||
text = msg[2]
|
||||
else:
|
||||
group_id = ""
|
||||
text = msg[1]
|
||||
if group_id:
|
||||
await bot.send_group_msg(group_id=group_id, message=at(user_id) + "\n管理员回复\n=======\n" + text)
|
||||
else:
|
||||
if user_id in [qq['user_id'] for qq in await bot.get_friend_list()]:
|
||||
await bot.send_private_msg(user_id=user_id, message="管理员回复\n=======\n" + text)
|
||||
await reply.finish("发送成功", at_sender=True)
|
||||
else:
|
||||
await reply.send(f"对象不是{list(bot.config.nickname)[0]}的好友...", at_sender=True)
|
||||
Binary file not shown.
Binary file not shown.
@ -1,174 +0,0 @@
|
||||
from nonebot import on_regex, on_keyword
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.typing import T_State
|
||||
from .genshin_handle import genshin_draw, update_genshin_info, reset_count
|
||||
from .prts_handle import update_prts_info, prts_draw, reload_pool
|
||||
from .pretty_handle import update_pretty_info, pretty_draw
|
||||
from .update_game_info import update_info
|
||||
from util.utils import is_number, scheduler
|
||||
from services.log import logger
|
||||
import re
|
||||
|
||||
|
||||
prts = on_regex(r'.*?方舟[1-9|一][0-9]{0,2}[抽|井]', priority=5, block=True)
|
||||
prts_update = on_keyword({'更新方舟信息', '更新明日方舟信息'}, permission=SUPERUSER, priority=1, block=True)
|
||||
prts_reload = on_keyword({'重载方舟卡池'}, priority=1, block=True)
|
||||
|
||||
genshin = on_regex('.*?原神[1-9|一][0-9]{0,2}[抽|井]', priority=5, block=True)
|
||||
genshin_reset = on_keyword({'重置原神抽卡'}, priority=1, block=True)
|
||||
genshin_update = on_keyword({'更新原神信息'}, permission=SUPERUSER, priority=1, block=True)
|
||||
|
||||
pretty = on_regex('.*?马娘卡?[1-9|一][0-9]{0,2}[抽|井]', priority=5, block=True)
|
||||
pretty_update = on_keyword({'更新马娘信息', '更新赛马娘信息'}, permission=SUPERUSER, priority=1, block=True)
|
||||
|
||||
|
||||
@prts.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
msg = str(event.get_message()).strip()
|
||||
if msg in ['方舟一井', '方舟1井']:
|
||||
num = 300
|
||||
else:
|
||||
rmsg = re.search(r'.*?方舟(.*)抽', msg)
|
||||
if rmsg and is_number(rmsg.group(1)):
|
||||
try:
|
||||
num = int(rmsg.group(1))
|
||||
except ValueError:
|
||||
await prts.finish('必!须!是!数!字!', at_sender=True)
|
||||
if num > 300:
|
||||
await prts.finish('一井都满不足不了你嘛!快爬开!', at_sender=True)
|
||||
if num < 1:
|
||||
await prts.finish('虚空抽卡???', at_sender=True)
|
||||
else:
|
||||
return
|
||||
# print(num)
|
||||
await prts.send(await prts_draw(num), at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 方舟{num}抽")
|
||||
|
||||
|
||||
@prts_reload.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await reload_pool()
|
||||
await prts_reload.finish('重载完成!')
|
||||
|
||||
|
||||
@genshin.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
msg = str(event.get_message()).strip()
|
||||
if msg in ['原神一井', '原神1井']:
|
||||
num = 180
|
||||
else:
|
||||
rmsg = re.search(r'.*?原神(.*)抽', msg)
|
||||
if rmsg and is_number(rmsg.group(1)):
|
||||
try:
|
||||
num = int(rmsg.group(1))
|
||||
except ValueError:
|
||||
await genshin.finish('必!须!是!数!字!', at_sender=True)
|
||||
if num > 300:
|
||||
await genshin.finish('一井都满不足不了你嘛!快爬开!', at_sender=True)
|
||||
if num < 1:
|
||||
await genshin.finish('虚空抽卡???', at_sender=True)
|
||||
else:
|
||||
return
|
||||
await genshin.send(await genshin_draw(event.user_id, num), at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 原神{num}抽")
|
||||
|
||||
|
||||
@genshin_reset.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
reset_count(event.user_id)
|
||||
await genshin_reset.send('重置了原神抽卡次数', at_sender=True)
|
||||
|
||||
|
||||
@pretty.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
msg = str(event.get_message()).strip()
|
||||
if msg in ['赛马娘一井', '赛马娘1井', '马娘一井', '马娘1井', '赛马娘卡一井', '赛马娘卡1井', '马娘卡一井', '马娘卡1井']:
|
||||
num = 200
|
||||
if msg.find("卡") == -1:
|
||||
pool_name = 'horse'
|
||||
else:
|
||||
pool_name = 'card'
|
||||
else:
|
||||
rmsg = re.search(r'.*?马娘(.*)抽', msg)
|
||||
if rmsg:
|
||||
num = rmsg.group(1)
|
||||
if num[0] == '卡':
|
||||
num = num[1:]
|
||||
pool_name = 'card'
|
||||
else:
|
||||
pool_name = 'horse'
|
||||
if is_number(num):
|
||||
try:
|
||||
num = int(num)
|
||||
except ValueError:
|
||||
await genshin.finish('必!须!是!数!字!', at_sender=True)
|
||||
if num > 200:
|
||||
await genshin.finish('一井都满不足不了你嘛!快爬开!', at_sender=True)
|
||||
if num < 1:
|
||||
await genshin.finish('虚空抽卡???', at_sender=True)
|
||||
else:
|
||||
return
|
||||
await pretty.send(await pretty_draw(num, pool_name), at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 赛马娘{num}抽")
|
||||
|
||||
|
||||
@prts_update.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await update_prts_info()
|
||||
await reload_pool()
|
||||
await prts_update.finish('更新完成!')
|
||||
|
||||
|
||||
@genshin_update.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await update_genshin_info()
|
||||
await genshin_update.finish('更新完成!')
|
||||
|
||||
|
||||
@pretty_update.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await update_pretty_info()
|
||||
await genshin_update.finish('更新完成!')
|
||||
|
||||
|
||||
# 更新资源
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=4,
|
||||
minute=1,
|
||||
)
|
||||
async def _():
|
||||
try:
|
||||
await update_prts_info()
|
||||
logger.info('自动更新明日方舟信息')
|
||||
except Exception as e:
|
||||
logger.error(f'自动更新明日方舟信息出错 e:{e}')
|
||||
try:
|
||||
await update_genshin_info()
|
||||
logger.info('自动更新原神信息')
|
||||
except Exception as e:
|
||||
logger.error(f'自动更新原神信息出错 e:{e}')
|
||||
try:
|
||||
await update_pretty_info()
|
||||
logger.info('自动更新赛马娘信息')
|
||||
except Exception as e:
|
||||
logger.error(f'自动更新赛马娘信息出错 e:{e}')
|
||||
|
||||
|
||||
# 每天四点重载up卡池
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=4,
|
||||
minute=1,
|
||||
)
|
||||
async def _():
|
||||
await reload_pool()
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,119 +0,0 @@
|
||||
import aiohttp
|
||||
from bs4 import BeautifulSoup
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from configs.path_config import DRAW_PATH
|
||||
from util.user_agent import get_user_agent
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
up_char_file = Path(DRAW_PATH) / "draw_card_up" / "prts_up_char.json"
|
||||
|
||||
prts_url = "https://wiki.biligame.com/arknights/%E6%96%B0%E9%97%BB%E5%85%AC%E5%91%8A"
|
||||
|
||||
|
||||
def _get_up_char(r: str, text: str):
|
||||
pr = re.search(r, text)
|
||||
chars = pr.group(1)
|
||||
probability = pr.group(2)
|
||||
chars = chars.replace('[限定]', '').replace('[', '').replace(']', '')
|
||||
probability = probability.replace('【', '')
|
||||
return chars, probability
|
||||
|
||||
|
||||
class PrtsAnnouncement:
|
||||
|
||||
@staticmethod
|
||||
async def get_announcement_text():
|
||||
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
|
||||
async with session.get(prts_url, timeout=7) as res:
|
||||
soup = BeautifulSoup(await res.text(), 'lxml')
|
||||
trs = soup.find('table').find('tbody').find_all('tr')
|
||||
for tr in trs:
|
||||
a = tr.find_all('td')[-1].find('a')
|
||||
if a.text.find('寻访') != -1:
|
||||
url = a.get('href')
|
||||
break
|
||||
async with session.get(f'https://wiki.biligame.com/{url}', timeout=7) as res:
|
||||
return await res.text(), a.text[:-4]
|
||||
|
||||
@staticmethod
|
||||
async def update_up_char():
|
||||
up_char_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = {'up_char': {'6': {}, '5': {}, '4': {}}, 'title': '', 'time': ''}
|
||||
text, title = await PrtsAnnouncement.get_announcement_text()
|
||||
soup = BeautifulSoup(text, 'lxml')
|
||||
data['title'] = title
|
||||
context = soup.find('div', {'id': 'mw-content-text'}).find('div')
|
||||
data['pool_img'] = str(context.find('div', {'class': 'center'}).find('div').find('a').
|
||||
find('img').get('srcset')).split(' ')[-2]
|
||||
# print(context.find_all('p'))
|
||||
for p in context.find_all('p')[1:]:
|
||||
if p.text.find('活动时间') != -1:
|
||||
pr = re.search(r'.*?活动时间:(.*)', p.text)
|
||||
data['time'] = pr.group(1)
|
||||
elif p.text.find('★★★★★★') != -1:
|
||||
chars, probability = _get_up_char(r'.*?★★★★★★:(.*?)(.*?出率的?(.*?)%.*?).*?', p.text)
|
||||
slt = '/'
|
||||
if chars.find('\\') != -1:
|
||||
slt = '\\'
|
||||
for char in chars.split(slt):
|
||||
data['up_char']['6'][char.strip()] = probability.strip()
|
||||
elif p.text.find('★★★★★') != -1:
|
||||
chars, probability = _get_up_char(r'.*?★★★★★:(.*?)(.*?出率的?(.*?)%.*?).*?', p.text)
|
||||
slt = '/'
|
||||
if chars.find('\\') != -1:
|
||||
slt = '\\'
|
||||
for char in chars.split(slt):
|
||||
data['up_char']['5'][char.strip()] = probability.strip()
|
||||
elif p.text.find('★★★★') != -1:
|
||||
chars, probability = _get_up_char(r'.*?★★★★:(.*?)(.*?出率的?(.*?)%.*?).*?', p.text)
|
||||
slt = '/'
|
||||
if chars.find('\\') != -1:
|
||||
slt = '\\'
|
||||
for char in chars.split(slt):
|
||||
data['up_char']['4'][char.strip()] = probability.strip()
|
||||
break
|
||||
pr = re.search(r'.*?★:(.*?)(在(.*?)★.*?以(.*?)倍权值.*?).*?', p.text)
|
||||
if pr:
|
||||
char = pr.group(1)
|
||||
star = pr.group(2)
|
||||
weight = pr.group(3)
|
||||
char = char.replace('[限定]', '').replace('[', '').replace(']', '')
|
||||
data['up_char'][star][char.strip()] = f'权{weight}'
|
||||
# data['time'] = '03月09日16:00 - 05月23日03:59'
|
||||
if not is_expired(data):
|
||||
data['title'] = ''
|
||||
else:
|
||||
with open(up_char_file, 'w', encoding='utf8') as f:
|
||||
json.dump(data, f, indent=4, ensure_ascii=False)
|
||||
if not up_char_file.exists():
|
||||
with open(up_char_file, 'w', encoding='utf8') as f:
|
||||
json.dump(data, f, indent=4, ensure_ascii=False)
|
||||
else:
|
||||
with open(up_char_file, 'r', encoding='utf8') as f:
|
||||
old_data = json.load(f)
|
||||
if is_expired(old_data):
|
||||
return old_data
|
||||
else:
|
||||
with open(up_char_file, 'w', encoding='utf8') as f:
|
||||
json.dump(data, f, indent=4, ensure_ascii=False)
|
||||
return data
|
||||
|
||||
|
||||
# 是否过时
|
||||
def is_expired(data: dict):
|
||||
times = data['time'].split('-')
|
||||
for i in range(len(times)):
|
||||
times[i] = str(datetime.now().year) + '-' + times[i].split('日')[0].strip().replace('月', '-')
|
||||
start_date = datetime.strptime(times[0], '%Y-%m-%d').date()
|
||||
end_date = datetime.strptime(times[1], '%Y-%m-%d').date()
|
||||
now = datetime.now().date()
|
||||
return start_date < now < end_date
|
||||
|
||||
# ad = Announcement('https://wiki.biligame.com/arknights/%E6%96%B0%E9%97%BB%E5%85%AC%E5%91%8A')
|
||||
# asyncio.get_event_loop().run_until_complete(check_up_char('prts'))
|
||||
@ -1,104 +0,0 @@
|
||||
import nonebot
|
||||
from pathlib import Path
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
# 方舟概率
|
||||
PRTS_SIX_P = 0.02
|
||||
PRTS_FIVE_P = 0.08
|
||||
PRTS_FOUR_P = 0.48
|
||||
PRTS_THREE_P = 0.42
|
||||
|
||||
# 原神概率
|
||||
GENSHIN_FIVE_P = 0.006
|
||||
GENSHIN_FOUR_P = 0.051
|
||||
GENSHIN_THREE_P = 0.43
|
||||
GENSHIN_G_FOUR_P = 0.13
|
||||
GENSHIN_G_FIVE_P = 0.016
|
||||
I72_ADD = 0.0585
|
||||
|
||||
# 赛马娘概率
|
||||
PRETTY_THREE = 0.03
|
||||
PRETTY_TWO = 0.18
|
||||
PRETTY_ONE = 0.79
|
||||
|
||||
path_dict = {
|
||||
'genshin': '原神',
|
||||
'prts': '明日方舟',
|
||||
'pretty': '赛马娘',
|
||||
}
|
||||
|
||||
|
||||
_draw_config = Path() / "data" / "draw_card" / "draw_card_config" / "draw_card_config.json"
|
||||
|
||||
|
||||
driver: nonebot.Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
def check_config():
|
||||
global PRTS_SIX_P, PRTS_FOUR_P, PRTS_FIVE_P, PRTS_THREE_P, GENSHIN_G_FIVE_P, \
|
||||
GENSHIN_G_FOUR_P, GENSHIN_FOUR_P, GENSHIN_FIVE_P, I72_ADD, path_dict, PRETTY_THREE, \
|
||||
PRETTY_ONE, PRETTY_TWO, GENSHIN_THREE_P
|
||||
if _draw_config.exists():
|
||||
data = json.load(open(_draw_config, 'r', encoding='utf8'))
|
||||
PRTS_SIX_P = float(data['prts']['six'])
|
||||
PRTS_FIVE_P = float(data['prts']['five'])
|
||||
PRTS_FOUR_P = float(data['prts']['four'])
|
||||
PRTS_THREE_P = float(data['prts']['three'])
|
||||
|
||||
GENSHIN_FIVE_P = float(data['genshin']['five_char'])
|
||||
GENSHIN_FOUR_P = float(data['genshin']['four_char'])
|
||||
GENSHIN_THREE_P = float(data['genshin']['three_char'])
|
||||
GENSHIN_G_FIVE_P = float(data['genshin']['five_weapon'])
|
||||
GENSHIN_G_FOUR_P = float(data['genshin']['four_weapon'])
|
||||
I72_ADD = float(data['genshin']['72_add'])
|
||||
|
||||
PRETTY_THREE = float(data['pretty']['three'])
|
||||
PRETTY_TWO = float(data['pretty']['two'])
|
||||
PRETTY_ONE = float(data['pretty']['one'])
|
||||
|
||||
path_dict = data['path_dict']
|
||||
else:
|
||||
_draw_config.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_dict = {
|
||||
'path_dict': {
|
||||
'genshin': '原神',
|
||||
'prts': '明日方舟',
|
||||
'pretty': '赛马娘',
|
||||
},
|
||||
|
||||
'prts': {
|
||||
'six': 0.02,
|
||||
'five': 0.08,
|
||||
'four': 0.48,
|
||||
'three': 0.42,
|
||||
},
|
||||
|
||||
'genshin': {
|
||||
'five_char': 0.006,
|
||||
'four_char': 0.051,
|
||||
'three_char': 0.43,
|
||||
'five_weapon': 0.13,
|
||||
'four_weapon': 0.016,
|
||||
'72_add': 0.0585,
|
||||
},
|
||||
|
||||
'pretty': {
|
||||
'three': 0.03,
|
||||
'two': 0.18,
|
||||
'one': 0.79,
|
||||
}
|
||||
}
|
||||
json.dump(config_dict, open(_draw_config, 'w', encoding='utf8'), indent=4, ensure_ascii=False)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,149 +0,0 @@
|
||||
|
||||
import os
|
||||
import nonebot
|
||||
import random
|
||||
from .update_game_info import update_info
|
||||
from .util import generate_img, init_star_rst, BaseData, set_list
|
||||
from .config import GENSHIN_FIVE_P, GENSHIN_FOUR_P, GENSHIN_G_FIVE_P, GENSHIN_THREE_P, I72_ADD
|
||||
from dataclasses import dataclass
|
||||
from .init_card_pool import init_game_pool
|
||||
from configs.path_config import DRAW_PATH
|
||||
from util.init_result import image
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
driver: nonebot.Driver = nonebot.get_driver()
|
||||
|
||||
genshin_five = {}
|
||||
genshin_count = {}
|
||||
genshin_pl_count = {}
|
||||
|
||||
ALL_CHAR = []
|
||||
ALL_ARM = []
|
||||
|
||||
|
||||
@dataclass
|
||||
class GenshinChar(BaseData):
|
||||
pass
|
||||
|
||||
|
||||
async def genshin_draw(user_id: int, count: int):
|
||||
# 0 1 2
|
||||
cnlist = ['★★★★★', '★★★★', '★★★']
|
||||
genshin_list, five_list, five_olist, five_dict, star_list = _format_card_information(count, user_id)
|
||||
rst = init_star_rst(star_list, cnlist, five_list, five_olist)
|
||||
print(five_list)
|
||||
temp = ''
|
||||
if count > 90:
|
||||
genshin_list = set_list(genshin_list)
|
||||
return image(b64=await generate_img(genshin_list, 'genshin', star_list)) + '\n' + rst[:-1] + \
|
||||
temp[:-1] + f'\n距离保底发还剩 {90 - genshin_count[user_id] if genshin_count.get(user_id) else "^"} 抽' \
|
||||
+ "\n【五星:0.6%,四星:5.1%\n第72抽开始五星概率每抽加0.585%】"
|
||||
|
||||
|
||||
async def update_genshin_info():
|
||||
global ALL_CHAR, ALL_ARM
|
||||
url = 'https://wiki.biligame.com/ys/角色筛选'
|
||||
data, code = await update_info(url, 'genshin')
|
||||
if code == 200:
|
||||
ALL_CHAR = init_game_pool('genshin', data, GenshinChar)
|
||||
url = 'https://wiki.biligame.com/ys/武器图鉴'
|
||||
data, code = await update_info(url, 'genshin_arm', ['头像', '名称', '类型', '稀有度.alt', '初始基础属性1',
|
||||
'初始基础属性2', '攻击力(MAX)', '副属性(MAX)', '技能'])
|
||||
if code == 200:
|
||||
ALL_ARM = init_game_pool('genshin', data, GenshinChar)
|
||||
|
||||
|
||||
# asyncio.get_event_loop().run_until_complete(update_genshin_info())
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def init_data():
|
||||
global ALL_CHAR, ALL_ARM
|
||||
if not os.path.exists(DRAW_PATH + '/draw_card_config/genshin.json') or \
|
||||
not os.path.exists(DRAW_PATH + '/draw_card_config/genshin_arm.json'):
|
||||
await update_genshin_info()
|
||||
else:
|
||||
with open(DRAW_PATH + '/draw_card_config/genshin.json', 'r', encoding='utf8') as f:
|
||||
genshin_dict = json.load(f)
|
||||
with open(DRAW_PATH + '/draw_card_config/genshin_arm.json', 'r', encoding='utf8') as f:
|
||||
genshin_arm_dict = json.load(f)
|
||||
ALL_CHAR = init_game_pool('genshin', genshin_dict, GenshinChar)
|
||||
ALL_ARM = init_game_pool('genshin', genshin_arm_dict, GenshinChar)
|
||||
|
||||
|
||||
# 抽取卡池
|
||||
def _get_genshin_card(mode: int = 1, add: float = 0.0):
|
||||
global ALL_ARM, ALL_CHAR
|
||||
if mode == 1:
|
||||
star = random.sample([5, 4, 3],
|
||||
counts=[int(GENSHIN_FIVE_P * 1000) + int(add * 1000), int(GENSHIN_FOUR_P * 1000),
|
||||
int(GENSHIN_THREE_P * 1000)],
|
||||
k=1)[0]
|
||||
elif mode == 2:
|
||||
star = random.sample([5, 4],
|
||||
counts=[int(GENSHIN_G_FIVE_P * 1000) + int(add * 1000), int(GENSHIN_FOUR_P * 1000)],
|
||||
k=1)[0]
|
||||
else:
|
||||
star = 5
|
||||
chars = [x for x in (ALL_ARM if random.random() < 0.5 or star == 3 else ALL_CHAR) if x.star == star]
|
||||
return random.choice(chars), abs(star - 5)
|
||||
|
||||
|
||||
def _format_card_information(_count: int, user_id):
|
||||
genshin_list = []
|
||||
star_list = [0, 0, 0]
|
||||
five_index_list = []
|
||||
five_list = []
|
||||
five_dict = {}
|
||||
add = 0.0
|
||||
if genshin_count.get(user_id) and _count <= 90:
|
||||
f_count = genshin_count[user_id]
|
||||
else:
|
||||
f_count = 0
|
||||
if genshin_pl_count.get(user_id) and _count <= 90:
|
||||
count = genshin_pl_count[user_id]
|
||||
else:
|
||||
count = 0
|
||||
for i in range(_count):
|
||||
count += 1
|
||||
f_count += 1
|
||||
# 十连保底
|
||||
if count == 10 and f_count != 90:
|
||||
if f_count >= 72:
|
||||
add += I72_ADD
|
||||
char, code = _get_genshin_card(2, add)
|
||||
count = 0
|
||||
# 大保底
|
||||
elif f_count == 90:
|
||||
char, code = _get_genshin_card(3)
|
||||
else:
|
||||
if f_count >= 72:
|
||||
add += I72_ADD
|
||||
char, code = _get_genshin_card(add=add)
|
||||
if code == 1:
|
||||
count = 0
|
||||
star_list[code] += 1
|
||||
if code == 0:
|
||||
if _count <= 90:
|
||||
genshin_five[user_id] = f_count
|
||||
add = 0.0
|
||||
f_count = 0
|
||||
five_list.append(char.name)
|
||||
five_index_list.append(i)
|
||||
try:
|
||||
five_dict[char.name] += 1
|
||||
except KeyError:
|
||||
five_dict[char.name] = 1
|
||||
genshin_list.append(char)
|
||||
if _count <= 90:
|
||||
genshin_count[user_id] = f_count
|
||||
genshin_pl_count[user_id] = count
|
||||
return genshin_list, five_list, five_index_list, five_dict, star_list
|
||||
|
||||
|
||||
def reset_count(user_id: int):
|
||||
genshin_count[user_id] = 0
|
||||
genshin_pl_count[user_id] = 0
|
||||
@ -1,33 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
|
||||
def init_game_pool(game: str, data: dict, Operator: Any):
|
||||
tmp_lst = []
|
||||
if game == 'prts':
|
||||
for key in data.keys():
|
||||
limited = False
|
||||
recruit_only = False
|
||||
event_only = False
|
||||
if '限定寻访' in data[key]['获取途径']:
|
||||
limited = True
|
||||
if len(data[key]['获取途径']) == 1 and data[key]['获取途径'][0] == '公开招募':
|
||||
recruit_only = True
|
||||
if '活动获取' in data[key]['获取途径']:
|
||||
event_only = True
|
||||
if key.find('阿米娅') != -1:
|
||||
continue
|
||||
tmp_lst.append(Operator(name=key, star=int(data[key]['星级']),
|
||||
limited=limited, recruit_only=recruit_only, event_only=event_only))
|
||||
if game == 'genshin':
|
||||
for key in data.keys():
|
||||
if key.find('旅行者') != -1:
|
||||
continue
|
||||
tmp_lst.append(Operator(name=key, star=int(data[key]['稀有度'][:1]), limited=False))
|
||||
if game == 'pretty':
|
||||
for key in data.keys():
|
||||
tmp_lst.append(Operator(name=key, star=data[key]['初始星级'], limited=False))
|
||||
if game == 'pretty_card':
|
||||
for key in data.keys():
|
||||
tmp_lst.append(Operator(name=data[key]['中文名'], star=len(data[key]['稀有度']), limited=False))
|
||||
return tmp_lst
|
||||
|
||||
@ -1,105 +0,0 @@
|
||||
|
||||
import os
|
||||
import nonebot
|
||||
from util.init_result import image
|
||||
from configs.path_config import DRAW_PATH
|
||||
from .update_game_info import update_info
|
||||
from .util import download_img, init_star_rst, generate_img, max_card, BaseData, set_list
|
||||
import random
|
||||
from .config import PRETTY_THREE, PRETTY_TWO, PRETTY_ONE
|
||||
from dataclasses import dataclass
|
||||
from .init_card_pool import init_game_pool
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
driver: nonebot.Driver = nonebot.get_driver()
|
||||
|
||||
ALL_CHAR = []
|
||||
ALL_CARD = []
|
||||
|
||||
|
||||
@dataclass
|
||||
class PrettyChar(BaseData):
|
||||
pass
|
||||
|
||||
|
||||
async def pretty_draw(count: int, pool_name):
|
||||
if pool_name == 'card':
|
||||
cnlist = ['SSR', 'SR', 'R']
|
||||
else:
|
||||
cnlist = ['★★★', '★★', '★']
|
||||
obj_list, obj_dict, three_list, star_list, three_olist = _format_card_information(count, pool_name)
|
||||
rst = init_star_rst(star_list, cnlist, three_list, three_olist)
|
||||
if count > 90:
|
||||
obj_list = set_list(obj_list)
|
||||
return image(b64=await generate_img(obj_list, 'pretty', star_list)) \
|
||||
+ '\n' + rst[:-1] + '\n' + max_card(obj_dict)
|
||||
|
||||
|
||||
async def update_pretty_info():
|
||||
global ALL_CHAR, ALL_CARD
|
||||
url = 'https://wiki.biligame.com/umamusume/赛马娘图鉴'
|
||||
data, code = await update_info(url, 'pretty')
|
||||
if code == 200:
|
||||
ALL_CHAR = init_game_pool('pretty', data, PrettyChar)
|
||||
url = 'https://wiki.biligame.com/umamusume/支援卡图鉴'
|
||||
data, code = await update_info(url, 'pretty_card')
|
||||
if code == 200:
|
||||
ALL_CARD = init_game_pool('pretty_card', data, PrettyChar)
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def init_data():
|
||||
global ALL_CHAR, ALL_CARD
|
||||
if not os.path.exists(DRAW_PATH + '/draw_card_config/pretty.json') or\
|
||||
not os.path.exists(DRAW_PATH + '/draw_card_config/pretty_card.json'):
|
||||
await update_pretty_info()
|
||||
for icon_url in [
|
||||
'https://patchwiki.biligame.com/images/umamusume/thumb/0/06/q23szwkbtd7pfkqrk3wcjlxxt9z595o.png'
|
||||
'/40px-SSR.png',
|
||||
'https://patchwiki.biligame.com/images/umamusume/thumb/3/3b/d1jmpwrsk4irkes1gdvoos4ic6rmuht.png'
|
||||
'/40px-SR.png',
|
||||
'https://patchwiki.biligame.com/images/umamusume/thumb/f/f7/afqs7h4snmvovsrlifq5ib8vlpu2wvk.png'
|
||||
'/40px-R.png']:
|
||||
await download_img(icon_url, 'pretty', icon_url.split('-')[-1][:-4])
|
||||
else:
|
||||
with open(DRAW_PATH + '/draw_card_config/pretty.json', 'r', encoding='utf8') as f:
|
||||
pretty_char_dict = json.load(f)
|
||||
with open(DRAW_PATH + '/draw_card_config/pretty_card.json', 'r', encoding='utf8') as f:
|
||||
pretty_card_dict = json.load(f)
|
||||
ALL_CHAR = init_game_pool('pretty', pretty_char_dict, PrettyChar)
|
||||
ALL_CARD = init_game_pool('pretty_card', pretty_card_dict, PrettyChar)
|
||||
|
||||
|
||||
# 抽取卡池
|
||||
def _get_pretty_card(itype):
|
||||
global ALL_CHAR, ALL_CARD
|
||||
star = random.sample([3, 2, 1],
|
||||
counts=[int(PRETTY_THREE * 100), int(PRETTY_TWO * 100),
|
||||
int(PRETTY_ONE * 100)],
|
||||
k=1)[0]
|
||||
chars = [x for x in (ALL_CARD if itype == 'card' else ALL_CHAR) if x.star == star]
|
||||
return random.choice(chars), abs(star - 3)
|
||||
|
||||
|
||||
# 整理数据
|
||||
def _format_card_information(count: int, pool_name: str):
|
||||
three_list = []
|
||||
three_olist = []
|
||||
obj_list = []
|
||||
obj_dict = {}
|
||||
star_list = [0, 0, 0]
|
||||
for i in range(count):
|
||||
obj, code = _get_pretty_card(pool_name)
|
||||
star_list[code] += 1
|
||||
if code == 0:
|
||||
three_list.append(obj.name)
|
||||
three_olist.append(i)
|
||||
try:
|
||||
obj_dict[obj.name] += 1
|
||||
except KeyError:
|
||||
obj_dict[obj.name] = 1
|
||||
obj_list.append(obj)
|
||||
return obj_list, obj_dict, three_list, star_list, three_olist
|
||||
@ -1,162 +0,0 @@
|
||||
|
||||
import os
|
||||
import nonebot
|
||||
import random
|
||||
from .config import PRTS_FIVE_P, PRTS_FOUR_P, PRTS_SIX_P, PRTS_THREE_P
|
||||
from .update_game_info import update_info
|
||||
from .util import generate_img, init_star_rst, max_card, BaseData, UpEvent, set_list
|
||||
from .init_card_pool import init_game_pool
|
||||
from pathlib import Path
|
||||
from .announcement import PrtsAnnouncement
|
||||
from dataclasses import dataclass
|
||||
from util.init_result import image
|
||||
from configs.path_config import DRAW_PATH
|
||||
from services.log import logger
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
driver: nonebot.Driver = nonebot.get_driver()
|
||||
|
||||
up_char_file = Path() / "data" / "draw_card" / "draw_card_up" / "prts_up_char.json"
|
||||
|
||||
prts_dict = {}
|
||||
UP_OPERATOR = []
|
||||
ALL_OPERATOR = []
|
||||
_CURRENT_POOL_TITLE = ''
|
||||
|
||||
|
||||
@dataclass
|
||||
class Operator(BaseData):
|
||||
recruit_only: bool # 公招限定
|
||||
event_only: bool # 活动获得干员
|
||||
# special_only: bool # 升变/异格干员
|
||||
|
||||
|
||||
async def prts_draw(count: int = 300):
|
||||
cnlist = ['★★★★★★', '★★★★★', '★★★★', '★★★']
|
||||
operator_list, operator_dict, six_list, star_list, six_olist = _format_card_information(count)
|
||||
up_list = []
|
||||
if _CURRENT_POOL_TITLE:
|
||||
for x in UP_OPERATOR:
|
||||
for operator in x.operators:
|
||||
up_list.append(operator)
|
||||
rst = init_star_rst(star_list, cnlist, six_list, six_olist, up_list)
|
||||
if count > 90:
|
||||
operator_list = set_list(operator_list)
|
||||
pool_info = "当前up池: " if _CURRENT_POOL_TITLE else ""
|
||||
return pool_info + _CURRENT_POOL_TITLE + image(b64=await generate_img(operator_list, 'prts', star_list)) \
|
||||
+ '\n' + rst[:-1] + '\n' + max_card(operator_dict)
|
||||
|
||||
|
||||
async def update_prts_info():
|
||||
global prts_dict, ALL_OPERATOR
|
||||
url = 'https://wiki.biligame.com/arknights/干员数据表'
|
||||
data, code = await update_info(url, 'prts', ['头像', '名称', '阵营', '星级', '性别', '是否感染', '初始生命', '初始防御',
|
||||
'初始法抗', '再部署', '部署费用', '阻挡数', '攻击速度', '标签'])
|
||||
if code == 200:
|
||||
prts_dict = data
|
||||
ALL_OPERATOR = init_game_pool('prts', prts_dict, Operator)
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
async def init_data():
|
||||
global prts_dict, ALL_OPERATOR
|
||||
if not os.path.exists(DRAW_PATH + '/draw_card_config/prts.json'):
|
||||
await update_prts_info()
|
||||
else:
|
||||
with open(DRAW_PATH + '/draw_card_config/prts.json', 'r', encoding='utf8') as f:
|
||||
prts_dict = json.load(f)
|
||||
ALL_OPERATOR = init_game_pool('prts', prts_dict, Operator)
|
||||
await _init_up_char()
|
||||
# print([x.operators for x in UP_OPERATOR if x.star == 5 and x.zoom > 1])
|
||||
|
||||
|
||||
# 抽取干员
|
||||
def _get_operator_card():
|
||||
star = random.sample([6, 5, 4, 3],
|
||||
counts=[int(PRTS_SIX_P * 100), int(PRTS_FIVE_P * 100),
|
||||
int(PRTS_FOUR_P * 100), int(PRTS_THREE_P * 100)],
|
||||
k=1)[0]
|
||||
if _CURRENT_POOL_TITLE:
|
||||
zooms = [x.zoom for x in UP_OPERATOR if x.star == star]
|
||||
zoom = 0
|
||||
weight = 0
|
||||
# 分配概率和权重
|
||||
for z in zooms:
|
||||
if z < 1:
|
||||
zoom = z
|
||||
else:
|
||||
weight = z
|
||||
# UP
|
||||
if random.random() < zoom:
|
||||
up_operators = [x.operators for x in UP_OPERATOR if x.star == star and x.zoom < 1][0]
|
||||
up_operator_name = random.choice(up_operators)
|
||||
# print(up_operator_name)
|
||||
acquire_operator = [x for x in ALL_OPERATOR if x.name == up_operator_name][0]
|
||||
else:
|
||||
all_star_operators = [x for x in ALL_OPERATOR if x.star == star
|
||||
and not any([x.limited, x.event_only, x.recruit_only])]
|
||||
weight_up_operators = [x.operators for x in UP_OPERATOR if x.star == star and x.zoom > 1]
|
||||
# 权重
|
||||
if weight_up_operators and random.random() < 1.0 / float(len(all_star_operators)) * weight:
|
||||
up_operator_name = random.choice(weight_up_operators[0])
|
||||
acquire_operator = [x for x in ALL_OPERATOR if x.name == up_operator_name][0]
|
||||
else:
|
||||
acquire_operator = random.choice(all_star_operators)
|
||||
else:
|
||||
acquire_operator = random.choice([x for x in ALL_OPERATOR if x.star == star
|
||||
and not any([x.limited, x.event_only, x.recruit_only])])
|
||||
# print(f'{acquire_operator}: {star}')
|
||||
return acquire_operator, abs(star - 6)
|
||||
|
||||
|
||||
# 整理抽卡数据
|
||||
def _format_card_information(count: int):
|
||||
operator_list = [] # 抽取的干员列表
|
||||
operator_dict = {} # 抽取各干员次数
|
||||
star_list = [0, 0, 0, 0] # 各个星级次数
|
||||
six_list = [] # 六星干员列表
|
||||
six_index_list = [] # 六星干员获取位置
|
||||
for i in range(count):
|
||||
operator, code = _get_operator_card()
|
||||
star_list[code] += 1
|
||||
if code == 0:
|
||||
six_list.append(operator.name)
|
||||
six_index_list.append(i)
|
||||
try:
|
||||
operator_dict[operator.name] += 1
|
||||
except KeyError:
|
||||
operator_dict[operator.name] = 1
|
||||
operator_list.append(operator)
|
||||
return operator_list, operator_dict, six_list, star_list, six_index_list
|
||||
|
||||
|
||||
# 获取up干员和概率
|
||||
async def _init_up_char():
|
||||
global up_char_dict, _CURRENT_POOL_TITLE
|
||||
up_char_dict = await PrtsAnnouncement.update_up_char()
|
||||
# print(up_char_dict)
|
||||
_CURRENT_POOL_TITLE = up_char_dict['title']
|
||||
up_char_dict = up_char_dict['up_char']
|
||||
logger.info(f'成功获取明日方舟当前up信息...当前up池: {_CURRENT_POOL_TITLE}')
|
||||
average_dict = {'6': {}, '5': {}, '4': {}}
|
||||
for star in up_char_dict.keys():
|
||||
for key in up_char_dict[star].keys():
|
||||
if average_dict[star].get(up_char_dict[star][key]):
|
||||
average_dict[star][up_char_dict[star][key]].append(key)
|
||||
else:
|
||||
average_dict[star][up_char_dict[star][key]] = [key]
|
||||
up_char_dict = {'6': {}, '5': {}, '4': {}}
|
||||
for star in average_dict.keys():
|
||||
for str_zoom in average_dict[star].keys():
|
||||
if str_zoom[0] == '权':
|
||||
zoom = float(str_zoom[1:])
|
||||
else:
|
||||
zoom = float(str_zoom) / 100
|
||||
UP_OPERATOR.append(UpEvent(star=int(star), operators=average_dict[star][str_zoom], zoom=zoom))
|
||||
|
||||
|
||||
async def reload_pool():
|
||||
await _init_up_char()
|
||||
@ -1,162 +0,0 @@
|
||||
#coding:utf-8
|
||||
import aiohttp
|
||||
from configs.path_config import DRAW_PATH
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from services.log import logger
|
||||
from bs4 import BeautifulSoup
|
||||
from .util import download_img
|
||||
from urllib.parse import unquote
|
||||
import bs4
|
||||
from util.user_agent import get_user_agent
|
||||
import re
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
async def update_info(url: str, game_name: str, info_list: list = None) -> 'dict, int':
|
||||
try:
|
||||
with open(DRAW_PATH + f'/draw_card_config/{game_name}.json', 'r', encoding='utf8') as f:
|
||||
data = json.load(f)
|
||||
except (ValueError, FileNotFoundError):
|
||||
data = {}
|
||||
try:
|
||||
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
|
||||
async with session.get(url, timeout=7) as response:
|
||||
soup = BeautifulSoup(await response.text(), 'lxml')
|
||||
max_count = 0
|
||||
_tbody = None
|
||||
for tbody in soup.find_all('tbody'):
|
||||
if len(tbody.find_all('tr')) > max_count:
|
||||
_tbody = tbody
|
||||
max_count = len(tbody.find_all('tr'))
|
||||
trs = _tbody.find_all('tr')
|
||||
att_dict = {'头像': 0, '名称': 1}
|
||||
index = 2
|
||||
for th in trs[0].find_all('th')[2:]:
|
||||
text = th.text
|
||||
if text[-1] == '\n':
|
||||
text = text[:-1]
|
||||
att_dict[text] = index
|
||||
index += 1
|
||||
for tr in trs[1:]:
|
||||
member_dict = {}
|
||||
k_name = ''
|
||||
tds = tr.find_all('td')
|
||||
if not info_list:
|
||||
info_list = att_dict.keys()
|
||||
for key in info_list:
|
||||
attr = ''
|
||||
if key.find('.') != -1:
|
||||
key = key.split('.')
|
||||
attr = key[-1]
|
||||
key = key[0]
|
||||
td = tds[att_dict[key]]
|
||||
last_tag = unquote(_find_last_tag(td, attr), 'utf-8')
|
||||
if game_name.find('pretty') == -1 and last_tag.find('http') == -1:
|
||||
last_tag = last_tag.split('.')[0]
|
||||
if key == '名称':
|
||||
k_name = last_tag
|
||||
member_dict[key] = last_tag
|
||||
if game_name == 'pretty' and key == '初始星级':
|
||||
member_dict['初始星级'] = len(td.find_all('img'))
|
||||
avatar_img = await _modify_avatar_url(session, game_name, member_dict["名称"])
|
||||
if avatar_img:
|
||||
member_dict['头像'] = avatar_img
|
||||
name = member_dict['名称']
|
||||
if game_name == 'pretty_card':
|
||||
name = member_dict['中文名']
|
||||
await download_img(member_dict['头像'], game_name, name)
|
||||
if k_name:
|
||||
data[k_name] = member_dict
|
||||
logger.info(f'{k_name} is update...')
|
||||
data = await _last_check(data, game_name, session)
|
||||
except TimeoutError:
|
||||
return {}, 999
|
||||
with open(DRAW_PATH + f'/draw_card_config/{game_name}.json', 'w', encoding='utf8') as wf:
|
||||
wf.write(json.dumps(data, ensure_ascii=False, indent=4))
|
||||
return data, 200
|
||||
|
||||
|
||||
def _find_last_tag(element: bs4.element.Tag, attr: str) -> str:
|
||||
last_tag = []
|
||||
for des in element.descendants:
|
||||
last_tag.append(des)
|
||||
if len(last_tag) == 1 and last_tag[0] == '\n':
|
||||
last_tag = ''
|
||||
elif last_tag[-1] == '\n':
|
||||
last_tag = last_tag[-2]
|
||||
else:
|
||||
last_tag = last_tag[-1]
|
||||
if attr and str(last_tag):
|
||||
last_tag = last_tag[attr]
|
||||
elif str(last_tag).find('<img') != -1:
|
||||
if last_tag.get('srcset'):
|
||||
last_tag = str(last_tag.get('srcset')).strip().split(' ')[-2].strip()
|
||||
else:
|
||||
last_tag = last_tag['src']
|
||||
else:
|
||||
last_tag = str(last_tag)
|
||||
if str(last_tag) and str(last_tag)[-1] == '\n':
|
||||
last_tag = str(last_tag)[:-1]
|
||||
return last_tag
|
||||
|
||||
|
||||
# 获取大图(小图快爬)
|
||||
async def _modify_avatar_url(session: aiohttp.ClientSession, game_name: str, char_name: str):
|
||||
if game_name == 'prts':
|
||||
async with session.get(f'https://wiki.biligame.com/arknights/{char_name}', timeout=7) as res:
|
||||
soup = BeautifulSoup(await res.text(), 'lxml')
|
||||
try:
|
||||
img_url = str(soup.find('img', {'class': 'img-bg'})['srcset']).split(' ')[-2]
|
||||
except KeyError:
|
||||
img_url = str(soup.find('img', {'class': 'img-bg'})['src'])
|
||||
return img_url
|
||||
if game_name == 'genshin':
|
||||
return None
|
||||
if game_name == 'pretty_card':
|
||||
async with session.get(f'https://wiki.biligame.com/umamusume/{char_name}', timeout=7) as res:
|
||||
soup = BeautifulSoup(await res.text(), 'lxml')
|
||||
img_url = soup.find('div', {'class': 'support_card-left'}).find('div').find('img').get('src')
|
||||
return img_url
|
||||
|
||||
|
||||
# 数据最后处理(是否需要额外数据)
|
||||
async def _last_check(data: dict, game_name: str, session: aiohttp.ClientSession):
|
||||
if game_name == 'prts':
|
||||
for key in data.keys():
|
||||
async with session.get(f'https://wiki.biligame.com/arknights/{key}', timeout=7) as res:
|
||||
soup = BeautifulSoup(await res.text(), 'lxml')
|
||||
obtain = str(soup.find('table', {'class': 'wikitable'}).find('tbody').find_all('td')[-1])
|
||||
obtain = re.search(r'<td.*?>([\s\S]*)</.*?', obtain).group(1)
|
||||
obtain = obtain[:-1] if obtain[-1] == '\n' else obtain
|
||||
if obtain.find('<br/>'):
|
||||
obtain = obtain.split('<br/>')
|
||||
elif obtain.find('<br>'):
|
||||
obtain = obtain.split('<br>')
|
||||
data[key]['获取途径'] = obtain
|
||||
# if game_name == 'genshin':
|
||||
# for key in data.keys():
|
||||
# async with session.get(f'https://wiki.biligame.com/ys/{key}', timeout=7) as res:
|
||||
# soup = BeautifulSoup(await res.text(), 'lxml')
|
||||
# trs = soup.find('div', {'class': 'poke-bg'}).find('table').find('tbody').find_all('tr')
|
||||
# for tr in trs:
|
||||
# if tr.find('th').text.find('常驻/限定') != -1:
|
||||
# data[key]['常驻/限定'] = tr.find('td').text
|
||||
# break
|
||||
if game_name == 'pretty':
|
||||
for keys in data.keys():
|
||||
for key in data[keys].keys():
|
||||
# print(f'key --> {data[keys][key]}')
|
||||
r = re.search(r'.*?40px-(.*)图标.png', str(data[keys][key]))
|
||||
if r:
|
||||
data[keys][key] = r.group(1)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
|
||||
# ul = soup.find('div', {'class': 'savelist_bot'}).find('ul')
|
||||
|
||||
|
||||
@ -1,161 +0,0 @@
|
||||
import os
|
||||
import aiohttp
|
||||
import aiofiles
|
||||
from asyncio.exceptions import TimeoutError
|
||||
from aiohttp.client_exceptions import InvalidURL
|
||||
from typing import List, Union, Set
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from .config import path_dict
|
||||
import nonebot
|
||||
from util.utils import cn2py
|
||||
from util.img_utils import CreateImg
|
||||
from util.user_agent import get_user_agent
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from dataclasses import dataclass
|
||||
from services.log import logger
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
|
||||
driver: nonebot.Driver = nonebot.get_driver()
|
||||
|
||||
|
||||
@dataclass
|
||||
class BaseData:
|
||||
name: str
|
||||
star: int
|
||||
limited: bool # 限定
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpEvent:
|
||||
star: int # 对应up星级
|
||||
operators: List[BaseData] # 干员列表
|
||||
zoom: float # up提升倍率
|
||||
|
||||
|
||||
async def download_img(url: str, path: str, name: str) -> bool:
|
||||
path = path.split('_')[0]
|
||||
codename = cn2py(name)
|
||||
# if not _p.exists():
|
||||
# _p.mkdir(parents=True, exist_ok=True)
|
||||
if not os.path.exists(IMAGE_PATH + f'/draw_card/{path}/{codename}.png'):
|
||||
try:
|
||||
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
|
||||
async with session.get(url, timeout=7) as response:
|
||||
async with aiofiles.open(IMAGE_PATH + f'/draw_card/{path}/{codename}.png', 'wb') as f:
|
||||
await f.write(await response.read())
|
||||
logger.info(f'下载 {path_dict[path]} 图片成功,名称:{name},url:{url}')
|
||||
return True
|
||||
except TimeoutError:
|
||||
logger.info(f'下载 {path_dict[path]} 图片超时,名称:{name},url:{url}')
|
||||
return False
|
||||
except InvalidURL:
|
||||
logger.info(f'下载 {path_dict[path]} 链接错误,名称:{name},url:{url}')
|
||||
return False
|
||||
else:
|
||||
# logger.info(f'{path_dict[path]} 图片 {name} 已存在')
|
||||
return False
|
||||
|
||||
|
||||
@driver.on_startup
|
||||
def _check_dir():
|
||||
for dir_name in path_dict.keys():
|
||||
_p = Path(IMAGE_PATH + f'/draw_card/' + dir_name)
|
||||
if not _p.exists():
|
||||
_p.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
async def generate_img(card_set: Union[Set[BaseData], List[BaseData]], game_name: str, star_list: list) -> str:
|
||||
# try:
|
||||
img_list = []
|
||||
color_list = []
|
||||
for x in card_set:
|
||||
if game_name == 'prts':
|
||||
if x.star == 6:
|
||||
color_list.append('#FFD700')
|
||||
elif x.star == 5:
|
||||
color_list.append('#DAA520')
|
||||
elif x.star == 4:
|
||||
color_list.append('#9370D8')
|
||||
else:
|
||||
color_list.append('white')
|
||||
pyname = cn2py(x.name)
|
||||
img_list.append(IMAGE_PATH + f'/draw_card/{game_name}/{pyname}.png')
|
||||
img_len = len(img_list)
|
||||
w = 100 * 10
|
||||
if img_len <= 10:
|
||||
w = 100 * img_len
|
||||
h = 100
|
||||
elif img_len % 10 == 0:
|
||||
h = 100 * int(img_len / 10)
|
||||
else:
|
||||
h = 100 * int(img_len / 10) + 100
|
||||
card_img = await asyncio.get_event_loop().run_in_executor(None, _pst, h, img_list, game_name, color_list)
|
||||
num = 0
|
||||
for n in star_list:
|
||||
num += n
|
||||
A = CreateImg(w, h)
|
||||
A.paste(card_img)
|
||||
return A.pic2bs4()
|
||||
|
||||
|
||||
def _pst(h: int, img_list: list, game_name: str, color_list: list):
|
||||
card_img = CreateImg(100 * 10, h, 100, 100)
|
||||
idx = 0
|
||||
for img in img_list:
|
||||
try:
|
||||
if game_name == 'prts':
|
||||
bk = CreateImg(100, 100, color=color_list[idx])
|
||||
b = CreateImg(94, 94, background=img)
|
||||
bk.paste(b, (3, 3))
|
||||
b = bk
|
||||
idx += 1
|
||||
else:
|
||||
b = CreateImg(100, 100, background=img)
|
||||
except FileNotFoundError:
|
||||
print(f'{img} not exists')
|
||||
b = CreateImg(100, 100, color='black')
|
||||
card_img.paste(b)
|
||||
return card_img
|
||||
|
||||
|
||||
def init_star_rst(star_list: list, cnlist: list, max_star_list: list, max_star_olist: list, up_list: list = None) -> str:
|
||||
if not up_list:
|
||||
up_list = []
|
||||
rst = ''
|
||||
for i in range(len(star_list)):
|
||||
if star_list[i]:
|
||||
rst += f'[{cnlist[i]}×{star_list[i]}] '
|
||||
rst += '\n'
|
||||
for i in range(len(max_star_list)):
|
||||
if max_star_list[i] in up_list:
|
||||
rst += f'第 {max_star_olist[i]+1} 抽获取UP {max_star_list[i]}\n'
|
||||
else:
|
||||
rst += f'第 {max_star_olist[i]+1} 抽获取 {max_star_list[i]}\n'
|
||||
return rst
|
||||
|
||||
|
||||
def max_card(_dict: dict):
|
||||
_max_value = max(_dict.values())
|
||||
_max_user = list(_dict.keys())[list(_dict.values()).index(_max_value)]
|
||||
return f'抽取到最多的是{_max_user},共抽取了{_max_value}次'
|
||||
# ThreeHighest = nlargest(3, operator_dict, key=operator_dict.get)
|
||||
# rst = '最喜欢你的前三位是干员是:\n'
|
||||
# for name in ThreeHighest:
|
||||
# rst += f'{name} 共投了 {operator_dict[name]} 份简历\n'
|
||||
# return rst[:-1]
|
||||
|
||||
|
||||
def set_list(lst: List[BaseData]) -> list:
|
||||
tmp = []
|
||||
name_lst = []
|
||||
for x in lst:
|
||||
if x.name not in name_lst:
|
||||
tmp.append(x)
|
||||
name_lst.append(x.name)
|
||||
return tmp
|
||||
|
||||
@ -1,60 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from services.log import logger
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from nonebot.typing import T_State
|
||||
from util.utils import scheduler, get_bot
|
||||
from .data_source import get_epic_game
|
||||
from models.group_remind import GroupRemind
|
||||
from nonebot.adapters.cqhttp.exception import ActionFailed
|
||||
|
||||
__plugin_usage__ = 'epic免费游戏提醒'
|
||||
|
||||
|
||||
epic = on_command("epic", priority=5, block=True)
|
||||
|
||||
|
||||
@epic.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
# try:
|
||||
if str(event.get_message()) in ['帮助']:
|
||||
await epic.finish(__plugin_usage__)
|
||||
try:
|
||||
result = await get_epic_game()
|
||||
except:
|
||||
result = '网络出错了!'
|
||||
await epic.send(result)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 获取epic免费游戏")
|
||||
# except Exception as e:
|
||||
# logger.error(f'epic 出错 e:{e}')
|
||||
# await epic.finish('网络好像炸了,再试一次?', at_sender=True)
|
||||
|
||||
|
||||
# epic免费游戏
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=12,
|
||||
minute=1,
|
||||
)
|
||||
async def _():
|
||||
# try:
|
||||
bot = get_bot()
|
||||
gl = await bot.get_group_list(self_id=bot.self_id)
|
||||
gl = [g['group_id'] for g in gl]
|
||||
for g in gl:
|
||||
if await GroupRemind.get_status(g, 'epic'):
|
||||
result = await get_epic_game()
|
||||
if result == '今天没有游戏可以白嫖了!':
|
||||
return
|
||||
try:
|
||||
await bot.send_group_msg(group_id=g,
|
||||
message=result)
|
||||
except ActionFailed:
|
||||
logger.error(f'{g}群 epic免费游戏推送错误')
|
||||
# except Exception as e:
|
||||
# logger.error(f'epic免费游戏推送错误 e:{e}')
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,46 +0,0 @@
|
||||
import aiohttp
|
||||
import aiofiles
|
||||
from util.utils import get_local_proxy
|
||||
import feedparser
|
||||
import platform
|
||||
from util.init_result import image
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from util.user_agent import get_user_agent
|
||||
if platform.system() == 'Windows':
|
||||
import asyncio
|
||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
||||
|
||||
|
||||
url = 'https://rsshub.app/epicgames/freegames'
|
||||
|
||||
|
||||
async def get_epic_game() -> str:
|
||||
result = ''
|
||||
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
|
||||
async with session.get(url, proxy=get_local_proxy(), timeout=7) as response:
|
||||
data = feedparser.parse(await response.text())['entries']
|
||||
if len(data) == 0:
|
||||
return result
|
||||
index = 0
|
||||
for item in data:
|
||||
title = item['title']
|
||||
img_url = item['summary'][item['summary'].find('src="')+5: item['summary'].rfind('"')]
|
||||
async with session.get(img_url, proxy=get_local_proxy(), timeout=7) as res:
|
||||
async with aiofiles.open(IMAGE_PATH + f'temp/epic_{index}.jpg', 'wb') as f:
|
||||
await f.write(await res.read())
|
||||
link = item['link']
|
||||
result += image(f'epic_{index}.jpg', 'temp') + f'\n【游戏】| {title}\n【链接】 | {link}\n'
|
||||
index += 1
|
||||
if result != '':
|
||||
result = 'epic限免游戏(速速白嫖):\n' + result
|
||||
else:
|
||||
result = '今天没有游戏可以白嫖了!'
|
||||
print(result)
|
||||
return result
|
||||
|
||||
|
||||
|
||||
|
||||
# print(asyncio.get_event_loop().run_until_complete(get_epic_game()))
|
||||
|
||||
|
||||
@ -1,55 +0,0 @@
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from nonebot import on_command
|
||||
from util.utils import get_message_imgs, get_message_text
|
||||
from util.init_result import share
|
||||
from services.log import logger
|
||||
|
||||
|
||||
__plugin_usage__ = '用法:\n格式:网址 标题 内容(可省略) 图片(可省略)\n示例:假消息 www.4399.com 我喜欢萝莉 为什么我喜欢... (图片)'
|
||||
|
||||
|
||||
fake_msg = on_command('假消息', priority=5, block=True)
|
||||
|
||||
|
||||
@fake_msg.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
msg = get_message_text(event.json()).split(' ')
|
||||
img = get_message_imgs(event.json())
|
||||
if not msg or msg in ['帮助']:
|
||||
await fake_msg.finish(__plugin_usage__)
|
||||
if len(msg) > 1:
|
||||
if len(msg) == 2:
|
||||
url = msg[0]
|
||||
title = msg[1]
|
||||
content = ''
|
||||
else:
|
||||
url = msg[0]
|
||||
title = msg[1]
|
||||
content = msg[2]
|
||||
if img:
|
||||
img = img[0]
|
||||
else:
|
||||
img = ''
|
||||
if url.find('http://') == -1:
|
||||
url = 'http://' + url
|
||||
await fake_msg.send(share(url, title, content, img))
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 构造假消息 url {url}, title {title}, content {content}")
|
||||
else:
|
||||
await fake_msg.finish('消息格式错误:\n网址 标题 内容(可省略) 图片(可省略)')
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
from nonebot.adapters.cqhttp.permission import GROUP
|
||||
from configs.path_config import IMAGE_PATH
|
||||
from util.img_utils import get_img_hash
|
||||
import random
|
||||
from util.init_result import image
|
||||
from nonebot import on_message
|
||||
from util.utils import get_message_text, get_message_imgs, get_local_proxy
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
|
||||
import aiohttp
|
||||
import aiofiles
|
||||
from collections import defaultdict
|
||||
from configs.config import FUDU_PROBABILITY
|
||||
|
||||
|
||||
class Fudu:
|
||||
def __init__(self):
|
||||
self.mlist = defaultdict(list)
|
||||
|
||||
def append(self, key, content):
|
||||
self.mlist[key].append(content)
|
||||
|
||||
def clear(self, key):
|
||||
self.mlist[key] = []
|
||||
|
||||
def size(self, key) -> int:
|
||||
return len(self.mlist[key])
|
||||
|
||||
def check(self, key, content) -> bool:
|
||||
return self.mlist[key][0] == content
|
||||
|
||||
def get(self, key):
|
||||
return self.mlist[key][0]
|
||||
|
||||
|
||||
_fudulist = Fudu()
|
||||
|
||||
|
||||
fudu = on_message(permission=GROUP, priority=9)
|
||||
|
||||
|
||||
@fudu.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if event.is_tome() or state["_prefix"]["raw_command"]:
|
||||
return
|
||||
if get_message_text(event.json()):
|
||||
if get_message_text(event.json()).find('@可爱的小真寻') != -1:
|
||||
await fudu.finish('复制粘贴的虚空艾特?', at_sender=True)
|
||||
imgs = get_message_imgs(event.json())
|
||||
msg = get_message_text(event.json())
|
||||
if not imgs and not msg:
|
||||
return
|
||||
if imgs:
|
||||
img_hash = await get_fudu_img_hash(imgs[0], event.group_id)
|
||||
else:
|
||||
img_hash = ''
|
||||
add_msg = msg + '|-|' + img_hash
|
||||
if _fudulist.size(event.group_id) == 0:
|
||||
_fudulist.append(event.group_id, add_msg)
|
||||
elif _fudulist.check(event.group_id, add_msg):
|
||||
_fudulist.append(event.group_id, add_msg)
|
||||
else:
|
||||
_fudulist.clear(event.group_id)
|
||||
_fudulist.append(event.group_id, add_msg)
|
||||
if _fudulist.size(event.group_id) > 2:
|
||||
if random.random() < FUDU_PROBABILITY:
|
||||
if random.random() < 0.2:
|
||||
await fudu.finish("打断施法!")
|
||||
if imgs and msg:
|
||||
rst = msg + image(f'compare_{event.group_id}_img.jpg', 'temp')
|
||||
elif imgs:
|
||||
rst = image(f'compare_{event.group_id}_img.jpg', 'temp')
|
||||
elif msg:
|
||||
rst = msg
|
||||
else:
|
||||
rst = ''
|
||||
if rst:
|
||||
await fudu.send(rst)
|
||||
_fudulist.clear(event.group_id)
|
||||
|
||||
|
||||
async def get_fudu_img_hash(url, group_id):
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, proxy=get_local_proxy(), timeout=5) as response:
|
||||
async with aiofiles.open(IMAGE_PATH + f"temp/compare_{group_id}_img.jpg", 'wb') as f:
|
||||
await f.write(await response.read())
|
||||
img_hash = get_img_hash(IMAGE_PATH + f"temp/compare_{group_id}_img.jpg")
|
||||
return str(img_hash)
|
||||
@ -1,49 +0,0 @@
|
||||
from .alc import get_almanac_base64_str, load_data
|
||||
import os
|
||||
from util.utils import get_bot, scheduler
|
||||
from nonebot import on_command
|
||||
from models.level_user import LevelUser
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
|
||||
from util.init_result import image
|
||||
from services.log import logger
|
||||
from models.group_remind import GroupRemind
|
||||
|
||||
FILE_PATH = os.path.dirname(__file__)
|
||||
|
||||
almanac = on_command('原神黄历', priority=5, block=True)
|
||||
reload = on_command('重载原神黄历数据', priority=5, block=True)
|
||||
|
||||
|
||||
@almanac.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
almanac_base64 = get_almanac_base64_str()
|
||||
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
|
||||
await almanac.send(mes)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 发送查看原神黄历")
|
||||
|
||||
|
||||
@reload.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
if await LevelUser.check_level(event.user_id, event.group_id, 5):
|
||||
load_data()
|
||||
await reload.send("重载成功")
|
||||
|
||||
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=10,
|
||||
minute=25,
|
||||
)
|
||||
async def _():
|
||||
# 每日提醒
|
||||
bot = get_bot()
|
||||
gl = await bot.get_group_list(self_id=bot.self_id)
|
||||
gl = [g['group_id'] for g in gl]
|
||||
almanac_base64 = get_almanac_base64_str()
|
||||
mes = image(b64=almanac_base64) + "\n ※ 黄历数据来源于 genshin.pub"
|
||||
for gid in gl:
|
||||
if await GroupRemind.get_status(gid, 'almanac'):
|
||||
await bot.send_group_msg(group_id=int(gid), message=mes)
|
||||
Binary file not shown.
Binary file not shown.
@ -1,123 +0,0 @@
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from io import BytesIO
|
||||
|
||||
import os
|
||||
import json
|
||||
import random
|
||||
import base64
|
||||
import time
|
||||
|
||||
FILE_PATH = os.path.dirname(__file__)
|
||||
FONT_PATH = os.path.join(FILE_PATH, "汉仪文黑.ttf")
|
||||
|
||||
data = {} # configs.json里的数据
|
||||
|
||||
almanac_data = {
|
||||
# 生成的黄历base64字符串和黄历更新日期
|
||||
"date": "",
|
||||
"almanac_base64_str": ""
|
||||
}
|
||||
|
||||
chinese = {"0": "", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六", "7": "七", "8": "八", "9": "九"}
|
||||
|
||||
|
||||
def month_to_chinese(month: str):
|
||||
# 把日期数字转成中文数字
|
||||
m = int(month)
|
||||
if m < 10:
|
||||
return chinese[month[-1]]
|
||||
elif m < 20:
|
||||
return "十" + chinese[month[-1]]
|
||||
else:
|
||||
return chinese[month[0]] + "十" + chinese[month[-1]]
|
||||
|
||||
|
||||
def load_data():
|
||||
# 载入config.json文件的数据
|
||||
global data
|
||||
with open(os.path.join(FILE_PATH, 'config.json'), 'r', encoding='UTF-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
almanac_data["date"] = ""
|
||||
almanac_data["almanac_base64_str"] = ""
|
||||
|
||||
|
||||
load_data()
|
||||
|
||||
|
||||
def seed_random_list(seed: str, l: list):
|
||||
# 使用随机种子随机选择列表中的元素,相同的种子和列表将返回同样的输出
|
||||
seed = seed + str(l)
|
||||
random.seed(seed)
|
||||
index = random.random() * len(l)
|
||||
return l[int(index)]
|
||||
|
||||
|
||||
def generate_almanac():
|
||||
# 生成黄历图片,然后转换成base64保存到 almanac_data["almanac_base64_str"]
|
||||
|
||||
seed = time.strftime("%Y-%m-%d")
|
||||
offset = 1
|
||||
today_luck = []
|
||||
l = list(data.keys())
|
||||
|
||||
while len(today_luck) < 6:
|
||||
# 随机6个不同的运势放到 today_luck
|
||||
r = seed_random_list(str(offset) + seed, l)
|
||||
if r in today_luck:
|
||||
offset += 1
|
||||
else:
|
||||
today_luck.append(r)
|
||||
|
||||
back = Image.open(os.path.join(FILE_PATH, "back.png"))
|
||||
|
||||
year = time.strftime("%Y")
|
||||
month = month_to_chinese(time.strftime("%m")) + "月"
|
||||
day = month_to_chinese(time.strftime("%d")) + "日"
|
||||
|
||||
draw = ImageDraw.Draw(back)
|
||||
draw.text((118, 165), year, fill="#8d7650ff", font=ImageFont.truetype(FONT_PATH, size=30), anchor="mm",
|
||||
align="center")
|
||||
draw.text((260, 165), day, fill="#f7f8f2ff", font=ImageFont.truetype(FONT_PATH, size=35), anchor="mm",
|
||||
align="center")
|
||||
draw.text((410, 165), month, fill="#8d7650ff", font=ImageFont.truetype(FONT_PATH, size=30), anchor="mm",
|
||||
align="center")
|
||||
|
||||
buff = Image.new("RGBA", (325, 160))
|
||||
debuff = Image.new("RGBA", (325, 160))
|
||||
|
||||
buff_draw = ImageDraw.Draw(buff)
|
||||
debuff_draw = ImageDraw.Draw(debuff)
|
||||
|
||||
for i in range(3):
|
||||
buff_name = today_luck[i]
|
||||
debuff_name = today_luck[(i + 3)]
|
||||
|
||||
buff_effect = seed_random_list(seed, data[buff_name]["buff"])
|
||||
debuff_effect = seed_random_list(seed, data[debuff_name]["debuff"])
|
||||
|
||||
buff_draw.text((0, i * 53), buff_name, fill="#756141ff", font=ImageFont.truetype(FONT_PATH, size=25))
|
||||
debuff_draw.text((0, i * 53), debuff_name, fill="#756141ff", font=ImageFont.truetype(FONT_PATH, size=25))
|
||||
|
||||
buff_draw.text((0, i * 53 + 28), buff_effect, fill="#b5b3acff", font=ImageFont.truetype(FONT_PATH, size=19))
|
||||
debuff_draw.text((0, i * 53 + 28), debuff_effect, fill="#b5b3acff", font=ImageFont.truetype(FONT_PATH, size=19))
|
||||
|
||||
back.paste(buff, (150, 230), buff)
|
||||
back.paste(debuff, (150, 400), debuff)
|
||||
|
||||
bio = BytesIO()
|
||||
back.save(bio, format='PNG')
|
||||
base64_str = base64.b64encode(bio.getvalue()).decode()
|
||||
|
||||
almanac_data["date"] = time.strftime("%Y-%m-%d")
|
||||
almanac_data["almanac_base64_str"] = 'base64://' + base64_str
|
||||
|
||||
|
||||
def get_almanac_base64_str():
|
||||
# if almanac_data["date"] == time.strftime("%Y-%m-%d"):
|
||||
# return almanac_data["almanac_base64_str"]
|
||||
# else:
|
||||
# generate_almanac()
|
||||
# return almanac_data["almanac_base64_str"]
|
||||
generate_almanac()
|
||||
return almanac_data["almanac_base64_str"]
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
@ -1,70 +0,0 @@
|
||||
{
|
||||
"抽卡":{
|
||||
"buff": ["欧气满满,十连出金","出金不歪"],
|
||||
"debuff": ["武器大师","保底出金","金色会是痛苦大剑"]
|
||||
},
|
||||
"刷世界boss":{
|
||||
"buff": ["双攻双爆角斗士"],
|
||||
"debuff": ["只有保底材料","贪生怕死角斗士"]
|
||||
},
|
||||
"刷风本":{
|
||||
"buff": ["会有极品猎人套","会掉真正的少女心","治疗加成少女头"],
|
||||
"debuff": ["勇往直前少女心","少女飘摇的杀意","少女暴怒的容颜"]
|
||||
},
|
||||
"刷火本":{
|
||||
"buff": ["魔女帽子火伤杯","暴伤魔女帽!","火伤魔女心!"],
|
||||
"debuff": ["幡 然 醒 悟","这么阴间的地方真的会有魔女套吗?","不务正业火魔女","会匹配到3个卢姥爷"]
|
||||
},
|
||||
"刷岩本":{
|
||||
"buff": ["悠久的磐岩伴你左右","岩神的庇护常在"],
|
||||
"debuff": ["防御流星杯,你值得拥有"]
|
||||
},
|
||||
"刷宗室":{
|
||||
"buff": ["物理伤害骑士道,元素精通宗室套"],
|
||||
"debuff": ["贪生怕死骑士道,物理伤害宗室杯"]
|
||||
},
|
||||
"刷冰本":{
|
||||
"buff": ["双暴词条概率up"],
|
||||
"debuff": ["防御力船帽,无人可及"]
|
||||
},
|
||||
"刷雷本":{
|
||||
"buff": ["愿雷鸟伴你左右"],
|
||||
"debuff": ["来表演一个只掉平雷套的绝活","风神忽悠雷凶兆"]
|
||||
},
|
||||
"锄大地":{
|
||||
"buff": ["会掉一大堆紫色材料"],
|
||||
"debuff": ["深渊法师爱你哟","会被冰水法控到死"]
|
||||
},
|
||||
"挖矿":{
|
||||
"buff": ["开矿出双材料"],
|
||||
"debuff": ["去别人世界会被拒"]
|
||||
},
|
||||
"刷天赋本":{
|
||||
"buff": ["金色!我看到了金色的书!"],
|
||||
"debuff": ["2蓝2绿不会变"]
|
||||
},
|
||||
"刷突破材料":{
|
||||
"buff": ["金色!我看到了金色的材料!"],
|
||||
"debuff": ["2蓝2绿不会变"]
|
||||
},
|
||||
"升级圣遗物":{
|
||||
"buff": ["稀有词条跳跳跳","会双爆拉满"],
|
||||
"debuff": ["女 仆 狂 喜","无中生有防御力","生命拉满","完美避开双爆"]
|
||||
},
|
||||
"打风魔龙":{
|
||||
"buff": ["看我一箭一个风魔鸡","今天特瓦林可以给想要的突破材料","5金加原胚!"],
|
||||
"debuff": ["会不小心掉下平台","不小心被地板烫死了"]
|
||||
},
|
||||
"打狼王":{
|
||||
"buff": ["今天安德琉斯的心情不错,可以py一下","5金加原胚!"],
|
||||
"debuff": ["狼尾巴*1"]
|
||||
},
|
||||
"打公子":{
|
||||
"buff": ["今天可以和公子py想要的突破材料","5金加原胚!"],
|
||||
"debuff": ["要角没有!要命一条!"]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
@ -1,72 +0,0 @@
|
||||
from nonebot import on_command
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from util.init_result import image
|
||||
|
||||
import time
|
||||
|
||||
material = on_command('今日素材', aliases={'今日材料', '今天素材', '今天材料'}, priority=5, block=True)
|
||||
role_material = on_command('天赋材料', priority=5, block=True)
|
||||
|
||||
|
||||
def get_today_material(name: str):
|
||||
# 返回今天的材料图片CQ码
|
||||
if name == '天赋材料':
|
||||
return image('天赋材料.png', "genshin/material/")
|
||||
week = time.strftime("%w")
|
||||
png_name = ''
|
||||
if week == "0":
|
||||
return "今天是周日,所有材料副本都开放了。"
|
||||
elif week in ["1", "4"]:
|
||||
png_name = f"{name}_周一周四.png"
|
||||
elif week in ["2", "5"]:
|
||||
png_name = f"{name}_周二周五.png"
|
||||
elif week in ["3", "6"]:
|
||||
png_name = f"{name}_周三周六.png"
|
||||
|
||||
return image(png_name, "genshin/material/")
|
||||
|
||||
|
||||
# @sv.on_fullmatch('开启原神每日素材提醒')
|
||||
# async def open_remind(bot , ev):
|
||||
# gid = str(ev.group_id)
|
||||
# if not (gid in group_list):
|
||||
# group_list.append(gid)
|
||||
# save_group_list()
|
||||
# await bot.send(ev, "每日提醒已开启,每天8点会发送今日素材")
|
||||
#
|
||||
#
|
||||
# @sv.on_fullmatch('关闭原神每日素材提醒')
|
||||
# async def off_remind(bot , ev):
|
||||
# gid = str(ev.group_id)
|
||||
# if gid in group_list:
|
||||
# group_list.remove(gid)
|
||||
# save_group_list()
|
||||
# await bot.send(ev, "每日提醒已关闭")
|
||||
|
||||
@material.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
if time.strftime("%w") == "0":
|
||||
await material.send("今天是周日,所有材料副本都开放了。")
|
||||
return
|
||||
arms_material_CQ = get_today_material("武器突破材料")
|
||||
roles_material_CQ = get_today_material("角色天赋材料")
|
||||
await material.send(arms_material_CQ + roles_material_CQ)
|
||||
|
||||
|
||||
@role_material.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
await material.send(get_today_material("天赋材料"))
|
||||
|
||||
# @sv.scheduled_job('cron', hour='8')
|
||||
# async def material_remind():
|
||||
# # 每日提醒
|
||||
# if time.strftime("%w") == "0":
|
||||
# # 如果今天是周日就不发了
|
||||
# return
|
||||
# bot = get_bot()
|
||||
# arms_material_CQ = get_today_material("武器突破材料")
|
||||
# roles_material_CQ = get_today_material("角色天赋材料")
|
||||
# for gid in group_list:
|
||||
# await bot.send_group_msg(group_id=int(gid), message=arms_material_CQ)
|
||||
# await bot.send_group_msg(group_id=int(gid), message=roles_material_CQ)
|
||||
Binary file not shown.
@ -1,37 +0,0 @@
|
||||
from .qiu_translation import qiu_qiu_word_translation, qiu_qiu_phrase_translation
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from nonebot.typing import T_State
|
||||
from nonebot import on_command
|
||||
from util.utils import get_message_text
|
||||
from services.log import logger
|
||||
|
||||
|
||||
qiuqiu = on_command("丘丘语翻译", aliases={"丘丘一下", "丘丘翻译"}, priority=5, block=True)
|
||||
|
||||
suffix = "\n※ 只能从丘丘语翻译为中文,不能反向翻译\n" \
|
||||
"※ 注意空格,不要加入任何标点符号\n" \
|
||||
"※ 翻译数据来源于 米游社论坛"
|
||||
|
||||
|
||||
@qiuqiu.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
txt = get_message_text(event.json()).lower()
|
||||
if txt == "":
|
||||
return
|
||||
mes = qiu_qiu_phrase_translation(txt)
|
||||
if not mes:
|
||||
mes = qiu_qiu_word_translation(txt)
|
||||
mes += suffix
|
||||
# print(mes)
|
||||
await qiuqiu.send(mes, at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 发送丘丘翻译:" + txt)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@ -1,127 +0,0 @@
|
||||
{
|
||||
"word": {
|
||||
|
||||
"a": "啊",
|
||||
|
||||
"beru": "做",
|
||||
"biadam": "找死啊",
|
||||
"biat": "暴揍",
|
||||
"buka": "肚子",
|
||||
|
||||
"celi": "元素",
|
||||
|
||||
"dada": "厉害",
|
||||
"dala": "什么",
|
||||
"domu": "跳舞",
|
||||
|
||||
"eleka": "此时此刻",
|
||||
|
||||
"guru": "咕",
|
||||
"gusha": "草",
|
||||
|
||||
"ika": "敌人",
|
||||
|
||||
"kundela": "活着",
|
||||
"kuzi": "强大",
|
||||
"kucha": "吃草",
|
||||
|
||||
"la": "啦~",
|
||||
"lata": "水元素",
|
||||
|
||||
"mani": "给予",
|
||||
"mi": "我",
|
||||
"mimi": "我们",
|
||||
"mita": "肉类",
|
||||
"mosi": "吃",
|
||||
"movo": "带来",
|
||||
"muhe": "胜利",
|
||||
|
||||
"ni": "风",
|
||||
"nini": "风暴",
|
||||
"nunu": "睡觉",
|
||||
"nye": "不",
|
||||
|
||||
"odomu": "朋友",
|
||||
"olah": "你好",
|
||||
|
||||
"plata": "盾牌",
|
||||
"pupu": "噗噗",
|
||||
|
||||
"sada": "唱歌",
|
||||
"shato": "伴随",
|
||||
"si": "什么",
|
||||
|
||||
"tomo": "感激",
|
||||
"todo": "放心",
|
||||
"tiga": "矿石",
|
||||
|
||||
"upa": "聚集",
|
||||
"unu": "乌努",
|
||||
|
||||
"valo": "谢谢你",
|
||||
"vin": "酒",
|
||||
|
||||
"ya": "人",
|
||||
"yaya": "人们",
|
||||
"ye": "家伙",
|
||||
"yeye": "这些家伙",
|
||||
"yo": "你",
|
||||
"yoyo": "你们",
|
||||
|
||||
"zido": "杀死"
|
||||
|
||||
},
|
||||
"phrase": {
|
||||
"beru si": "做什么",
|
||||
"biadam": "可恶啊,找死啊,愤怒语气",
|
||||
"biat": "打爆,暴揍;可恶的",
|
||||
|
||||
"dada": " 极好的,厉害的",
|
||||
"dala": "表示疑问,不明白的集合,翻译为哪个,什么",
|
||||
|
||||
"guru-guru": "拟声词,形容肚子咕咕叫的声音,饥饿",
|
||||
"guru guru": "拟声词,形容肚子咕咕叫的声音,饥饿",
|
||||
"gusha": "植物类食物,不怎么好的,难过的",
|
||||
|
||||
"kucha pupu": "拟声词,吃草时候的拟声词,咯吱噗噗,形容吃草吃得香,贬义",
|
||||
|
||||
"mita": "肉类,好的,好东西,有时代丘丘人,丘丘人部落,好肉族",
|
||||
"mosi mita": "吃肉,表示开心",
|
||||
"mosi gusha": "吃草,表示难过",
|
||||
"movo": "带来,搬运;可引申为收获,丰收",
|
||||
"muhe": "胜利,战胜;成功的",
|
||||
|
||||
"nini": "大量风元素,风暴,狂风",
|
||||
"nye": "表示否定,没有了,不是",
|
||||
|
||||
"pupu":"拟声词,噗噗,表示嘲讽",
|
||||
|
||||
"sada": "唱歌,歌颂",
|
||||
"shato": "乘着,伴随着",
|
||||
|
||||
"upa": "凝聚,聚集,集合;聚落,部落",
|
||||
"unu": "乌努,丘丘人所崇拜的神灵",
|
||||
|
||||
"valo": "谢谢你,不客气/再见",
|
||||
"vin": "酒的,喝酒有关的,酒桶盖子",
|
||||
|
||||
"ya": "特指人类,一个人类",
|
||||
"yaya": "人类的复数 ,大群人类",
|
||||
"ye": "你这个家伙,蔑称;或用于地位高者对地位低者的称呼",
|
||||
"yeye": "你们这些家伙,蔑称,ye的复数",
|
||||
"yo": "你,友善称呼",
|
||||
"yoyo": "你们,yo的复数,友善称呼ye",
|
||||
|
||||
|
||||
|
||||
"nye mita da ye mosi zido": "再见,一路平安",
|
||||
"vin plata dada": "你的酒桶盾牌真不错",
|
||||
"kucha pupu gucha ye": "你咯吱噗噗的吃草的样子真的好搞笑",
|
||||
"mani nini biaodomu": "愿风暴给予你死亡",
|
||||
"celi dada mimi nunu": "赞美元素,我们睡觉吧",
|
||||
"muhe ye": "你们是不可战胜的",
|
||||
"ye dada": "你们可真棒",
|
||||
"ye yika": "你们是敌人",
|
||||
"nini zido": "愿风暴杀死你"
|
||||
}
|
||||
}
|
||||
@ -1,71 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
FILE_PATH = os.path.dirname(__file__)
|
||||
|
||||
QIU_QIU_WORD = {}
|
||||
QIU_QIU_PHRASE = {}
|
||||
|
||||
with open(os.path.join(FILE_PATH, 'qiu_qiu_dictionary.json'), 'r', encoding='UTF-8') as f:
|
||||
data = json.load(f)
|
||||
QIU_QIU_WORD = data["word"]
|
||||
QIU_QIU_PHRASE = data["phrase"]
|
||||
|
||||
|
||||
def compare_words(word):
|
||||
# 比对word库是否有匹配的单词,有的话返回翻译,没有返回原词
|
||||
if word in QIU_QIU_WORD:
|
||||
return QIU_QIU_WORD[word]
|
||||
|
||||
return word
|
||||
|
||||
|
||||
def compare_phrase(phrase):
|
||||
# 比对phrase库是否有匹配的单词,有的话返回翻译,没有的话匹配word库,都没有返回原词
|
||||
if phrase in QIU_QIU_PHRASE:
|
||||
return QIU_QIU_PHRASE[phrase]
|
||||
if phrase in QIU_QIU_WORD:
|
||||
return QIU_QIU_WORD[phrase]
|
||||
|
||||
return phrase
|
||||
|
||||
|
||||
def qiu_qiu_word_translation(txt: str):
|
||||
# 对语句按空格分隔替换单词翻译
|
||||
txt_list = txt.split(" ")
|
||||
mes = "你查询的的丘丘语意思为:\n"
|
||||
|
||||
for word in txt_list:
|
||||
tra_word = compare_words(word)
|
||||
|
||||
if tra_word == word:
|
||||
# 如果是原词表示没有翻译,前后加空格接回语句里
|
||||
if not mes[-1] == " ":
|
||||
mes += " "
|
||||
mes += tra_word
|
||||
mes += " "
|
||||
else:
|
||||
mes += tra_word
|
||||
mes += "\n"
|
||||
return mes
|
||||
|
||||
|
||||
def qiu_qiu_phrase_translation(phrase):
|
||||
# 语句翻译,先看phrase库是不是有匹配的语句
|
||||
# 没有的话把单词拆开返回单词的意思
|
||||
tra_phrase = compare_phrase(phrase)
|
||||
if tra_phrase != phrase:
|
||||
return f"\n翻译丘丘语意思为:\n【{tra_phrase}】\n"
|
||||
|
||||
txt_list = phrase.split(" ")
|
||||
mes = "没有查到这句丘丘语,以下是单词的翻译\n"
|
||||
for word in txt_list:
|
||||
if word == " ":
|
||||
continue
|
||||
tra_word = compare_phrase(word)
|
||||
if tra_word == word:
|
||||
mes += f"{word} : 没有这个词的翻译\n"
|
||||
else:
|
||||
mes += f"{word} : {tra_word}\n"
|
||||
|
||||
return mes
|
||||
@ -1,96 +0,0 @@
|
||||
from nonebot import on_command, on_regex
|
||||
from .query_resource import get_resource_map_mes, get_resource_list_mes, up_label_and_point_list
|
||||
from util.utils import get_message_text, scheduler
|
||||
from nonebot.adapters.cqhttp import Bot, MessageEvent
|
||||
from nonebot.typing import T_State
|
||||
import os
|
||||
from services.log import logger
|
||||
import re
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
qr = on_command("原神资源查询", priority=5, block=True)
|
||||
qr_lst = on_command("原神资源列表", priority=5, block=True)
|
||||
rex_qr = on_regex('.*?(在哪|在哪里|哪有|哪里有).*?', priority=5, block=True)
|
||||
|
||||
|
||||
with open(os.path.dirname(__file__) + '/resource_type_id.json', 'r', encoding='utf-8') as f:
|
||||
in_list = [n['name'] for n in json.load(f).values()]
|
||||
|
||||
|
||||
@qr.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
resource_name = get_message_text(event.json())
|
||||
if resource_name == "" or resource_name not in in_list:
|
||||
return
|
||||
|
||||
await qr.send(get_resource_map_mes(resource_name), at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 查询原神材料:" + resource_name)
|
||||
|
||||
|
||||
@rex_qr.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
msg = get_message_text(event.json())
|
||||
if msg.find('在哪') != -1:
|
||||
rs = re.search('(.*)在哪.*?', msg)
|
||||
resource_name = rs.group(1) if rs else ''
|
||||
else:
|
||||
rs = re.search('.*?(哪有|哪里有)(.*)', msg)
|
||||
resource_name = rs.group(2) if rs else ''
|
||||
if resource_name:
|
||||
msg = get_resource_map_mes(resource_name)
|
||||
if msg == '发送 原神资源列表 查看所有资源名称':
|
||||
return
|
||||
await rex_qr.send(msg, at_sender=True)
|
||||
logger.info(
|
||||
f"(USER {event.user_id}, GROUP {event.group_id if event.message_type != 'private' else 'private'})"
|
||||
f" 查询原神材料:" + resource_name)
|
||||
|
||||
|
||||
@qr_lst.handle()
|
||||
async def _(bot: Bot, event: MessageEvent, state: T_State):
|
||||
# 长条消息经常发送失败,所以只能这样了
|
||||
mes_list = []
|
||||
txt = get_resource_list_mes()
|
||||
txt_list = txt.split("\n")
|
||||
if event.message_type == 'group':
|
||||
for txt in txt_list:
|
||||
data = {
|
||||
"type": "node",
|
||||
"data": {
|
||||
"name": f"这里是{list(bot.config.nickname)[0]}酱",
|
||||
"uin": f"{bot.self_id}",
|
||||
"content": txt
|
||||
}
|
||||
}
|
||||
mes_list.append(data)
|
||||
# await bot.send(ev, get_resource_list_mes(), at_sender=True)
|
||||
if event.message_type == 'group':
|
||||
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
|
||||
else:
|
||||
rst = ''
|
||||
for i in range(len(txt_list)):
|
||||
rst += txt_list[i] + '\n'
|
||||
if i % 5 == 0:
|
||||
if rst:
|
||||
await qr_lst.send(rst)
|
||||
rst = ''
|
||||
|
||||
# await qr_lst.send(Message(mes_list))
|
||||
|
||||
|
||||
@scheduler.scheduled_job(
|
||||
'cron',
|
||||
hour=5,
|
||||
minute=1,
|
||||
)
|
||||
async def _():
|
||||
try:
|
||||
up_label_and_point_list()
|
||||
logger.info(f'每日更新原神材料信息成功!')
|
||||
except Exception as e:
|
||||
logger.error(f'每日更新原神材料信息错误:{e}')
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
Before Width: | Height: | Size: 14 KiB |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user