Support run command specifying uid

This commit is contained in:
xtaodada 2024-06-12 20:43:28 +08:00
parent 1fc72d29e3
commit dc447696ef
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
16 changed files with 146 additions and 247 deletions

@ -1 +1 @@
Subproject commit db839a7ad8ebd96b8488b67acdb088c85b87c42e
Subproject commit c47d04c3502deaf239c61f1c179e592d3c71aa29

View File

@ -51,37 +51,33 @@ class PlayerActivityPlugins(Plugin):
self.assets = assets
self.helper = helper
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> int:
async def get_uid(self, user_id: int, reply: Optional[Message], player_id: int, offset: int) -> int:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_ = None, user_id
if args:
for i in args:
if i is not None:
if i.isdigit() and len(i) == 9:
uid = int(i)
uid, user_id_ = player_id, user_id
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
player_info = await self.helper.players_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
player_info = await self.helper.players_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid
@handler.command("fantastic_story", block=False)
@handler.message(filters.Regex("^评书奇谭信息查询(.*)"), block=False)
async def fantastic_story_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def fantastic_story_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询评书奇谭信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.fantastic_story_render(client, uid)
except AttributeError as exc:
@ -132,12 +128,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("yitai_battle", block=False)
@handler.message(filters.Regex("^以太战线信息查询(.*)"), block=False)
async def yitai_battle_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def yitai_battle_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询以太战线信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.yitai_battle_render(client, uid)
except AttributeError as exc:
@ -180,12 +177,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("endless_side", block=False)
@handler.message(filters.Regex("^无尽位面信息查询(.*)"), block=False)
async def endless_side_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def endless_side_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询无尽位面信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.endless_side_render(client, uid)
except AttributeError as exc:
@ -232,12 +230,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("fox_story", block=False)
@handler.message(filters.Regex("^狐斋志异信息查询(.*)"), block=False)
async def fox_story_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def fox_story_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询狐斋志异信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.fox_story_render(client, uid)
except AttributeError as exc:
@ -578,12 +577,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("boxing_show", block=False)
@handler.message(filters.Regex("^斗技表演赛信息查询(.*)"), block=False)
async def boxing_show_command_start(self, update: Update, context: CallbackContext) -> None:
async def boxing_show_command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询斗技表演赛信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.boxing_show_render(client, uid)
except AttributeError as exc:
@ -634,12 +634,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("space_zoo", block=False)
@handler.message(filters.Regex("^异宠拾遗信息查询(.*)"), block=False)
async def space_zoo_command_start(self, update: Update, context: CallbackContext) -> None:
async def space_zoo_command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询异宠拾遗信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.space_zoo_render(client, uid)
except AttributeError as exc:
@ -690,12 +691,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("treasure_dungeon", block=False)
@handler.message(filters.Regex("^地城探宝信息查询(.*)"), block=False)
async def treasure_dungeon_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def treasure_dungeon_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询地城探宝信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.treasure_dungeon_render(client, uid)
if render_result is None:
@ -760,12 +762,13 @@ class PlayerActivityPlugins(Plugin):
@handler.command("copper_man", block=False)
@handler.message(filters.Regex("^金人巷信息查询(.*)"), block=False)
async def copper_man_command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def copper_man_command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询金人巷信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
uid = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.copper_man_render(client, uid)
except AttributeError as exc:

View File

@ -190,11 +190,12 @@ class AvatarListPlugin(Plugin):
async def avatar_list(self, update: "Update", _: "ContextTypes.DEFAULT_TYPE"):
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
all_avatars = "全部" in message.text or "all" in message.text # 是否发送全部角色
self.log_user(update, logger.info, "[bold]练度统计[/bold]: all=%s", all_avatars, extra={"markup": True})
await message.reply_chat_action(ChatAction.TYPING)
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid, offset=offset) as client:
notice = await message.reply_text("彦卿需要收集整理数据,还请耐心等待哦~")
self.add_delete_message_job(notice, delay=60)
characters: List["StarRailDetailCharacter"] = await self.get_avatars_data(client)

View File

@ -83,34 +83,31 @@ class ChallengePlugin(Plugin):
self.history_data_abyss = history_data_abyss
self.cache = RedisCache(redis.client, key="plugin:challenge:history")
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> int:
async def get_uid(self, user_id: int, reply: Optional[Message], player_id: int, offset: int) -> int:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_ = None, user_id
if args:
for i in args:
if i is not None and i.isdigit() and len(i) == 9:
uid = int(i)
uid, user_id_ = player_id, user_id
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
player_info = await self.helper.players_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
player_info = await self.helper.players_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid
@handler.command("challenge", block=False)
@handler.message(filters.Regex(msg_pattern), block=False)
async def command_start(self, update: Update, context: CallbackContext) -> None:
async def command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid: int = await self.get_uid(user_id, context.args, message.reply_to_message)
uid, offset = self.get_real_uid_or_offset(update)
uid: int = await self.get_uid(user_id, message.reply_to_message, uid, offset)
# 若查询帮助
if (message.text.startswith("/") and "help" in message.text) or "帮助" in message.text:
@ -468,10 +465,11 @@ class ChallengePlugin(Plugin):
@handler.command("challenge_history", block=False)
@handler.message(filters.Regex(r"^混沌回忆历史数据"), block=False)
async def abyss_history_command_start(self, update: Update, context: CallbackContext) -> None:
async def abyss_history_command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid: int = await self.get_uid(user_id, context.args, message.reply_to_message)
uid, offset = self.get_real_uid_or_offset(update)
uid: int = await self.get_uid(user_id, message.reply_to_message, uid, offset)
self.log_user(update, logger.info, "查询混沌回忆历史数据 uid[%s]", uid)
async with self.helper.genshin_or_public(user_id, uid=uid) as _:

View File

@ -82,34 +82,31 @@ class ChallengeStoryPlugin(Plugin):
self.history_data_abyss = history_data_abyss
self.cache = RedisCache(redis.client, key="plugin:challenge_story:history")
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> int:
async def get_uid(self, user_id: int, reply: Optional[Message], player_id: int, offset: int) -> int:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_ = None, user_id
if args:
for i in args:
if i is not None and i.isdigit() and len(i) == 9:
uid = int(i)
uid, user_id_ = player_id, user_id
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
player_info = await self.helper.players_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
player_info = await self.helper.players_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid
@handler.command("challenge_story", block=False)
@handler.message(filters.Regex(msg_pattern), block=False)
async def command_start(self, update: Update, context: CallbackContext) -> None:
async def command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid: int = await self.get_uid(user_id, context.args, message.reply_to_message)
uid, offset = self.get_real_uid_or_offset(update)
uid: int = await self.get_uid(user_id, message.reply_to_message, uid, offset)
# 若查询帮助
if (message.text.startswith("/") and "help" in message.text) or "帮助" in message.text:
@ -484,10 +481,11 @@ class ChallengeStoryPlugin(Plugin):
@handler.command("challenge_story_history", block=False)
@handler.message(filters.Regex(r"^虚构叙事历史数据"), block=False)
async def challenge_story_history_command_start(self, update: Update, context: CallbackContext) -> None:
async def challenge_story_history_command_start(self, update: Update, _: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid: int = await self.get_uid(user_id, context.args, message.reply_to_message)
uid, offset = self.get_real_uid_or_offset(update)
uid: int = await self.get_uid(user_id, message.reply_to_message, uid, offset)
self.log_user(update, logger.info, "查询虚构叙事历史数据 uid[%s]", uid)
async with self.helper.genshin_or_public(user_id, uid=uid) as _:

View File

@ -92,10 +92,11 @@ class DailyNotePlugin(Plugin):
async def command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "每日便签命令请求")
try:
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid, offset=offset) as client:
render_result = await self._get_daily_note(client)
except DataNotPublic:
reply_message = await message.reply_text(

View File

@ -96,6 +96,7 @@ class LedgerPlugin(Plugin):
async def command_start(self, update: Update, context: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
now = datetime.now()
now_time = (now - timedelta(days=1)) if now.day == 1 and now.hour <= 4 else now
@ -130,7 +131,7 @@ class LedgerPlugin(Plugin):
self.log_user(update, logger.info, "查询开拓月历")
await message.reply_chat_action(ChatAction.TYPING)
try:
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid, offset=offset) as client:
render_result = await self._start_get_ledger(client, year, month)
except DataNotPublic:
reply_message = await message.reply_text(
@ -238,9 +239,10 @@ class LedgerPlugin(Plugin):
async def ledger_history_command_start(self, update: "Update", _: "ContextTypes.DEFAULT_TYPE") -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询开拓月历历史数据")
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid, offset=offset) as client:
await self.get_session_button_data(user_id, client.player_id, force=True)
buttons = await self.gen_season_button(user_id, client.player_id)
if not buttons:
@ -256,13 +258,13 @@ class LedgerPlugin(Plugin):
if reply_message.photo:
self.kitsune = reply_message.photo[-1].file_id
async def get_ledger_history_page(self, update: "Update", user_id: int, result: str):
async def get_ledger_history_page(self, update: "Update", user_id: int, uid: int, result: str):
"""翻页处理"""
callback_query = update.callback_query
self.log_user(update, logger.info, "切换开拓月历历史数据页 page[%s]", result)
page = int(result.split("_")[1])
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid) as client:
buttons = await self.gen_season_button(user_id, client.player_id, page)
if not buttons:
await callback_query.answer("还没有开拓月历历史数据哦~", show_alert=True)
@ -292,7 +294,7 @@ class LedgerPlugin(Plugin):
)
return _result, _user_id, _uid
result, user_id, _ = await get_ledger_history_callback(callback_query.data)
result, user_id, uid = await get_ledger_history_callback(callback_query.data)
if user.id != user_id:
await callback_query.answer(text="这不是你的按钮!\n" + config.notice.user_mismatch, show_alert=True)
return
@ -300,7 +302,7 @@ class LedgerPlugin(Plugin):
await callback_query.answer(text="此按钮不可用", show_alert=True)
return
if result.startswith("p_"):
await self.get_ledger_history_page(update, user_id, result)
await self.get_ledger_history_page(update, user_id, uid, result)
return
data_id = int(result)
data = await self.history_data_ledger.get_by_id(data_id)

