import json import urllib.request import subprocess import time token = json.loads(urllib.request.urlopen( 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwd483c2fba24ae30a&corpsecret=nU1xezyHyonS9rOJ9Kwo3i5OM9iuWc1TrjXf-rOYZx0' ).read()).get('access_token', '') print('Token acquired') cmd = "mysql -h sh-cdb-6fzlwnms.sql.tencentcdb.com -P 63912 -u assistant_prod -p'U%$4Tu_C3+4' -e 'SET NAMES utf8mb4; SELECT customer_id FROM ai_assistant.customers WHERE name = customer_id;' 2>&1 | grep -v Warning" result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cids = [l.strip() for l in result.stdout.decode('utf-8').strip().split('\n') if l.strip() and not l.startswith('customer_id')] print('Found %d customers without name' % len(cids)) fixed = 0 failed = 0 for cid in cids: try: url = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=' + token + '&external_userid=' + cid data = json.loads(urllib.request.urlopen(url, timeout=10).read()) if data.get('errcode') == 0: c = data.get('external_contact', {}) name = c.get('name', '') if name: updates = ["name='" + name + "'", "avatar='" + c.get('avatar', '') + "'", "type='" + ('企业' if c.get('type') == 1 else '个人' if c.get('type') == 2 else 'UNKNOWN') + "'"] g = c.get('gender') if g == 1: updates.append("gender='MALE'") elif g == 2: updates.append("gender='FEMALE'") uid = c.get('unionid', '') if uid: updates.append("unionid='" + uid + "'") sql = 'UPDATE ai_assistant.customers SET ' + ', '.join(updates) + " WHERE customer_id='" + cid + "';" subprocess.run(['mysql', '-h', 'sh-cdb-6fzlwnms.sql.tencentcdb.com', '-P', '63912', '-u', 'assistant_prod', '-pU%$4Tu_C3+4', '-e', sql], stdout=subprocess.PIPE, stderr=subprocess.PIPE) fixed += 1 print('Fixed: %s -> %s' % (cid, name)) else: failed += 1 else: failed += 1 print('Failed: %s -> %d %s' % (cid, data.get('errcode'), str(data.get('errmsg', ''))[:50])) time.sleep(0.05) except Exception as e: failed += 1 print('Error: %s -> %s' % (cid, str(e)[:80])) print('Done. Fixed=%d, Failed=%d' % (fixed, failed))