1
0
mirror of https://github.com/Oreomeow/VIP.git synced 2026-02-02 18:19:33 +08:00

♻️ 'Refactored by Sourcery' (#14)

Co-authored-by: Sourcery AI <>
This commit is contained in:
sourcery-ai[bot]
2022-10-08 14:43:43 +08:00
committed by GitHub
parent 3cc4a1bc0f
commit 6f437ddef5
17 changed files with 232 additions and 298 deletions

View File

@@ -126,9 +126,8 @@ def login_retry(*args, **kwargs):
sess_id, session = func(username, password) sess_id, session = func(username, password)
if sess_id != "-1": if sess_id != "-1":
return sess_id, session return sess_id, session
else: if number == max_retry:
if number == max_retry: return sess_id, session
return sess_id, session
else: else:
return ret, ret_session return ret, ret_session
@@ -154,8 +153,7 @@ def captcha_solver(captcha_image_url: str, session: requests.session) -> dict:
"data": str(encoded_string)[2:-1], "data": str(encoded_string)[2:-1],
} }
r = requests.post(url=url, json=data) r = requests.post(url=url, json=data)
j = json.loads(r.text) return json.loads(r.text)
return j
def handle_captcha_solved_result(solved: dict) -> str: def handle_captcha_solved_result(solved: dict) -> str:
@@ -175,26 +173,25 @@ def handle_captcha_solved_result(solved: dict) -> str:
log("[Captcha Solver] You are using your own apikey.") log("[Captcha Solver] You are using your own apikey.")
text = solved_text text = solved_text
operators = ["X", "x", "+", "-"] operators = ["X", "x", "+", "-"]
if any(x in text for x in operators): if all(x not in text for x in operators):
for operator in operators:
operator_pos = text.find(operator)
if operator == "x" or operator == "X":
operator = "*"
if operator_pos != -1:
left_part = text[:operator_pos]
right_part = text[operator_pos + 1:]
if left_part.isdigit() and right_part.isdigit():
return eval(
"{left} {operator} {right}".format(
left=left_part, operator=operator, right=right_part
)
)
else:
# Because these symbols("X", "x", "+", "-") do not appear at the same time,
# it just contains an arithmetic symbol.
return text
else:
return text return text
for operator in operators:
operator_pos = text.find(operator)
if operator in ["x", "X"]:
operator = "*"
if operator_pos != -1:
left_part = text[:operator_pos]
right_part = text[operator_pos + 1:]
return (
eval(
"{left} {operator} {right}".format(
left=left_part, operator=operator, right=right_part
)
)
if left_part.isdigit() and right_part.isdigit()
else text
)
else: else:
print(solved) print(solved)
raise KeyError("Failed to find parsed results.") raise KeyError("Failed to find parsed results.")
@@ -208,15 +205,13 @@ def get_captcha_solver_usage() -> dict:
"apikey": APIKEY, "apikey": APIKEY,
} }
r = requests.get(url=url, params=params) r = requests.get(url=url, params=params)
j = json.loads(r.text) return json.loads(r.text)
return j
@login_retry(max_retry=LOGIN_MAX_RETRY_COUNT) @login_retry(max_retry=LOGIN_MAX_RETRY_COUNT)
def login(username: str, password: str) -> (str, requests.session): def login(username: str, password: str) -> (str, requests.session):
headers = {"user-agent": user_agent, "origin": "https://www.euserv.com"} headers = {"user-agent": user_agent, "origin": "https://www.euserv.com"}
url = "https://support.euserv.com/index.iphp" url = "https://support.euserv.com/index.iphp"
captcha_image_url = "https://support.euserv.com/securimage_show.php"
session = requests.Session() session = requests.Session()
sess = session.get(url, headers=headers) sess = session.get(url, headers=headers)
@@ -237,58 +232,56 @@ def login(username: str, password: str) -> (str, requests.session):
f.raise_for_status() f.raise_for_status()
if ( if (
f.text.find("Hello") == -1 f.text.find("Hello") != -1
and f.text.find("Confirm or change your customer data here") == -1 or f.text.find("Confirm or change your customer data here") != -1
): ):
if ( return sess_id, session
if (
f.text.find( f.text.find(
"To finish the login process please solve the following captcha." "To finish the login process please solve the following captcha."
) )
== -1 == -1
): ):
return "-1", session return "-1", session
else: log("[Captcha Solver] 进行验证码识别...")
log("[Captcha Solver] 进行验证码识别...") captcha_image_url = "https://support.euserv.com/securimage_show.php"
solved_result = captcha_solver(captcha_image_url, session) solved_result = captcha_solver(captcha_image_url, session)
captcha_code = handle_captcha_solved_result(solved_result) captcha_code = handle_captcha_solved_result(solved_result)
log("[Captcha Solver] 识别的验证码是: {}".format(captcha_code)) log(f"[Captcha Solver] 识别的验证码是: {captcha_code}")
if CHECK_CAPTCHA_SOLVER_USAGE: if CHECK_CAPTCHA_SOLVER_USAGE:
usage = get_captcha_solver_usage() usage = get_captcha_solver_usage()
log( log(
"[Captcha Solver] current date {0} api usage count: {1}".format( "[Captcha Solver] current date {0} api usage count: {1}".format(
usage[0]["date"], usage[0]["count"] usage[0]["date"], usage[0]["count"]
)
)
f2 = session.post(
url,
headers=headers,
data={
"subaction": "login",
"sess_id": sess_id,
"captcha_code": captcha_code,
},
) )
if ( )
f2.text.find(
"To finish the login process please solve the following captcha."
)
== -1
):
log("[Captcha Solver] 验证通过")
return sess_id, session
else:
log("[Captcha Solver] 验证失败")
return "-1", session
else: f2 = session.post(
url,
headers=headers,
data={
"subaction": "login",
"sess_id": sess_id,
"captcha_code": captcha_code,
},
)
if (
f2.text.find(
"To finish the login process please solve the following captcha."
)
== -1
):
log("[Captcha Solver] 验证通过")
return sess_id, session return sess_id, session
else:
log("[Captcha Solver] 验证失败")
return "-1", session
def get_servers(sess_id: str, session: requests.session) -> {}: def get_servers(sess_id: str, session: requests.session) -> {}:
d = {} d = {}
url = "https://support.euserv.com/index.iphp?sess_id=" + sess_id url = f"https://support.euserv.com/index.iphp?sess_id={sess_id}"
headers = {"user-agent": user_agent, "origin": "https://www.euserv.com"} headers = {"user-agent": user_agent, "origin": "https://www.euserv.com"}
f = session.get(url=url, headers=headers) f = session.get(url=url, headers=headers)
f.raise_for_status() f.raise_for_status()
@@ -297,16 +290,15 @@ def get_servers(sess_id: str, session: requests.session) -> {}:
"#kc2_order_customer_orders_tab_content_1 .kc2_order_table.kc2_content_table tr" "#kc2_order_customer_orders_tab_content_1 .kc2_order_table.kc2_content_table tr"
): ):
server_id = tr.select(".td-z1-sp1-kc") server_id = tr.select(".td-z1-sp1-kc")
if not len(server_id) == 1: if len(server_id) != 1:
continue continue
flag = ( flag = (
True tr.select(".td-z1-sp2-kc .kc2_order_action_container")[0]
if tr.select(".td-z1-sp2-kc .kc2_order_action_container")[0]
.get_text() .get_text()
.find("Contract extension possible from") .find("Contract extension possible from")
== -1 == -1
else False
) )
d[server_id[0].get_text()] = flag d[server_id[0].get_text()] = flag
return d return d
@@ -337,7 +329,7 @@ def renew(
} }
f = session.post(url, headers=headers, data=data) f = session.post(url, headers=headers, data=data)
f.raise_for_status() f.raise_for_status()
if not json.loads(f.text)["rs"] == "success": if json.loads(f.text)["rs"] != "success":
return False return False
token = json.loads(f.text)["token"]["value"] token = json.loads(f.text)["token"]["value"]
data = { data = {
@@ -358,7 +350,7 @@ def check(sess_id: str, session: requests.session):
for key, val in d.items(): for key, val in d.items():
if val: if val:
flag = False flag = False
log("[EUserv] ServerID: %s Renew Failed!" % key) log(f"[EUserv] ServerID: {key} Renew Failed!")
if flag: if flag:
log("[EUserv] ALL Work Done! Enjoy~") log("[EUserv] ALL Work Done! Enjoy~")
@@ -368,7 +360,7 @@ def check(sess_id: str, session: requests.session):
def coolpush(): def coolpush():
c = "EUserv续费日志\n\n" + desp c = "EUserv续费日志\n\n" + desp
data = json.dumps({"c": c}) data = json.dumps({"c": c})
url = "https://push.xuthus.cc/" + COOL_PUSH_MODE + "/" + COOL_PUSH_SKEY url = f"https://push.xuthus.cc/{COOL_PUSH_MODE}/{COOL_PUSH_SKEY}"
response = requests.post(url, data=data) response = requests.post(url, data=data)
if response.status_code != 200: if response.status_code != 200:
print("酷推 推送失败") print("酷推 推送失败")
@@ -397,7 +389,7 @@ def server_chan():
("text", "EUserv续费日志"), ("text", "EUserv续费日志"),
("desp", desp) ("desp", desp)
) )
response = requests.post("https://sc.ftqq.com/" + SCKEY + ".send", data=data) response = requests.post(f"https://sc.ftqq.com/{SCKEY}.send", data=data)
if response.status_code != 200: if response.status_code != 200:
print("Server酱 推送失败") print("Server酱 推送失败")
else: else:
@@ -410,7 +402,10 @@ def telegram():
("chat_id", TG_USER_ID), ("chat_id", TG_USER_ID),
("text", "EUserv续费日志\n\n" + desp) ("text", "EUserv续费日志\n\n" + desp)
) )
response = requests.post("https://" + TG_API_HOST + "/bot" + TG_BOT_TOKEN + "/sendMessage", data=data) response = requests.post(
f"https://{TG_API_HOST}/bot{TG_BOT_TOKEN}/sendMessage", data=data
)
if response.status_code != 200: if response.status_code != 200:
print("Telegram Bot 推送失败") print("Telegram Bot 推送失败")
else: else:
@@ -419,8 +414,16 @@ def telegram():
# wecomchan https://github.com/easychen/wecomchan # wecomchan https://github.com/easychen/wecomchan
def wecomchan(): def wecomchan():
response = requests.get(WECOMCHAN_DOMAIN + "wecomchan?sendkey=" + WECOMCHAN_SEND_KEY + "&msg_type=text" + "&to_user=" + response = requests.get(
WECOMCHAN_TO_USER + "&msg=" + "EUserv续费日志\n\n" + desp) (
(
f"{WECOMCHAN_DOMAIN}wecomchan?sendkey={WECOMCHAN_SEND_KEY}&msg_type=text&to_user={WECOMCHAN_TO_USER}&msg="
+ "EUserv续费日志\n\n"
)
+ desp
)
)
if response.status_code != 200: if response.status_code != 200:
print("wecomchan 推送失败") print("wecomchan 推送失败")
else: else:
@@ -462,10 +465,10 @@ def email():
) )
print("eMail 推送成功") print("eMail 推送成功")
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
print(str(e)) print(e)
print("eMail 推送失败") print("eMail 推送失败")
except SMTPDataError as e1: except SMTPDataError as e1:
print(str(e1)) print(e1)
print("eMail 推送失败") print("eMail 推送失败")
@@ -486,15 +489,15 @@ def main_handler(event, context):
log("[EUserv] 第 %d 个账号登陆失败,请检查登录信息" % (i + 1)) log("[EUserv] 第 %d 个账号登陆失败,请检查登录信息" % (i + 1))
continue continue
SERVERS = get_servers(sessid, s) SERVERS = get_servers(sessid, s)
log("[EUserv] 检测到第 {} 个账号有 {} 台 VPS正在尝试续期".format(i + 1, len(SERVERS))) log(f"[EUserv] 检测到第 {i + 1} 个账号有 {len(SERVERS)} 台 VPS正在尝试续期")
for k, v in SERVERS.items(): for k, v in SERVERS.items():
if v: if v:
if not renew(sessid, s, passwd_list[i], k): if not renew(sessid, s, passwd_list[i], k):
log("[EUserv] ServerID: %s Renew Error!" % k) log(f"[EUserv] ServerID: {k} Renew Error!")
else: else:
log("[EUserv] ServerID: %s has been successfully renewed!" % k) log(f"[EUserv] ServerID: {k} has been successfully renewed!")
else: else:
log("[EUserv] ServerID: %s does not need to be renewed" % k) log(f"[EUserv] ServerID: {k} does not need to be renewed")
time.sleep(15) time.sleep(15)
check(sessid, s) check(sessid, s)
time.sleep(5) time.sleep(5)

View File

@@ -41,7 +41,7 @@ password = args.password
def qlnotify(desp): def qlnotify(desp):
cur_path = os.path.abspath(os.path.dirname(__file__)) cur_path = os.path.abspath(os.path.dirname(__file__))
if os.path.exists(cur_path + "/notify.py"): if os.path.exists(f"{cur_path}/notify.py"):
try: try:
from notify import send from notify import send
except Exception: except Exception:
@@ -97,7 +97,7 @@ class FreeNom:
msg = "get page token failed" msg = "get page token failed"
print(msg) print(msg)
return return
token = match.group(1) token = match[1]
# domains # domains
domains = re.findall(domain_info_ptn, r.text) domains = re.findall(domain_info_ptn, r.text)

View File

@@ -49,9 +49,8 @@ def exwechat_get_ShortTimeMedia(img_url):
def exwechat_send(title, digest, content): def exwechat_send(title, digest, content):
url = ( url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token
)
data = { data = {
"touser": touser, "touser": touser,
"agentid": agentid, "agentid": agentid,
@@ -96,7 +95,7 @@ if sckey:
if result["data"]["errno"] == 0: if result["data"]["errno"] == 0:
print("Server酱推送成功!") print("Server酱推送成功!")
else: else:
errorNotify += "Server酱推送错误: " + result + "\n" errorNotify += f"Server酱推送错误: {result}" + "\n"
except Exception as e: except Exception as e:
print(e) print(e)
errorNotify += "Server酱推送错误!\n" errorNotify += "Server酱推送错误!\n"
@@ -116,21 +115,14 @@ if pptoken:
title = urllib.parse.quote_plus(title.replace("\n", "<br>")) title = urllib.parse.quote_plus(title.replace("\n", "<br>"))
message = urllib.parse.quote_plus(message.replace("\n", "<br>")) message = urllib.parse.quote_plus(message.replace("\n", "<br>"))
res = requests.get( res = requests.get(
host f"{host}send?token={pptoken}&title={title}&content={message}&template=html&topic={pptopic}"
+ "send?token="
+ pptoken
+ "&title="
+ title
+ "&content="
+ message
+ "&template=html&topic="
+ pptopic
) )
result = res.json() result = res.json()
if result["code"] == 200: if result["code"] == 200:
print("成功通过PushPlus将结果通知给相关用户!") print("成功通过PushPlus将结果通知给相关用户!")
else: else:
errorNotify += "PushPlus推送错误: " + result + "\n" errorNotify += f"PushPlus推送错误: {result}" + "\n"
except Exception as e: except Exception as e:
print(e) print(e)
errorNotify += "PushPlus推送错误!\n" errorNotify += "PushPlus推送错误!\n"
@@ -141,11 +133,11 @@ title = os.getenv("TITLE")
message = os.getenv("MSG") message = os.getenv("MSG")
qywx_am_ay = re.split(",", qywx_am) qywx_am_ay = re.split(",", qywx_am)
corpid = qywx_am_ay[0]
corpsecret = qywx_am_ay[1] corpsecret = qywx_am_ay[1]
touser = qywx_am_ay[2] touser = qywx_am_ay[2]
agentid = qywx_am_ay[3] agentid = qywx_am_ay[3]
corpid = qywx_am_ay[0]
if corpid: if corpid:
info = "" info = ""
if corpsecret: if corpsecret:
@@ -158,7 +150,7 @@ if corpid:
if result["errcode"] == 0: if result["errcode"] == 0:
print("成功通过企业微信将结果通知给用户!") print("成功通过企业微信将结果通知给用户!")
else: else:
errorNotify += "企业微信推送错误: " + res.text + "\n" errorNotify += f"企业微信推送错误: {res.text}" + "\n"
except Exception as e: except Exception as e:
print(e) print(e)
errorNotify += "企业微信推送错误!\n" errorNotify += "企业微信推送错误!\n"

View File

@@ -20,7 +20,7 @@ requests.packages.urllib3.disable_warnings()
def qlnotify(desp): def qlnotify(desp):
cur_path = os.path.abspath(os.path.dirname(__file__)) cur_path = os.path.abspath(os.path.dirname(__file__))
if os.path.exists(cur_path + "/notify.py"): if os.path.exists(f"{cur_path}/notify.py"):
try: try:
from notify import send from notify import send
except Exception: except Exception:
@@ -44,7 +44,7 @@ class SspanelQd(object):
msgall = "" msgall = ""
for i in range(len(self.base_url)): for i in range(len(self.base_url)):
email = self.email[i].split("@") email = self.email[i].split("@")
email = email[0] + "%40" + email[1] email = f"{email[0]}%40{email[1]}"
password = self.password[i] password = self.password[i]
session = requests.session() session = requests.session()
@@ -70,30 +70,32 @@ class SspanelQd(object):
print(msg) print(msg)
continue continue
login_url = self.base_url[i] + "/auth/login" login_url = f"{self.base_url[i]}/auth/login"
headers = { headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
} }
post_data = "email=" + email + "&passwd=" + password + "&code=" post_data = f"email={email}&passwd={password}&code="
post_data = post_data.encode() post_data = post_data.encode()
response = session.post(login_url, post_data, headers=headers, verify=False) response = session.post(login_url, post_data, headers=headers, verify=False)
headers = { headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
"Referer": self.base_url[i] + "/user", "Referer": f"{self.base_url[i]}/user",
} }
response = session.post( response = session.post(
self.base_url[i] + "/user/checkin", headers=headers, verify=False f"{self.base_url[i]}/user/checkin", headers=headers, verify=False
) )
msg = (response.json()).get("msg") msg = (response.json()).get("msg")
msgall = msgall + self.base_url[i] + "\n\n" + msg + "\n\n" msgall = msgall + self.base_url[i] + "\n\n" + msg + "\n\n"
print(msg) print(msg)
info_url = self.base_url[i] + "/user" info_url = f"{self.base_url[i]}/user"
response = session.get(info_url, verify=False) response = session.get(info_url, verify=False)
return msgall return msgall

View File

@@ -19,7 +19,7 @@ def loadSend():
global send global send
cur_path = os.path.abspath(os.path.dirname(__file__)) cur_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(cur_path) sys.path.append(cur_path)
if os.path.exists(cur_path + "/deleteDuplicateTasksNotify.py"): if os.path.exists(f"{cur_path}/deleteDuplicateTasksNotify.py"):
try: try:
from deleteDuplicateTasksNotify import send from deleteDuplicateTasksNotify import send
except Exception: except Exception:
@@ -38,19 +38,14 @@ def getTaskList():
url = "http://%s:5700/api/crons?searchValue=&t=%d" % (ip, t) url = "http://%s:5700/api/crons?searchValue=&t=%d" % (ip, t)
response = requests.get(url=url, headers=headers) response = requests.get(url=url, headers=headers)
responseContent = json.loads(response.content.decode("utf-8")) responseContent = json.loads(response.content.decode("utf-8"))
if responseContent["code"] == 200: return responseContent["data"] if responseContent["code"] == 200 else []
taskList = responseContent["data"]
return taskList
else:
# 没有获取到taskList返回空
return []
def getDuplicate(taskList): def getDuplicate(taskList):
wholeNames = {} wholeNames = {}
duplicateID = [] duplicateID = []
for task in taskList: for task in taskList:
if task["name"] in wholeNames.keys(): if task["name"] in wholeNames:
duplicateID.append(task["_id"]) duplicateID.append(task["_id"])
else: else:
wholeNames[task["name"]] = 1 wholeNames[task["name"]] = 1
@@ -59,12 +54,10 @@ def getDuplicate(taskList):
def getData(duplicateID): def getData(duplicateID):
rawData = "[" rawData = "["
count = 0 for count, id in enumerate(duplicateID):
for id in duplicateID:
rawData += '"%s"' % id rawData += '"%s"' % id
if count < len(duplicateID) - 1: if count < len(duplicateID) - 1:
rawData += ", " rawData += ", "
count += 1
rawData += "]" rawData += "]"
return rawData return rawData
@@ -77,7 +70,7 @@ def deleteDuplicateTasks(duplicateID):
response = requests.delete(url=url, headers=headers, data=data) response = requests.delete(url=url, headers=headers, data=data)
msg = json.loads(response.content.decode("utf-8")) msg = json.loads(response.content.decode("utf-8"))
if msg["code"] != 200: if msg["code"] != 200:
print("出错!,错误信息为:%s" % msg) print(f"出错!,错误信息为:{msg}")
else: else:
print("成功删除重复任务") print("成功删除重复任务")
@@ -100,7 +93,7 @@ if __name__ == "__main__":
# 直接从 /ql/config/auth.json中读取当前token # 直接从 /ql/config/auth.json中读取当前token
token = loadToken() token = loadToken()
# send("成功获取token!","") # send("成功获取token!","")
headers["Authorization"] = "Bearer %s" % token headers["Authorization"] = f"Bearer {token}"
taskList = getTaskList() taskList = getTaskList()
# 如果仍旧是空的,则报警 # 如果仍旧是空的,则报警
if len(taskList) == 0: if len(taskList) == 0:

View File

@@ -53,16 +53,11 @@ if "QQ_SKEY" in os.environ and os.environ["QQ_SKEY"] and "QQ_MODE" in os.environ
QQ_SKEY = os.environ["QQ_SKEY"] QQ_SKEY = os.environ["QQ_SKEY"]
QQ_MODE = os.environ["QQ_MODE"] QQ_MODE = os.environ["QQ_MODE"]
# 获取pushplus+ PUSH_PLUS_TOKEN # 获取pushplus+ PUSH_PLUS_TOKEN
if "PUSH_PLUS_TOKEN" in os.environ: if "PUSH_PLUS_TOKEN" in os.environ and len(os.environ["PUSH_PLUS_TOKEN"]) > 1:
if len(os.environ["PUSH_PLUS_TOKEN"]) > 1: PUSH_PLUS_TOKEN = os.environ["PUSH_PLUS_TOKEN"]
PUSH_PLUS_TOKEN = os.environ["PUSH_PLUS_TOKEN"]
# print("已获取并使用Env环境 PUSH_PLUS_TOKEN")
# 获取企业微信应用推送 QYWX_AM # 获取企业微信应用推送 QYWX_AM
if "QYWX_AM" in os.environ: if "QYWX_AM" in os.environ and len(os.environ["QYWX_AM"]) > 1:
if len(os.environ["QYWX_AM"]) > 1: QYWX_AM = os.environ["QYWX_AM"]
QYWX_AM = os.environ["QYWX_AM"]
# print("已获取并使用Env环境 QYWX_AM")
if BARK: if BARK:
notify_mode.append('bark') notify_mode.append('bark')
# print("BARK 推送打开") # print("BARK 推送打开")
@@ -90,7 +85,7 @@ if QYWX_AM:
def message(str_msg): def message(str_msg):
global message_info global message_info
print(str_msg) print(str_msg)
message_info = "{}\n{}".format(message_info, str_msg) message_info = f"{message_info}\n{str_msg}"
sys.stdout.flush() sys.stdout.flush()
@@ -150,7 +145,7 @@ def telegram_bot(title, content):
payload = {'chat_id': str(TG_USER_ID), 'text': f'{title}\n\n{content}', 'disable_web_page_preview': 'true'} payload = {'chat_id': str(TG_USER_ID), 'text': f'{title}\n\n{content}', 'disable_web_page_preview': 'true'}
proxies = None proxies = None
if TG_PROXY_IP and TG_PROXY_PORT: if TG_PROXY_IP and TG_PROXY_PORT:
proxyStr = "http://{}:{}".format(TG_PROXY_IP, TG_PROXY_PORT) proxyStr = f"http://{TG_PROXY_IP}:{TG_PROXY_PORT}"
proxies = {"http": proxyStr, "https": proxyStr} proxies = {"http": proxyStr, "https": proxyStr}
try: try:
response = requests.post(url=url, headers=headers, params=payload, proxies=proxies).json() response = requests.post(url=url, headers=headers, params=payload, proxies=proxies).json()
@@ -167,7 +162,7 @@ def telegram_bot(title, content):
def dingding_bot(title, content): def dingding_bot(title, content):
timestamp = str(round(time.time() * 1000)) # 时间戳 timestamp = str(round(time.time() * 1000)) # 时间戳
secret_enc = DD_BOT_SECRET.encode('utf-8') secret_enc = DD_BOT_SECRET.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, DD_BOT_SECRET) string_to_sign = f'{timestamp}\n{DD_BOT_SECRET}'
string_to_sign_enc = string_to_sign.encode('utf-8') string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest() hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) # 签名 sign = urllib.parse.quote_plus(base64.b64encode(hmac_code)) # 签名
@@ -274,7 +269,8 @@ class WeCom:
return data["access_token"] return data["access_token"]
def send_text(self, message, touser="@all"): def send_text(self, message, touser="@all"):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.get_access_token()}'
send_values = { send_values = {
"touser": touser, "touser": touser,
"msgtype": "text", "msgtype": "text",
@@ -290,7 +286,8 @@ class WeCom:
return respone["errmsg"] return respone["errmsg"]
def send_mpnews(self, title, message, media_id, touser="@all"): def send_mpnews(self, title, message, media_id, touser="@all"):
send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.get_access_token()}'
send_values = { send_values = {
"touser": touser, "touser": touser,
"msgtype": "mpnews", "msgtype": "mpnews",

View File

@@ -4,6 +4,7 @@ cron: 20 10 */7 * *
new Env('禁用重复任务'); new Env('禁用重复任务');
""" """
import json import json
import logging import logging
import os import os
@@ -17,17 +18,13 @@ logger = logging.getLogger(name=None) # 创建一个日志对象
logging.Formatter("%(message)s") # 日志内容格式化 logging.Formatter("%(message)s") # 日志内容格式化
logger.setLevel(logging.INFO) # 设置日志等级 logger.setLevel(logging.INFO) # 设置日志等级
logger.addHandler(logging.StreamHandler()) # 添加控制台日志 logger.addHandler(logging.StreamHandler()) # 添加控制台日志
# logger.addHandler(logging.FileHandler(filename="text.log", mode="w")) # 添加文件日志 if ipport := os.getenv("IPPORT"):
ipport = ipport.lstrip("http://").rstrip("/")
else:
ipport = os.getenv("IPPORT")
if not ipport:
logger.info( logger.info(
"如果报错请在环境变量中添加你的真实 IP:端口\n名称IPPORT\t127.0.0.1:5700\n或在 config.sh 中添加 export IPPORT='127.0.0.1:5700'" "如果报错请在环境变量中添加你的真实 IP:端口\n名称IPPORT\t127.0.0.1:5700\n或在 config.sh 中添加 export IPPORT='127.0.0.1:5700'"
) )
ipport = "localhost:5700" ipport = "localhost:5700"
else:
ipport = ipport.lstrip("http://").rstrip("/")
sub_str = os.getenv("RES_SUB", "Aaron-lv_sync") sub_str = os.getenv("RES_SUB", "Aaron-lv_sync")
sub_list = sub_str.split("&") sub_list = sub_str.split("&")
res_only = os.getenv("RES_ONLY", True) res_only = os.getenv("RES_ONLY", True)
@@ -43,7 +40,7 @@ def load_send() -> None:
send = None send = None
cur_path = os.path.abspath(os.path.dirname(__file__)) cur_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(cur_path) sys.path.append(cur_path)
if os.path.exists(cur_path + "/notify.py"): if os.path.exists(f"{cur_path}/notify.py"):
try: try:
from notify import send from notify import send
except Exception: except Exception:
@@ -52,14 +49,11 @@ def load_send() -> None:
def get_tasklist() -> list: def get_tasklist() -> list:
tasklist = []
t = round(time.time() * 1000) t = round(time.time() * 1000)
url = f"http://{ipport}/api/crons?searchValue=&t={t}" url = f"http://{ipport}/api/crons?searchValue=&t={t}"
response = requests.get(url=url, headers=headers) response = requests.get(url=url, headers=headers)
datas = json.loads(response.content.decode("utf-8")) datas = json.loads(response.content.decode("utf-8"))
if datas.get("code") == 200: return datas.get("data") if datas.get("code") == 200 else []
tasklist = datas.get("data")
return tasklist
def filter_res_sub(tasklist: list) -> tuple: def filter_res_sub(tasklist: list) -> tuple:
@@ -95,7 +89,7 @@ def get_duplicate_list(tasklist: list) -> tuple:
cmds.append(task.get("command")) cmds.append(task.get("command"))
name_list = [] name_list = []
for i, name in enumerate(names): for name in names:
if name not in name_list: if name not in name_list:
name_list.append(name) name_list.append(name)
@@ -122,7 +116,7 @@ def get_duplicate_list(tasklist: list) -> tuple:
def reserve_task_only( def reserve_task_only(
tem_ids: list, tem_tasks: list, dup_ids: list, res_list: list tem_ids: list, tem_tasks: list, dup_ids: list, res_list: list
) -> list: ) -> list:
if len(tem_ids) == 0: if not tem_ids:
return tem_ids return tem_ids
logger.info("\n=== 最终筛选开始 ===") logger.info("\n=== 最终筛选开始 ===")

View File

@@ -45,10 +45,7 @@ while count:
from telethon.sessions import StringSession from telethon.sessions import StringSession
break break
except Exception: except Exception:
if count == 2: pip = 'pip3' if count == 2 else 'pip'
pip = 'pip3'
else:
pip = 'pip'
print(f'检测到没有 telethon 库,开始换源进行安装,将使用 {pip} 命令') print(f'检测到没有 telethon 库,开始换源进行安装,将使用 {pip} 命令')
os.system(f'{pip} install telethon -i https://pypi.tuna.tsinghua.edu.cn/simple') os.system(f'{pip} install telethon -i https://pypi.tuna.tsinghua.edu.cn/simple')
count -= 1 count -= 1
@@ -59,10 +56,7 @@ while count:
import requests import requests
break break
except Exception: except Exception:
if count == 2: pip = 'pip3' if count == 2 else 'pip'
pip = 'pip3'
else:
pip = 'pip'
print(f'检测到没有 requests 库,开始换源进行安装,将使用 {pip} 命令') print(f'检测到没有 requests 库,开始换源进行安装,将使用 {pip} 命令')
os.system(f'{pip} install requests -i https://pypi.tuna.tsinghua.edu.cn/simple') os.system(f'{pip} install requests -i https://pypi.tuna.tsinghua.edu.cn/simple')
count -= 1 count -= 1
@@ -137,8 +131,7 @@ def accountBean(docker_file_path):
for line in f: for line in f:
bean_account_line = re.findall(r'获得 [0-9]{2} 京豆', line, re.DOTALL) bean_account_line = re.findall(r'获得 [0-9]{2} 京豆', line, re.DOTALL)
if bean_account_line != []: if bean_account_line != []:
bean_account = int(re.findall(r"\d{2,}", bean_account_line[0])[0]) return int(re.findall(r"\d{2,}", bean_account_line[0])[0])
return bean_account
if line.find("'code': '1'") != -1: if line.find("'code': '1'") != -1:
return 20 return 20

View File

@@ -25,20 +25,18 @@ jd_cookie = ""
def getSToken(): def getSToken():
time_stamp = int(time.time() * 1000) time_stamp = int(time.time() * 1000)
get_url = ( get_url = f"https://plogin.m.jd.com/cgi-bin/mm/new_login_entrance?lang=chs&appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state={time_stamp}&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport"
"https://plogin.m.jd.com/cgi-bin/mm/new_login_entrance?lang=chs&appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state=%s&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport"
% time_stamp
)
get_header = { get_header = {
"Connection": "Keep-Alive", "Connection": "Keep-Alive",
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json, text/plain, */*", "Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-cn", "Accept-Language": "zh-cn",
"Referer": "https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state=%s&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport" "Referer": f"https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wq.jd.com/passport/LoginRedirect?state={time_stamp}&returnurl=https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport",
% time_stamp,
"User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122", "User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122",
"Host": "plogin.m.jd.com", "Host": "plogin.m.jd.com",
} }
resp = requests.get(url=get_url, headers=get_header) resp = requests.get(url=get_url, headers=get_header)
parseGetRespCookie(resp.headers, resp.json()) parseGetRespCookie(resp.headers, resp.json())
@@ -56,27 +54,25 @@ def parseGetRespCookie(headers, get_resp):
def getOKLToken(): def getOKLToken():
post_time_stamp = int(time.time() * 1000) post_time_stamp = int(time.time() * 1000)
post_url = ( post_url = f"https://plogin.m.jd.com/cgi-bin/m/tmauthreflogurl?s_token={s_token}&v={post_time_stamp}&remember=true"
"https://plogin.m.jd.com/cgi-bin/m/tmauthreflogurl?s_token=%s&v=%s&remember=true"
% (s_token, post_time_stamp)
)
post_data = { post_data = {
"lang": "chs", "lang": "chs",
"appid": 300, "appid": 300,
"returnurl": "https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action" "returnurl": f"https://wqlogin2.jd.com/passport/LoginRedirect?state={post_time_stamp}&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action",
% post_time_stamp,
"source": "wq_passport", "source": "wq_passport",
} }
post_header = { post_header = {
"Connection": "Keep-Alive", "Connection": "Keep-Alive",
"Content-Type": "application/x-www-form-urlencoded; Charset=UTF-8", "Content-Type": "application/x-www-form-urlencoded; Charset=UTF-8",
"Accept": "application/json, text/plain, */*", "Accept": "application/json, text/plain, */*",
"Cookie": cookies, "Cookie": cookies,
"Referer": "https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport" "Referer": f"https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state={post_time_stamp}&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport",
% post_time_stamp,
"User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122", "User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122",
"Host": "plogin.m.jd.com", "Host": "plogin.m.jd.com",
} }
try: try:
global okl_token global okl_token
resp = requests.post( resp = requests.post(
@@ -146,37 +142,34 @@ async def my_cookie(event):
) )
convdata = await conv.wait_event(press_event(SENDER)) convdata = await conv.wait_event(press_event(SENDER))
res = bytes.decode(convdata.data) res = bytes.decode(convdata.data)
if res == "cancel": if res != "cancel":
login = False
await jdbot.delete_messages(chat_id, cookiemsg)
msg = await conv.send_message("对话已取消")
conv.cancel()
else:
raise exceptions.TimeoutError() raise exceptions.TimeoutError()
login = False
await jdbot.delete_messages(chat_id, cookiemsg)
msg = await conv.send_message("对话已取消")
conv.cancel()
except exceptions.TimeoutError: except exceptions.TimeoutError:
expired_time = time.time() + 60 * 2 expired_time = time.time() + 60 * 2
while login: while login:
check_time_stamp = int(time.time() * 1000) check_time_stamp = int(time.time() * 1000)
check_url = ( check_url = f"https://plogin.m.jd.com/cgi-bin/m/tmauthchecktoken?&token={token}&ou_state=0&okl_token={okl_token}"
"https://plogin.m.jd.com/cgi-bin/m/tmauthchecktoken?&token=%s&ou_state=0&okl_token=%s"
% (token, okl_token)
)
check_data = { check_data = {
"lang": "chs", "lang": "chs",
"appid": 300, "appid": 300,
"returnurl": "https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action" "returnurl": f"https://wqlogin2.jd.com/passport/LoginRedirect?state={check_time_stamp}&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action",
% check_time_stamp,
"source": "wq_passport", "source": "wq_passport",
} }
check_header = { check_header = {
"Referer": "https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state=%s&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport" "Referer": f"https://plogin.m.jd.com/login/login?appid=300&returnurl=https://wqlogin2.jd.com/passport/LoginRedirect?state={check_time_stamp}&returnurl=//home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&/myJd/home.action&source=wq_passport",
% check_time_stamp,
"Cookie": cookies, "Cookie": cookies,
"Connection": "Keep-Alive", "Connection": "Keep-Alive",
"Content-Type": "application/x-www-form-urlencoded; Charset=UTF-8", "Content-Type": "application/x-www-form-urlencoded; Charset=UTF-8",
"Accept": "application/json, text/plain, */*", "Accept": "application/json, text/plain, */*",
"User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122", "User-Agent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5 UCBrowser/13.4.2.1122",
} }
resp = requests.post( resp = requests.post(
url=check_url, headers=check_header, data=check_data, timeout=30 url=check_url, headers=check_header, data=check_data, timeout=30
) )

View File

@@ -20,12 +20,9 @@ def post_tg(url, count):
r = requests.get(url) r = requests.get(url)
if '"ok":true,' in r.text: if '"ok":true,' in r.text:
print("发送成功!") print("发送成功!")
pass
else: else:
count = count + 1 count = count + 1
if count > 5: if count <= 5:
pass
else:
time.sleep(3) time.sleep(3)
print("发送失败,正在重试") print("发送失败,正在重试")
post_tg(url, count) post_tg(url, count)
@@ -85,38 +82,31 @@ while True:
with requests.get("https://hostloc.cherbim.ml/", stream=True, timeout=5) as r: with requests.get("https://hostloc.cherbim.ml/", stream=True, timeout=5) as r:
print(time.strftime("%m-%d %H:%M:%S", time.localtime())) print(time.strftime("%m-%d %H:%M:%S", time.localtime()))
for i in r.json()["new_data"][0][15:]: for i in r.json()["new_data"][0][15:]:
if i["主题ID"] in hostloc_list or i["主题"] in hostloc_title: if (
pass i["主题ID"] not in hostloc_list
else: and i["主题"] not in hostloc_title
):
hostloc_list = hostloc_list[1::] hostloc_list = hostloc_list[1::]
hostloc_list.append(i["主题ID"]) hostloc_list.append(i["主题ID"])
hostloc_title = hostloc_title[1::] hostloc_title = hostloc_title[1::]
hostloc_title.append(i["主题"]) hostloc_title.append(i["主题"])
a = "https://www.hostloc.com/thread-{0}-1-1.html".format(i["主题ID"]) a = "https://www.hostloc.com/thread-{0}-1-1.html".format(i["主题ID"])
time_1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) time_1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if "论坛bug此贴内容无法查看~" not in i["主题内容"][0:100]: a = a if "论坛bug此贴内容无法查看~" not in i["主题内容"][:100] else f"<s>{a}</s>"
a = a
else:
a = f"<s>{a}</s>"
text = ( text = (
"主 题:" f'主 题:<b>{i["主题"].replace("&", "%26").replace("<", "%26lt%3b").replace(">", "%26gt%3b").replace("#", " ")}</b>'
+ "<b>{}</b>".format(
i["主题"]
.replace("&", "%26")
.replace("<", "%26lt%3b")
.replace(">", "%26gt%3b")
.replace("#", " ")
)
+ "\n" + "\n"
+ "发 布 者:" + "发 布 者:"
+ """<a href="{0}">{1}</a>""".format(i["发布者链接"], i["发布者"]) + """<a href="{0}">{1}</a>""".format(
i["发布者链接"], i["发布者"]
)
+ "\n" + "\n"
+ "时 间:" + "时 间:"
+ time_1 + time_1
+ "\n" + "\n"
+ "内容预览:" + "内容预览:"
+ """<b>{0}</b>""".format( + """<b>{0}</b>""".format(
i["主题内容"][0:100] i["主题内容"][:100]
.replace("&", "%26") .replace("&", "%26")
.replace("<", "%26lt%3b") .replace("<", "%26lt%3b")
.replace(">", "%26gt%3b") .replace(">", "%26gt%3b")
@@ -126,16 +116,13 @@ while True:
+ "直达链接: " + "直达链接: "
+ a + a
) )
print(text) print(text)
# 修改为你自己的bot api token和chat_id(可以是用户也可以是频道) # 修改为你自己的bot api token和chat_id(可以是用户也可以是频道)
chat_id = os.environ.get("HOST_GROUP_ID") chat_id = os.environ.get("HOST_GROUP_ID")
bot_api_token = os.environ.get("HOST_BOT_TOKEN") bot_api_token = os.environ.get("HOST_BOT_TOKEN")
tg_url = ( tg_url = f"https://api.telegram.org/bot{bot_api_token}/sendMessage?parse_mode=HTML&chat_id={chat_id}&text={text}"
f"https://api.telegram.org/bot{bot_api_token}/sendMessage?parse_mode=HTML&chat_id="
+ chat_id
+ "&text="
+ text
)
b = 0 b = 0
post_tg(tg_url, b) post_tg(tg_url, b)
time.sleep(2) time.sleep(2)

View File

@@ -3,6 +3,7 @@
pip3 install telethon pysocks httpx pip3 install telethon pysocks httpx
""" """
import os import os
import time import time
@@ -36,31 +37,31 @@ jdhealth = os.environ.get("jdhealth")
for num in range(len(api_id_list)): for num in range(len(api_id_list)):
session_name = ["id_" + str(i) for i in api_id_list] session_name = [f"id_{str(i)}" for i in api_id_list]
client = TelegramClient(session_name[num], api_id_list[num], api_hash_list[num]) client = TelegramClient(session_name[num], api_id_list[num], api_hash_list[num])
client.start() client.start()
# 第一项是机器人ID第二项是发送的文字 # 第一项是机器人ID第二项是发送的文字
# 种豆得豆 # 种豆得豆
if jdplantbean is not None: if jdplantbean is not None:
client.send_message("@BotFather", "/bean " + jdplantbean) client.send_message("@BotFather", f"/bean {jdplantbean}")
# 东东农场 # 东东农场
if jdfruit is not None: if jdfruit is not None:
client.send_message("@BotFather", "/farm " + jdfruit) client.send_message("@BotFather", f"/farm {jdfruit}")
# 京喜工厂 # 京喜工厂
if jxfactory is not None: if jxfactory is not None:
client.send_message("@BotFather", "/jxfactory " + jxfactory) client.send_message("@BotFather", f"/jxfactory {jxfactory}")
# 闪购盲盒 # 闪购盲盒
if jdsgmh is not None: if jdsgmh is not None:
client.send_message("@BotFather", "/sgmh " + jdsgmh) client.send_message("@BotFather", f"/sgmh {jdsgmh}")
# 东东工厂 # 东东工厂
if jdfactory is not None: if jdfactory is not None:
client.send_message("@BotFather", "/ddfactory " + jdfactory) client.send_message("@BotFather", f"/ddfactory {jdfactory}")
# 东东萌宠 # 东东萌宠
if jdpet is not None: if jdpet is not None:
client.send_message("@BotFather", "/pet " + jdpet) client.send_message("@BotFather", f"/pet {jdpet}")
# 东东健康 # 东东健康
if jdhealth is not None: if jdhealth is not None:
client.send_message("@BotFather", "/health " + jdhealth) client.send_message("@BotFather", f"/health {jdhealth}")
time.sleep(5) # 延时5秒等待机器人回应一般是秒回应但也有发生阻塞的可能 time.sleep(5) # 延时5秒等待机器人回应一般是秒回应但也有发生阻塞的可能
client.send_read_acknowledge("@BotFather") # 将机器人回应设为已读 client.send_read_acknowledge("@BotFather") # 将机器人回应设为已读

View File

@@ -36,13 +36,12 @@ headers = {"User-Agent": "Dalvik/2.1.0 (Linux; U; Android 9; MI 6 MIUI/20.6.18)"
# 获取登录 code # 获取登录 code
def get_code(location): def get_code(location):
code_pattern = re.compile("(?<=access=).*?(?=&)") code_pattern = re.compile("(?<=access=).*?(?=&)")
code = code_pattern.findall(location)[0] return code_pattern.findall(location)[0]
return code
# 登录 # 登录
def login(_user, password): def login(_user, password):
url1 = "https://api-user.huami.com/registrations/+86" + _user + "/tokens" url1 = f"https://api-user.huami.com/registrations/+86{_user}/tokens"
_headers = { _headers = {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"User-Agent": "MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)", "User-Agent": "MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)",
@@ -89,11 +88,11 @@ def main(_user, _passwd, _step):
_user = str(_user) _user = str(_user)
password = str(_passwd) password = str(_passwd)
_step = str(_step) _step = str(_step)
if _user == "" or password == "": if not _user or not password:
print("用户名或密码不能为空!") print("用户名或密码不能为空!")
return "user and passwd not empty" return "user and passwd not empty"
if _step == "": if not _step:
print("已设置为随机步数18000-25000") print("已设置为随机步数18000-25000")
_step = str(random.randint(18000, 25000)) _step = str(random.randint(18000, 25000))
login_token, userid = login(_user, password) login_token, userid = login(_user, password)
@@ -111,7 +110,7 @@ def main(_user, _passwd, _step):
find_date = re.compile(r".*?date%22%3A%22(.*?)%22%2C%22data.*?") find_date = re.compile(r".*?date%22%3A%22(.*?)%22%2C%22data.*?")
find_step = re.compile(r".*?ttl%5C%22%3A(.*?)%2C%5C%22dis.*?") find_step = re.compile(r".*?ttl%5C%22%3A(.*?)%2C%5C%22dis.*?")
data_json = re.sub(find_date.findall(data_json)[0], today, str(data_json)) data_json = re.sub(find_date.findall(data_json)[0], today, data_json)
data_json = re.sub(find_step.findall(data_json)[0], _step, str(data_json)) data_json = re.sub(find_step.findall(data_json)[0], _step, str(data_json))
url = f"https://api-mifit-cn.huami.com/v1/data/band_data.json?&t={t}" url = f"https://api-mifit-cn.huami.com/v1/data/band_data.json?&t={t}"
@@ -130,18 +129,16 @@ def main(_user, _passwd, _step):
def get_time(): def get_time():
url = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp" url = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp"
response = requests.get(url, headers=headers).json() response = requests.get(url, headers=headers).json()
t = response["data"]["t"] return response["data"]["t"]
return t
# 获取app_token # 获取app_token
def get_app_token(login_token): def get_app_token(login_token):
url = f"https://account-cn.huami.com/v1/client/app_tokens?app_name=com.xiaomi.hm.health&dn=api-user.huami.com%2Capi-mifit.huami.com%2Capp-analytics.huami.com&login_token={login_token}" url = f"https://account-cn.huami.com/v1/client/app_tokens?app_name=com.xiaomi.hm.health&dn=api-user.huami.com%2Capi-mifit.huami.com%2Capp-analytics.huami.com&login_token={login_token}"
response = requests.get(url, headers=headers).json() response = requests.get(url, headers=headers).json()
app_token = response["token_info"]["app_token"]
# print("app_token获取成功") # print("app_token获取成功")
# print(app_token) # print(app_token)
return app_token return response["token_info"]["app_token"]
# 推送 server 酱 # 推送 server 酱
@@ -227,7 +224,7 @@ def wxpush(msg, usr, corpid, corpsecret, agentid=1000002):
# 获取 access_token每次的 access_token 都不一样,所以需要运行一次请求一次 # 获取 access_token每次的 access_token 都不一样,所以需要运行一次请求一次
def get_access_token(_base_url, _corpid, _corpsecret): def get_access_token(_base_url, _corpid, _corpsecret):
urls = _base_url + "corpid=" + _corpid + "&corpsecret=" + _corpsecret urls = f"{_base_url}corpid={_corpid}&corpsecret={_corpsecret}"
resp = requests.get(urls).json() resp = requests.get(urls).json()
access_token = resp["access_token"] access_token = resp["access_token"]
return access_token return access_token
@@ -271,7 +268,7 @@ def wxpush(msg, usr, corpid, corpsecret, agentid=1000002):
if __name__ == "__main__": if __name__ == "__main__":
# Push Mode # Push Mode
Pm = os.environ.get("PMODE") Pm = os.environ.get("PMODE")
if Pm == "wx" or Pm == "nwx": if Pm in ["wx", "nwx"]:
_sckey = os.environ.get("PKEY") _sckey = os.environ.get("PKEY")
if _sckey == "": if _sckey == "":
print("未提供 sckey不进行推送") print("未提供 sckey不进行推送")
@@ -309,11 +306,11 @@ if __name__ == "__main__":
if len(user_list) == len(passwd_list): if len(user_list) == len(passwd_list):
push = "" push = ""
for line in range(0, len(user_list)): for line in range(len(user_list)):
if len(step_array) == 2: if len(step_array) == 2:
step = str(random.randint(int(step_array[0]), int(step_array[1]))) step = str(random.randint(int(step_array[0]), int(step_array[1])))
print(f"已设置为随机步数({step_array[0]}-{step_array[1]}") print(f"已设置为随机步数({step_array[0]}-{step_array[1]}")
elif str(step) == "": elif not str(step):
step = "" step = ""
push += main(user_list[line], passwd_list[line], step) + "\n" push += main(user_list[line], passwd_list[line], step) + "\n"
if Pm == "wx": if Pm == "wx":
@@ -329,7 +326,5 @@ if __name__ == "__main__":
wxpush(push, sl[0], sl[1], sl[2]) wxpush(push, sl[0], sl[1], sl[2])
elif Pm == "pp": elif Pm == "pp":
push_pushplus(token, push) push_pushplus(token, push)
elif Pm == "off":
pass
else: else:
print("用户名和密码数量不对") print("用户名和密码数量不对")

View File

@@ -14,6 +14,7 @@ STEP: 步数 空或不填则为 18000-25000 之间随机,自定义示
MI_API: api 接口 MI_API: api 接口
""" """
import os import os
import random import random
@@ -32,7 +33,7 @@ else:
if len(step_array) == 2: if len(step_array) == 2:
step = str(random.randint(int(step_array[0]), int(step_array[1]))) step = str(random.randint(int(step_array[0]), int(step_array[1])))
print(f"已设置为随机步数({step_array[0]}-{step_array[1]}") print(f"已设置为随机步数({step_array[0]}-{step_array[1]}")
elif str(step) == "": elif not str(step):
step = int(random.uniform(18000, 25000)) step = int(random.uniform(18000, 25000))

View File

@@ -88,7 +88,7 @@ def get_args():
def get_envs(): def get_envs():
infos = { return {
"phone": os.getenv("NETEASE_USER"), "phone": os.getenv("NETEASE_USER"),
"password": os.getenv("NETEASE_PWD"), "password": os.getenv("NETEASE_PWD"),
"sc_key": os.getenv("PUSH_KEY"), "sc_key": os.getenv("PUSH_KEY"),
@@ -103,14 +103,12 @@ def get_envs():
"qmsg_key": os.getenv("QMSG_KEY"), "qmsg_key": os.getenv("QMSG_KEY"),
"ding_token": os.getenv("DD_BOT_TOKEN"), "ding_token": os.getenv("DD_BOT_TOKEN"),
} }
return infos
# Calculate the MD5 value of text # Calculate the MD5 value of text
# 计算字符串的32位小写MD5值 # 计算字符串的32位小写MD5值
def calc_md5(text): def calc_md5(text):
md5_text = hashlib.md5(text.encode(encoding="utf-8")).hexdigest() return hashlib.md5(text.encode(encoding="utf-8")).hexdigest()
return md5_text
# AES Encrypt # AES Encrypt
@@ -185,7 +183,7 @@ class Push:
headers = {"Content-type": "application/x-www-form-urlencoded"} headers = {"Content-type": "application/x-www-form-urlencoded"}
content = {"title": "网易云打卡", "desp": self.text} content = {"title": "网易云打卡", "desp": self.text}
ret = requests.post(url, headers=headers, data=content) ret = requests.post(url, headers=headers, data=content)
print("ServerChan: " + ret.text) print(f"ServerChan: {ret.text}")
# Telegram Bot Push # Telegram Bot Push
def telegram_push(self): def telegram_push(self):
@@ -198,7 +196,7 @@ class Push:
"text": self.text, "text": self.text,
} }
ret = requests.post(url, data=data) ret = requests.post(url, data=data)
print("Telegram: " + ret.text) print(f"Telegram: {ret.text}")
# Bark Push # Bark Push
def bark_push(self): def bark_push(self):
@@ -209,7 +207,7 @@ class Push:
headers = {"Content-Type": "application/json;charset=utf-8"} headers = {"Content-Type": "application/json;charset=utf-8"}
url = "https://api.day.app/{0}/?isArchive={1}".format(arg[0], arg[1]) url = "https://api.day.app/{0}/?isArchive={1}".format(arg[0], arg[1])
ret = requests.post(url, json=data, headers=headers) ret = requests.post(url, json=data, headers=headers)
print("Bark: " + ret.text) print(f"Bark: {ret.text}")
# PushPlus Push # PushPlus Push
def push_plus_push(self): def push_plus_push(self):
@@ -220,7 +218,7 @@ class Push:
arg[0], "网易云打卡", self.text, "html" arg[0], "网易云打卡", self.text, "html"
) )
ret = requests.get(url) ret = requests.get(url)
print("pushplus: " + ret.text) print(f"pushplus: {ret.text}")
# Wecom Push # Wecom Push
def wecom_id_push(self): def wecom_id_push(self):
@@ -252,7 +250,7 @@ class Push:
if ret["errcode"] != 0: if ret["errcode"] != 0:
print("微信推送配置错误") print("微信推送配置错误")
else: else:
print("Wecom: " + ret) print(f"Wecom: {ret}")
# Qmsg Push # Qmsg Push
def qmsg_push(self): def qmsg_push(self):
@@ -261,7 +259,7 @@ class Push:
arg = self.info["qmsg_key"] arg = self.info["qmsg_key"]
url = "https://qmsg.zendee.cn/send/{0}?msg={1}".format(arg[0], self.text) url = "https://qmsg.zendee.cn/send/{0}?msg={1}".format(arg[0], self.text)
ret = requests.post(url) ret = requests.post(url)
print("Qmsg: " + ret.text) print(f"Qmsg: {ret.text}")
# Ding Talk Push # Ding Talk Push
def ding_talk_push(self): def ding_talk_push(self):
@@ -274,7 +272,7 @@ class Push:
{"msgtype": "text", "text": {"content": "【CMLU】\n\n" + self.text}} {"msgtype": "text", "text": {"content": "【CMLU】\n\n" + self.text}}
) )
ret = requests.post(url, headers=header, data=data) ret = requests.post(url, headers=header, data=data)
print("Ding: " + ret.text) print(f"Ding: {ret.text}")
# 加密类,实现网易云音乐前端加密流程 # 加密类,实现网易云音乐前端加密流程
@@ -398,8 +396,9 @@ class CloudMusic:
# 获取用户的收藏歌单 # 获取用户的收藏歌单
def get_subscribe_playlists(self): def get_subscribe_playlists(self):
private_url = ( private_url = (
"https://music.163.com/weapi/user/playlist?csrf_token=" + self.csrf f"https://music.163.com/weapi/user/playlist?csrf_token={self.csrf}"
) )
res = self.session.post( res = self.session.post(
url=private_url, url=private_url,
data=self.enc.encrypt( data=self.enc.encrypt(
@@ -417,18 +416,15 @@ class CloudMusic:
ret = json.loads(res.text) ret = json.loads(res.text)
subscribed_lists = [] subscribed_lists = []
if ret["code"] == 200: if ret["code"] == 200:
for li in ret["playlist"]: subscribed_lists.extend(li["id"] for li in ret["playlist"] if li["subscribed"])
if li["subscribed"]:
subscribed_lists.append(li["id"])
else: else:
print("个人订阅歌单获取失败 " + str(ret["code"]) + "" + ret["message"]) print("个人订阅歌单获取失败 " + str(ret["code"]) + "" + ret["message"])
return subscribed_lists return subscribed_lists
# 获取某一歌单内的所有音乐ID # 获取某一歌单内的所有音乐ID
def get_list_musics(self, mlist): def get_list_musics(self, mlist):
detail_url = ( detail_url = f"https://music.163.com/weapi/v6/playlist/detail?csrf_token={self.csrf}"
"https://music.163.com/weapi/v6/playlist/detail?csrf_token=" + self.csrf
)
musics = [] musics = []
for m in mlist: for m in mlist:
res = self.session.post( res = self.session.post(

View File

@@ -70,16 +70,11 @@ if (
QQ_SKEY = os.environ["QQ_SKEY"] QQ_SKEY = os.environ["QQ_SKEY"]
QQ_MODE = os.environ["QQ_MODE"] QQ_MODE = os.environ["QQ_MODE"]
# 获取pushplus+ PUSH_PLUS_TOKEN # 获取pushplus+ PUSH_PLUS_TOKEN
if "PUSH_PLUS_TOKEN" in os.environ: if "PUSH_PLUS_TOKEN" in os.environ and len(os.environ["PUSH_PLUS_TOKEN"]) > 1:
if len(os.environ["PUSH_PLUS_TOKEN"]) > 1: PUSH_PLUS_TOKEN = os.environ["PUSH_PLUS_TOKEN"]
PUSH_PLUS_TOKEN = os.environ["PUSH_PLUS_TOKEN"]
# print("已获取并使用Env环境 PUSH_PLUS_TOKEN")
# 获取企业微信应用推送 QYWX_AM # 获取企业微信应用推送 QYWX_AM
if "QYWX_AM" in os.environ: if "QYWX_AM" in os.environ and len(os.environ["QYWX_AM"]) > 1:
if len(os.environ["QYWX_AM"]) > 1: QYWX_AM = os.environ["QYWX_AM"]
QYWX_AM = os.environ["QYWX_AM"]
# print("已获取并使用Env环境 QYWX_AM")
if BARK: if BARK:
notify_mode.append("bark") notify_mode.append("bark")
# print("BARK 推送打开") # print("BARK 推送打开")
@@ -107,7 +102,7 @@ if QYWX_AM:
def message(str_msg): def message(str_msg):
global message_info global message_info
print(str_msg) print(str_msg)
message_info = "{}\n{}".format(message_info, str_msg) message_info = f"{message_info}\n{str_msg}"
sys.stdout.flush() sys.stdout.flush()
@@ -171,7 +166,7 @@ def telegram_bot(title, content):
} }
proxies = None proxies = None
if TG_PROXY_IP and TG_PROXY_PORT: if TG_PROXY_IP and TG_PROXY_PORT:
proxyStr = "http://{}:{}".format(TG_PROXY_IP, TG_PROXY_PORT) proxyStr = f"http://{TG_PROXY_IP}:{TG_PROXY_PORT}"
proxies = {"http": proxyStr, "https": proxyStr} proxies = {"http": proxyStr, "https": proxyStr}
try: try:
response = requests.post( response = requests.post(
@@ -190,7 +185,7 @@ def telegram_bot(title, content):
def dingding_bot(title, content): def dingding_bot(title, content):
timestamp = str(round(time.time() * 1000)) # 时间戳 timestamp = str(round(time.time() * 1000)) # 时间戳
secret_enc = DD_BOT_SECRET.encode("utf-8") secret_enc = DD_BOT_SECRET.encode("utf-8")
string_to_sign = "{}\n{}".format(timestamp, DD_BOT_SECRET) string_to_sign = f"{timestamp}\n{DD_BOT_SECRET}"
string_to_sign_enc = string_to_sign.encode("utf-8") string_to_sign_enc = string_to_sign.encode("utf-8")
hmac_code = hmac.new( hmac_code = hmac.new(
secret_enc, string_to_sign_enc, digestmod=hashlib.sha256 secret_enc, string_to_sign_enc, digestmod=hashlib.sha256

View File

@@ -41,8 +41,7 @@ queue = asyncio.Queue()
# 文件夹/文件名称处理 # 文件夹/文件名称处理
def validate_title(title): def validate_title(title):
r_str = r"[\/\\\:\*\?\"\<\>\|\n]" # '/ \ : * ? " < > |' r_str = r"[\/\\\:\*\?\"\<\>\|\n]" # '/ \ : * ? " < > |'
new_title = re.sub(r_str, "_", title) # 替换为下划线 return re.sub(r_str, "_", title)
return new_title
# 获取相册标题 # 获取相册标题
@@ -52,10 +51,9 @@ async def get_group_caption(message):
async for msg in client.iter_messages( async for msg in client.iter_messages(
entity=entity, reverse=True, offset_id=message.id - 9, limit=10 entity=entity, reverse=True, offset_id=message.id - 9, limit=10
): ):
if msg.grouped_id == message.grouped_id: if msg.grouped_id == message.grouped_id and msg.text != "":
if msg.text != "": group_caption = msg.text
group_caption = msg.text return group_caption
return group_caption
return group_caption return group_caption
@@ -140,15 +138,15 @@ async def worker(name):
@events.register(events.NewMessage(pattern="/start", from_users=admin_id)) @events.register(events.NewMessage(pattern="/start", from_users=admin_id))
async def handler(update): async def handler(update):
text = update.message.text.split(" ") text = update.message.text.split(" ")
msg = ( if len(text) == 1 or len(text) not in [2, 3]:
"参数错误,请按照参考格式输入:\n\n" msg = (
"1.普通群组\n" "参数错误,请按照参考格式输入:\n\n"
"<i>/start https://t.me/fkdhlg 0 </i>\n\n" "1.普通群组\n"
"2.私密群组(频道) 链接为随便复制一条群组消息链接\n" "<i>/start https://t.me/fkdhlg 0 </i>\n\n"
"<i>/start https://t.me/12000000/1 0 </i>\n\n" "2.私密群组(频道) 链接为随便复制一条群组消息链接\n"
"Tips:如果不输入offset_id默认从第一条开始下载" "<i>/start https://t.me/12000000/1 0 </i>\n\n"
) "Tips:如果不输入offset_id默认从第一条开始下载"
if len(text) == 1: )
await bot.send_message(admin_id, msg, parse_mode="HTML") await bot.send_message(admin_id, msg, parse_mode="HTML")
return return
elif len(text) == 2: elif len(text) == 2:
@@ -168,7 +166,7 @@ async def handler(update):
"chat输入错误请输入频道或群组的链接\n\n" f"错误类型:{e.__class__}" f"异常消息:{e}" "chat输入错误请输入频道或群组的链接\n\n" f"错误类型:{e.__class__}" f"异常消息:{e}"
) )
return return
elif len(text) == 3: else:
chat_id = text[1] chat_id = text[1]
offset_id = int(text[2]) offset_id = int(text[2])
try: try:
@@ -185,9 +183,6 @@ async def handler(update):
"chat输入错误请输入频道或群组的链接\n\n" f"错误类型:{type(e).__class__}" f"异常消息:{e}" "chat输入错误请输入频道或群组的链接\n\n" f"错误类型:{type(e).__class__}" f"异常消息:{e}"
) )
return return
else:
await bot.send_message(admin_id, msg, parse_mode="HTML")
return
if chat_title: if chat_title:
print(f"{get_local_time()} - 开始下载:{chat_title}({entity.id}) - {offset_id}") print(f"{get_local_time()} - 开始下载:{chat_title}({entity.id}) - {offset_id}")
last_msg_id = 0 last_msg_id = 0
@@ -266,10 +261,13 @@ async def all_chat_download(update):
try: try:
if type(message.media) == MessageMediaWebPage: if type(message.media) == MessageMediaWebPage:
return return
if message.media.document.mime_type == "image/webp": if (
file_name = f"{message.media.document.id}.webp" message.media.document.mime_type
if message.media.document.mime_type == "application/x-tgsticker": == "application/x-tgsticker"
):
file_name = f"{message.media.document.id}.tgs" file_name = f"{message.media.document.id}.tgs"
elif message.media.document.mime_type == "image/webp":
file_name = f"{message.media.document.id}.webp"
for i in message.document.attributes: for i in message.document.attributes:
try: try:
file_name = i.file_name file_name = i.file_name

View File

@@ -123,7 +123,7 @@ def run_M_N():
os.chdir(node_p) os.chdir(node_p)
# print(node_d) # print(node_d)
# print(os.path.dirname(node_p)) # print(os.path.dirname(node_p))
command = "%s app.js -p %s -f %s" % (node_d, userport, ip) command = f"{node_d} app.js -p {userport} -f {ip}"
subprocess.Popen(command, shell=False, creationflags=CREATE_NO_WINDOW) subprocess.Popen(command, shell=False, creationflags=CREATE_NO_WINDOW)
print("成功启动 NODE 代理,命令行:", command) print("成功启动 NODE 代理,命令行:", command)
@@ -136,12 +136,7 @@ def procressexist(processname="cloudmusic.exe"): # 检测进程是否健在(默
time.sleep(sleep) time.sleep(sleep)
pl = psutil.pids() pl = psutil.pids()
try: try:
for pid in pl: return any(psutil.Process(pid).name() == processname for pid in pl)
if psutil.Process(pid).name() == processname:
return True
break
else:
return False
except: except:
return False return False
@@ -166,5 +161,4 @@ run_M_N()
while procressexist() and procressexist("node.exe"): while procressexist() and procressexist("node.exe"):
print("网易云音乐进程和 NODE 进程健在!") print("网易云音乐进程和 NODE 进程健在!")
pass
killprocess() killprocess()