demo_400AD.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. # -*- codeing = utf-8 -*-
  2. # @Time : 2023/12/10 18:20
  3. # @Author : Clown
  4. # @File : demo_400AD.py
  5. # @Software : PyCharm
  6. import pymysql
  7. from datetime import datetime,timedelta,time
  8. from dateutil.parser import parse
  9. import traceback
  10. from all_key_table import update_key_value_pair_7qiaoPlus
  11. import json
  12. import requests
  13. import ddddocr
  14. import pandas as pd
  15. from bs4 import BeautifulSoup
  16. import execjs
  17. import time as tms
  18. from urllib.parse import quote
  19. import math
  20. def linkTomySql(host, passwd, db_name, port):
  21. '''连接至数据库返回【db】,v2新增local_infile=1 打开文件导入权限'''
  22. try:
  23. # 本地连接为:localhost 服务器连接为:124.222.188.59
  24. db = pymysql.connect (
  25. host=host, user="root",
  26. passwd=passwd,
  27. db=db_name,
  28. port=port,
  29. charset='utf8mb4',
  30. local_infile=1)
  31. print ('\nconnect to mysql server 成功')
  32. print ('---------------------------------------')
  33. except:
  34. print ("\ncould not connect to mysql server")
  35. db = "连接失败"
  36. return db
  37. def read_key_value_pair(db, brand_name, wm_plate, owner):
  38. '''按条件读取,数据库中all_key_table表里的key_value_pair字段中的值,以键值对的形式输出
  39. db:数据库,
  40. brand_name:品牌名,
  41. wm_plate:外卖平台MEITUAN或ELEME,
  42. owner:账号权限all或one
  43. '''
  44. cursor = db.cursor ()
  45. sql = f'SELECT key_value_pair FROM all_key_table WHERE brand_name = "{brand_name}" AND wm_plate = "{wm_plate}" AND owner = "{owner}";'
  46. cursor.execute (sql)
  47. pair = json.loads (cursor.fetchall ()[0][0])
  48. return pair
  49. def orderTo7qiao(db,lastCatchTime_ago_s,solutionCntAll,solutionJsonData):
  50. solutionjsondata = {'data':solutionJsonData}
  51. key_json = read_key_value_pair (db, '道一云', '7qiaoPlus', 'all')
  52. applicationId = '63631ee57005c0103426fdc7'
  53. processId = '642128bd80236836229b3b1d'
  54. Token = key_json['data']
  55. headers_api = {
  56. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36',
  57. "Content-type": "application/json",
  58. "X-Auth0-Token": Token}
  59. url = f'https://qiqiao.do1.com.cn/plus/cgi-bin/open/applications/{applicationId}/workflow/process_definitions/{processId}/start'
  60. params_json = {
  61. "nextNodesAndHandlers": [{"activityDefinitionId": "obj_02"}],
  62. "variables": {"任务触发时间": lastCatchTime_ago_s,'solutioncntall':solutionCntAll,'solutionjsondata':json.dumps(solutionjsondata,ensure_ascii=False)},
  63. "loginUserId":"92874ed35ecb45f51a58adcf18e99b5e"}
  64. try:
  65. resp = requests.post(url,headers =headers_api,json=params_json)
  66. msg = resp.json()['msg']
  67. print(resp.text)
  68. if msg == '执行成功':
  69. operation_results = '无异常'
  70. else:
  71. operation_results = f'[orderTo7qiao]-返回结果为{msg}'
  72. except Exception as e:
  73. operation_results = f'[orderTo7qiao]-道一云端无法连接{e}'
  74. return operation_results
  75. def sendMsgToRot(url,msg_txt):
  76. params_json = {
  77. "msgtype": "markdown",
  78. "markdown": {
  79. "content": msg_txt,
  80. "mentioned_list":["@all"]
  81. }}
  82. resp = requests.post(url,json=params_json).text
  83. print(resp)
  84. # 查询计时器时间,输出起始时间
  85. def select400_ad_time_meter(db,minutes):
  86. cursor = db.cursor ()
  87. sql = f'SELECT * FROM 400_ad_time_meter WHERE id = 1;'
  88. cursor.execute (sql)
  89. lastCatchTime_ago = cursor.fetchall ()[0][0]
  90. lastCatchTime_ago_s = (lastCatchTime_ago + timedelta(seconds=1)).strftime('%Y-%m-%d %H:%M:%S')
  91. # 更新间隔
  92. lastCatchTime_now_s = (lastCatchTime_ago + timedelta(minutes=minutes)).strftime('%Y-%m-%d %H:%M:%S')
  93. cursor.close()
  94. return lastCatchTime_ago_s,lastCatchTime_now_s
  95. # 更新计时器时间
  96. def update400_ad_time_meter(db,lastCatchTime_now_s):
  97. cursor = db.cursor ()
  98. sql = f'UPDATE 400_ad_time_meter SET lastCatchTime = "{lastCatchTime_now_s}" WHERE id = 1;'
  99. cursor.execute(sql)
  100. db.commit()
  101. cursor.close()
  102. # 新增记录至抓取记录表
  103. def insert400_ad_solution_catch(db,insert_valuse):
  104. cursor = db.cursor ()
  105. sql = f'INSERT INTO 400_ad_solution_catch VALUES (%s,%s,%s,%s,%s,%s,%s,%s);'
  106. cursor.execute (sql,insert_valuse)
  107. db.commit ()
  108. cursor.close ()
  109. # 新增记录至抓取明细记录表
  110. def insert400_ad_solution_info(db,insert_valuse):
  111. cursor = db.cursor ()
  112. sql = f'INSERT INTO 400_ad_solution_info VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);'
  113. cursor.execute (sql,insert_valuse)
  114. db.commit ()
  115. cursor.close ()
  116. # 图像识别
  117. ocr = ddddocr.DdddOcr(show_ad = False)
  118. def dOcrImage(image_path):
  119. with open(image_path,'rb') as f:
  120. img_bytes = f.read()
  121. text = ocr.classification(img_bytes)
  122. print(text)
  123. return text
  124. # 验证码验证之后获取对应的headers中的code码
  125. def getCodeAndCodeId(save_path,typeName,cookie):
  126. if typeName == 'xt4008':
  127. url = 'https://www.xt4008.com/api/xuntec/login/admin/code'
  128. headers = {
  129. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  130. 'content-type': 'application/x-www-form-urlencoded'}
  131. resp = requests.get(url, headers = headers)
  132. codeid = resp.headers.get('Codeid')
  133. data = resp.content
  134. with open(save_path+'code.png', mode = "wb") as f:
  135. f.write(data)
  136. # print(codeid)
  137. code = dOcrImage(save_path+'code.png')
  138. out_json = {'code':code,'codeId':codeid}
  139. elif typeName == '400pt':
  140. now = datetime.now()
  141. formatted_time = now.strftime("%a %b %d %Y %H:%M:%S GMT ") + "0800 (中国标准时间)"
  142. url = 'https://www.400pt.net/platform/pm/getVaildImg'
  143. data = f'now={formatted_time}'
  144. headers = {
  145. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  146. 'content-type': 'application/x-www-form-urlencoded',
  147. 'cookie':cookie}
  148. resp = requests.get(url, headers = headers,data=quote(data))
  149. data = resp.content
  150. with open(save_path+'code.png', mode = "wb") as f:
  151. f.write(data)
  152. code = dOcrImage(save_path+'code.png')
  153. out_json = {'code':code,'codeId':'codeid'}
  154. return out_json
  155. # step1网址'https://www.400pt.net/'获取待授权cookie_id信息
  156. def getCookie():
  157. url = 'https://www.400pt.net/'
  158. headers = {
  159. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  160. 'content-type': 'application/x-www-form-urlencoded'}
  161. resp = requests.get(url,headers=headers).headers.get('Set-Cookie')
  162. cookie_id = resp.split(';')[0]
  163. return cookie_id
  164. # step2网址'https://www.400pt.net/'授权cookie_id信息,使cookie_id信息变的有效
  165. def getInhtml(cookie_id):
  166. url = 'https://www.400pt.net/api/cust/auth/index'
  167. headers = {
  168. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  169. 'Referer': 'https://www.400pt.net/',
  170. 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  171. 'Cookie':cookie_id,
  172. 'Upgrade-Insecure-Requests':'1'}
  173. resp = requests.get(url,headers=headers)
  174. def getMd5(url,strIn):
  175. if url != '':
  176. url = url
  177. headers = {
  178. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'}
  179. resp = requests.get(url, headers = headers).text
  180. with open('md5.js', mode = 'w') as f:
  181. f.write(resp)
  182. else:
  183. with open("md5.js", "r") as file:
  184. resp = file.read()
  185. ctx = execjs.compile(resp)
  186. result = ctx.call("MD5",strIn)
  187. # print(result)
  188. return result
  189. def getJsScript():
  190. url = 'https://www.400pt.net/api/cust/auth/index'
  191. headers = {
  192. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'}
  193. resp = requests.get(url, headers = headers).text
  194. soup = BeautifulSoup(resp, 'html.parser')
  195. tags = soup.find_all(src=True)
  196. tag_dict = {}
  197. ii = ['md5','login.js']
  198. for tag in tags:
  199. tag_text = tag['src']
  200. for i in ii:
  201. if i in tag_text:
  202. tag_dict[i]='https://www.400pt.net/'+tag_text
  203. getMd5(tag_dict['md5'],'')
  204. def getToken(userName,pwd,typeName,img_path):
  205. cookie_id = ''
  206. if typeName == '400pt':
  207. cookie_id=getCookie()
  208. # print(cookie_id)
  209. code_json = getCodeAndCodeId(img_path, typeName,cookie_id)
  210. loginName = userName
  211. pwd = pwd
  212. md5 = getMd5('',pwd)
  213. # print(f'md5:{md5}')
  214. timestamp = int(tms.time()*1000)
  215. # print(timestamp)
  216. password = getMd5('',md5+str(timestamp))
  217. # print(password)
  218. url = 'https://www.400pt.net/platform/pm/admin/login'
  219. params = f'loginName={loginName}&password={password}&pwd={md5}&authCode={code_json["code"]}&timestamp={int(timestamp)}&loginType=0'
  220. headers = {
  221. 'Accept':'application/json, text/javascript, */*; q=0.01',
  222. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  223. 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
  224. 'Cookie':cookie_id,
  225. 'Sec-Ch-Ua':'"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
  226. 'Sec-Ch-Ua-Mobile':'?0',
  227. 'Sec-Ch-Ua-Platform':'"Windows"',
  228. 'Sec-Fetch-Dest':'empty',
  229. 'Sec-Fetch-Mode':'cors',
  230. 'Sec-Fetch-Site':'same-origin',
  231. 'X-Requested-With':'XMLHttpRequest'}
  232. resp = requests.post(url,headers=headers,params = params)
  233. getInhtml(cookie_id)
  234. elif typeName == 'xt4008':
  235. code_json = getCodeAndCodeId(img_path, typeName, cookie_id)
  236. url = 'https://www.xt4008.com/api/xuntec/login/admin/login'
  237. headers = {
  238. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  239. 'content-type': 'application/x-www-form-urlencoded'}
  240. params = {'userName': int(userName),
  241. 'passWord': pwd,
  242. 'code': code_json['code'],
  243. 'codeId': code_json['codeId']}
  244. resp = requests.post(url, headers = headers, params = params)
  245. # print(resp.text)
  246. cookie_id = resp.json()['data']['token']
  247. # print(resp.text)
  248. return cookie_id
  249. # 选择所有有效账户
  250. def selectAllUsers(db):
  251. cursor = db.cursor ()
  252. sql = f'''SELECT * FROM 400_ad_app_id_sct WHERE state = 1;'''
  253. cursor.execute (sql)
  254. out = cursor.fetchall ()
  255. list_out = []
  256. for row in out:
  257. dict_out = {'brandName':row[0],
  258. 'userName':row[2],
  259. 'secret':row[1],
  260. 'typeName':row[3]}
  261. list_out.append(dict_out)
  262. cursor.close()
  263. return list_out
  264. # 获取网站资源信息
  265. def p400AD(userName, secret, typeName, lastCatchTime_ago_s, lastCatchTime_now_s):
  266. # 此路径可进行自定义
  267. img_path = ''
  268. resp = {'data':[]}
  269. a = 0
  270. n = 0
  271. while a == 0 and n <= 5:
  272. try:
  273. token = getToken(userName, secret, typeName, img_path)
  274. a = 1
  275. except:
  276. error_results = traceback.format_exc()
  277. print(f'getToken:{error_results}')
  278. tms.sleep(2)
  279. a = 0
  280. n += 1
  281. if typeName == 'xt4008':
  282. pageNum = 1
  283. pages_cnt = 1
  284. resp = {'data':[],'solutionCnt':0}
  285. while pageNum <= pages_cnt:
  286. url = f'https://www.xt4008.com/api/xuntec/callAcdReport/queryCallDetailPd?token={token}&page={pageNum}'
  287. headers = {
  288. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'}
  289. params = {"msisdn": userName,
  290. "caller": "",
  291. "called": "",
  292. "callSts": "",
  293. "callerCode": "",
  294. "startTime": lastCatchTime_ago_s,
  295. "endTime": lastCatchTime_now_s,
  296. "remarkStatus": "",
  297. "end_code": ""}
  298. resp_0 = requests.post(url, headers = headers, json = params)
  299. # print(pageNum,resp_0.text)
  300. resp['data'].append(resp_0.json())
  301. if pageNum == 1:
  302. pages_cnt = resp_0.json()['data']['pageCount']
  303. resp['solutionCnt'] = resp_0.json()['data']['total']
  304. else:
  305. ...
  306. pageNum += 1
  307. elif typeName == '400pt':
  308. cookie = f'{token};'
  309. # print(cookie)
  310. url = 'https://www.400pt.net/api/cust/report/customerReportCallListExport'
  311. headers = {
  312. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  313. 'content-type': 'application/x-www-form-urlencoded',
  314. 'Cookie': f'{cookie}uid=c_10974'}
  315. params = {'status': 1,
  316. 'startDate': lastCatchTime_ago_s,
  317. 'endDate': lastCatchTime_now_s,
  318. 'rows': 80,
  319. 'isForm': 1,
  320. 'page': 1}
  321. resp = requests.post(url, headers = headers, params = params)
  322. # print(resp.text)
  323. data = resp.content
  324. save_path = ''
  325. with open(save_path + '记录.csv', mode = "wb") as f:
  326. f.write(data)
  327. df_json = pd.read_csv('记录.csv', encoding = 'gbk', keep_default_na = '').to_dict('records')
  328. resp = {'data':df_json,'solutionCnt':len(df_json)}
  329. return resp
  330. def dump400Josn(db, userName, brandName, routeName, typeName, response_json):
  331. solutionJsonDatas = []
  332. datas = response_json['data']
  333. if typeName == 'xt4008':
  334. for data in datas:
  335. rows = data['data']['rows']
  336. if rows is None:
  337. ...
  338. else:
  339. for row in rows:
  340. clueId = row['call_id']
  341. commitTime = parse(row['formatter_calltime']).strftime("%Y-%m-%d %H:%M:%S")
  342. solutionType = typeName
  343. clueName = '未知'
  344. cluePhoneNumber = row['caller_id']
  345. flowChannelName = '-'
  346. try:
  347. area = row['callerCityName']
  348. except:
  349. area = '未知区域'
  350. searchWord = '-'
  351. keyword = '-'
  352. solutionInfo = json.dumps(row, ensure_ascii = False)
  353. userName = userName
  354. insert_valuse = (clueId, commitTime, solutionType, clueName, cluePhoneNumber, flowChannelName, area, searchWord, keyword,solutionInfo, userName, brandName, routeName)
  355. insert400_ad_solution_info(db, insert_valuse)
  356. solutionJsonData = {'clueId': clueId,
  357. 'commitTime': commitTime,
  358. 'solutionType': solutionType,
  359. 'clueName': clueName,
  360. 'cluePhoneNumber': cluePhoneNumber,
  361. 'flowChannelName': flowChannelName,
  362. 'area': area,
  363. 'searchWord': searchWord,
  364. 'keyword': keyword,
  365. 'userName': userName,
  366. 'brandName': brandName,
  367. 'routeName': routeName}
  368. solutionJsonDatas.append(solutionJsonData)
  369. elif typeName == '400pt':
  370. for data in datas:
  371. commitTime = parse(data['来电时间']).strftime("%Y-%m-%d %H:%M:%S")
  372. solutionType = typeName
  373. clueName = '未知'
  374. cluePhoneNumber = str(data['主叫号码'])
  375. clueId = str(int(parse(commitTime).timestamp()))+ cluePhoneNumber
  376. flowChannelName = '-'
  377. try:
  378. area = data['主叫归属地']
  379. except:
  380. area = '未知区域'
  381. searchWord = '-'
  382. keyword = '-'
  383. solutionInfo = json.dumps(data, ensure_ascii = False)
  384. userName = userName
  385. insert_valuse = (
  386. clueId, commitTime, solutionType, clueName, cluePhoneNumber, flowChannelName, area, searchWord, keyword,
  387. solutionInfo, userName, brandName, routeName)
  388. insert400_ad_solution_info(db, insert_valuse)
  389. solutionJsonData = {'clueId': clueId,
  390. 'commitTime': commitTime,
  391. 'solutionType': solutionType,
  392. 'clueName': clueName,
  393. 'cluePhoneNumber': cluePhoneNumber,
  394. 'flowChannelName': flowChannelName,
  395. 'area': area,
  396. 'searchWord': searchWord,
  397. 'keyword': keyword,
  398. 'userName': userName,
  399. 'brandName': brandName,
  400. 'routeName': routeName}
  401. solutionJsonDatas.append(solutionJsonData)
  402. return solutionJsonDatas
  403. # 运行数据获取及数据库数据录入
  404. def run400AD(db, userName, secret, typeName, brandName, routeName, lastCatchTime_ago_s, lastCatchTime_now_s, result):
  405. solutionJsonDataList = []
  406. a = 0
  407. n = 0
  408. while a == 0 and n <= 10:
  409. try:
  410. response_json = p400AD(userName, secret, typeName, lastCatchTime_ago_s, lastCatchTime_now_s)
  411. a = 1
  412. except:
  413. tms.sleep(2)
  414. a = 0
  415. n += 1
  416. if n == 1:
  417. desc = f'[{result}]success'
  418. else:
  419. desc = f'[{result}]restart[{n}]times'
  420. solutionCnt = response_json['solutionCnt']
  421. solutionJsonDatas = dump400Josn(db, userName,brandName,routeName, typeName, response_json)
  422. solutionJsonDataList = solutionJsonDataList + solutionJsonDatas
  423. response_data = json.dumps(response_json,ensure_ascii = False)
  424. insert_valuse = (lastCatchTime_now_s, response_data, solutionCnt, desc, typeName, userName, brandName, routeName)
  425. insert400_ad_solution_catch(db, insert_valuse)
  426. return solutionCnt,solutionJsonDataList
  427. df_timeTable = pd.read_excel('timeTableForRunOrStop.xlsx',sheet_name = 'timeTable')
  428. list_date2str = lambda df_in : [data_out.strftime("%Y-%m-%d") for data_out in df_in]
  429. runDateList = list_date2str(list(df_timeTable[df_timeTable['status']=='run']['date']))
  430. stopDateList = list_date2str(list(df_timeTable[df_timeTable['status']=='stop']['date']))
  431. df_timeTable_dict = df_timeTable.to_dict('records')
  432. timeTable_df2dict = lambda df_in : {data_out['date'].strftime("%Y-%m-%d"):data_out['memo'] for data_out in df_in}
  433. timeTable_dict = timeTable_df2dict(df_timeTable_dict)
  434. def dateTimeStopRun(lastCatchTime_ago_s):
  435. weekday_text = ['周一','周二','周三','周四','周五','周六','周日']
  436. # url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7d89dfd6-04f2-430f-9b14-e5c0ff38c9c8'
  437. url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cf7139e1-e623-41ca-8541-5dc6e26d43b0'
  438. result = 'run'
  439. weekday_value = parse(lastCatchTime_ago_s).weekday()
  440. date_value = parse(lastCatchTime_ago_s).date().strftime("%Y-%m-%d")
  441. next_date_value = (parse(lastCatchTime_ago_s).date()+timedelta(days = 1)).strftime("%Y-%m-%d")
  442. time_value = (parse(lastCatchTime_ago_s )+ timedelta(seconds = -1)).time()
  443. start_time = time(9, 30)
  444. end_time = time(17, 50)
  445. if weekday_value in [0,1,2,3,4] or date_value in stopDateList:
  446. if start_time <= time_value <= end_time:
  447. result = 'stop'
  448. text = ''
  449. if time_value == start_time and date_value not in runDateList:
  450. text = f'**【{date_value}({weekday_text[weekday_value]})】\n自动值守【<font color=\"warning\">已关闭</font>】**\n请注意接听[09:30-18:00]期间的400来电,并即时录入推送!辛苦!'
  451. sendMsgToRot(url,text)
  452. elif time_value == end_time:
  453. if next_date_value in stopDateList:
  454. text = f'**【{date_value}({weekday_text[weekday_value]})】\n自动值守【<font color=\"info\">已开启</font>】**\n系统将自动推送[今日18:00-次日9:30]期间的400来电!\n' \
  455. f'**提醒:\n明天【{next_date_value}({weekday_text[weekday_value+1]})】为【<font color=\"warning\">工作日({timeTable_dict[next_date_value]})</font>】**\n请注意正常接听[09:30-18:00]期间的400来电,并即时录入推送!辛苦!'
  456. sendMsgToRot(url, text)
  457. elif next_date_value in runDateList:
  458. if date_value not in runDateList:
  459. text = f'**【{date_value}({weekday_text[weekday_value]})】\n自动值守【<font color=\"info\">已开启</font>】**\n系统将自动推送[今日18:00-假期结束次日9:30]期间的400来电!**\n预祝 {timeTable_dict[next_date_value]}假期愉快!**'
  460. sendMsgToRot(url, text)
  461. else:
  462. ...
  463. elif weekday_value+1 in [5]:
  464. text = f'**【{date_value}({weekday_text[weekday_value]})】\n自动值守【<font color=\"info\">已开启</font>】**\n系统将自动推送[今日18:00-下周一9:30]期间的400来电!**\n周末愉快!**'
  465. sendMsgToRot(url, text)
  466. else:
  467. text = f'**【{date_value}({weekday_text[weekday_value]})】\n自动值守【<font color=\"info\">已开启</font>】**\n系统将自动推送[今日18:00-次日9:30]期间的400来电!'
  468. sendMsgToRot(url, text)
  469. # print(text)
  470. else:
  471. if time_value == end_time and next_date_value in stopDateList:
  472. text = f'**提醒:\n明天【{next_date_value}({weekday_text[weekday_value + 1]})】为【<font color=\"warning\">工作日({timeTable_dict[next_date_value]})</font>】**\n请注意正常接听[09:30-18:00]期间的400来电,并即时录入推送!辛苦!'
  473. sendMsgToRot(url, text)
  474. if date_value in runDateList:
  475. result = 'run'
  476. return result
  477. # 多账号计时抓取投流数据
  478. def runADsolution(db,minutes):
  479. # 基础参数
  480. operation_results = '无异常'
  481. e = 'no'
  482. users_info = selectAllUsers(db)
  483. try:
  484. lastCatchTime_ago_s, lastCatchTime_now_s = select400_ad_time_meter(db,minutes)
  485. result = dateTimeStopRun(lastCatchTime_ago_s)
  486. for user_info in users_info:
  487. brandName = user_info['brandName']
  488. userName = user_info['userName']
  489. secret = user_info['secret']
  490. typeName = user_info['typeName']
  491. routeName = '400'
  492. solutionCntAll,solutionJsonDataList = run400AD(db, userName, secret, typeName, brandName, routeName, lastCatchTime_ago_s, lastCatchTime_now_s, result)
  493. if result == 'stop':
  494. print(result)
  495. elif result == 'run':
  496. print(result)
  497. if 1==0:
  498. if solutionCntAll > 0:
  499. if len(str(solutionJsonDataList)) >= 5000:
  500. for solutionJsonDataList_0 in solutionJsonDataList:
  501. operation_results = orderTo7qiao(db, lastCatchTime_now_s, 1, solutionJsonDataList_0)
  502. tms.sleep(0.5)
  503. else:
  504. operation_results = orderTo7qiao(db, lastCatchTime_now_s, solutionCntAll, solutionJsonDataList)
  505. else:
  506. operation_results = '无异常'
  507. except Exception as ee:
  508. e = ee
  509. operation_results = traceback.format_exc()
  510. # 发送报错信息
  511. if operation_results != '无异常':
  512. url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=cf7139e1-e623-41ca-8541-5dc6e26d43b0'
  513. msg_txt = f'<font color=\"warning\">【400数据同步】服务端出现异常,请管理员尽快处理!</font>\n>Exception->{e}\nDetail->{operation_results}'
  514. sendMsgToRot(url, msg_txt)
  515. a = 1/0
  516. else:
  517. update400_ad_time_meter(db, lastCatchTime_now_s)
  518. def run(db):
  519. # 初始化时间周期
  520. # 更新间隔
  521. minute = 10
  522. f_now = datetime.now ()
  523. f_mm = f_now.strftime ("%M")
  524. f_ss = f_now.strftime ("%S")
  525. f_c = int (f_mm) % minute
  526. wait_s = (minute - f_c - 1) * 60 + 59 - int (f_ss)
  527. tms.sleep (wait_s)
  528. # 执行循环
  529. while True:
  530. now = datetime.now ()
  531. mm = now.strftime ("%M")
  532. ss = now.strftime ("%S")
  533. c = int (mm) % minute
  534. if c == 0 and ss == '01':
  535. s = tms.time ()
  536. # print(now)
  537. runADsolution(db,minute)
  538. tms.sleep (minute * 60 - 0.5 - (tms.time () - s))
  539. if __name__ == '__main__':
  540. # host = 'clownted.top'
  541. # passwd = '111...Clown'
  542. # db_name = 'zuzu_data'
  543. # port = 63306
  544. if 1==1:
  545. host = 'localhost'
  546. passwd = '111???clown'
  547. db_name = 'hexingxing'
  548. port = 3306
  549. db = linkTomySql(host, passwd, db_name, port)
  550. # list_out = selectAllUsers(db)
  551. # print(list_out)
  552. if 1 == 1:
  553. userName = '4009017757'
  554. secret = '4N+0xuYCWiNoawOggredIQ=='
  555. typeName = 'xt4008'
  556. lastCatchTime_ago_s = '2023-12-01 00:00:00'
  557. lastCatchTime_now_s = '2023-12-07 00:00:59'
  558. brandName = '浆小白'
  559. routeName = '400'
  560. run400AD(db, userName, secret, typeName, brandName, routeName, lastCatchTime_ago_s, lastCatchTime_now_s, 'run')
  561. userName = '4009018187'
  562. secret = 'Abcd123456'
  563. typeName = '400pt'
  564. run400AD(db, userName, secret, typeName, brandName, routeName, lastCatchTime_ago_s, lastCatchTime_now_s, 'run')
  565. if 1 == 0:
  566. getJsScript()
  567. # 更新至当前,用于重启服务时,自动更新数据
  568. minutes = 10 #时间间隔
  569. # minutes_for_d = 10 #延时时间
  570. lastCatchTime_ago_s, lastCatchTime_now_s = select400_ad_time_meter(db,minutes)
  571. cnt = int((datetime.now().timestamp() - parse(lastCatchTime_ago_s).timestamp())/60/minutes)*minutes
  572. # lastCatchTime_ago_s, lastCatchTime_now_s = select400_ad_time_meter(db, cnt)
  573. # print(cnt)
  574. # print(lastCatchTime_now_s)
  575. if cnt > 0 :
  576. runADsolution(db,cnt)
  577. else:
  578. ...
  579. tms.sleep(10)
  580. # 正式运行
  581. print('正式运行')
  582. run(db)
  583. db.close()
  584. # a = '2023-12-12 17:50:01'
  585. # dateTimeStopRun(a)