新增xx是我xx用于个性化角色别名

This commit is contained in:
CMHopeSunshine 2022-08-26 17:13:18 +08:00
parent 9f4c3882f3
commit 4eb95741b3
7 changed files with 104 additions and 57 deletions

View File

@ -16,7 +16,7 @@ except KeyError:
logger.error('请在.env.prod文件中中配置超级用户SUPERUSERS')
try:
NICKNAME: str = list(DRIVER.config.superusers)[0]
NICKNAME: str = list(DRIVER.config.nickname)[0]
except KeyError:
NICKNAME = '派蒙'

View File

@ -259,3 +259,13 @@ class PlayerInfo(Model):
info.update_time = datetime.datetime.now()
await info.save()
class PlayerAlias(Model):
id = fields.IntField(pk=True, generated=True, auto_increment=True)
user_id: str = fields.CharField(max_length=255)
"""玩家qid"""
alias: str = fields.CharField(max_length=255)
"""别名"""
character: str = fields.CharField(max_length=255)
"""实际角色"""

View File

@ -8,6 +8,7 @@ from nonebot.params import CommandArg
from nonebot.permission import SUPERUSER
from nonebot.plugin import PluginMetadata
from LittlePaimon import NICKNAME
from LittlePaimon.database.models import LastQuery, PrivateCookie, PublicCookie, Character, PlayerInfo, GeneralSub, \
DailyNoteSub, MihoyoBBSSub
from LittlePaimon.utils import logger
@ -69,7 +70,7 @@ async def _(event: MessageEvent, msg: Message = CommandArg()):
if not msg:
await ysb.finish(f'成功绑定uid为{uid.group()}如果还需绑定cookie可看教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1',
at_sender=True)
if 'cookie_token' in msg and any(i in msg for i in ['account_id', 'login_uid', 'ltuid', 'stuid']):
elif msg:
if data := await get_bind_game_info(msg):
game_name = data['nickname']
game_uid = data['game_role_id']
@ -81,20 +82,20 @@ async def _(event: MessageEvent, msg: Message = CommandArg()):
await PrivateCookie.update_or_create(user_id=str(event.user_id), uid=game_uid, mys_id=mys_id,
defaults={'cookie': msg,
'stoken': f'stuid={mys_id};stoken={stoken};'})
await ysb.send(f'{game_name}成功绑定cookie{game_uid}', at_sender=True)
await ysb.send(f'{game_name}成功绑定cookie{game_uid},开始愉快地享用{NICKNAME}吧!', at_sender=True)
else:
await PrivateCookie.update_or_create(user_id=str(event.user_id), uid=game_uid, mys_id=mys_id,
defaults={'cookie': msg})
await ysb.send(f'{game_name}成功绑定cookie{game_uid}但是cookie中没有login_ticket或lt无效,米游币相关功能无法使用哦',
await ysb.send(f'{game_name}成功绑定cookie{game_uid}但是cookie中没有login_ticket,米游币相关功能无法使用哦',
at_sender=True)
if not isinstance(event, PrivateMessageEvent):
if await recall_message(event):
await ysb.finish('当前非私聊对话已将你的cookie撤回')
await ysb.finish(f'当前非私聊对话,{NICKNAME}帮你把cookie撤回啦')
else:
await ysb.finish('当前非私聊对话,建议绑定完将cookie撤回')
await ysb.finish(f'当前非私聊对话,{NICKNAME}建议绑定完将cookie撤回')
else:
logger.info('原神Cookie', '', {'用户': str(event.user_id)}, '绑定失败cookie已失效', False)
await ysb.finish('这个cookie无效,请确认是否正确\n获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n', at_sender=True)
await ysb.finish('这个cookie无效,请确认是否正确\n获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n', at_sender=True)
elif pm.config.CookieWeb_enable:
await ysb.finish(
f'获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n获取后,使用[ysb cookie]指令绑定或前往{pm.config.CookieWeb_url}网页添加绑定',
@ -159,8 +160,7 @@ async def _(event: MessageEvent):
@pck.handle()
async def _(event: MessageEvent, msg: Message = CommandArg()):
msg = msg.extract_plain_text().strip()
if 'cookie_token' in msg and any(i in msg for i in ['account_id', 'login_uid', 'ltuid', 'stuid']):
if msg := msg.extract_plain_text().strip():
if await get_bind_game_info(msg):
ck = await PublicCookie.create(cookie=msg)
logger.info('原神Cookie', f'{ck.id}号公共cookie', None, '添加成功', True)

View File

@ -1,12 +1,15 @@
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Message, MessageEvent
from nonebot.internal.params import Arg
from nonebot import on_command, on_regex
from nonebot.adapters.onebot.v11 import Message, MessageEvent, MessageSegment
from nonebot.params import Arg, RegexDict
from nonebot.plugin import PluginMetadata
from LittlePaimon import NICKNAME
from LittlePaimon.database.models import PlayerAlias
from LittlePaimon.utils import logger
from LittlePaimon.utils.message import CommandPlayer, CommandCharacter, CommandUID
from LittlePaimon.utils.genshin import GenshinInfoManager
from LittlePaimon.utils.tool import freq_limiter
from LittlePaimon.utils.typing import CHARA_RE
from .draw_player_card import draw_player_card
from .draw_character_bag import draw_chara_bag
@ -61,6 +64,12 @@ update_info = on_command('udi', aliases={'更新角色信息', '更新面板', '
'pm_usage': '更新角色信息(uid)',
'pm_priority': 6
})
add_alias = on_regex(rf'((?P<chara>{CHARA_RE})是[我俺咱]的?(?P<alias>\w+))|([我俺咱]的?(?P<alias2>\w+)[是叫名](?P<chara2>{CHARA_RE}))', priority=10, block=True, state={
'pm_name': '角色别名设置',
'pm_description': '设置专属于你的角色别名',
'pm_usage': '<角色名>是我<别名>',
'pm_priority': 7
})
@ys.handle()
@ -154,11 +163,11 @@ async def _(event: MessageEvent, players=CommandPlayer(only_cn=False), character
for character in characters:
character_info = await gim.get_character(name=character)
if not character_info:
logger.info('原神角色卡片', '➤➤', {'角色': character}, '没有该角色信息', False)
msg += f'\n暂无你{character}信息,请先更新角色信息'
logger.info('原神角色卡片', '➤➤', {'角色': character}, '没有该角色信息,发送随机图', True)
msg += MessageSegment.image(f'http://img.genshin.cherishmoon.fun/{character}')
else:
img = await draw_chara_card(character_info)
logger.info('原神角色卡片', '➤➤', {}, '制图完成', True)
logger.info('原神角色卡片', '➤➤', {'角色': character}, '制图完成', True)
msg += img
else:
# 当查询对象有多个时,只查询第一个角色
@ -168,10 +177,11 @@ async def _(event: MessageEvent, players=CommandPlayer(only_cn=False), character
logger.info('原神角色卡片', '', {'用户': player.user_id, 'UID': player.uid})
character_info = await gim.get_character(name=characters[0])
if not character_info:
msg += f'\n暂无{player.uid}{characters[0]}信息,请先更新角色信息'
logger.info('原神角色卡片', '➤➤', {'角色': characters[0]}, '没有该角色信息,发送随机图', True)
msg += MessageSegment.image(f'http://img.genshin.cherishmoon.fun/{characters[0]}')
else:
img = await draw_chara_card(character_info)
logger.info('原神角色卡片', '➤➤', {}, '制图完成', True)
logger.info('原神角色卡片', '➤➤', {'角色': characters[0]}, '制图完成', True)
msg += img
await ysd.finish(msg, at_sender=True)
@ -232,3 +242,11 @@ async def _(event: MessageEvent, uid=CommandUID(), msg: str = Arg('msg')):
result = f'更新失败,错误信息:{e}'
running_udi.remove(f'{event.user_id}-{uid}')
await update_info.finish(f'UID{uid}:\n{result}', at_sender=True)
@add_alias.handle()
async def _(event: MessageEvent, regex_dict: dict = RegexDict()):
chara = regex_dict['chara'] or regex_dict['chara2']
alias = regex_dict['alias'] or regex_dict['alias2']
await PlayerAlias.update_or_create(user_id=str(event.user_id), alias=alias, character=chara)
await add_alias.finish(f'{NICKNAME}知道{chara}是你的{alias}啦..')

View File

@ -13,13 +13,10 @@ from LittlePaimon.utils.files import load_json
from LittlePaimon.utils.genshin_api import get_enka_data, get_mihoyo_public_data, get_mihoyo_private_data
from LittlePaimon.utils.typing import DataSourceType
from LittlePaimon.utils.alias import get_name_by_id
from LittlePaimon.utils.typing import CHARACTERS
ra_score = load_json(JSON_DATA / 'score.json')
talent_map = load_json(JSON_DATA / 'role_skill.json')
all_character_list = ['神里绫华', '', '丽莎', '芭芭拉', '凯亚', '迪卢克', '雷泽', '安柏', '温迪', '香菱', '北斗', '行秋', '', '凝光', '可莉', '钟离',
'菲谢尔', '班尼特', '达达利亚', '诺艾尔', '七七', '重云', '甘雨', '阿贝多', '迪奥娜', '莫娜', '刻晴', '砂糖', '辛焱', '罗莎莉亚', '胡桃',
'枫原万叶', '烟绯', '宵宫', '托马', '优菈', '雷电将军', '早柚', '珊瑚宫心海', '五郎', '九条裟罗', '荒泷一斗', '八重神子', '夜兰', '埃洛伊',
'申鹤', '云堇', '久岐忍', '神里绫人', '鹿野院平藏', '提纳里', '柯莱', '多莉']
class GenshinInfoManager:
@ -50,14 +47,14 @@ class GenshinInfoManager:
await self.set_last_query()
mihoyo_result = await self.update_from_mihoyo()
if mihoyo_result != '更新成功':
result += f'\n2.{mihoyo_result}'
result += f'{mihoyo_result}\n'
enka_result = await self.update_from_enka()
if not enka_result.endswith('更新成功'):
result += f'1.{enka_result}'
if not enka_result.startswith('更新成功'):
result += f'{enka_result}\n'
if include_talent and await self.is_bind():
talent_result = await self.update_talent()
if talent_result not in ['更新成功', mihoyo_result]:
result += f'\n3.{talent_result}'
result += f'{talent_result}\n'
return result or enka_result
async def update_from_enka(self) -> str:
@ -201,7 +198,7 @@ class GenshinInfoManager:
return result, []
player_info = await PlayerInfo.get_or_none(user_id=self.user_id, uid=self.uid)
character_list = []
for character_name in all_character_list:
for character_name in CHARACTERS:
if character := await self.get_character(name=character_name):
character_list.append(character)
return player_info, character_list

View File

@ -1,3 +1,4 @@
import random
import re
import time
from io import BytesIO
@ -12,11 +13,12 @@ from nonebot.matcher import Matcher
from nonebot.params import CommandArg, Depends
from nonebot.typing import T_State
from LittlePaimon.database.models import LastQuery, PrivateCookie, Player
from LittlePaimon.database.models import LastQuery, PrivateCookie, Player, PlayerAlias
from LittlePaimon.utils import aiorequests, load_image
from LittlePaimon.utils.alias import get_match_alias
from LittlePaimon.utils.image import PMImage
from LittlePaimon.utils.filter import filter_msg
from LittlePaimon.utils.typing import CHARACTERS, MALE_CHARACTERS, FEMALE_CHARACTERS, GIRL_CHARACTERS, BOY_CHARACTERS, LOLI_CHARACTERS
class MessageBuild:
@ -151,8 +153,8 @@ class MessageBuild:
def CommandPlayer(limit: int = 3, only_cn: bool = True) -> List[Player]:
"""
获取查询操作中的user_iduid和图片并将过滤uid后的msg存放到T_State中
:param: 限制个数
:param: 是否只接受国服uid
:param limit: 限制个数
:param only_cn: 是否只接受国服uid
:return: 查询对象列表
"""
@ -172,6 +174,8 @@ def CommandPlayer(limit: int = 3, only_cn: bool = True) -> List[Player]:
info += f'{u}尚未提供uid\n'
if info:
await matcher.finish(info, at_sender=True)
else:
state['main_user'] = users[0]
else:
user = users[0]
uids: List[str] = []
@ -184,6 +188,7 @@ def CommandPlayer(limit: int = 3, only_cn: bool = True) -> List[Player]:
extra_info = replace_all(extra_info, uids)
for uid in uids:
query_list.append(Player(user_id=user, uid=uid))
state['main_user'] = str(event.user_id)
if len(query_list) > limit:
query_list = query_list[:limit]
@ -198,8 +203,7 @@ def CommandPlayer(limit: int = 3, only_cn: bool = True) -> List[Player]:
def CommandUID(only_cn: bool = True) -> str:
"""
从消息中提取uid
:param: 限制个数
:param: 是否只接受国服uid
:param only_cn: 是否只接受国服uid
:return: uid
"""
@ -222,18 +226,36 @@ def CommandUID(only_cn: bool = True) -> str:
def CommandCharacter(limit: int = 3, replace_uid: bool = True) -> List[str]:
"""
从命令中提取出原神的角色需配合CommandUID使用
:param: 限制个数
:param limit: 限制个数
:param replace_uid: 是否先移除msg中的uid
:return: 角色名列表
"""
async def _character(matcher: Matcher, state: T_State, msg: str = Arg('msg')):
async def _character(matcher: Matcher, state: T_State, user_id: str = Arg('main_user')):
msg = state['_prefix']['command_arg'].extract_plain_text().strip() if replace_uid else state['msg']
if not msg:
await matcher.finish('请给出要查询的角色名称')
return random.choice(CHARACTERS)
character_list = []
characters = msg.split(' ')
for character_name in characters:
character_match = get_match_alias(character_name, '角色', True)
if character_match:
if character_match := await PlayerAlias.get_or_none(user_id=user_id, alias=character_name):
character_list.append(character_match.character)
msg.replace(character_name, '')
elif character_name in ['老婆', '老公', '女儿', '儿子', '爸爸', '妈妈']:
if character_name == '老公':
character_list.append(random.choice(MALE_CHARACTERS + BOY_CHARACTERS))
elif character_name == '老婆':
character_list.append(random.choice(FEMALE_CHARACTERS + GIRL_CHARACTERS))
elif character_name == '女儿':
character_list.append(random.choice(GIRL_CHARACTERS + LOLI_CHARACTERS))
elif character_name == '儿子':
character_list.append(random.choice(BOY_CHARACTERS))
elif character_name == '爸爸':
character_list.append(random.choice(MALE_CHARACTERS))
elif character_name == '妈妈':
character_list.append(random.choice(FEMALE_CHARACTERS))
msg.replace(character_name, '')
elif character_match := get_match_alias(character_name, '角色', True):
character_list.append(list(character_match.keys())[0])
msg.replace(character_name, '')
if not character_list:
@ -243,25 +265,7 @@ def CommandCharacter(limit: int = 3, replace_uid: bool = True) -> List[str]:
character_list = character_list[:limit]
return character_list
async def _character2(matcher: Matcher, state: T_State, msg: Message = CommandArg()):
msg = msg.extract_plain_text().strip()
if not msg:
await matcher.finish('请给出要查询的角色名称')
character_list = []
characters = msg.split(' ')
for character_name in characters:
character_match = get_match_alias(character_name, '角色', True)
if character_match:
character_list.append(list(character_match.keys())[0])
msg.replace(character_name, '')
if not character_list:
await matcher.finish(f'没有名为{msg}的角色!')
state['msg'] = msg
if len(character_list) > limit:
character_list = character_list[:limit]
return character_list
return Depends(_character) if replace_uid else Depends(_character2)
return Depends(_character)
def CommandObjectID() -> int:
@ -328,7 +332,7 @@ def CommandTime() -> Optional[Tuple[int, int]]:
def _datetime(msg: Message = CommandArg()):
msg = msg.extract_plain_text().strip()
if match := re.search(r'(\d{1,2}):(\d{2})', msg):
return match.group(1), match.group(2)
return match[1], match[2]
return None
return Depends(_datetime)

View File

@ -12,4 +12,22 @@ PropType = Literal['基础生命', '额外生命', '基础攻击', '额外攻击
CN_NUMBER = ['', '', '', '', '', '', '', '', '', '', '', '十一', '十二']
CHARACTERS = ['神里绫华', '', '丽莎', '芭芭拉', '凯亚', '迪卢克', '雷泽', '安柏', '温迪', '香菱', '北斗', '行秋', '', '凝光', '可莉', '钟离',
'菲谢尔', '班尼特', '达达利亚', '诺艾尔', '七七', '重云', '甘雨', '阿贝多', '迪奥娜', '莫娜', '刻晴', '砂糖', '辛焱', '罗莎莉亚', '胡桃',
'枫原万叶', '烟绯', '宵宫', '托马', '优菈', '雷电将军', '早柚', '珊瑚宫心海', '五郎', '九条裟罗', '荒泷一斗', '八重神子', '夜兰', '埃洛伊',
'申鹤', '云堇', '久岐忍', '神里绫人', '鹿野院平藏', '提纳里', '柯莱']
"""全角色"""
MALE_CHARACTERS = ['凯亚', '迪卢克', '钟离', '达达利亚', '托马', '荒泷一斗', '神里绫人']
"""成男角色"""
FEMALE_CHARACTERS = ['', '丽莎', '北斗', '凝光', '罗莎莉亚', '优菈', '雷电将军', '九条裟罗', '八重神子', '夜兰', '申鹤']
"""成女角色"""
GIRL_CHARACTERS = ['神里绫华', '芭芭拉', '安柏', '香菱', '菲谢尔', '诺艾尔', '甘雨', '莫娜', '刻晴', '砂糖', '辛焱', '胡桃', '烟绯', '宵宫', '珊瑚宫心海', '埃洛伊', '云堇', '久岐忍', '柯莱']
"""少女角色"""
BOY_CHARACTERS = ['雷泽', '温迪', '行秋', '', '班尼特', '重云', '阿贝多', '枫原万叶', '五郎', '鹿野院平藏', '提纳里']
"""少男角色"""
LOLI_CHARACTERS = ['七七', '可莉', '迪奥娜', '早柚']
"""萝莉"""
CHARA_RE = '|'.join(CHARACTERS)