chore: 添加定时执行,添加拔萝卜任务 (#177)

* chore: 添加定时执行,添加拔萝卜任务

* chore: 提升版本号1.7.2
This commit is contained in:
Night-stars-1 2023-11-19 20:19:54 +08:00 committed by GitHub
parent ea361a0e04
commit 61f7ca9ae5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 57 additions and 17 deletions

View File

@ -3,17 +3,18 @@
import asyncio import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from utils.api.login import Login from utils.api.login import Login
from utils.api.sign import BaseSign from utils.api.sign import BaseSign
from utils.config import ConfigManager from utils.config import ConfigManager
from utils.logger import log, get_message from utils.logger import get_message, log
from utils.request import notify_me from utils.request import notify_me
from utils.utils import get_token
from utils.system_info import print_info from utils.system_info import print_info
from utils.utils import get_token
_conf = ConfigManager.data_obj _conf = ConfigManager.data_obj
async def main(): async def main():
"""启动签到""" """启动签到"""
print_info() print_info()
@ -40,4 +41,18 @@ async def main():
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) if _conf.preference.hour and _conf.preference.minute:
# 创建一个新的事件循环
loop = asyncio.get_event_loop()
scheduler = AsyncIOScheduler()
scheduler.add_job(main, 'cron', hour=_conf.preference.hour, minute=_conf.preference.minute, id='miuitask')
scheduler.start()
try:
loop.run_forever()
except (KeyboardInterrupt, SystemExit):
pass
finally:
scheduler.shutdown()
else:
asyncio.run(main())

View File

@ -2,7 +2,7 @@
import time import time
from typing import Dict, List, Optional, Type, Union from typing import Dict, List, Optional, Type, Union, Any
from ..data_model import ApiResultHandler, DailyTasksResult, SignResultHandler from ..data_model import ApiResultHandler, DailyTasksResult, SignResultHandler
from ..request import get, post from ..request import get, post
@ -44,12 +44,13 @@ class BaseSign:
api_data = ApiResultHandler(result) api_data = ApiResultHandler(result)
if api_data.success: if api_data.success:
task_status = [] task_status = []
task = next(filter(lambda x: x['head']['title'] == "每日任务", api_data.data)) tasks: List[Dict[str, List[Dict[str, Any]]]] = filter(lambda x: x['head']['title'] in ["每日任务", "其他任务"], api_data.data)
for daily_task in task['data']: for task in tasks:
task_name = daily_task['title'] for daily_task in task['data']:
task_desc = daily_task.get('desc', '') task_name = daily_task['title']
show_type = True if daily_task['showType'] == 0 else False # pylint: disable=simplifiable-if-expression task_desc = daily_task.get('desc', '')
task_status.append(DailyTasksResult(name=task_name, showType=show_type, desc=task_desc)) show_type = True if daily_task['showType'] == 0 else False # pylint: disable=simplifiable-if-expression
task_status.append(DailyTasksResult(name=task_name, showType=show_type, desc=task_desc))
return task_status return task_status
else: else:
if not nolog: if not nolog:
@ -83,13 +84,16 @@ class BaseSign:
result = response.json() result = response.json()
api_data = SignResultHandler(result) api_data = SignResultHandler(result)
if api_data: if api_data:
log.success(f"{self.NAME}结果: 成长值+" + api_data.growth) if api_data.growth:
log.success(f"{self.NAME}结果: 成长值+{api_data.growth}")
else:
log.success(f"{self.NAME}结果: {api_data.message}")
return True return True
elif api_data.ck_invalid: elif api_data.ck_invalid:
log.error(f"{self.NAME}失败: Cookie无效") log.error(f"{self.NAME}失败: Cookie无效")
return False return False
else: else:
log.error(f"{self.NAME}失败:" + api_data.message) log.error(f"{self.NAME}失败:{api_data.message}")
return False return False
except Exception: # pylint: disable=broad-exception-caught except Exception: # pylint: disable=broad-exception-caught
log.exception(f"{self.NAME}出错") log.exception(f"{self.NAME}出错")
@ -219,6 +223,15 @@ class ThumbUp(BaseSign):
URL_SIGN = 'https://api.vip.miui.com/mtop/planet/vip/content/announceThumbUp' URL_SIGN = 'https://api.vip.miui.com/mtop/planet/vip/content/announceThumbUp'
class CarrotPull(BaseSign):
"""
参与拔萝卜获得奖励
"""
NAME = "参与拔萝卜获得奖励"
DATA = {
'miui_vip_ph': "{miui_vip_ph}"
}
URL_SIGN = 'https://api.vip.miui.com/api/carrot/pull'
# 注册签到任务 # 注册签到任务
BaseSign.AVAILABLE_SIGNS[CheckIn.NAME] = CheckIn BaseSign.AVAILABLE_SIGNS[CheckIn.NAME] = CheckIn
@ -228,3 +241,4 @@ BaseSign.AVAILABLE_SIGNS[BrowseSpecialPage.NAME] = BrowseSpecialPage
BaseSign.AVAILABLE_SIGNS[BoardFollow.NAME] = BoardFollow BaseSign.AVAILABLE_SIGNS[BoardFollow.NAME] = BoardFollow
BaseSign.AVAILABLE_SIGNS[BoardUnFollow.NAME] = BoardUnFollow BaseSign.AVAILABLE_SIGNS[BoardUnFollow.NAME] = BoardUnFollow
BaseSign.AVAILABLE_SIGNS[ThumbUp.NAME] = ThumbUp BaseSign.AVAILABLE_SIGNS[ThumbUp.NAME] = ThumbUp
BaseSign.AVAILABLE_SIGNS[CarrotPull.NAME] = CarrotPull