View File

@ -1,125 +0,0 @@
from typing import Optional, List, Dict, TYPE_CHECKING
from simnet.errors import BadRequest as SimnetBadRequest
from simnet.models.starrail.chronicle.museum import StarRailMuseumBasic, StarRailMuseumDetail
from telegram import Update, Message
from telegram.constants import ChatAction
from telegram.ext import CallbackContext, filters
from core.dependence.assets import AssetsService
from core.plugin import Plugin, handler
from core.services.cookies.error import TooManyRequestPublicCookies
from core.services.template.models import RenderResult
from core.services.template.services import TemplateService
from plugins.tools.genshin import GenshinHelper
from utils.log import logger
from utils.uid import mask_number
if TYPE_CHECKING:
from simnet import StarRailClient
__all__ = ("PlayerMuseumPlugins",)
class NotHaveData(Exception):
"""没有数据"""
class PlayerMuseumPlugins(Plugin):
"""玩家冬城博物珍奇簿查询"""
def __init__(
self,
template: TemplateService,
assets: AssetsService,
helper: GenshinHelper,
):
self.template_service = template
self.assets = assets
self.helper = helper
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> int:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_ = None, user_id
if args:
for i in args:
if i is not None:
if i.isdigit() and len(i) == 9:
uid = int(i)
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
if player_info is not None:
uid = player_info.player_id
return uid
@handler.command("museum", block=False)
@handler.message(filters.Regex("^博物馆信息查询(.*)"), block=False)
async def command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
self.log_user(update, logger.info, "查询博物馆信息命令请求")
try:
uid = await self.get_uid(user_id, context.args, message.reply_to_message)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.render(client, uid)
except TooManyRequestPublicCookies:
await message.reply_text("用户查询次数过多 请稍后重试")
return
except AttributeError as exc:
logger.error("冬城博物珍奇簿数据有误")
logger.exception(exc)
await message.reply_text("冬城博物珍奇簿数据有误 估计是彦卿晕了")
return
except NotHaveData:
reply_message = await message.reply_text("没有查找到冬城博物珍奇簿数据")
if filters.ChatType.GROUPS.filter(reply_message):
self.add_delete_message_job(message)
self.add_delete_message_job(reply_message)
return
await message.reply_chat_action(ChatAction.UPLOAD_PHOTO)
await render_result.reply_photo(message, filename=f"{user_id}.png")
@staticmethod
async def get_rander_data(uid: int, basic: StarRailMuseumBasic, detail: StarRailMuseumDetail) -> Dict:
exhibitions = []
for region in detail.regions:
for exhibition in region.exhibitions:
exhibitions.append(exhibition)
all_exhibitions = [exhibitions[i : i + 7] for i in range(0, len(exhibitions), 7)]
return {
"uid": mask_number(uid),
"basic": basic,
"all_exhibitions": all_exhibitions,
"directors": detail.director,
}
async def render(self, client: "StarRailClient", uid: Optional[int] = None) -> RenderResult:
if uid is None:
uid = client.player_id
try:
basic = await client.get_starrail_museum_info(uid)
detail = await client.get_starrail_museum_detail(uid)
except SimnetBadRequest as e:
if e.retcode == 10301:
raise NotHaveData from e
raise e
data = await self.get_rander_data(uid, basic, detail)
return await self.template_service.render(
"starrail/museum/museum.html",
data,
{"width": 1000, "height": 1000},
full_page=True,
query_selector="#main-container",
)

View File

@ -83,28 +83,30 @@ class PlayerCards(Plugin):
return PlayerInfo.parse_obj(data)
async def get_uid_and_ch(
self, user_id: int, args: List[str], reply: Optional[Message]
self,
user_id: int,
args: List[str],
reply: Optional["Message"],
player_id: int,
offset: int,
) -> Tuple[Optional[int], Optional[str]]:
"""通过消息获取 uid优先级args > reply > self"""
uid, ch_name, user_id_ = None, None, user_id
uid, ch_name, user_id_ = player_id, None, user_id
if args:
for i in args:
if i is not None:
if i.isdigit() and len(i) == 9:
uid = int(i)
else:
ch_name = roleToName(i)
if i is not None and not i.startswith("@"):
ch_name = roleToName(i)
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.player_service.get_player(user_id_)
player_info = await self.player_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.player_service.get_player(user_id)
player_info = await self.player_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid, ch_name
@ -125,7 +127,8 @@ class PlayerCards(Plugin):
message = update.effective_message
args = self.get_args(context)
await message.reply_chat_action(ChatAction.TYPING)
uid, ch_name = await self.get_uid_and_ch(user_id, args, message.reply_to_message)
uid, offset = self.get_real_uid_or_offset(update)
uid, ch_name = await self.get_uid_and_ch(user_id, args, message.reply_to_message, uid, offset)
if uid is None:
raise PlayerNotFoundError(user_id)
data = await self._load_history(uid)

View File

@ -91,7 +91,8 @@ class Redeem(Plugin):
self.add_delete_message_job(reply_message)
async def redeem_codes(self, update: Update, user_id: int, codes: List[str]):
async with self.genshin_helper.genshin(user_id) as client:
uid, offset = self.get_real_uid_or_offset(update)
async with self.genshin_helper.genshin(user_id, player_id=uid, offset=offset) as client:
chinese = client.region == Region.CHINESE
uid = client.player_id
tasks = []
@ -108,7 +109,7 @@ class Redeem(Plugin):
if filters.ChatType.GROUPS.filter(message):
self.add_delete_message_job(message)
limit = self.max_code_in_pub_message
codes = [i for i in self.get_args(context) if i][:limit]
codes = [i for i in self.get_args(context) if not i.startswith("@")][:limit]
self.log_user(update, logger.info, "兑换码兑换命令请求 codes[%s]", codes)
if not codes:
return

View File

@ -78,7 +78,9 @@ class RedeemRunner:
error = None
try:
async with self.genshin_helper.genshin(
result.user_id, region=RegionEnum.HOYOLAB if only_region else None
result.user_id,
region=RegionEnum.HOYOLAB if only_region else None,
player_id=result.uid,
) as client:
client: "StarRailClient"
result.uid = client.player_id

View File

@ -58,27 +58,26 @@ class PlayerRoguePlugins(Plugin):
self.assets = assets
self.helper = helper
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> Tuple[int, bool]:
async def get_uid(
self, user_id: int, args: List[str], reply: Optional[Message], player_id: int, offset: int
) -> Tuple[int, bool]:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_, pre = None, user_id, False
uid, user_id_, pre = player_id, user_id, False
if args:
for i in args:
if i is not None:
if i.isdigit() and len(i) == 9:
uid = int(i)
if "" in i:
pre = True
if i is not None and "" in i:
pre = True
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
player_info = await self.helper.players_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
player_info = await self.helper.players_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid, pre
@ -88,9 +87,10 @@ class PlayerRoguePlugins(Plugin):
async def command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
self.log_user(update, logger.info, "查询模拟宇宙信息命令请求")
try:
uid, pre = await self.get_uid(user_id, context.args, message.reply_to_message)
uid, pre = await self.get_uid(user_id, context.args, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.render(client, pre, uid)
except TooManyRequestPublicCookies:

View File

@ -348,9 +348,12 @@ class RoleDetailPlugin(Plugin.Conversation):
async def command_start(self, update: "Update", context: "ContextTypes.DEFAULT_TYPE") -> None:
user_id = await self.get_real_user_id(update)
message = update.effective_message
uid, offset = self.get_real_uid_or_offset(update)
args = self.get_args(context)
ch_name = None
for i in args:
if i.startswith("@"):
continue
ch_name = roleToName(i)
if ch_name:
break
@ -361,7 +364,7 @@ class RoleDetailPlugin(Plugin.Conversation):
ch_name,
)
await message.reply_chat_action(ChatAction.TYPING)
async with self.helper.genshin(user_id) as client:
async with self.helper.genshin(user_id, player_id=uid, offset=offset) as client:
nickname, data = await self.get_characters(client.player_id, client)
uid = client.player_id
if ch_name is None:
@ -443,7 +446,7 @@ class RoleDetailPlugin(Plugin.Conversation):
try:
nickname, data = await self.get_characters(uid)
except NeedClient:
async with self.helper.genshin(user.id) as client:
async with self.helper.genshin(user.id, player_id=uid) as client:
nickname, data = await self.get_characters(client.player_id, client)
if page:
buttons = self.gen_button(data, user.id, uid, page)
@ -518,7 +521,7 @@ class RoleDetailPlugin(Plugin.Conversation):
try:
nickname, data = await self.get_characters(uid)
except NeedClient:
async with self.helper.genshin(user.id) as client:
async with self.helper.genshin(user.id, player_id=uid) as client:
nickname, data = await self.get_characters(client.player_id, client)
rec = data.get_recommend_property_by_cid(char_id)
if not rec:

View File

@ -41,37 +41,33 @@ class PlayerStatsPlugins(Plugin):
self.phone_theme = phone_theme
self.player_info_service = player_info_service
async def get_uid(self, user_id: int, args: List[str], reply: Optional[Message]) -> int:
async def get_uid(self, user_id: int, reply: Optional[Message], player_id: int, offset: int) -> int:
"""通过消息获取 uid优先级args > reply > self"""
uid, user_id_ = None, user_id
if args:
for i in args:
if i is not None:
if i.isdigit() and len(i) == 9:
uid = int(i)
uid, user_id_ = player_id, user_id
if reply:
try:
user_id_ = reply.from_user.id
except AttributeError:
pass
if not uid:
player_info = await self.helper.players_service.get_player(user_id_)
player_info = await self.helper.players_service.get_player(user_id_, offset=offset)
if player_info is not None:
uid = player_info.player_id
if (not uid) and (user_id_ != user_id):
player_info = await self.helper.players_service.get_player(user_id)
player_info = await self.helper.players_service.get_player(user_id, offset=offset)
if player_info is not None:
uid = player_info.player_id
return uid
@handler.command("stats", player=True, block=False)
@handler.message(filters.Regex("^玩家统计查询(.*)"), player=True, block=False)
async def command_start(self, update: Update, context: CallbackContext) -> Optional[int]:
async def command_start(self, update: Update, _: CallbackContext) -> Optional[int]:
user_id = await self.get_real_user_id(update)
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
self.log_user(update, logger.info, "查询游戏用户命令请求")
try:
uid: int = await self.get_uid(user_id, context.args, message.reply_to_message)
uid: int = await self.get_uid(user_id, message.reply_to_message, uid, offset)
async with self.helper.genshin_or_public(user_id, uid=uid) as client:
render_result = await self.render(client, uid)
except TooManyRequestPublicCookies:

View File

@ -71,16 +71,16 @@ class WishLogPlugin(Plugin.Conversation):
self.gacha_log = GachaLog()
self.wish_photo = None
async def get_player_id(self, uid: int) -> Optional[int]:
async def get_player_id(self, user_id: int, player_id: int, offset: int) -> int:
"""获取绑定的游戏ID"""
logger.debug("尝试获取已绑定的星穹铁道账号")
player = await self.players_service.get_player(uid)
player = await self.players_service.get_player(user_id, player_id=player_id, offset=offset)
if player is None:
raise PlayerNotFoundError(uid)
raise PlayerNotFoundError(user_id)
return player.player_id
async def _refresh_user_data(
self, user: User, data: dict = None, authkey: str = None, verify_uid: bool = True
self, user: User, player_id: int, data: dict = None, authkey: str = None, verify_uid: bool = True
) -> str:
"""刷新用户数据
:param user: 用户
@ -90,7 +90,6 @@ class WishLogPlugin(Plugin.Conversation):
"""
try:
logger.debug("尝试获取已绑定的星穹铁道账号")
player_id = await self.get_player_id(user.id)
if authkey:
new_num = await self.gacha_log.get_gacha_log_data(user.id, player_id, authkey)
return "更新完成,本次没有新增数据" if new_num == 0 else f"更新完成,本次共新增{new_num}条跃迁记录"
@ -113,7 +112,7 @@ class WishLogPlugin(Plugin.Conversation):
logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
return config.notice.user_not_found
async def import_from_file(self, user: User, message: Message, document: Document = None) -> None:
async def import_from_file(self, user: User, player_id: int, message: Message, document: Document = None) -> None:
if not document:
document = message.document
# TODO: 使用 mimetype 判断文件类型
@ -148,7 +147,7 @@ class WishLogPlugin(Plugin.Conversation):
reply = await message.reply_text("文件解析成功,正在导入数据")
await message.reply_chat_action(ChatAction.TYPING)
try:
text = await self._refresh_user_data(user, data=data, verify_uid=file_type == "json")
text = await self._refresh_user_data(user, player_id, data=data, verify_uid=file_type == "json")
except Exception as exc: # pylint: disable=W0703
logger.error("文件解析失败 %s", repr(exc))
text = "文件解析失败,请检查文件是否符合 SRGF 标准"
@ -159,8 +158,11 @@ class WishLogPlugin(Plugin.Conversation):
@handler.message(filters=filters.Regex("^导入跃迁记录(.*)") & filters.ChatType.PRIVATE, block=False)
@handler.command(command="start", filters=filters.Regex("warp_log_import$"), block=False)
async def command_start(self, update: "Update", context: "ContextTypes.DEFAULT_TYPE") -> int:
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
user = update.effective_user
player_id = await self.get_player_id(user.id, uid, offset)
context.chat_data["uid"] = player_id
args = self.get_args(context)
logger.info("用户 %s[%s] 导入跃迁记录命令请求", user.full_name, user.id)
authkey = from_url_get_authkey(args[0] if args else "")
@ -181,17 +183,18 @@ class WishLogPlugin(Plugin.Conversation):
text += "\n\n> 由于你绑定的 Cookie 中存在 stoken ,本次通过 stoken 自动刷新数据"
reply = await message.reply_text(text)
await message.reply_chat_action(ChatAction.TYPING)
data = await self._refresh_user_data(user, authkey=authkey)
data = await self._refresh_user_data(user, player_id, authkey=authkey)
await reply.edit_text(data)
return ConversationHandler.END
@conversation.state(state=INPUT_URL)
@handler.message(filters=~filters.COMMAND, block=False)
async def import_data_from_message(self, update: Update, _: CallbackContext) -> int:
async def import_data_from_message(self, update: Update, context: CallbackContext) -> int:
message = update.effective_message
user = update.effective_user
player_id = context.chat_data["uid"]
if message.document:
await self.import_from_file(user, message)
await self.import_from_file(user, player_id, message)
return ConversationHandler.END
if not message.text:
await message.reply_text("请发送文件或链接")
@ -199,7 +202,7 @@ class WishLogPlugin(Plugin.Conversation):
authkey = from_url_get_authkey(message.text)
reply = await message.reply_text(WAITING)
await message.reply_chat_action(ChatAction.TYPING)
text = await self._refresh_user_data(user, authkey=authkey)
text = await self._refresh_user_data(user, player_id, authkey=authkey)
await reply.edit_text(text)
return ConversationHandler.END
@ -207,11 +210,12 @@ class WishLogPlugin(Plugin.Conversation):
@handler.command(command="warp_log_delete", filters=filters.ChatType.PRIVATE, block=False)
@handler.message(filters=filters.Regex("^删除跃迁记录(.*)") & filters.ChatType.PRIVATE, block=False)
async def command_start_delete(self, update: Update, context: CallbackContext) -> int:
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
user = update.effective_user
logger.info("用户 %s[%s] 删除跃迁记录命令请求", user.full_name, user.id)
try:
player_id = await self.get_player_id(user.id)
player_id = await self.get_player_id(user.id, uid, offset)
context.chat_data["uid"] = player_id
except PlayerNotFoundError:
logger.info("未查询到用户 %s[%s] 所绑定的账号信息", user.full_name, user.id)
@ -240,6 +244,7 @@ class WishLogPlugin(Plugin.Conversation):
@handler.command(command="warp_log_force_delete", block=False, admin=True)
async def command_warp_log_force_delete(self, update: Update, context: CallbackContext):
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
args = self.get_args(context)
if not args:
@ -249,7 +254,7 @@ class WishLogPlugin(Plugin.Conversation):
cid = int(args[0])
if cid < 0:
raise ValueError("Invalid cid")
player_id = await self.get_player_id(cid)
player_id = await self.get_player_id(cid, uid, offset)
_, status = await self.gacha_log.load_history_info(str(cid), str(player_id), only_status=True)
if not status:
await message.reply_text("该用户还没有导入跃迁记录")
@ -266,12 +271,13 @@ class WishLogPlugin(Plugin.Conversation):
@handler.command(command="warp_log_export", filters=filters.ChatType.PRIVATE, block=False)
@handler.message(filters=filters.Regex("^导出跃迁记录(.*)") & filters.ChatType.PRIVATE, block=False)
async def command_start_export(self, update: Update, context: CallbackContext) -> None:
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
user = update.effective_user
logger.info("用户 %s[%s] 导出跃迁记录命令请求", user.full_name, user.id)
try:
await message.reply_chat_action(ChatAction.TYPING)
player_id = await self.get_player_id(user.id)
player_id = await self.get_player_id(user.id, uid, offset)
path = await self.gacha_log.gacha_log_to_srgf(str(user.id), str(player_id))
await message.reply_chat_action(ChatAction.UPLOAD_DOCUMENT)
await message.reply_document(document=open(path, "rb+"), caption=f"跃迁记录导出文件 - SRGF {SRGF_VERSION}")
@ -331,9 +337,8 @@ class WishLogPlugin(Plugin.Conversation):
buttons.append([InlineKeyboardButton("五星抽卡统计", callback_data=f"get_wish_log|{user_id}|{uid}|count|five")])
return buttons
async def wish_log_pool_choose(self, user_id: int, message: "Message"):
async def wish_log_pool_choose(self, user_id: int, player_id: int, message: "Message"):
await message.reply_chat_action(ChatAction.TYPING)
player_id = await self.get_player_id(user_id)
gacha_log, status = await self.gacha_log.load_history_info(str(user_id), str(player_id))
if not status:
raise GachaLogNotFound
@ -351,9 +356,8 @@ class WishLogPlugin(Plugin.Conversation):
if reply_message.photo:
self.wish_photo = reply_message.photo[-1].file_id
async def wish_log_pool_send(self, user_id: int, pool_type: "StarRailBannerType", message: "Message"):
async def wish_log_pool_send(self, user_id: int, uid: int, pool_type: "StarRailBannerType", message: "Message"):
await message.reply_chat_action(ChatAction.TYPING)
uid = await self.get_player_id(user_id)
png_data = await self.rander_wish_log_analysis(user_id, uid, pool_type)
if isinstance(png_data, str):
reply = await message.reply_text(png_data)
@ -371,6 +375,7 @@ class WishLogPlugin(Plugin.Conversation):
@handler.message(filters=filters.Regex("^跃迁记录?(光锥|角色|常驻|新手)$"), block=False)
async def command_start_analysis(self, update: Update, context: CallbackContext) -> None:
user_id = await self.get_real_user_id(update)
uid, offset = self.get_real_uid_or_offset(update)
message = update.effective_message
pool_type = None
if args := self.get_args(context):
@ -384,10 +389,11 @@ class WishLogPlugin(Plugin.Conversation):
pool_type = StarRailBannerType.NOVICE
self.log_user(update, logger.info, "跃迁记录命令请求 || 参数 %s", pool_type.name if pool_type else None)
try:
player_id = await self.get_player_id(user_id, uid, offset)
if pool_type is None:
await self.wish_log_pool_choose(user_id, message)
await self.wish_log_pool_choose(user_id, player_id, message)
else:
await self.wish_log_pool_send(user_id, pool_type, message)
await self.wish_log_pool_send(user_id, player_id, pool_type, message)
except GachaLogNotFound:
self.log_user(update, logger.info, "未找到跃迁记录")
buttons = [

View File

@ -217,8 +217,10 @@ class GenshinHelper(Plugin):
raise ServiceNotFoundError(*filter(lambda x: x is None, temp))
@asynccontextmanager
async def genshin(self, user_id: int, region: Optional[RegionEnum] = None) -> StarRailClient: # skipcq: PY-R1000 #
player = await self.players_service.get_player(user_id, region)
async def genshin( # skipcq: PY-R1000 #
self, user_id: int, region: Optional[RegionEnum] = None, player_id: int = None, offset: int = 0
) -> StarRailClient:
player = await self.players_service.get_player(user_id, region, player_id, offset)
if player is None:
raise PlayerNotFoundError(user_id)
@ -303,8 +305,10 @@ class GenshinHelper(Plugin):
await self.devices_service.update(devices)
raise exc
async def get_genshin_client(self, user_id: int, region: Optional[RegionEnum] = None) -> StarRailClient:
player = await self.players_service.get_player(user_id, region)
async def get_genshin_client(
self, user_id: int, region: Optional[RegionEnum] = None, player_id: int = None, offset: int = 0
) -> StarRailClient:
player = await self.players_service.get_player(user_id, region, player_id, offset)
if player is None:
raise PlayerNotFoundError(user_id)
@ -382,17 +386,23 @@ class GenshinHelper(Plugin):
@asynccontextmanager
async def genshin_or_public(
self, user_id: int, region: Optional[RegionEnum] = None, uid: Optional[int] = None
self,
user_id: int,
region: Optional[RegionEnum] = None,
uid: Optional[int] = None,
offset: int = 0,
) -> StarRailClient:
try:
async with self.genshin(user_id, region) as client:
async with self.genshin(user_id, region, uid, offset) as client:
client.public = False
if uid and recognize_game_biz(uid, client.game) != recognize_game_biz(client.player_id, client.game):
# 如果 uid 和 player_id 服务器不一致,说明是跨服的,需要使用公共的 cookies
raise CookiesNotFoundError(user_id)
yield client
except CookiesNotFoundError:
except (CookiesNotFoundError, PlayerNotFoundError):
if uid:
if uid < 10:
raise PlayerNotFoundError(user_id)
region = RegionEnum.HYPERION if uid < 600000000 else RegionEnum.HOYOLAB
async with self.public_genshin(user_id, region, uid) as client:
try: