diff --git a/jdCookie.py b/jdCookie.py index 443ebba..53d0d63 100644 --- a/jdCookie.py +++ b/jdCookie.py @@ -7,15 +7,14 @@ import os import time -import logging -logging.basicConfig(level=logging.INFO, format='%(message)s') -logger = logging.getLogger() +from functools import partial +print = partial(print, flush=True) def get_cookies(): CookieJDs = [] if os.environ.get("JD_COOKIE"): - logger.info("已获取并使用Env环境 Cookie") + print("已获取并使用Env环境 Cookie") if '&' in os.environ["JD_COOKIE"]: CookieJDs = os.environ["JD_COOKIE"].split('&') elif '\n' in os.environ["JD_COOKIE"]: @@ -37,13 +36,13 @@ def get_cookies(): CookieJDs = sorted(set(CookieJDs), key=CookieJDs.index) # return CookieJDs else: - logger.info("未获取到正确✅格式的京东账号Cookie") + print("未获取到正确✅格式的京东账号Cookie") return - logger.info(f"====================共{len(CookieJDs)}个京东账号Cookie=========\n") - logger.info(f"==================脚本执行- 北京时间(UTC+8):{time.strftime('%Y/%m/%d %H:%M:%S', time.localtime())}=====================\n") + print(f"====================共{len(CookieJDs)}个京东账号Cookie=========\n") + print(f"==================脚本执行- 北京时间(UTC+8):{time.strftime('%Y/%m/%d %H:%M:%S', time.localtime())}=====================\n") return CookieJDs # if __name__ == "__main__": # get_cookies() -# logger.info(os.environ.get("JD_COOKIE")) +# print(os.environ.get("JD_COOKIE")) diff --git a/jd_jinggengInvite.py b/jd_jinggengInvite.py index 7095ad6..86b0a7e 100644 --- a/jd_jinggengInvite.py +++ b/jd_jinggengInvite.py @@ -23,9 +23,8 @@ from datetime import datetime import json import random from urllib.parse import quote_plus, unquote_plus -import logging -logging.basicConfig(level=logging.INFO, format='%(message)s') -logger = logging.getLogger() +from functools import partial +print = partial(print, flush=True) import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) @@ -34,7 +33,7 @@ try: from jdCookie import get_cookies getCk = get_cookies() except: - logger.info("请先下载依赖脚本,\n下载链接: https://raw.githubusercontent.com/shufflewzc/faker2/main/jdCookie.py") + print("请先下载依赖脚本,\n下载链接: https://raw.githubusercontent.com/shufflewzc/faker2/main/jdCookie.py") sys.exit(3) redis_url = os.environ.get("redis_url") if os.environ.get("redis_url") else "172.17.0.1" redis_pwd = os.environ.get("redis_pwd") if os.environ.get("redis_pwd") else "" @@ -45,12 +44,13 @@ inviterNicks = [ "pWGUWZJQ3actex0X2vQyLsjNhNaYFy2HteErE6izlhTf9nrGY7gBkCdGU4C6z%2FxD" ] if "&" not in jinggengInviteJoin: - logger.info("⚠️jinggengInviteJoin变量有误!退出程序!") + print("⚠️jinggengInviteJoin变量有误!退出程序!") sys.exit() ac_id = jinggengInviteJoin.split("&")[0] user_id = jinggengInviteJoin.split("&")[1] inviterNick = random.choice(inviterNicks) activity_url = f"https://jinggeng-isv.isvjcloud.com/ql/front/showInviteJoin?id={ac_id}&user_id={user_id}&inviterNick={inviterNick}" +print(f"【🛳活动入口】{activity_url}") def redis_conn(): try: @@ -59,12 +59,12 @@ def redis_conn(): pool = redis.ConnectionPool(host=redis_url, port=6379, decode_responses=True, socket_connect_timeout=5, password=redis_pwd) r = redis.Redis(connection_pool=pool) r.get('conn_test') - logger.info('✅redis连接成功') + print('✅redis连接成功') return r except: - logger.info("⚠️redis连接异常") + print("⚠️redis连接异常") except: - logger.info("⚠️缺少redis依赖,请运行pip3 install redis") + print("⚠️缺少redis依赖,请运行pip3 install redis") def getToken(ck, r=None): try: @@ -76,12 +76,12 @@ def getToken(ck, r=None): try: if r is not None: Token = r.get(f'{activityUrl.split("https://")[1].split("-")[0]}_{pt_pin}') - # logger.info("Token过期时间", r.ttl(f'{activityUrl.split("https://")[1].split("-")[0]}_{pt_pin}')) + # print("Token过期时间", r.ttl(f'{activityUrl.split("https://")[1].split("-")[0]}_{pt_pin}')) if Token is not None: - logger.info(f"♻️获取缓存Token->: {Token}") + print(f"♻️获取缓存Token->: {Token}") return Token else: - logger.info("🈳去设置Token缓存-->") + print("🈳去设置Token缓存-->") s.headers = { 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate, br', @@ -94,20 +94,20 @@ def getToken(ck, r=None): 'Accept': '*/*' } sign_txt = sign({"url": f"{activityUrl}", "id": ""}, 'isvObfuscator') - # logger.info(sign_txt) + # print(sign_txt) f = s.post('https://api.m.jd.com/client.action', verify=False, timeout=30) if f.status_code != 200: - logger.info(f.status_code) + print(f.status_code) return else: if "参数异常" in f.text: return Token_new = f.json()['token'] - logger.info(f"Token->: {Token_new}") + print(f"Token->: {Token_new}") if r.set(f'{activityUrl.split("https://")[1].split("-")[0]}_{pt_pin}', Token_new, ex=1800): - logger.info("✅Token缓存设置成功") + print("✅Token缓存设置成功") else: - logger.info("❌Token缓存设置失败") + print("❌Token缓存设置失败") return Token_new else: s.headers = { @@ -122,16 +122,16 @@ def getToken(ck, r=None): 'Accept': '*/*' } sign_txt = sign({"url": f"{activityUrl}", "id": ""}, 'isvObfuscator') - # logger.info(sign_txt) + # print(sign_txt) f = s.post('https://api.m.jd.com/client.action', verify=False, timeout=30) if f.status_code != 200: - logger.info(f.status_code) + print(f.status_code) return else: if "参数异常" in f.text: return Token = f.json()['token'] - logger.info(f"Token->: {Token}") + print(f"Token->: {Token}") return Token except: return @@ -194,7 +194,7 @@ def getActivity(index=1, isOpenCard=0, inviterCode=None, getIndex=0): response = requests.request("GET", url, headers=headers) html_text = response.text if response.status_code == 493: - logger.info(response.status_code, "⚠️ip疑似黑了,休息一会再来撸~") + print(response.status_code, "⚠️ip疑似黑了,休息一会再来撸~") sys.exit() # if response.cookies: cookies = response.cookies.get_dict() @@ -219,7 +219,7 @@ def getActivity(index=1, isOpenCard=0, inviterCode=None, getIndex=0): shop_sid = soup.find('input', attrs={'id': 'shop_sid'})['value'] inviteSuccNums = (soup.find('input', attrs={'id': 'helpLogs'})['value']) inviteSetting2s = eval(soup.find('input', attrs={'id': 'inviteSetting2'})['value']) - logger.info(f"店铺名称: {shop_title} \n活动名称: {actName} \n店铺ID: {shop_sid}") + print(f"店铺名称: {shop_title} \n活动名称: {actName} \n店铺ID: {shop_sid}") num1 = {'1': 'one', '2': 'two', '3': 'three', '4': 'four'} num2 = {'1': 'leveOneNum', '2': 'leveTwoNum', '3': 'leveThreeNum', '4': 'leveFourNum'} needInviteNums = [] @@ -238,16 +238,16 @@ def getActivity(index=1, isOpenCard=0, inviterCode=None, getIndex=0): denomination = inviteSetting2['denomination'] awardId = inviteSetting2['id'] # inviteSucc = soup.find('input', attrs={'id': 'inviteSucc'})['value'] - logger.info(f"奖品{b}: {equityName} 奖励: {denomination} 总数: {freezeQuantity}份 剩余: {availableQuantity}份 需要邀请: {leveNum}人") + print(f"奖品{b}: {equityName} 奖励: {denomination} 总数: {freezeQuantity}份 剩余: {availableQuantity}份 需要邀请: {leveNum}人") if availableQuantity > 0: needInviteNums.append((leveNum, awardId, equityType)) if len(needInviteNums) == 0: - logger.info(f"⛈⛈⛈活动奖品全部发完啦!") + print(f"⛈⛈⛈活动奖品全部发完啦!") sys.exit() return errorMsg, inviteSuccNums, needInviteNums return errorMsg0 elif "活动已结束" in html_text: - logger.info("😭活动已结束,下次早点来~") + print("😭活动已结束,下次早点来~") sys.exit() else: return set_cookie @@ -276,7 +276,7 @@ def setMixNick(token): refresh_cookies(response) return setMixNick0 except Exception as e: - logger.info(e) + print(e) return def recordActPvUvdata(token): @@ -351,12 +351,12 @@ def bindWithVender(cookie): if res['success']: open_result = res['message'] if "火爆" in open_result: - logger.info(f"\t⛈⛈⛈{open_result}") + print(f"\t⛈⛈⛈{open_result}") else: - logger.info(f"\t🎉🎉🎉{open_result}") + print(f"\t🎉🎉🎉{open_result}") return res['message'] except Exception as e: - logger.info(e) + print(e) def receiveInviteJoinAward(token, awardId): url = "https://jinggeng-isv.isvjcloud.com/ql/front/receiveInviteJoinAward" @@ -382,9 +382,9 @@ def receiveInviteJoinAward(token, awardId): if msg['isSendSucc']: awardType = msg['drawAwardDto']['awardType'].replace('JD_BEAN', '京豆').replace('JD_POINT', '积分') awardDenomination = msg['drawAwardDto']['awardDenomination'] - logger.info(f"\t🎉🎉成功领取{awardDenomination}{awardType}") + print(f"\t🎉🎉成功领取{awardDenomination}{awardType}") else: - logger.info(f"\t🎉🎉{res['msg']}") + print(f"\t🎉🎉{res['msg']}") if __name__ == '__main__': @@ -394,7 +394,7 @@ if __name__ == '__main__': if not cks: sys.exit() except: - logger.info("未获取到有效COOKIE,退出程序!") + print("未获取到有效COOKIE,退出程序!") sys.exit() global inviterCode, inviteSuccNums, activityUrl, needInviteNums, rewardIndex, firstCk inviteSuccNums = 0 @@ -408,7 +408,7 @@ if __name__ == '__main__': if num == 1: firstCk = cookie if num % 5 == 0: - logger.info("⏰等待5s") + print("⏰等待5s") time.sleep(5) global ua, activityCookie, token, getIndex getIndex = 0 @@ -418,8 +418,8 @@ if __name__ == '__main__': pt_pin = unquote_plus(pt_pin) except IndexError: pt_pin = f'用户{num}' - logger.info(f'\n******开始【京东账号{num}】{pt_pin} *********\n') - logger.info(datetime.now()) + print(f'\n******开始【京东账号{num}】{pt_pin} *********\n') + print(datetime.now()) token = '' activityCookie = '' activityCookie = getActivity(num, 0, inviterCode, 0) @@ -427,54 +427,54 @@ if __name__ == '__main__': token = getToken(cookie, r) if token is None: if num == 1: - logger.info(f"⚠️车头获取Token失败,退出本程序!") + print(f"⚠️车头获取Token失败,退出本程序!") # sys.exit() os._exit() - logger.info(f"⚠️获取Token失败!⏰等待3s") + print(f"⚠️获取Token失败!⏰等待3s") time.sleep(3) continue except: - logger.info(f"⚠️获取Token失败!⏰等待3s") + print(f"⚠️获取Token失败!⏰等待3s") time.sleep(3) continue time.sleep(1.5) setMixNick0 = setMixNick(token) if setMixNick0 is None: if num == 1: - logger.info(f"⚠️车头获取邀请码失败,退出本程序!") + print(f"⚠️车头获取邀请码失败,退出本程序!") sys.exit() else: continue else: - logger.info(f"邀请码->: {setMixNick0}") + print(f"邀请码->: {setMixNick0}") time.sleep(1) - logger.info(f"准备助力-->: {inviterCode}") + print(f"准备助力-->: {inviterCode}") inviteSuccNum = getActivity(num, 0, inviterCode, 1) if num == 1: errorMsg0 = inviteSuccNum[0] if "跳开卡页面" not in errorMsg0: - logger.info("无法助力自己") + print("无法助力自己") inviteSuccNums0 = inviteSuccNum[1] needInviteNums = inviteSuccNum[2] inviteSuccNums = len(eval(inviteSuccNums0)) - logger.info(f"🛳已经邀请{inviteSuccNums}人") + print(f"🛳已经邀请{inviteSuccNums}人") for i, needNum0 in enumerate(needInviteNums): needNum = needNum0[0] awardId = needNum0[1] if inviteSuccNums >= needNum: - logger.info(f"🎉恭喜已完成第{i + 1}档邀请,快去领奖吧!") + print(f"🎉恭喜已完成第{i + 1}档邀请,快去领奖吧!") time.sleep(1) recordActPvUvdata(token) checkTokenInSession(token) time.sleep(1) if equityType == "JD_GOODS": - logger.info(f"\t🎉🎉成功获得实物奖励,请尽快前往领取:{activityUrl}") + print(f"\t🎉🎉成功获得实物奖励,请尽快前往领取:{activityUrl}") else: receiveInviteJoinAward(token, awardId) rewardIndex += 1 time.sleep(3) if i + 1 == len(needInviteNums): - logger.info("🎉🎉🎉奖励全部领取完毕~") + print("🎉🎉🎉奖励全部领取完毕~") sys.exit() time.sleep(1) inviterCode = setMixNick0 @@ -482,12 +482,12 @@ if __name__ == '__main__': continue else: errorMsg1 = inviteSuccNum - # logger.info("num != 1", errorMsg1) + # print("num != 1", errorMsg1) if "跳开卡页面" not in errorMsg1: if "已成功邀请您加入本店会员" in errorMsg1: - logger.info("⛈已经是会员了,无法完成助力") + print("⛈已经是会员了,无法完成助力") else: - logger.info(f"🛳{errorMsg1}") + print(f"🛳{errorMsg1}") time.sleep(1) continue time.sleep(1.5) @@ -495,16 +495,16 @@ if __name__ == '__main__': checkTokenInSession(token) time.sleep(1) shopmember(cookie) - logger.info("现在去开卡") + print("现在去开卡") open_result = bindWithVender(cookie) if open_result is not None: if "火爆" in open_result: time.sleep(1.5) - logger.info("\t尝试重新入会 第1次") + print("\t尝试重新入会 第1次") open_result = bindWithVender(cookie) if "火爆" in open_result: time.sleep(1.5) - logger.info("\t尝试重新入会 第2次") + print("\t尝试重新入会 第2次") open_result = bindWithVender(cookie) time.sleep(1) if num == 1: @@ -513,15 +513,15 @@ if __name__ == '__main__': time.sleep(2) recordActPvUvdata(token) checkTokenInSession(token) - # logger.info(errorMsg2, '============================') + # print(errorMsg2, '============================') if num == 1 and "开卡失败" in errorMsg2: - logger.info(f"⚠️车头疑似火爆号,退出本程序!") + print(f"⚠️车头疑似火爆号,退出本程序!") sys.exit() if "已成功邀请您加入本店会员" in errorMsg2: inviteSuccNums += 1 - logger.info(f"🛳已经邀请{inviteSuccNums}人") + print(f"🛳已经邀请{inviteSuccNums}人") for i, needNum1 in enumerate(needInviteNums): - # logger.info(i, needNum1) + # print(i, needNum1) needNum = needNum1[0] awardId = needNum1[1] equityType = needNum1[2] @@ -529,7 +529,7 @@ if __name__ == '__main__': if rewardIndex >= i + 1: time.sleep(1) continue - logger.info(f"🎉恭喜已完成第{i + 1}档邀请,快去领奖吧!") + print(f"🎉恭喜已完成第{i + 1}档邀请,快去领奖吧!") token = getToken(firstCk, r) activityCookie = getActivity(1, 0, inviterCode, 3) setMixNick(token) @@ -537,13 +537,13 @@ if __name__ == '__main__': recordActPvUvdata(token) time.sleep(0.5) if equityType == "JD_GOODS": - logger.info(f"\t🎉🎉成功获得实物奖励,请尽快前往领取:{activityUrl}") + print(f"\t🎉🎉成功获得实物奖励,请尽快前往领取:{activityUrl}") else: receiveInviteJoinAward(token, awardId) rewardIndex += 1 time.sleep(3) if i + 1 == len(needInviteNums): - logger.info("🎉🎉🎉奖励全部领取完毕~") + print("🎉🎉🎉奖励全部领取完毕~") sys.exit() if num == 1: inviterCode = setMixNick0 diff --git a/jd_tanwei.js b/jd_tanwei.js new file mode 100644 index 0000000..db182f8 --- /dev/null +++ b/jd_tanwei.js @@ -0,0 +1,254 @@ + +/* +探味奇遇记 +活动时间:9月17结束 +35 1,7 * * * https://raw.githubusercontent.com/6dylan6/jdpro/main/jd_tanwei.js + */ + +const $ = new Env('探味奇遇记'); +const notify = $.isNode() ? require('./sendNotify') : ''; +const jdCookieNode = $.isNode() ? require('./jdCookie.js') : ''; +let jdNotify = true; +//IOS等用户直接用NobyDa的jd cookie +let cookiesArr = [], cookie = '', message = ''; +let encryptProjectId = 'VJiJnJrbCQpimXqRLhRaZYPRUTy'; +if ($.isNode()) { + Object.keys(jdCookieNode).forEach((item) => { + cookiesArr.push(jdCookieNode[item]) + }) + if (process.env.JD_DEBUG && process.env.JD_DEBUG === 'false') console.log = () => { }; +} else { + cookiesArr = [$.getdata('CookieJD'), $.getdata('CookieJD2'), ...jsonParse($.getdata('CookiesJD') || "[]").map(item => item.cookie)].filter(item => !!item); +} +const JD_API_HOST = 'https://api.m.jd.com/client.action'; +!(async () => { + if (!cookiesArr[0]) { + $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/bean/signIndex.action', { "open-url": "https://bean.m.jd.com/bean/signIndex.action" }); + return; + } + for (let i = 0; i < cookiesArr.length; i++) { + if (cookiesArr[i]) { + cookie = cookiesArr[i]; + $.UserName = decodeURIComponent(cookie.match(/pt_pin=([^; ]+)(?=;?)/) && cookie.match(/pt_pin=([^; ]+)(?=;?)/)[1]) + $.index = i + 1; + $.isLogin = true; + $.nickName = ''; + await TotalBean(); + console.log(`\n******开始【京东账号${$.index}】${$.nickName || $.UserName}*********\n`); + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { "open-url": "https://bean.m.jd.com/bean/signIndex.action" }); + if ($.isNode()) { + await notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + } + continue + } + await twqyj(); + await $.wait(1000) + } + } +})() + .catch((e) => { + $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '') + }) + .finally(() => { + $.done(); + }) + + +async function twqyj() { + try { + let tk = await queryInteractiveInfo(); + for (let key of Object.keys(tk.assignmentList).reverse()){ + let vo = tk.assignmentList[key] + if (vo.completionFlag && vo.assignmentType != 30) { + console.log('此任务已完成') + } else if (new Date(vo.assignmentStartTime).getTime() > Date.now()) { + console.log('此任务还没到开放时间:',vo.assignmentStartTime) + } else if (vo.assignmentType == 30) { + await dotask(encryptProjectId,vo.encryptAssignmentId,{"ext":{"exchangeNum":1}}) + } else { + if (vo.ext && vo.ext.extraType == 'sign1') { + await sign(encryptProjectId,vo.encryptAssignmentId) + } else { + await dotask(encryptProjectId,vo.encryptAssignmentId) + } + } + await $.wait(1000) + } + } catch (e) { + $.logErr(e) + } + +} + +async function queryInteractiveInfo() { + return new Promise(async (resolve) => { + $.post(taskUrl("queryInteractiveInfo", {"encryptProjectId":encryptProjectId,"sourceCode":"acemsg0406"}), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`queryInteractiveInfo API请求失败,请检查网路重试`) + } else { + if (safeGet(data)) { + data = JSON.parse(data) + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(data) + } + }) + }) +} + +async function sign(encryptProjectId, AssignmentId) { + return new Promise(async (resolve) => { + $.post(taskUrl("doInteractiveAssignment", { "encryptProjectId": encryptProjectId, "encryptAssignmentId": AssignmentId, "sourceCode": "acemsg0406", "itemId": "1", "completionFlag": "true" }), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`doInteractiveAssignment API请求失败,请检查网路重试`) + } else { + if (safeGet(data)) { + data = JSON.parse(data) + if (data.subCode == 0) { + if (data.rewardsInfo.successRewards['3'] && data.rewardsInfo.successRewards['3'].length != 0) { + console.log(`${data.rewardsInfo.successRewards['3'][0].rewardName},获得${data.rewardsInfo.successRewards['3'][0].quantity}京豆`); + } else if (data.rewardsInfo.failRewards.length != 0) { + console.log(`失败:${data.rewardsInfo.failRewards[0].msg}`); + } + } else { + console.log(data.msg); + } + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(data) + } + }) + }) +} + +async function dotask(encryptProjectId, AssignmentId, body1 = {}) { + let body = { "encryptProjectId": encryptProjectId, "encryptAssignmentId": AssignmentId, "sourceCode": "acemsg0406", "completionFlag": true,...body1} + return new Promise(async (resolve) => { + $.post(taskUrl("doInteractiveAssignment", body), async (err, resp, data) => { + try { + if (err) { + console.log(`${JSON.stringify(err)}`) + console.log(`doInteractiveAssignment API请求失败,请检查网路重试`) + } else { + if (safeGet(data)) { + data = JSON.parse(data) + if (data.subCode == '0' && data.rewardsInfo.hasOwnProperty('successRewards') ) { + if (data.rewardsInfo.successRewards['3'] && data.rewardsInfo.successRewards['3'].length != 0) { + console.log(`${data.rewardsInfo.successRewards['3'][0].rewardName},获得${data.rewardsInfo.successRewards['3'][0].quantity}京豆`); +// } else if (data.rewardsInfo.failRewards.length != 0) { +// console.log(`失败:${data.rewardsInfo.failRewards[0].msg}`); + } + } else { + console.log(data.msg); + } + } + } + } catch (e) { + $.logErr(e, resp) + } finally { + resolve(data) + } + }) + }) +} + +function taskUrl(functionId, body = {}) { + return { + url: `${JD_API_HOST}?functionId=${functionId}&body=${encodeURI(JSON.stringify(body))}&appid=publicUseApi&client=wh5&clientVersion=1.0.0&networkType=&t=${(new Date).getTime()}`, + headers: { + 'Host': 'api.m.jd.com', + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': 'https://h5.m.jd.com', + 'User-Agent': $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), + 'Referer': 'https://h5.m.jd.com/babelDiy/Zeus/4HEXbcWBwHW2yxmoY9LnBoCZ9kcB/index.html', + 'Cookie': cookie + } + } +} + +function TotalBean() { + return new Promise(async resolve => { + const options = { + url: "https://wq.jd.com/user_new/info/GetJDUserInfoUnion?sceneval=2", + headers: { + Host: "wq.jd.com", + Accept: "*/*", + Connection: "keep-alive", + Cookie: cookie, + "User-Agent": $.isNode() ? (process.env.JD_USER_AGENT ? process.env.JD_USER_AGENT : (require('./USER_AGENTS').USER_AGENT)) : ($.getdata('JDUA') ? $.getdata('JDUA') : "jdapp;iPhone;9.4.4;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1"), + "Accept-Language": "zh-cn", + "Referer": "https://home.m.jd.com/myJd/newhome.action?sceneval=2&ufc=&", + "Accept-Encoding": "gzip, deflate, br" + } + } + $.get(options, (err, resp, data) => { + try { + if (err) { + $.logErr(err) + } else { + if (data) { + data = JSON.parse(data); + if (data['retcode'] === 1001) { + $.isLogin = false; + return; + } + if (data['retcode'] === 0 && data.data && data.data.hasOwnProperty("userInfo")) { + $.nickName = data.data.userInfo.baseInfo.nickname; + } + } else { + console.log('京东服务器返回空数据'); + } + } + } catch (e) { + $.logErr(e) + } finally { + resolve(); + } + }) + }) +} +function showMsg() { + return new Promise(resolve => { + if (!jdNotify) { + $.msg($.name, '', `${message}`); + } else { + $.log(`京东账号${$.index}${$.nickName}\n${message}`); + } + resolve() + }) +} +function safeGet(data) { + try { + if (typeof JSON.parse(data) == "object") { + return true; + } + } catch (e) { + console.log(e); + console.log(`京东服务器访问数据为空,请检查自身设备网络情况`); + return false; + } +} +function jsonParse(str) { + if (typeof str == "string") { + try { + return JSON.parse(str); + } catch (e) { + console.log(e); + $.msg($.name, '', '请勿随意在BoxJs输入框修改内容\n建议通过脚本去获取cookie') + return []; + } + } +} +// prettier-ignore +function Env(t, e) { "undefined" != typeof process && JSON.stringify(process.env).indexOf("GITHUB") > -1 && process.exit(0); class s { constructor(t) { this.env = t } send(t, e = "GET") { t = "string" == typeof t ? { url: t } : t; let s = this.get; return "POST" === e && (s = this.post), new Promise((e, i) => { s.call(this, t, (t, s, r) => { t ? i(t) : e(s) }) }) } get(t) { return this.send.call(this.env, t) } post(t) { return this.send.call(this.env, t, "POST") } } return new class { constructor(t, e) { this.name = t, this.http = new s(this), this.data = null, this.dataFile = "box.dat", this.logs = [], this.isMute = !1, this.isNeedRewrite = !1, this.logSeparator = "\n", this.startTime = (new Date).getTime(), Object.assign(this, e), this.log("", `🔔${this.name}, 开始!`) } isNode() { return "undefined" != typeof module && !!module.exports } isQuanX() { return "undefined" != typeof $task } isSurge() { return "undefined" != typeof $httpClient && "undefined" == typeof $loon } isLoon() { return "undefined" != typeof $loon } toObj(t, e = null) { try { return JSON.parse(t) } catch { return e } } toStr(t, e = null) { try { return JSON.stringify(t) } catch { return e } } getjson(t, e) { let s = e; const i = this.getdata(t); if (i) try { s = JSON.parse(this.getdata(t)) } catch { } return s } setjson(t, e) { try { return this.setdata(JSON.stringify(t), e) } catch { return !1 } } getScript(t) { return new Promise(e => { this.get({ url: t }, (t, s, i) => e(i)) }) } runScript(t, e) { return new Promise(s => { let i = this.getdata("@chavy_boxjs_userCfgs.httpapi"); i = i ? i.replace(/\n/g, "").trim() : i; let r = this.getdata("@chavy_boxjs_userCfgs.httpapi_timeout"); r = r ? 1 * r : 20, r = e && e.timeout ? e.timeout : r; const [o, h] = i.split("@"), n = { url: `http://${h}/v1/scripting/evaluate`, body: { script_text: t, mock_type: "cron", timeout: r }, headers: { "X-Key": o, Accept: "*/*" } }; this.post(n, (t, e, i) => s(i)) }).catch(t => this.logErr(t)) } loaddata() { if (!this.isNode()) return {}; { this.fs = this.fs ? this.fs : require("fs"), this.path = this.path ? this.path : require("path"); const t = this.path.resolve(this.dataFile), e = this.path.resolve(process.cwd(), this.dataFile), s = this.fs.existsSync(t), i = !s && this.fs.existsSync(e); if (!s && !i) return {}; { const i = s ? t : e; try { return JSON.parse(this.fs.readFileSync(i)) } catch (t) { return {} } } } } writedata() { if (this.isNode()) { this.fs = this.fs ? this.fs : require("fs"), this.path = this.path ? this.path : require("path"); const t = this.path.resolve(this.dataFile), e = this.path.resolve(process.cwd(), this.dataFile), s = this.fs.existsSync(t), i = !s && this.fs.existsSync(e), r = JSON.stringify(this.data); s ? this.fs.writeFileSync(t, r) : i ? this.fs.writeFileSync(e, r) : this.fs.writeFileSync(t, r) } } lodash_get(t, e, s) { const i = e.replace(/\[(\d+)\]/g, ".$1").split("."); let r = t; for (const t of i) if (r = Object(r)[t], void 0 === r) return s; return r } lodash_set(t, e, s) { return Object(t) !== t ? t : (Array.isArray(e) || (e = e.toString().match(/[^.[\]]+/g) || []), e.slice(0, -1).reduce((t, s, i) => Object(t[s]) === t[s] ? t[s] : t[s] = Math.abs(e[i + 1]) >> 0 == +e[i + 1] ? [] : {}, t)[e[e.length - 1]] = s, t) } getdata(t) { let e = this.getval(t); if (/^@/.test(t)) { const [, s, i] = /^@(.*?)\.(.*?)$/.exec(t), r = s ? this.getval(s) : ""; if (r) try { const t = JSON.parse(r); e = t ? this.lodash_get(t, i, "") : e } catch (t) { e = "" } } return e } setdata(t, e) { let s = !1; if (/^@/.test(e)) { const [, i, r] = /^@(.*?)\.(.*?)$/.exec(e), o = this.getval(i), h = i ? "null" === o ? null : o || "{}" : "{}"; try { const e = JSON.parse(h); this.lodash_set(e, r, t), s = this.setval(JSON.stringify(e), i) } catch (e) { const o = {}; this.lodash_set(o, r, t), s = this.setval(JSON.stringify(o), i) } } else s = this.setval(t, e); return s } getval(t) { return this.isSurge() || this.isLoon() ? $persistentStore.read(t) : this.isQuanX() ? $prefs.valueForKey(t) : this.isNode() ? (this.data = this.loaddata(), this.data[t]) : this.data && this.data[t] || null } setval(t, e) { return this.isSurge() || this.isLoon() ? $persistentStore.write(t, e) : this.isQuanX() ? $prefs.setValueForKey(t, e) : this.isNode() ? (this.data = this.loaddata(), this.data[e] = t, this.writedata(), !0) : this.data && this.data[e] || null } initGotEnv(t) { this.got = this.got ? this.got : require("got"), this.cktough = this.cktough ? this.cktough : require("tough-cookie"), this.ckjar = this.ckjar ? this.ckjar : new this.cktough.CookieJar, t && (t.headers = t.headers ? t.headers : {}, void 0 === t.headers.Cookie && void 0 === t.cookieJar && (t.cookieJar = this.ckjar)) } get(t, e = (() => { })) { t.headers && (delete t.headers["Content-Type"], delete t.headers["Content-Length"]), this.isSurge() || this.isLoon() ? (this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { "X-Surge-Skip-Scripting": !1 })), $httpClient.get(t, (t, s, i) => { !t && s && (s.body = i, s.statusCode = s.status), e(t, s, i) })) : this.isQuanX() ? (this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { hints: !1 })), $task.fetch(t).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => e(t))) : this.isNode() && (this.initGotEnv(t), this.got(t).on("redirect", (t, e) => { try { if (t.headers["set-cookie"]) { const s = t.headers["set-cookie"].map(this.cktough.Cookie.parse).toString(); s && this.ckjar.setCookieSync(s, null), e.cookieJar = this.ckjar } } catch (t) { this.logErr(t) } }).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => { const { message: s, response: i } = t; e(s, i, i && i.body) })) } post(t, e = (() => { })) { if (t.body && t.headers && !t.headers["Content-Type"] && (t.headers["Content-Type"] = "application/x-www-form-urlencoded"), t.headers && delete t.headers["Content-Length"], this.isSurge() || this.isLoon()) this.isSurge() && this.isNeedRewrite && (t.headers = t.headers || {}, Object.assign(t.headers, { "X-Surge-Skip-Scripting": !1 })), $httpClient.post(t, (t, s, i) => { !t && s && (s.body = i, s.statusCode = s.status), e(t, s, i) }); else if (this.isQuanX()) t.method = "POST", this.isNeedRewrite && (t.opts = t.opts || {}, Object.assign(t.opts, { hints: !1 })), $task.fetch(t).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => e(t)); else if (this.isNode()) { this.initGotEnv(t); const { url: s, ...i } = t; this.got.post(s, i).then(t => { const { statusCode: s, statusCode: i, headers: r, body: o } = t; e(null, { status: s, statusCode: i, headers: r, body: o }, o) }, t => { const { message: s, response: i } = t; e(s, i, i && i.body) }) } } time(t, e = null) { const s = e ? new Date(e) : new Date; let i = { "M+": s.getMonth() + 1, "d+": s.getDate(), "H+": s.getHours(), "m+": s.getMinutes(), "s+": s.getSeconds(), "q+": Math.floor((s.getMonth() + 3) / 3), S: s.getMilliseconds() }; /(y+)/.test(t) && (t = t.replace(RegExp.$1, (s.getFullYear() + "").substr(4 - RegExp.$1.length))); for (let e in i) new RegExp("(" + e + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? i[e] : ("00" + i[e]).substr(("" + i[e]).length))); return t } msg(e = t, s = "", i = "", r) { const o = t => { if (!t) return t; if ("string" == typeof t) return this.isLoon() ? t : this.isQuanX() ? { "open-url": t } : this.isSurge() ? { url: t } : void 0; if ("object" == typeof t) { if (this.isLoon()) { let e = t.openUrl || t.url || t["open-url"], s = t.mediaUrl || t["media-url"]; return { openUrl: e, mediaUrl: s } } if (this.isQuanX()) { let e = t["open-url"] || t.url || t.openUrl, s = t["media-url"] || t.mediaUrl; return { "open-url": e, "media-url": s } } if (this.isSurge()) { let e = t.url || t.openUrl || t["open-url"]; return { url: e } } } }; if (this.isMute || (this.isSurge() || this.isLoon() ? $notification.post(e, s, i, o(r)) : this.isQuanX() && $notify(e, s, i, o(r))), !this.isMuteLog) { let t = ["", "==============📣系统通知📣=============="]; t.push(e), s && t.push(s), i && t.push(i), console.log(t.join("\n")), this.logs = this.logs.concat(t) } } log(...t) { t.length > 0 && (this.logs = [...this.logs, ...t]), console.log(t.join(this.logSeparator)) } logErr(t, e) { const s = !this.isSurge() && !this.isQuanX() && !this.isLoon(); s ? this.log("", `❗️${this.name}, 错误!`, t.stack) : this.log("", `❗️${this.name}, 错误!`, t) } wait(t) { return new Promise(e => setTimeout(e, t)) } done(t = {}) { const e = (new Date).getTime(), s = (e - this.startTime) / 1e3; this.log("", `🔔${this.name}, 结束! 🕛 ${s} 秒`), this.log(), (this.isSurge() || this.isQuanX() || this.isLoon()) && $done(t) } }(t, e) } \ No newline at end of file diff --git a/jd_try.js b/jd_try.js index 8a0abe9..868e96b 100644 --- a/jd_try.js +++ b/jd_try.js @@ -1,16 +1,15 @@ /* + * 2022-07-20 修复获取试用列表风控问题; * 2022-08-12 修复申请试用风控,更换nolan接口 - * 如需运行请自行添加环境变量:JD_TRY,值填 true 即可运行 - * 上一作者说了每天最多300个商店,总上限为500个,jd_unsubscribe.js我已更新为批量取关版 - * 请提前取关至少250个商店确保京东试用脚本正常运行 + * By https://github.com/6dylan6/jdpro/ + * 基于X1a0He版本修改 + * @Address: https://github.com/X1a0He/jd_scripts_fixed/blob/main/jd_try_xh.js -如需运行请自行添加环境变量:JD_TRY="true" 即可运行 脚本是否耗时只看args_xh.maxLength的大小(申请数量),默认50个,申请100个差不多15分钟 上一作者说每天申请上限300个(自测,没有申请过上限),关注店铺上限500个 关注店铺满了就无法继续申请,可用批量取关店铺取消关注 部分环境变量说明,详细请参考58行往下: -export JD_TRY="true"是否允许,默认false export JD_TRY_PASSZC="false" #不过滤种草官类试用,默认true过滤 export JD_TRY_MAXLENGTH="50" #商品数组的最大长度,默认50个 export JD_TRY_PRICE="XX"#商品原价格,大于XX才申请,默认20 @@ -19,13 +18,13 @@ export JD_TRY_APPLYNUMFILTER="10000" #过滤大于设定值的已申请人数 export JD_TRY_MINSUPPLYNUM="1" #最小提供数量 export JD_TRY_SENDNUM="10" #每隔多少账号发送一次通知,默认为4 export JD_TRY_UNIFIED="false" 默认采用不同试用组 -export JD_TRY_NUM="7" 最多跑多少个CK,默认10 +export JD_TRY_NUM="5" 最多跑多少个CK,默认10 -cron "1 1 1 1 1" jd_try.js +定时自定义,能用多久随缘了!!! */ + const $ = new Env('京东试用') const URL = 'https://api.m.jd.com/client.action' - let trialActivityIdList = [] let trialActivityTitleList = [] let notifyMsg = '' @@ -41,18 +40,19 @@ $.getNum = 0; $.try = true; $.sentNum = 0; $.cookiesArr = [] +//默认的过滤关键词 $.innerKeyWords = [ "幼儿园", "教程", "英语", "辅导", "培训", "孩子", "小学", "成人用品", "套套", "情趣", "自慰", "阳具", "飞机杯", "男士用品", "女士用品", "内衣", "高潮", "避孕", "乳腺", "肛塞", "肛门", - "宝宝", "玩具", "芭比", "娃娃", "男用", + "宝宝", "芭比", "娃娃", "男用", "女用", "神油", "足力健", "老年", "老人", "宠物", "饲料", "丝袜", "黑丝", "磨脚", "脚皮", "除臭", "性感", "内裤", "跳蛋", "安全套", "龟头", "阴道", "阴部", "手机卡", "电话卡", "流量卡", - "玉坠","和田玉","习题","试卷","手机壳","钢化膜" + "习题", "试卷", ] //下面很重要,遇到问题请把下面注释看一遍再来问 let args_xh = { @@ -187,113 +187,114 @@ let args_xh = { !(async () => { await $.wait(500) // 如果你要运行京东试用这个脚本,麻烦你把环境变量 JD_TRY 设置为 true - if (1) { - await requireConfig() - if (!$.cookiesArr[0]) { - $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', { - "open-url": "https://bean.m.jd.com/" - }) - return - } - args_xh.tabId = args_xh.tabId.sort(() => 0.5 - Math.random()) - for (let i = 0; i < args_xh.try_num; i++) { - if ($.cookiesArr[i]) { - $.cookie = $.cookiesArr[i]; - $.UserName = decodeURIComponent($.cookie.match(/pt_pin=(.+?);/) && $.cookie.match(/pt_pin=(.+?);/)[1]) - $.index = i + 1; - $.isLogin = true; - $.nickName = ''; - //await totalBean(); - console.log(`\n开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); - $.except = false; - if(args_xh.except.includes($.UserName)){ - console.log(`跳过账号:${$.nickName || $.UserName}`) - $.except = true; - continue - } - if(!$.isLogin){ - $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { - "open-url": "https://bean.m.jd.com/bean/signIndex.action" - }); - await $.notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); - continue - } - $.totalTry = 0 - $.totalSuccess = 0 - $.nowTabIdIndex = 0; - $.nowPage = 1; - $.nowItem = 1; - $.retrynum = 0 - $.jda='__jda='+_jda('1xxxxxxxx.164xxxxxxxxxxxxxxxxxxx.164xxxxxxx.165xxxxxx.165xxxxxx.1xx') - if (!args_xh.unified) { - trialActivityIdList = [] - trialActivityTitleList = [] - } - $.isLimit = false; - // 获取tabList的,不知道有哪些的把这里的注释解开跑一遍就行了 - //await try_tabList(); - // return; - $.isForbidden = false - $.wrong = false - size = 1 + if (process.env.JD_TRY && process.env.JD_TRY === 'true') { + $.log('\n遇到问题请先看脚本内注释;解决不了可联系https://t.me/dylan_jdpro\n'); + await requireConfig() + if (!$.cookiesArr[0]) { + $.msg($.name, '【提示】请先获取京东账号一cookie\n直接使用NobyDa的京东签到获取', 'https://bean.m.jd.com/', { + "open-url": "https://bean.m.jd.com/" + }) + return + } + args_xh.tabId = args_xh.tabId.sort(() => 0.5 - Math.random()) + for (let i = 0; i < args_xh.try_num; i++) { + if ($.cookiesArr[i]) { + $.cookie = $.cookiesArr[i]; + $.UserName = decodeURIComponent($.cookie.match(/pt_pin=(.+?);/) && $.cookie.match(/pt_pin=(.+?);/)[1]) + $.index = i + 1; + $.isLogin = true; + $.nickName = ''; + await totalBean(); + console.log(`\n开始【京东账号${$.index}】${$.nickName || $.UserName}\n`); + $.except = false; + if (args_xh.except.includes($.UserName)) { + console.log(`跳过账号:${$.nickName || $.UserName}`) + $.except = true; + continue + } + if (!$.isLogin) { + $.msg($.name, `【提示】cookie已失效`, `京东账号${$.index} ${$.nickName || $.UserName}\n请重新登录获取\nhttps://bean.m.jd.com/bean/signIndex.action`, { + "open-url": "https://bean.m.jd.com/bean/signIndex.action" + }); + await $.notify.sendNotify(`${$.name}cookie已失效 - ${$.UserName}`, `京东账号${$.index} ${$.UserName}\n请重新登录获取cookie`); + continue + } + $.totalTry = 0 + $.totalSuccess = 0 + $.nowTabIdIndex = 0; + $.nowPage = 1; + $.nowItem = 1; + $.retrynum = 0 + $.jda = '__jda=' + _jda('1xxxxxxxx.164xxxxxxxxxxxxxxxxxxx.164xxxxxxx.165xxxxxx.165xxxxxx.1xx') + if (!args_xh.unified) { + trialActivityIdList = [] + trialActivityTitleList = [] + } + $.isLimit = false; + // 获取tabList的,不知道有哪些的把这里的注释解开跑一遍就行了 + //await try_tabList(); + // return; + $.isForbidden = false + $.wrong = false + size = 1 - while (trialActivityIdList.length < args_xh.maxLength && $.retrynum < 3) { - if ($.nowTabIdIndex === args_xh.tabId.length) { - console.log(`tabId组已遍历完毕,不在获取商品\n`); - break; - } else { - await try_feedsList(args_xh.tabId[$.nowTabIdIndex], $.nowPage) //获取对应tabId的试用页面 - } - if (trialActivityIdList.length < args_xh.maxLength) { - console.log(`间隔等待中,请等待3秒 \n`) - await $.wait(3000); - } + while (trialActivityIdList.length < args_xh.maxLength && $.retrynum < 3) { + if ($.nowTabIdIndex === args_xh.tabId.length) { + console.log(`tabId组已遍历完毕,不在获取商品\n`); + break; + } else { + await try_feedsList(args_xh.tabId[$.nowTabIdIndex], $.nowPage) //获取对应tabId的试用页面 } - if ($.isForbidden === false && $.isLimit === false) { - console.log(`稍后将执行试用申请,请等待 2 秒\n`) - await $.wait(2000); - for (let i = 0; i < trialActivityIdList.length && $.isLimit === false; i++) { - if ($.isLimit) { - console.log("试用上限") - break - } - if ($.isForbidden) { console.log('403了,跳出'); break } - await try_apply(trialActivityTitleList[i], trialActivityIdList[i]) - //console.log(`间隔等待中,请等待 ${args_xh.applyInterval} ms\n`) - const waitTime = generateRandomInteger(args_xh.applyInterval, 9000); - console.log(`随机等待${waitTime}ms后继续`); - await $.wait(waitTime); - } - console.log("试用申请执行完毕...") - // await try_MyTrials(1, 1) //申请中的商品 - $.giveupNum = 0; - $.successNum = 0; - $.getNum = 0; - $.completeNum = 0; - await try_MyTrials(1, 2) //申请成功的商品 - // await try_MyTrials(1, 3) //申请失败的商品 - await showMsg() + if (trialActivityIdList.length < args_xh.maxLength) { + console.log(`间隔等待中,请等待3秒 \n`) + await $.wait(3000); } } - if ($.isNode()) { - if ($.index % args_xh.sendNum === 0) { - $.sentNum++; - console.log(`正在进行第 ${$.sentNum} 次发送通知,发送数量:${args_xh.sendNum}`) - await $.notify.sendNotify(`${$.name}`, `${notifyMsg}`) - notifyMsg = ""; + if ($.isForbidden === false && $.isLimit === false) { + console.log(`稍后将执行试用申请,请等待 2 秒\n`) + await $.wait(2000); + for (let i = 0; i < trialActivityIdList.length && $.isLimit === false; i++) { + if ($.isLimit) { + console.log("试用上限") + break + } + if ($.isForbidden) { console.log('403了,跳出'); break } + await try_apply(trialActivityTitleList[i], trialActivityIdList[i]) + //console.log(`间隔等待中,请等待 ${args_xh.applyInterval} ms\n`) + const waitTime = generateRandomInteger(args_xh.applyInterval, 9000); + console.log(`随机等待${waitTime}ms后继续`); + await $.wait(waitTime); } + console.log("试用申请执行完毕...") + // await try_MyTrials(1, 1) //申请中的商品 + $.giveupNum = 0; + $.successNum = 0; + $.getNum = 0; + $.completeNum = 0; + await try_MyTrials(1, 2) //申请成功的商品 + // await try_MyTrials(1, 3) //申请失败的商品 + await showMsg() } } - if ($.isNode() && $.except === false) { - if (($.cookiesArr.length - ($.sentNum * args_xh.sendNum)) < args_xh.sendNum && notifyMsg.length != 0) { - console.log(`正在进行最后一次发送通知,发送数量:${($.cookiesArr.length - ($.sentNum * args_xh.sendNum))}`) + if ($.isNode()) { + if ($.index % args_xh.sendNum === 0) { + $.sentNum++; + console.log(`正在进行第 ${$.sentNum} 次发送通知,发送数量:${args_xh.sendNum}`) await $.notify.sendNotify(`${$.name}`, `${notifyMsg}`) notifyMsg = ""; } } - } else { - console.log(`\n您未设置变量export JD_TRY="true"运行【京东试用】脚本, 结束运行!\n`) } + if ($.isNode() && $.except === false) { + if (($.cookiesArr.length - ($.sentNum * args_xh.sendNum)) < args_xh.sendNum && notifyMsg.length != 0) { + console.log(`正在进行最后一次发送通知,发送数量:${($.cookiesArr.length - ($.sentNum * args_xh.sendNum))}`) + await $.notify.sendNotify(`${$.name}`, `${notifyMsg}`) + notifyMsg = ""; + } + } + } else { + console.log(`\n您未设置变量export JD_TRY="true"运行【京东试用】脚本, 结束运行!\n`) + } })().catch((e) => { console.error(`❗️ ${$.name} 运行错误!\n${e}`) }).finally(() => $.done()) @@ -509,19 +510,19 @@ function try_apply(title, activityId) { body = await geth5st(body); if(!body) return; let opt = - { - "url": `${URL}?${body}}`, - 'headers': { - 'Cookie': $.cookie + $.jda, - 'user-agent': 'jdapp;iPhone;10.1.2;15.0;ff2caa92a8529e4788a34b3d8d4df66d9573f499;network/wifi;model/iPhone13,4;addressid/2074196292;appBuild/167802;jdSupportDarkMode/1;Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1', - 'Referer': 'https://prodev.m.jd.com/', - 'origin': 'https://prodev.m.jd.com/', - 'Accept': 'application/json,text/plain,*/*', - 'Accept-Encoding': 'gzip, deflate, br', - 'Accept-Language': 'zh-cn', - 'Content-Type': 'application/x-www-form-urlencoded', - }, - } + { + "url": `${URL}?${body}}`, + 'headers': { + 'Cookie': $.cookie + $.jda, + 'user-agent': 'jdapp;iPhone;10.1.2;15.0;ff2caa92a8529e4788a34b3d8d4df66d9573f499;network/wifi;model/iPhone13,4;addressid/2074196292;appBuild/167802;jdSupportDarkMode/1;Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1', + 'Referer': 'https://prodev.m.jd.com/', + 'origin': 'https://prodev.m.jd.com/', + 'Accept': 'application/json,text/plain,*/*', + 'Accept-Encoding': 'gzip, deflate, br', + 'Accept-Language': 'zh-cn', + 'Content-Type': 'application/x-www-form-urlencoded', + }, + } $.get(opt, (err, resp, data) => { try { if (err) { @@ -722,14 +723,15 @@ function geth5st(body) { "functionId": "try_apply", "body": body, "appid": "newtry", - "client": "wh5", + "client": "wh5", "clientVersion": "11.0.2", "ua": 'jdapp;iPhone;10.1.2;15.0;ff2caa92a8529e4788a34b3d8d4df66d9573f499;network/wifi;model/iPhone13,4;addressid/2074196292;appBuild/167802;jdSupportDarkMode/1;Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1', "pin": encodeURIComponent($.UserName) }), headers: { "Content-Type": "application/json" - } + }, + timeout: 30000, },str=''; return new Promise((resolve) => { $.post(opt, (err, resp, data) => { @@ -973,7 +975,7 @@ function Env(name, opts) { if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [] path.slice(0, -1).reduce((a, c, i) => (Object(a[c]) === a[c] ? a[c] : (a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] : {})), obj)[ path[path.length - 1] - ] = value + ] = value return obj } @@ -1343,4 +1345,4 @@ function Env(name, opts) { } } })(name, opts) -} \ No newline at end of file +} diff --git a/utils/jdCookie.py b/utils/jdCookie.py new file mode 100644 index 0000000..53d0d63 --- /dev/null +++ b/utils/jdCookie.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# @Time : 2022/7/6 23:00 +# @Author : HarbourJ +# @TG : https://t.me/HarbourToulu +# @File : jdCookie.py + +import os +import time +from functools import partial +print = partial(print, flush=True) + + +def get_cookies(): + CookieJDs = [] + if os.environ.get("JD_COOKIE"): + print("已获取并使用Env环境 Cookie") + if '&' in os.environ["JD_COOKIE"]: + CookieJDs = os.environ["JD_COOKIE"].split('&') + elif '\n' in os.environ["JD_COOKIE"]: + CookieJDs = os.environ["JD_COOKIE"].split('\n') + else: + CookieJDs = [os.environ["JD_COOKIE"]] + # return CookieJDs + else: + if os.path.exists("JD_COOKIE.txt"): + with open("JD_COOKIE.txt", 'r') as f: + JD_COOKIEs = f.read().strip() + if JD_COOKIEs: + if '&' in JD_COOKIEs: + CookieJDs = JD_COOKIEs.split('&') + elif '\n' in JD_COOKIEs: + CookieJDs = JD_COOKIEs.split('\n') + else: + CookieJDs = [JD_COOKIEs] + CookieJDs = sorted(set(CookieJDs), key=CookieJDs.index) + # return CookieJDs + else: + print("未获取到正确✅格式的京东账号Cookie") + return + + print(f"====================共{len(CookieJDs)}个京东账号Cookie=========\n") + print(f"==================脚本执行- 北京时间(UTC+8):{time.strftime('%Y/%m/%d %H:%M:%S', time.localtime())}=====================\n") + return CookieJDs + +# if __name__ == "__main__": +# get_cookies() +# print(os.environ.get("JD_COOKIE"))