View File

@ -54,7 +54,7 @@ class Account(BaseModel):
"""社区在活动期间可能会出现限时的“浏览指定专题页”任务,启用功能意味着你愿意自行承担相关风险""" """社区在活动期间可能会出现限时的“浏览指定专题页”任务,启用功能意味着你愿意自行承担相关风险"""
BoardFollow: bool = False BoardFollow: bool = False
"""社区可能会出现限时的“加入圈子”任务,启用功能意味着你愿意自行承担相关风险""" """社区可能会出现限时的“加入圈子”任务,启用功能意味着你愿意自行承担相关风险"""
carrotpull: bool = False CarrotPull: bool = False
"""社区拔萝卜,启用功能意味着你愿意自行承担相关风险""" """社区拔萝卜,启用功能意味着你愿意自行承担相关风险"""
@validator("password", allow_reuse=True) @validator("password", allow_reuse=True)
@ -90,6 +90,10 @@ class Preference(BaseModel):
"""极验自定义params参数""" """极验自定义params参数"""
geetest_data: Dict = {} geetest_data: Dict = {}
"""极验自定义data参数""" """极验自定义data参数"""
hour: Optional[str] = None
"""自动执行的时间"""
minute: Optional[str] = None
"""自动执行的时间"""
class Config(BaseModel): class Config(BaseModel):

View File

@ -28,10 +28,14 @@ class ApiResultHandler(BaseModel):
for key in ["code", "status"]: for key in ["code", "status"]:
if self.status is None: if self.status is None:
self.status = self.content.get(key) self.status = self.content.get(key)
if self.status is None and isinstance(self.data, dict):
self.status = self.data.get(key)
for key in ["desc", "message"]: for key in ["desc", "message"]:
if self.message == "": if self.message == "":
self.message = self.content.get(key, "") self.message = self.content.get(key, "")
if self.message is None and isinstance(self.data, dict):
self.message = self.data.get(key)
@property @property
def success(self): def success(self):
@ -95,9 +99,11 @@ class SignResultHandler(ApiResultHandler):
super().__init__(content=content) super().__init__(content=content)
self.growth = self.content.get("entity", {}) self.growth = self.content.get("entity", {})
if isinstance(self.growth, dict): if isinstance(self.growth, dict):
self.growth = self.growth.get("score", "未知") self.growth = self.growth.get("score")
elif isinstance(self.growth, int): elif isinstance(self.growth, int):
self.growth = str(self.growth) self.growth = str(self.growth)
else:
self.growth = None
# pylint: disable=trailing-whitespace # pylint: disable=trailing-whitespace
def __bool__(self): def __bool__(self):
""" """

View File

@ -1,7 +1,7 @@
''' '''
Date: 2023-11-13 20:29:19 Date: 2023-11-13 20:29:19
LastEditors: Night-stars-1 nujj1042633805@gmail.com LastEditors: Night-stars-1 nujj1042633805@gmail.com
LastEditTime: 2023-11-18 14:22:37 LastEditTime: 2023-11-19 14:39:20
''' '''
import platform import platform
from urllib.request import getproxies from urllib.request import getproxies
@ -10,7 +10,7 @@ from utils.logger import log
def print_info(): def print_info():
"""打印系统信息""" """打印系统信息"""
log.info("MIUI-AUTO-TASK v1.7.1") log.info("MIUI-AUTO-TASK v1.7.2")
log.info('---------- 系统信息 -------------') log.info('---------- 系统信息 -------------')
system_info() system_info()
log.info('---------- 项目信息 -------------') log.info('---------- 项目信息 -------------')

View File

@ -208,6 +208,7 @@ async def get_token(uid: str) -> str:
'a': 'GROW_UP_CHECKIN', 'a': 'GROW_UP_CHECKIN',
} }
response = await post('https://verify.sec.xiaomi.com/captcha/v2/data', params=params, headers=headers, data=data) response = await post('https://verify.sec.xiaomi.com/captcha/v2/data', params=params, headers=headers, data=data)
log.debug(response.text)
result = response.json() result = response.json()
api_data = TokenResultHandler(result) api_data = TokenResultHandler(result)
if api_data.success: if api_data.success: