|
|
@@ -0,0 +1,283 @@
|
|
|
+# -*- coding: utf-8 -*-
|
|
|
+"""磁力金牛广告托管模块(D线白盒重建·带护栏)。
|
|
|
+
|
|
|
+对照 伪码\\D_磁力金牛资金线.md:
|
|
|
+- F1 全自动托管主循环 @0x411E6B:刷余额(owner/info) → 当日报表(report/search
|
|
|
+ + chartReportWithRelativeRatio) → 自动停计划(消耗阈值止损,batch/putStatus)
|
|
|
+ → 自动调ROI(目标档位偏离,campaign/update/bid) → anchor 回写 yue/ciliroi
|
|
|
+ → 余额低于阈值触发充值下单
|
|
|
+- F2 支付成功记账 @0x41A6AB:insert into money(userName,amounts)
|
|
|
+- F3 充值下单+轮询 @0x5C770F:wallet/recharge(金额×1000) → kuaishoupay 收银台
|
|
|
+ → ksurl.cn 转二维码 → 轮询 order_state==SUCCESS
|
|
|
+
|
|
|
+与原工具的差异(护栏,刻意):
|
|
|
+- sql20.php 远程任务通道(A线C2)**不建**:充值/调价决策只来自本地 cfg;
|
|
|
+- 充值只做「下单+出码+轮询」,付款须人工扫码确认(原工具 F3③ 同款人工环节);
|
|
|
+- cfg['ads']['enabled'] 默认 False:关着时本模块只读(刷余额/报表/回写展示列),
|
|
|
+ 任何资金写操作(停计划/调ROI/充值下单)都不会执行,且各有独立子开关;
|
|
|
+- 每次资金相关动作记 warning 日志(含金额/计划id/ROI 目标值)。
|
|
|
+"""
|
|
|
+import logging
|
|
|
+import random
|
|
|
+import time
|
|
|
+from urllib.parse import quote
|
|
|
+
|
|
|
+from . import config, db
|
|
|
+from .httpclient import KSClient
|
|
|
+
|
|
|
+logger = logging.getLogger('kuaishou_tool.niu')
|
|
|
+
|
|
|
+# ── 端点(D线 §1/§2,C线F2 esp 线同族) ──────────────────────────────
|
|
|
+NIU_BASE = 'https://niu.e.kuaishou.com'
|
|
|
+OWNER_INFO_URL = NIU_BASE + '/rest/esp/owner/info'
|
|
|
+REPORT_URL = NIU_BASE + '/rest/esp/control-panel/report/search'
|
|
|
+CHART_URL = NIU_BASE + '/rest/esp/control-panel/report/chartReportWithRelativeRatio'
|
|
|
+STOP_URL = NIU_BASE + '/rest/esp/promotion/management/campaign/update/batch/putStatus'
|
|
|
+BID_URL = NIU_BASE + '/rest/esp/promotion/hosting/campaign/update/bid'
|
|
|
+RECHARGE_URL = NIU_BASE + '/rest/n/gateway/wallet/recharge'
|
|
|
+CASHIER_URL = 'https://www.kuaishoupay.com/pay/order/pc/trade/cashier'
|
|
|
+ORDER_QUERY_URL = 'https://www.kuaishoupay.com/pay/order/pc/trade/query'
|
|
|
+QR_MAKE_URL = 'https://ksurl.cn/createqrcode'
|
|
|
+
|
|
|
+# ── 托管参数默认值(全部可经 cfg['ads'] 覆盖) ───────────────────────
|
|
|
+ADS_DEFAULTS = {
|
|
|
+ 'enabled': False, # 总开关:False = 只读,不做任何资金写操作
|
|
|
+ 'interval_sec': 300, # 托管循环间隔
|
|
|
+ 'stop_enabled': True, # 写①:自动停计划(消耗阈值止损,D线F1③)
|
|
|
+ 'stop_cost_threshold': 10.0, # 消耗阈值(元;原工具默认10,「消耗大于或等于10元自动停止直播计划」)
|
|
|
+ 'bid_enabled': True, # 写②:自动调ROI(目标档位偏离,D线F1④)
|
|
|
+ 'roi_target': 0.0, # 目标ROI(0=不调;对应原「目标ROI1~6」档位取一)
|
|
|
+ 'roi_tolerance': 0.0, # 容差:|今日ROI-目标|<=容差 不动
|
|
|
+ 'recharge_enabled': False, # 写③:充值下单(付款仍须人工扫码)
|
|
|
+ 'recharge_threshold': 0.0, # 余额低于此值(元)触发;0=不触发
|
|
|
+ 'recharge_amount': 0.0, # 单次充值金额(元)
|
|
|
+ 'include_not_live': False, # 未开播账号是否参与(原工具「未开播用户参与充值」勾选项)
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+class NiuError(Exception):
|
|
|
+ """金牛接口调用失败。"""
|
|
|
+
|
|
|
+
|
|
|
+def _row_get(row, key, default=''):
|
|
|
+ """兼容 sqlite3.Row 与 dict 的按键取值。"""
|
|
|
+ try:
|
|
|
+ return row[key]
|
|
|
+ except (KeyError, IndexError, TypeError):
|
|
|
+ return default
|
|
|
+
|
|
|
+
|
|
|
+def _niu_headers(account_id=''):
|
|
|
+ """esp 线请求头(C线F2:ACCOUNT-ID/App-Key/requestSource/esp-platform)。"""
|
|
|
+ h = {'requestSource': 'PC', 'App-Key': 'ad.adUkmConfig.adEsp',
|
|
|
+ 'esp-platform': 'pc', 'esp-entrySrc': '204',
|
|
|
+ 'Accept': 'application/json,*/*', 'Content-Type': 'application/json'}
|
|
|
+ if account_id:
|
|
|
+ h['ACCOUNT-ID'] = str(account_id)
|
|
|
+ return h
|
|
|
+
|
|
|
+
|
|
|
+def _json_of(resp):
|
|
|
+ try:
|
|
|
+ return resp.json()
|
|
|
+ except Exception:
|
|
|
+ return None
|
|
|
+
|
|
|
+
|
|
|
+def _ok(resp):
|
|
|
+ j = _json_of(resp)
|
|
|
+ return isinstance(j, dict) and not (j.get('error_msg') or j.get('errorMsg'))
|
|
|
+
|
|
|
+
|
|
|
+# ═══════════════ 只读侧:余额 / 报表(D线F1①②) ═══════════════
|
|
|
+
|
|
|
+def owner_info(client):
|
|
|
+ """账户信息(F1①):data.userEspAccount.balance / data.liveStatus。"""
|
|
|
+ j = _json_of(client.get(OWNER_INFO_URL, headers=_niu_headers())) or {}
|
|
|
+ data = j.get('data') if isinstance(j.get('data'), dict) else {}
|
|
|
+ acc = data.get('userEspAccount') if isinstance(data.get('userEspAccount'), dict) else {}
|
|
|
+ return {'balance': float(acc.get('balance') or 0),
|
|
|
+ 'live': str(data.get('liveStatus') or ''), 'raw': j}
|
|
|
+
|
|
|
+
|
|
|
+def report_today(client, day=None):
|
|
|
+ """当日报表(F1②):data.sum.costTotal + data.data[].targetId/bidDetail。"""
|
|
|
+ day = day or time.strftime('%Y-%m-%d')
|
|
|
+ body = {'searchParam': {'sceneOrientedTypes': [21], # 21=直播(24=商品,另一份调用体)
|
|
|
+ 'startTime': day, 'endTime': day,
|
|
|
+ 'frozen': 0, 'searchLevel': 1}}
|
|
|
+ j = _json_of(client.post(REPORT_URL, json_body=body,
|
|
|
+ headers=_niu_headers())) or {}
|
|
|
+ data = j.get('data') if isinstance(j.get('data'), dict) else {}
|
|
|
+ rows = data.get('data') if isinstance(data.get('data'), list) else []
|
|
|
+ total = data.get('sum') if isinstance(data.get('sum'), dict) else {}
|
|
|
+ return {'cost': float(total.get('costTotal') or 0),
|
|
|
+ 'campaigns': [{'id': r.get('targetId'), 'bid': r.get('bidDetail')}
|
|
|
+ for r in rows if isinstance(r, dict)],
|
|
|
+ 'raw': j}
|
|
|
+
|
|
|
+
|
|
|
+def chart_today(client, day=None):
|
|
|
+ """今日ROI/GMV(F1②:chartReportWithRelativeRatio;返回字段名报告未还原,
|
|
|
+ 取 data.roi/data.gmv 常见形态,联调时按实际响应校正)。"""
|
|
|
+ day = day or time.strftime('%Y-%m-%d')
|
|
|
+ body = {'searchParam': {'sceneOrientedTypes': [21],
|
|
|
+ 'startTime': day, 'endTime': day}}
|
|
|
+ j = _json_of(client.post(CHART_URL, json_body=body,
|
|
|
+ headers=_niu_headers())) or {}
|
|
|
+ data = j.get('data') if isinstance(j.get('data'), dict) else {}
|
|
|
+ return {'roi': float(data.get('roi') or 0), 'gmv': float(data.get('gmv') or 0),
|
|
|
+ 'raw': j}
|
|
|
+
|
|
|
+
|
|
|
+# ═══════════════ 写侧①②:停计划 / 调ROI(D线F1③④/F8) ═══════════════
|
|
|
+
|
|
|
+def stop_campaigns(client, campaign_ids):
|
|
|
+ """批量停计划(batch/putStatus,body campaignIdList)。返回是否成功。"""
|
|
|
+ r = client.post(STOP_URL, json_body={'campaignIdList': [str(i) for i in campaign_ids]},
|
|
|
+ headers=_niu_headers())
|
|
|
+ return _ok(r)
|
|
|
+
|
|
|
+
|
|
|
+def update_roi(client, campaign_id, roi_ratio):
|
|
|
+ """调计划ROI(campaign/update/bid,D线F8 body:roiRatio/speed;
|
|
|
+ programCreative 完整结构报告未还原,白盒含 campaignId 便于服务端定位,
|
|
|
+ 联调时按实际接口校正)。"""
|
|
|
+ body = {'campaignId': str(campaign_id), 'programCreative': {},
|
|
|
+ 'roiRatio': f'{float(roi_ratio):g}', 'speed': 1}
|
|
|
+ r = client.post(BID_URL, json_body=body, headers=_niu_headers())
|
|
|
+ return _ok(r)
|
|
|
+
|
|
|
+
|
|
|
+# ═══════════════ 写侧③:充值下单→收银台→二维码→轮询(D线F3) ═══════════════
|
|
|
+
|
|
|
+def create_recharge_order(client, account_id, amount_yuan):
|
|
|
+ """充值建单(F3①):rechargeAmount=元×1000(D线注:金额=输入值×1000),
|
|
|
+ esp-id:22;x-nonce 原工具为写死常量,白盒改为每次随机。"""
|
|
|
+ body = {'walletType': 1, 'rechargeAmount': int(round(float(amount_yuan) * 1000)),
|
|
|
+ 'tradeType': 2, 'payWay': 3, 'payChannel': 0}
|
|
|
+ h = _niu_headers(account_id)
|
|
|
+ h['esp-id'] = '22'
|
|
|
+ h['x-nonce'] = '%.16f' % random.random()
|
|
|
+ j = _json_of(client.post(RECHARGE_URL, json_body=body, headers=h)) or {}
|
|
|
+ data = j.get('data') if isinstance(j.get('data'), dict) else {}
|
|
|
+ if not data.get('payCode'):
|
|
|
+ raise NiuError('充值建单失败:' + str(j.get('error_msg') or j)[:200])
|
|
|
+ return {'pay_code': str(data.get('payCode')),
|
|
|
+ 'merchant_id': str(data.get('merchantCode') or ''),
|
|
|
+ 'trace_id': str(j.get('traceId') or ''), 'raw': j}
|
|
|
+
|
|
|
+
|
|
|
+def cashier_qrcode(client, order):
|
|
|
+ """收银台→支付二维码(F3②③):POST cashier(merchant_id/out_order_no=traceId)
|
|
|
+ → qrcode_url;再经 ksurl.cn 转二维码图(付款仍须人工扫码)。"""
|
|
|
+ form = {'merchant_id': order['merchant_id'], 'out_order_no': order['trace_id']}
|
|
|
+ h = {'Content-Type': 'application/x-www-form-urlencoded',
|
|
|
+ 'Origin': NIU_BASE, 'Referer': NIU_BASE + '/', 'Sec-Fetch-Site': 'cross-site'}
|
|
|
+ j = _json_of(client.post(CASHIER_URL, data=form, headers=h)) or {}
|
|
|
+ pay_url = str(j.get('qrcode_url') or '')
|
|
|
+ if not pay_url:
|
|
|
+ raise NiuError('收银台未返回支付链接:' + str(j)[:200])
|
|
|
+ qr = (QR_MAKE_URL + '?contentType=URL&toShortUrl=false&content='
|
|
|
+ + quote(pay_url, safe=''))
|
|
|
+ return {'pay_url': pay_url, 'qr_image': qr,
|
|
|
+ 'interval': int(j.get('qrcode_interval') or 3), 'raw': j}
|
|
|
+
|
|
|
+
|
|
|
+def poll_order(client, order, timeout_sec=300, interval_sec=None):
|
|
|
+ """轮询订单状态(F3④):order_state==SUCCESS 即支付完成。返回是否成功。"""
|
|
|
+ form = {'merchant_id': order['merchant_id'], 'out_order_no': order['trace_id']}
|
|
|
+ h = {'Content-Type': 'application/x-www-form-urlencoded',
|
|
|
+ 'Origin': 'https://www.kuaishoupay.com'}
|
|
|
+ interval = interval_sec or 3
|
|
|
+ end = time.time() + timeout_sec
|
|
|
+ while time.time() < end:
|
|
|
+ j = _json_of(client.post(ORDER_QUERY_URL, data=form, headers=h)) or {}
|
|
|
+ if str(j.get('order_state')) == 'SUCCESS':
|
|
|
+ return True
|
|
|
+ time.sleep(interval)
|
|
|
+ return False
|
|
|
+
|
|
|
+
|
|
|
+def record_money(user_name, amount):
|
|
|
+ """充值记账(F2:insert into money)。"""
|
|
|
+ db.exe('INSERT INTO money (userName, amounts, createdTime) VALUES (?,?,?)',
|
|
|
+ (str(user_name), float(amount), db.now()))
|
|
|
+
|
|
|
+
|
|
|
+# ═══════════════ 托管决策与循环(D线F1 的白盒版) ═══════════════
|
|
|
+
|
|
|
+def auto_manage(cfg, anchor_row, client=None, account_id='') -> dict:
|
|
|
+ """单账号一次托管决策(F1 循环体的单账号粒度)。
|
|
|
+
|
|
|
+ 只读侧永远执行:余额/报表/ROI → 回写 anchor.yue/ciliroi(展示列);
|
|
|
+ 写侧(停计划/调ROI/充值下单)仅在 cfg['ads']['enabled'] 且各子开关开启时
|
|
|
+ 执行;充值只下单出码,付款须人工扫码。返回决策摘要 dict。
|
|
|
+ """
|
|
|
+ ads = dict(ADS_DEFAULTS)
|
|
|
+ ads.update(cfg.get('ads') or {})
|
|
|
+ uid = str(_row_get(anchor_row, 'uid', ''))
|
|
|
+ if client is None:
|
|
|
+ cookie = _row_get(anchor_row, 'cookie3', '') or _row_get(anchor_row, 'cookie1', '')
|
|
|
+ client = KSClient(cookie=cookie, did=_row_get(anchor_row, 'did', ''))
|
|
|
+ res = {'uid': uid, 'balance': None, 'stopped': [], 'adjusted': [], 'recharge': None}
|
|
|
+
|
|
|
+ info = owner_info(client)
|
|
|
+ rep = report_today(client)
|
|
|
+ chart = chart_today(client)
|
|
|
+ res['balance'] = info['balance']
|
|
|
+ db.exe('UPDATE anchor SET yue=?, ciliroi=? WHERE uid=?',
|
|
|
+ (f"{info['balance']:.2f}", f"{chart['roi']:.4f}", uid))
|
|
|
+ cids = [c['id'] for c in rep['campaigns'] if c['id']]
|
|
|
+
|
|
|
+ # 写①:自动停计划(消耗阈值止损)
|
|
|
+ if ads['enabled'] and ads['stop_enabled'] and cids \
|
|
|
+ and rep['cost'] >= float(ads['stop_cost_threshold']):
|
|
|
+ if stop_campaigns(client, cids):
|
|
|
+ res['stopped'] = list(cids)
|
|
|
+ logger.warning('自动停计划: uid=%s 消耗%.2f≥阈值%.2f 停止%s',
|
|
|
+ uid, rep['cost'], ads['stop_cost_threshold'], cids)
|
|
|
+ # 写②:自动调ROI(目标档位偏离)
|
|
|
+ target = float(ads['roi_target'] or 0)
|
|
|
+ tol = float(ads['roi_tolerance'] or 0)
|
|
|
+ if ads['enabled'] and ads['bid_enabled'] and target > 0 and cids \
|
|
|
+ and abs(chart['roi'] - target) > tol:
|
|
|
+ for cid in cids:
|
|
|
+ if update_roi(client, cid, target):
|
|
|
+ res['adjusted'].append(cid)
|
|
|
+ logger.warning('自动调ROI: uid=%s 今日%.4f→目标%.4f 计划%s',
|
|
|
+ uid, chart['roi'], target, res['adjusted'])
|
|
|
+ # 写③:充值下单(人工扫码付款)
|
|
|
+ if ads['enabled'] and ads['recharge_enabled'] \
|
|
|
+ and float(ads['recharge_threshold'] or 0) > 0 \
|
|
|
+ and float(ads['recharge_amount'] or 0) > 0 \
|
|
|
+ and info['balance'] < float(ads['recharge_threshold']) \
|
|
|
+ and (info['live'] == '直播中' or ads['include_not_live']):
|
|
|
+ order = create_recharge_order(client, account_id or uid,
|
|
|
+ float(ads['recharge_amount']))
|
|
|
+ q = cashier_qrcode(client, order)
|
|
|
+ res['recharge'] = {'amount': float(ads['recharge_amount']),
|
|
|
+ 'pay_code': order['pay_code'], 'qr_image': q['qr_image']}
|
|
|
+ logger.warning('充值下单: uid=%s 余额%.2f<%.2f 订单%.2f元 人工扫码付款: %s',
|
|
|
+ uid, info['balance'], ads['recharge_threshold'],
|
|
|
+ ads['recharge_amount'], q['qr_image'])
|
|
|
+ return res
|
|
|
+
|
|
|
+
|
|
|
+def run_auto(cfg, max_rounds=None, interval_sec=None):
|
|
|
+ """托管主循环(F1 的白盒版):遍历 anchor 逐账号 auto_manage。
|
|
|
+ 单账号异常不中断循环;默认只读(enabled=False 时写侧全部跳过)。"""
|
|
|
+ ads = dict(ADS_DEFAULTS)
|
|
|
+ ads.update(cfg.get('ads') or {})
|
|
|
+ interval = (interval_sec if interval_sec is not None
|
|
|
+ else int(ads.get('interval_sec') or 300))
|
|
|
+ rounds = 0
|
|
|
+ while max_rounds is None or rounds < max_rounds:
|
|
|
+ rounds += 1
|
|
|
+ for row in db.query('SELECT * FROM anchor ORDER BY id'):
|
|
|
+ try:
|
|
|
+ auto_manage(cfg, row)
|
|
|
+ except Exception as e:
|
|
|
+ logger.warning('托管异常 uid=%s: %s', _row_get(row, 'uid', ''), e)
|
|
|
+ if max_rounds is None or rounds < max_rounds:
|
|
|
+ time.sleep(interval)
|