初步支持星穹铁道签到

This commit is contained in:
qwerdvd 2023-04-26 19:41:51 +08:00
parent 1ffbeaa9c7
commit e8b1363e5e
14 changed files with 2306 additions and 8 deletions

666
.gitignore vendored Normal file
View File

@ -0,0 +1,666 @@
# Created by https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode,jetbrains+all,python
# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio,visualstudiocode,jetbrains+all,python
### JetBrains+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### JetBrains+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env/
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
### VisualStudioCode ###
!.vscode/*
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
# Support for Project snippet scope
.vscode/*.code-snippets
# Ignore code-workspaces
*.code-workspace
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/visualstudio,visualstudiocode,jetbrains+all,python,data
### CI ###
result.txt

37
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,37 @@
ci:
autofix_commit_msg: "🚨 `pre-commit-ci`修复格式错误"
skip:
- "poetry-lock"
autofix_prs: true
autoupdate_branch: v4
autoupdate_schedule: monthly
autoupdate_commit_msg: "⬆️ `pre-commit-ci`自动升级"
repos:
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/hadialqattan/pycln
rev: v2.1.3
hooks:
- id: pycln
- repo: https://github.com/python-poetry/poetry
rev: 1.4.0
hooks:
- id: poetry-check
- id: poetry-lock
- id: poetry-export
args: ["-f", "requirements.txt", "--without-hashes", "-o", "requirements.txt"]
verbose: true

0
StarRailUID/__full__.py Normal file
View File

View File

@ -0,0 +1,8 @@
# flake8: noqa
OLD_URL = "https://api-takumi.mihoyo.com"
STAR_RAIL_SIGN_INFO_URL = f'{OLD_URL}/event/luna/extra_info'
STAR_RAIL_SIGN_URL = f'{OLD_URL}/event/luna/extra_award'
_API = locals()

View File

@ -0,0 +1,100 @@
import random
import asyncio
from gsuid_core.sv import SV
from gsuid_core.bot import Bot
from gsuid_core.gss import gss
from gsuid_core.models import Event
from gsuid_core.aps import scheduler
from gsuid_core.logger import logger
from .sign import sign_in, daily_sign
from ....GenshinUID.GenshinUID.utils.database import get_sqla
from ....GenshinUID.GenshinUID.utils.error_reply import UID_HINT
from ....GenshinUID.GenshinUID.genshinuid_config.gs_config import gsconfig
SIGN_TIME = gsconfig.get_config('SignTime').data
sv_sign = SV('星穹铁道签到')
sv_sign_config = SV('星穹铁道管理', pm=2)
# 每日零点半执行米游社星穹铁道签到
@scheduler.scheduled_job('cron', hour=SIGN_TIME[0], minute=SIGN_TIME[1])
async def sign_at_night():
if gsconfig.get_config('SchedSignin').data:
await send_daily_sign()
# 群聊内 签到 功能
@sv_sign.on_fullmatch('sr签到')
async def get_sign_func(bot: Bot, ev: Event):
await bot.logger.info('[SR签到]QQ号: {}'.format(ev.user_id))
sqla = get_sqla(ev.bot_id)
uid = await sqla.get_bind_uid(ev.user_id)
if uid is None:
return await bot.send(UID_HINT)
await bot.logger.info('[SR签到]UID: {}'.format(uid))
await bot.send(await sign_in(uid))
@sv_sign_config.on_fullmatch('sr全部重签')
async def recheck(bot: Bot, ev: Event):
await bot.logger.info('开始执行[SR全部重签]')
await bot.send('已开始执行')
await send_daily_sign()
await bot.send('执行完成')
async def send_daily_sign():
logger.info('开始执行[SR每日全部签到]')
# 执行签到 并获得推送消息
result = await daily_sign()
private_msg_list = result['private_msg_list']
group_msg_list = result['group_msg_list']
logger.info('[SR每日全部签到]完成')
# 执行私聊推送
for qid in private_msg_list:
try:
for bot_id in gss.active_bot:
for single in private_msg_list[qid]:
await gss.active_bot[bot_id].target_send(
single['msg'], 'direct', qid, single['bot_id'], '', ''
)
except Exception as e:
logger.warning(f'[SR每日全部签到] QQ {qid} 私聊推送失败!错误信息:{e}')
await asyncio.sleep(0.5)
logger.info('[SR每日全部签到]私聊推送完成')
# 执行群聊推送
for gid in group_msg_list:
# 根据succee数判断是否为简洁推送
if group_msg_list[gid]['success'] >= 0:
report = (
'以下为签到失败报告:{}'.format(group_msg_list[gid]['push_message'])
if group_msg_list[gid]['push_message'] != ''
else ''
)
msg_title = '星穹铁道今日自动签到已完成!\n本群共签到成功{}人,共签到失败{}人。{}'.format(
group_msg_list[gid]['success'],
group_msg_list[gid]['failed'],
report,
)
else:
msg_title = group_msg_list[gid]['push_message']
# 发送群消息
try:
for bot_id in gss.active_bot:
await gss.active_bot[bot_id].target_send(
msg_title,
'group',
gid,
group_msg_list[gid]['bot_id'],
'',
'',
)
except Exception as e:
logger.warning(f'[SR每日全部签到]群 {gid} 推送失败!错误信息:{e}')
await asyncio.sleep(0.5 + random.randint(1, 3))
logger.info('[SR每日全部签到]群聊推送完成')

View File

@ -0,0 +1,174 @@
import random
import asyncio
from copy import deepcopy
from gsuid_core.gss import gss
from gsuid_core.logger import logger
from ..utils.mys_api import mys_api
from ....GenshinUID.GenshinUID.utils.database import get_sqla
from ....GenshinUID.GenshinUID.genshinuid_config.gs_config import gsconfig
private_msg_list = {}
group_msg_list = {}
already = 0
# 签到函数
async def sign_in(uid: str) -> str:
logger.info(f'[SR签到] {uid} 开始执行签到')
# 获得签到信息
sign_info = await mys_api.get_sign_info(uid)
# 初步校验数据
if isinstance(sign_info, int):
logger.warning(f'[SR签到] {uid} 出错, 请检查Cookies是否过期')
return '签到失败...请检查Cookies是否过期'
# 检测是否已签到
if sign_info['is_sign']:
logger.info(f'[SR签到] {uid} 该用户今日已签到,跳过...')
global already
already += 1
day_of_month = int(sign_info['today'].split('-')[-1])
signed_count = int(sign_info['total_sign_day'])
sign_missed = day_of_month - signed_count
return f'今日已签到!本月漏签次数:{sign_missed}'
# 实际进行签到
Header = {}
for index in range(4):
# 进行一次签到
sign_data = await mys_api.mys_sign(uid=uid, header=Header)
# 检测数据
if isinstance(sign_data, int):
logger.warning(f'[SR签到] {uid} 出错, 请检查Cookies是否过期')
return 'sr签到失败...请检查Cookies是否过期'
if 'risk_code' in sign_data:
# 出现校验码
if sign_data['risk_code'] == 375:
if gsconfig.get_config('CaptchaPass').data:
gt = sign_data['gt']
ch = sign_data['challenge']
vl, ch = await mys_api._pass(gt, ch, Header)
if vl:
delay = 1
Header['x-rpc-challenge'] = ch
Header['x-rpc-validate'] = vl
Header['x-rpc-seccode'] = f'{vl}|jordan'
logger.info(f'[SR签到] {uid} 已获取验证码, 等待时间{delay}')
await asyncio.sleep(delay)
else:
delay = 605 + random.randint(1, 120)
logger.info(f'[SR签到] {uid} 未获取验证码,等待{delay}秒后重试...')
await asyncio.sleep(delay)
continue
else:
logger.info('配置文件暂未开启[跳过无感验证],结束本次任务...')
return '签到失败...出现验证码!'
# 成功签到!
else:
if index == 0:
logger.info(f'[SR签到] {uid} 该用户无校验码!')
else:
logger.info(f'[SR签到] [无感验证] {uid} 该用户重试 {index} 次验证成功!')
break
elif (int(str(uid)[0]) > 5) and (sign_data['data']['code'] == 'ok'):
# 国际服签到无risk_code字段
logger.info(f'[SR国际服签到] {uid} 签到成功!')
break
else:
# 重试超过阈值
logger.warning('[SR签到] 超过请求阈值...')
return 'sr签到失败...出现验证码!\n请过段时间使用[签到]或由管理员[全部重签]或手动至米游社进行签到!'
# 签到失败
else:
im = 'sr签到失败!'
logger.warning(f'[SR签到] {uid} 签到失败, 结果: {im}')
return im
# 获取签到列表
sign_list = await mys_api.get_sign_list(uid)
new_sign_info = await mys_api.get_sign_info(uid)
if isinstance(sign_list, int) or isinstance(new_sign_info, int):
logger.warning(f'[SR签到] {uid} 出错, 请检查Cookies是否过期')
return 'sr签到失败...请检查Cookies是否过期'
# 获取签到奖励物品,拿旧的总签到天数 + 1 为新的签到天数,再 -1 即为今日奖励物品的下标
getitem = sign_list['awards'][int(sign_info['total_sign_day']) + 1 - 1]
get_im = f'本次sr签到获得{getitem["name"]}x{getitem["cnt"]}'
day_of_month = int(new_sign_info['today'].split('-')[-1])
signed_count = int(new_sign_info['total_sign_day'])
sign_missed = day_of_month - signed_count
if new_sign_info['is_sign']:
mes_im = 'sr签到成功'
else:
mes_im = 'sr签到失败...'
sign_missed -= 1
sign_missed = sign_info.get('sign_cnt_missed') or sign_missed
im = f'{mes_im}!\n{get_im}\n本月漏签次数:{sign_missed}'
logger.info(f'[SR签到] {uid} 签到完成, 结果: {mes_im}, 漏签次数: {sign_missed}')
return im
async def single_daily_sign(bot_id: str, uid: str, gid: str, qid: str):
im = await sign_in(uid)
if gid == 'on':
if qid not in private_msg_list:
private_msg_list[qid] = []
private_msg_list[qid].append({'bot_id': bot_id, 'uid': uid, 'msg': im})
else:
# 向群消息推送列表添加这个群
if gid not in group_msg_list:
group_msg_list[gid] = {
'bot_id': bot_id,
'success': 0,
'failed': 0,
'push_message': '',
}
# 检查是否开启简洁签到
if gsconfig.get_config('SignReportSimple').data:
# 如果失败, 则添加到推送列表
if im.startswith(('sr签到失败', '网络有点忙', 'OK', 'ok')):
message = f'[CQ:at,qq={qid}] {im}'
group_msg_list[gid]['failed'] += 1
group_msg_list[gid]['push_message'] += '\n' + message
else:
group_msg_list[gid]['success'] += 1
# 没有开启简洁签到, 则每条消息都要携带@信息
else:
# 不用MessageSegment.at(row[2]),因为不方便移植
message = f'[CQ:at,qq={qid}] {im}'
group_msg_list[gid]['push_message'] += '\n' + message
group_msg_list[gid]['success'] -= 1
async def daily_sign():
global already
tasks = []
for bot_id in gss.active_bot:
sqla = get_sqla(bot_id)
user_list = await sqla.get_all_user()
for user in user_list:
if user.sign_switch != 'off':
tasks.append(
single_daily_sign(
user.bot_id, user.uid, user.sign_switch, user.user_id
)
)
if len(tasks) >= 1:
await asyncio.gather(*tasks)
if already >= 1:
delay = 1
else:
delay = 50 + random.randint(3, 45)
logger.info(f'[SR签到] 已签到{len(tasks)}个用户, 等待{delay}秒进行下一次签到')
tasks.clear()
already = 0
await asyncio.sleep(delay)
await asyncio.gather(*tasks)
tasks.clear()
result = {
'private_msg_list': deepcopy(private_msg_list),
'group_msg_list': deepcopy(group_msg_list),
}
private_msg_list.clear()
group_msg_list.clear()
logger.info(result)
return result

View File

@ -0,0 +1,14 @@
import asyncio
import threading
from gsuid_core.logger import logger
async def all_start():
try:
pass
except Exception as e:
logger.exception(e)
threading.Thread(target=lambda: asyncio.run(all_start()), daemon=True).start()

View File

@ -0,0 +1,147 @@
import copy
from typing import Dict, Union, Literal, Optional, cast
from ..sruid_utils.api.mys.api import _API
from ....GenshinUID.GenshinUID.utils.database import get_sqla
from ....GenshinUID.GenshinUID.gsuid_utils.api.mys import MysApi
from ....GenshinUID.GenshinUID.genshinuid_config.gs_config import gsconfig
from ....GenshinUID.GenshinUID.gsuid_utils.api.mys.models import (
MysSign,
SignInfo,
)
from ....GenshinUID.GenshinUID.gsuid_utils.api.mys.tools import (
random_hex,
generate_os_ds,
get_web_ds_token,
)
mysVersion = '2.44.1'
_HEADER = {
'x-rpc-app_version': mysVersion,
'User-Agent': (
'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) '
f'AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/{mysVersion}'
),
'x-rpc-client_type': '5',
'Referer': 'https://webstatic.mihoyo.com/',
'Origin': 'https://webstatic.mihoyo.com',
}
class _MysApi(MysApi):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def _pass(self, gt: str, ch: str, header: Dict):
# 警告使用该服务例如某RR等需要注意风险问题
# 本项目不以任何形式提供相关接口
# 代码来源GITHUB项目MIT开源
_pass_api = gsconfig.get_config('_pass_API').data
if _pass_api:
data = await self._mys_request(
url=f'{_pass_api}&gt={gt}&challenge={ch}',
method='GET',
header=header,
)
if isinstance(data, int):
return None, None
else:
validate = data['data']['validate']
ch = data['data']['challenge']
else:
validate = None
return validate, ch
async def _upass(self, header: Dict, is_bbs: bool = False):
if is_bbs:
raw_data = await self.get_bbs_upass_link(header)
else:
raw_data = await self.get_upass_link(header)
if isinstance(raw_data, int):
return False
gt = raw_data['data']['gt']
ch = raw_data['data']['challenge']
vl, ch = await self._pass(gt, ch, header)
if vl:
await self.get_header_and_vl(header, ch, vl)
else:
return True
async def get_ck(
self, uid: str, mode: Literal['OWNER', 'RANDOM'] = 'RANDOM'
) -> Optional[str]:
sqla = get_sqla('TEMP')
if mode == 'RANDOM':
return await sqla.get_random_cookie(uid)
else:
return await sqla.get_user_cookie(uid)
async def get_stoken(self, uid: str) -> Optional[str]:
sqla = get_sqla('TEMP')
return await sqla.get_user_stoken(uid)
async def get_sign_info(self, uid) -> Union[SignInfo, int]:
# server_id = RECOGNIZE_SERVER.get(str(uid)[0])
is_os = self.check_os(uid)
if is_os:
params = {
'act_id': 'e202304121516551',
'lang': 'zh-cn',
}
header = {
'DS': generate_os_ds(),
}
else:
params = {
'act_id': 'e202304121516551',
'lang': 'zh-cn',
}
header = {}
data = await self._mys_req_get(
'STAR_RAIL_SIGN_INFO_URL', is_os, params, header
)
if isinstance(data, Dict):
data = cast(SignInfo, data['data'])
return data
async def mys_sign(
self, uid, header={}, server_id='cn_gf01'
) -> Union[MysSign, int]:
ck = await self.get_ck(uid, 'OWNER')
if ck is None:
return -51
if int(str(uid)[0]) < 6:
HEADER = copy.deepcopy(_HEADER)
HEADER['Cookie'] = ck
HEADER['x-rpc-device_id'] = random_hex(32)
HEADER['x-rpc-app_version'] = '2.44.1'
HEADER['x-rpc-client_type'] = '5'
HEADER['X_Requested_With'] = 'com.mihoyo.hyperion'
HEADER['DS'] = get_web_ds_token(True)
HEADER['Referer'] = (
'https://webstatic.mihoyo.com/bbs/event/signin/hkrpg'
'/mys_sign?act_id=e202304121516551&bbs_auth_required=true'
'&bbs_presentation_style=fullscreen&utm_source=share'
'&utm_medium=bbs&utm_campaign=app'
)
HEADER.update(header)
data = await self._mys_request(
url=_API['SIGN_URL'],
method='POST',
header=HEADER,
data={
'act_id': 'e202304121516551',
'lang': 'zh-cn',
},
)
else:
pass
if isinstance(data, Dict):
data = cast(MysSign, data['data'])
return data
mys_api = _MysApi()

2
StarRailUID/version.py Normal file
View File

@ -0,0 +1,2 @@
StarRailUID_version = '0.1.0'
StarRail_version = '1.0.5'

0
__init__.py Normal file
View File

0
__nest__.py Normal file
View File

1119
poetry.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,28 @@
[tool.black]
line-length = 79
target-version = ["py38", "py39", "py310"]
include = '\.pyi?$'
skip-string-normalization = true
extend-exclude = '''
'''
[tool.isort]
profile = "black"
line_length = 79
length_sort = true
skip_gitignore = true
force_sort_within_sections = true
extra_standard_library = ["typing_extensions"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
[build-system]
requires = ["poetry-core>=1.2.0"]
build-backend = "poetry.core.masonry.api"
[tool.poetry] [tool.poetry]
name = "starrailuid" name = "StarRailUID"
version = "0.1.0" version = "0.1.0"
description = "" description = ""
authors = ["qwerdvd <2450899274@qq.com>"] authors = ["qwerdvd <2450899274@qq.com>"]
@ -7,9 +30,22 @@ license = "GPL-3.0-or-later"
readme = "README.md" readme = "README.md"
[tool.poetry.dependencies] [tool.poetry.dependencies]
python = "^3.8" python = "^3.8.1"
[[tool.poetry.source]]
name = "USTC"
url = "https://pypi.mirrors.ustc.edu.cn/simple"
default = false
secondary = true
[build-system] [tool.poetry.group.dev.dependencies]
requires = ["poetry-core"] flake8 = "^6.0.0"
build-backend = "poetry.core.masonry.api" black = "^23.1.0"
isort = "^5.12.0"
pre-commit = "^2.21.0"
pycln = "^2.1.2"
[tool.poetry.group.test.dependencies]
nonebug = "^0.3.0"
pytest = "^7.2.0"
pytest-asyncio = "^0.20.3"

1
requirements.txt Normal file
View File

@ -0,0 +1 @@