wxbot.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import os
  4. import sys
  5. import traceback
  6. import webbrowser
  7. import pyqrcode
  8. import requests
  9. import mimetypes
  10. import json
  11. import xml.dom.minidom
  12. import urllib
  13. import time
  14. import re
  15. import random
  16. from traceback import format_exc
  17. from requests.exceptions import ConnectionError, ReadTimeout
  18. from Queue import Queue
  19. import HTMLParser
  20. import threading
  21. UNKONWN = 'unkonwn'
  22. SUCCESS = '200'
  23. SCANED = '201'
  24. TIMEOUT = '408'
  25. def show_image(file_path):
  26. """
  27. 跨平台显示图片文件
  28. :param file_path: 图片文件路径
  29. """
  30. if sys.version_info >= (3, 3):
  31. from shlex import quote
  32. else:
  33. from pipes import quote
  34. if sys.platform == "darwin":
  35. command = "open -a /Applications/Preview.app %s&" % quote(file_path)
  36. os.system(command)
  37. else:
  38. webbrowser.open(os.path.join(os.getcwd(),'temp',file_path))
  39. class SafeSession(requests.Session):
  40. def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None,
  41. timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None,
  42. json=None):
  43. for i in range(3):
  44. try:
  45. return super(SafeSession, self).request(method, url, params, data, headers, cookies, files, auth,
  46. timeout,
  47. allow_redirects, proxies, hooks, stream, verify, cert, json)
  48. except Exception as e:
  49. print e.message, traceback.format_exc()
  50. continue
  51. class WXBot:
  52. """WXBot功能类"""
  53. def __init__(self):
  54. self.DEBUG = False
  55. self.SCHEDULE_INTV = 5
  56. self.uuid = ''
  57. self.base_uri = ''
  58. self.redirect_uri = ''
  59. self.uin = ''
  60. self.sid = ''
  61. self.skey = ''
  62. self.pass_ticket = ''
  63. self.device_id = 'e' + repr(random.random())[2:17]
  64. self.base_request = {}
  65. self.sync_key_str = ''
  66. self.sync_key = []
  67. self.sync_host = ''
  68. #文件缓存目录
  69. self.temp_pwd = os.path.join(os.getcwd(), 'temp')
  70. if os.path.exists(self.temp_pwd) == False:
  71. os.makedirs(self.temp_pwd)
  72. self.session = SafeSession()
  73. self.session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5'})
  74. self.conf = {'qr': 'png'}
  75. self.my_account = {} # 当前账户
  76. # 所有相关账号: 联系人, 公众号, 群组, 特殊账号
  77. self.member_list = []
  78. # 所有群组的成员, {'group_id1': [member1, member2, ...], ...}
  79. self.group_members = {}
  80. # 所有账户, {'group_member':{'id':{'type':'group_member', 'info':{}}, ...}, 'normal_member':{'id':{}, ...}}
  81. self.account_info = {'group_member': {}, 'normal_member': {}}
  82. self.contact_list = [] # 联系人列表
  83. self.public_list = [] # 公众账号列表
  84. self.group_list = [] # 群聊列表
  85. self.special_list = [] # 特殊账号列表
  86. self.encry_chat_room_id_list = [] # 存储群聊的EncryChatRoomId,获取群内成员头像时需要用到
  87. self.file_index = 0 # 文件上传序号
  88. self.msg_queue = Queue() # 消息处理队列,handle_msg_all是从此队列拿消息的
  89. self.msg_thread = None
  90. self.schedule_thread = None
  91. self.inner_proc_thread = None
  92. @staticmethod
  93. def to_unicode(string, encoding='utf-8'):
  94. """
  95. 将字符串转换为Unicode
  96. :param string: 待转换字符串
  97. :param encoding: 字符串解码方式
  98. :return: 转换后的Unicode字符串
  99. """
  100. if isinstance(string, str):
  101. return string.decode(encoding)
  102. elif isinstance(string, unicode):
  103. return string
  104. else:
  105. raise Exception('Unknown Type')
  106. def get_contact(self):
  107. """获取当前账户的所有相关账号(包括联系人、公众号、群聊、特殊账号)"""
  108. url = self.base_uri + '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' \
  109. % (self.pass_ticket, self.skey, int(time.time()))
  110. r = self.session.post(url, data='{}')
  111. r.encoding = 'utf-8'
  112. if self.DEBUG:
  113. with open(os.path.join(self.temp_pwd,'contacts.json'), 'w') as f:
  114. f.write(r.text.encode('utf-8'))
  115. dic = json.loads(r.text)
  116. self.member_list = dic['MemberList']
  117. special_users = ['newsapp', 'fmessage', 'filehelper', 'weibo', 'qqmail',
  118. 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
  119. 'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp',
  120. 'blogapp', 'facebookapp', 'masssendapp', 'meishiapp',
  121. 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
  122. 'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c',
  123. 'officialaccounts', 'notification_messages', 'wxid_novlwrv3lqwv11',
  124. 'gh_22b87fa7cb3c', 'wxitil', 'userexperience_alarm', 'notification_messages']
  125. self.contact_list = []
  126. self.public_list = []
  127. self.special_list = []
  128. self.group_list = []
  129. for contact in self.member_list:
  130. if contact['VerifyFlag'] & 8 != 0: # 公众号
  131. self.public_list.append(contact)
  132. self.account_info['normal_member'][contact['UserName']] = {'type': 'public', 'info': contact}
  133. elif contact['UserName'] in special_users: # 特殊账户
  134. self.special_list.append(contact)
  135. self.account_info['normal_member'][contact['UserName']] = {'type': 'special', 'info': contact}
  136. elif contact['UserName'].find('@@') != -1: # 群聊
  137. self.group_list.append(contact)
  138. self.account_info['normal_member'][contact['UserName']] = {'type': 'group', 'info': contact}
  139. elif contact['UserName'] == self.my_account['UserName']: # 自己
  140. self.account_info['normal_member'][contact['UserName']] = {'type': 'self', 'info': contact}
  141. else:
  142. self.contact_list.append(contact)
  143. self.account_info['normal_member'][contact['UserName']] = {'type': 'contact', 'info': contact}
  144. self.batch_get_group_members()
  145. for group in self.group_members:
  146. for member in self.group_members[group]:
  147. if member['UserName'] not in self.account_info:
  148. self.account_info['group_member'][member['UserName']] = \
  149. {'type': 'group_member', 'info': member, 'group': group}
  150. return True
  151. def batch_get_group_members(self):
  152. """批量获取所有群聊成员信息"""
  153. url = self.base_uri + '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  154. params = {
  155. 'BaseRequest': self.base_request,
  156. "Count": len(self.group_list),
  157. "List": [{"UserName": group['UserName'], "EncryChatRoomId": ""} for group in self.group_list]
  158. }
  159. r = self.session.post(url, data=json.dumps(params))
  160. r.encoding = 'utf-8'
  161. dic = json.loads(r.text)
  162. group_members = {}
  163. encry_chat_room_id = {}
  164. for group in dic['ContactList']:
  165. gid = group['UserName']
  166. members = group['MemberList']
  167. group_members[gid] = members
  168. encry_chat_room_id[gid] = group['EncryChatRoomId']
  169. self.group_members = group_members
  170. self.encry_chat_room_id_list = encry_chat_room_id
  171. def get_group_member_name(self, gid, uid):
  172. """
  173. 获取群聊中指定成员的名称信息
  174. :param gid: 群id
  175. :param uid: 群聊成员id
  176. :return: 名称信息,类似 {"display_name": "test_user", "nickname": "test", "remark_name": "for_test" }
  177. """
  178. if gid not in self.group_members:
  179. return None
  180. group = self.group_members[gid]
  181. for member in group:
  182. if member['UserName'] == uid:
  183. names = {}
  184. if 'RemarkName' in member and member['RemarkName']:
  185. names['remark_name'] = member['RemarkName']
  186. if 'NickName' in member and member['NickName']:
  187. names['nickname'] = member['NickName']
  188. if 'DisplayName' in member and member['DisplayName']:
  189. names['display_name'] = member['DisplayName']
  190. return names
  191. return None
  192. def get_contact_info(self, uid):
  193. return self.account_info['normal_member'].get(uid)
  194. def get_group_member_info(self, uid):
  195. return self.account_info['group_member'].get(uid)
  196. def get_contact_name(self, uid):
  197. info = self.get_contact_info(uid)
  198. if info is None:
  199. return None
  200. info = info['info']
  201. name = {}
  202. if 'RemarkName' in info and info['RemarkName']:
  203. name['remark_name'] = info['RemarkName']
  204. if 'NickName' in info and info['NickName']:
  205. name['nickname'] = info['NickName']
  206. if 'DisplayName' in info and info['DisplayName']:
  207. name['display_name'] = info['DisplayName']
  208. if len(name) == 0:
  209. return None
  210. else:
  211. return name
  212. @staticmethod
  213. def get_contact_prefer_name(name):
  214. if name is None:
  215. return None
  216. if 'remark_name' in name:
  217. return name['remark_name']
  218. if 'nickname' in name:
  219. return name['nickname']
  220. if 'display_name' in name:
  221. return name['display_name']
  222. return None
  223. @staticmethod
  224. def get_group_member_prefer_name(name):
  225. if name is None:
  226. return None
  227. if 'remark_name' in name:
  228. return name['remark_name']
  229. if 'display_name' in name:
  230. return name['display_name']
  231. if 'nickname' in name:
  232. return name['nickname']
  233. return None
  234. def get_user_type(self, wx_user_id):
  235. """
  236. 获取特定账号与自己的关系
  237. :param wx_user_id: 账号id:
  238. :return: 与当前账号的关系
  239. """
  240. for account in self.contact_list:
  241. if wx_user_id == account['UserName']:
  242. return 'contact'
  243. for account in self.public_list:
  244. if wx_user_id == account['UserName']:
  245. return 'public'
  246. for account in self.special_list:
  247. if wx_user_id == account['UserName']:
  248. return 'special'
  249. for account in self.group_list:
  250. if wx_user_id == account['UserName']:
  251. return 'group'
  252. for group in self.group_members:
  253. for member in self.group_members[group]:
  254. if member['UserName'] == wx_user_id:
  255. return 'group_member'
  256. return 'unknown'
  257. def is_contact(self, uid):
  258. for account in self.contact_list:
  259. if uid == account['UserName']:
  260. return True
  261. return False
  262. def is_public(self, uid):
  263. for account in self.public_list:
  264. if uid == account['UserName']:
  265. return True
  266. return False
  267. def is_special(self, uid):
  268. for account in self.special_list:
  269. if uid == account['UserName']:
  270. return True
  271. return False
  272. def handle_msg_all(self, msg):
  273. """
  274. 处理所有消息,请子类化后覆盖此函数
  275. msg:
  276. msg_id -> 消息id
  277. msg_type_id -> 消息类型id
  278. user -> 发送消息的账号id
  279. content -> 消息内容
  280. :param msg: 收到的消息
  281. """
  282. pass
  283. @staticmethod
  284. def proc_at_info(msg):
  285. if not msg:
  286. return '', []
  287. segs = msg.split(u'\u2005')
  288. str_msg_all = ''
  289. str_msg = ''
  290. infos = []
  291. if len(segs) > 1:
  292. for i in range(0, len(segs) - 1):
  293. segs[i] += u'\u2005'
  294. pm = re.search(u'@.*\u2005', segs[i]).group()
  295. if pm:
  296. name = pm[1:-1]
  297. string = segs[i].replace(pm, '')
  298. str_msg_all += string + '@' + name + ' '
  299. str_msg += string
  300. if string:
  301. infos.append({'type': 'str', 'value': string})
  302. infos.append({'type': 'at', 'value': name})
  303. else:
  304. infos.append({'type': 'str', 'value': segs[i]})
  305. str_msg_all += segs[i]
  306. str_msg += segs[i]
  307. str_msg_all += segs[-1]
  308. str_msg += segs[-1]
  309. infos.append({'type': 'str', 'value': segs[-1]})
  310. else:
  311. infos.append({'type': 'str', 'value': segs[-1]})
  312. str_msg_all = msg
  313. str_msg = msg
  314. return str_msg_all.replace(u'\u2005', ''), str_msg.replace(u'\u2005', ''), infos
  315. def extract_msg_content(self, msg_type_id, msg):
  316. """
  317. content_type_id:
  318. 0 -> Text
  319. 1 -> Location
  320. 3 -> Image
  321. 4 -> Voice
  322. 5 -> Recommend
  323. 6 -> Animation
  324. 7 -> Share
  325. 8 -> Video
  326. 9 -> VideoCall
  327. 10 -> Redraw
  328. 11 -> Empty
  329. 99 -> Unknown
  330. :param msg_type_id: 消息类型id
  331. :param msg: 消息结构体
  332. :return: 解析的消息
  333. """
  334. mtype = msg['MsgType']
  335. content = HTMLParser.HTMLParser().unescape(msg['Content'])
  336. msg_id = msg['MsgId']
  337. msg_content = {}
  338. if msg_type_id == 0:
  339. return {'type': 11, 'data': ''}
  340. elif msg_type_id == 2: # File Helper
  341. return {'type': 0, 'data': content.replace('<br/>', '\n')}
  342. elif msg_type_id == 3: # 群聊
  343. sp = content.find('<br/>')
  344. uid = content[:sp]
  345. content = content[sp:]
  346. content = content.replace('<br/>', '')
  347. uid = uid[:-1]
  348. name = self.get_contact_prefer_name(self.get_contact_name(uid))
  349. if not name:
  350. name = self.get_group_member_prefer_name(self.get_group_member_name(msg['FromUserName'], uid))
  351. if not name:
  352. name = 'unknown'
  353. msg_content['user'] = {'id': uid, 'name': name}
  354. else: # Self, Contact, Special, Public, Unknown
  355. pass
  356. msg_prefix = (msg_content['user']['name'] + ':') if 'user' in msg_content else ''
  357. if mtype == 1:
  358. if content.find('http://weixin.qq.com/cgi-bin/redirectforward?args=') != -1:
  359. r = self.session.get(content)
  360. r.encoding = 'gbk'
  361. data = r.text
  362. pos = self.search_content('title', data, 'xml')
  363. msg_content['type'] = 1
  364. msg_content['data'] = pos
  365. msg_content['detail'] = data
  366. if self.DEBUG:
  367. print ' %s[Location] %s ' % (msg_prefix, pos)
  368. else:
  369. msg_content['type'] = 0
  370. if msg_type_id == 3 or (msg_type_id == 1 and msg['ToUserName'][:2] == '@@'): # Group text message
  371. msg_infos = self.proc_at_info(content)
  372. str_msg_all = msg_infos[0]
  373. str_msg = msg_infos[1]
  374. detail = msg_infos[2]
  375. msg_content['data'] = str_msg_all
  376. msg_content['detail'] = detail
  377. msg_content['desc'] = str_msg
  378. else:
  379. msg_content['data'] = content
  380. if self.DEBUG:
  381. try:
  382. print ' %s[Text] %s' % (msg_prefix, msg_content['data'])
  383. except UnicodeEncodeError:
  384. print ' %s[Text] (illegal text).' % msg_prefix
  385. elif mtype == 3:
  386. msg_content['type'] = 3
  387. msg_content['data'] = self.get_msg_img_url(msg_id)
  388. msg_content['img'] = self.session.get(msg_content['data']).content.encode('hex')
  389. if self.DEBUG:
  390. image = self.get_msg_img(msg_id)
  391. print ' %s[Image] %s' % (msg_prefix, image)
  392. elif mtype == 34:
  393. msg_content['type'] = 4
  394. msg_content['data'] = self.get_voice_url(msg_id)
  395. msg_content['voice'] = self.session.get(msg_content['data']).content.encode('hex')
  396. if self.DEBUG:
  397. voice = self.get_voice(msg_id)
  398. print ' %s[Voice] %s' % (msg_prefix, voice)
  399. elif mtype == 37:
  400. msg_content['type'] = 37
  401. msg_content['data'] = msg['RecommendInfo']
  402. if self.DEBUG:
  403. print ' %s[useradd] %s' % (msg_prefix,msg['RecommendInfo']['NickName'])
  404. elif mtype == 42:
  405. msg_content['type'] = 5
  406. info = msg['RecommendInfo']
  407. msg_content['data'] = {'nickname': info['NickName'],
  408. 'alias': info['Alias'],
  409. 'province': info['Province'],
  410. 'city': info['City'],
  411. 'gender': ['unknown', 'male', 'female'][info['Sex']]}
  412. if self.DEBUG:
  413. print ' %s[Recommend]' % msg_prefix
  414. print ' -----------------------------'
  415. print ' | NickName: %s' % info['NickName']
  416. print ' | Alias: %s' % info['Alias']
  417. print ' | Local: %s %s' % (info['Province'], info['City'])
  418. print ' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]
  419. print ' -----------------------------'
  420. elif mtype == 47:
  421. msg_content['type'] = 6
  422. msg_content['data'] = self.search_content('cdnurl', content)
  423. if self.DEBUG:
  424. print ' %s[Animation] %s' % (msg_prefix, msg_content['data'])
  425. elif mtype == 49:
  426. msg_content['type'] = 7
  427. if msg['AppMsgType'] == 3:
  428. app_msg_type = 'music'
  429. elif msg['AppMsgType'] == 5:
  430. app_msg_type = 'link'
  431. elif msg['AppMsgType'] == 7:
  432. app_msg_type = 'weibo'
  433. else:
  434. app_msg_type = 'unknown'
  435. msg_content['data'] = {'type': app_msg_type,
  436. 'title': msg['FileName'],
  437. 'desc': self.search_content('des', content, 'xml'),
  438. 'url': msg['Url'],
  439. 'from': self.search_content('appname', content, 'xml'),
  440. 'content': msg.get('Content') # 有的公众号会发一次性3 4条链接一个大图,如果只url那只能获取第一条,content里面有所有的链接
  441. }
  442. if self.DEBUG:
  443. print ' %s[Share] %s' % (msg_prefix, app_msg_type)
  444. print ' --------------------------'
  445. print ' | title: %s' % msg['FileName']
  446. print ' | desc: %s' % self.search_content('des', content, 'xml')
  447. print ' | link: %s' % msg['Url']
  448. print ' | from: %s' % self.search_content('appname', content, 'xml')
  449. print ' | content: %s' % (msg.get('content')[:20] if msg.get('content') else "unknown")
  450. print ' --------------------------'
  451. elif mtype == 62:
  452. msg_content['type'] = 8
  453. msg_content['data'] = content
  454. if self.DEBUG:
  455. print ' %s[Video] Please check on mobiles' % msg_prefix
  456. elif mtype == 53:
  457. msg_content['type'] = 9
  458. msg_content['data'] = content
  459. if self.DEBUG:
  460. print ' %s[Video Call]' % msg_prefix
  461. elif mtype == 10002:
  462. msg_content['type'] = 10
  463. msg_content['data'] = content
  464. if self.DEBUG:
  465. print ' %s[Redraw]' % msg_prefix
  466. elif mtype == 10000: # unknown, maybe red packet, or group invite
  467. msg_content['type'] = 12
  468. msg_content['data'] = msg['Content']
  469. if self.DEBUG:
  470. print ' [Unknown]'
  471. else:
  472. msg_content['type'] = 99
  473. msg_content['data'] = content
  474. if self.DEBUG:
  475. print ' %s[Unknown]' % msg_prefix
  476. return msg_content
  477. def handle_msg(self, r):
  478. """
  479. 处理原始微信消息的内部函数
  480. msg_type_id:
  481. 0 -> Init
  482. 1 -> Self
  483. 2 -> FileHelper
  484. 3 -> Group
  485. 4 -> Contact
  486. 5 -> Public
  487. 6 -> Special
  488. 99 -> Unknown
  489. :param r: 原始微信消息
  490. """
  491. for msg in r['AddMsgList']:
  492. user = {'id': msg['FromUserName'], 'name': 'unknown'}
  493. if msg['MsgType'] == 51: # init message
  494. msg_type_id = 0
  495. user['name'] = 'system'
  496. elif msg['MsgType'] == 37: # friend request
  497. msg_type_id = 37
  498. pass
  499. # content = msg['Content']
  500. # username = content[content.index('fromusername='): content.index('encryptusername')]
  501. # username = username[username.index('"') + 1: username.rindex('"')]
  502. # print u'[Friend Request]'
  503. # print u' Nickname:' + msg['RecommendInfo']['NickName']
  504. # print u' 附加消息:'+msg['RecommendInfo']['Content']
  505. # # print u'Ticket:'+msg['RecommendInfo']['Ticket'] # Ticket添加好友时要用
  506. # print u' 微信号:'+username #未设置微信号的 腾讯会自动生成一段微信ID 但是无法通过搜索 搜索到此人
  507. elif msg['FromUserName'] == self.my_account['UserName']: # Self
  508. msg_type_id = 1
  509. user['name'] = 'self'
  510. elif msg['ToUserName'] == 'filehelper': # File Helper
  511. msg_type_id = 2
  512. user['name'] = 'file_helper'
  513. elif msg['FromUserName'][:2] == '@@': # Group
  514. msg_type_id = 3
  515. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  516. elif self.is_contact(msg['FromUserName']): # Contact
  517. msg_type_id = 4
  518. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  519. elif self.is_public(msg['FromUserName']): # Public
  520. msg_type_id = 5
  521. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  522. elif self.is_special(msg['FromUserName']): # Special
  523. msg_type_id = 6
  524. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  525. else:
  526. msg_type_id = 99
  527. user['name'] = 'unknown'
  528. if not user['name']:
  529. user['name'] = 'unknown'
  530. user['name'] = HTMLParser.HTMLParser().unescape(user['name'])
  531. if self.DEBUG and msg_type_id != 0:
  532. print u'[MSG] %s:' % user['name']
  533. content = self.extract_msg_content(msg_type_id, msg)
  534. message = {'msg_type_id': msg_type_id,
  535. 'msg_id': msg['MsgId'],
  536. 'content': content,
  537. 'to_user_id': msg['ToUserName'],
  538. 'user': user}
  539. self.msg_queue.put(message)
  540. def schedule(self):
  541. """
  542. 做任务型事情的函数,如果需要,可以在子类中覆盖此函数
  543. 此函数在处理消息的间隙被调用,请不要长时间阻塞此函数
  544. """
  545. pass
  546. def proc_msg(self):
  547. while True:
  548. check_time = time.time()
  549. try:
  550. [retcode, selector] = self.sync_check()
  551. # print '[DEBUG] sync_check:', retcode, selector
  552. if retcode == '1100': # 从微信客户端上登出
  553. break
  554. elif retcode == '1101': # 从其它设备上登了网页微信
  555. break
  556. elif retcode == '0':
  557. if selector == '2': # 有新消息
  558. r = self.sync()
  559. if r is not None:
  560. self.handle_msg(r)
  561. elif selector == '3': # 未知
  562. r = self.sync()
  563. if r is not None:
  564. self.handle_msg(r)
  565. elif selector == '4': # 通讯录更新
  566. r = self.sync()
  567. if r is not None:
  568. self.get_contact()
  569. elif selector == '6': # 可能是红包
  570. r = self.sync()
  571. if r is not None:
  572. self.handle_msg(r)
  573. elif selector == '7': # 在手机上操作了微信
  574. r = self.sync()
  575. if r is not None:
  576. self.handle_msg(r)
  577. elif selector == '0': # 无事件
  578. pass
  579. else:
  580. print '[DEBUG] sync_check:', retcode, selector
  581. r = self.sync()
  582. if r is not None:
  583. self.handle_msg(r)
  584. else:
  585. print '[DEBUG] sync_check:', retcode, selector
  586. except:
  587. print '[ERROR] Except in proc_msg'
  588. print format_exc()
  589. check_time = time.time() - check_time
  590. if check_time < 0.8:
  591. time.sleep(1 - check_time)
  592. def msg_thread_proc(self):
  593. print '[INFO] Msg thread start'
  594. while True:
  595. if not self.msg_queue.empty():
  596. msg = self.msg_queue.get()
  597. self.handle_msg_all(msg)
  598. else:
  599. time.sleep(0.1)
  600. def schedule_thread_proc(self):
  601. print '[INFO] Schedule thread start'
  602. while True:
  603. check_time = time.time()
  604. self.schedule()
  605. check_time = time.time() - check_time
  606. if check_time < self.SCHEDULE_INTV:
  607. time.sleep(self.SCHEDULE_INTV - check_time)
  608. def login_and_init_with_restore(self):
  609. return self.restore_login_result()
  610. def login_and_init_with_qr(self):
  611. self.get_uuid()
  612. self.gen_qr_code(os.path.join(self.temp_pwd, 'wxqr.png'))
  613. print '[INFO] Please use WeChat to scan the QR code .'
  614. result = self.wait4login()
  615. if result != SUCCESS:
  616. print '[ERROR] Web WeChat login failed. failed code=%s' % (result,)
  617. return False
  618. if self.login():
  619. print '[INFO] Web WeChat login succeed .'
  620. else:
  621. print '[ERROR] Web WeChat login failed .'
  622. return False
  623. if self.init():
  624. print '[INFO] Web WeChat init succeed .'
  625. else:
  626. print '[INFO] Web WeChat init failed'
  627. return False
  628. self.status_notify()
  629. self.get_contact()
  630. self.test_sync_check()
  631. self.save_login_result()
  632. return True
  633. def run_inner(self):
  634. print '[INFO] Get %d contacts' % len(self.contact_list)
  635. print '[INFO] Start to process messages .'
  636. self.proc_msg()
  637. def run(self):
  638. if not self.login_and_init_with_restore():
  639. print '[INFO] Restore login failed !'
  640. if not self.login_and_init_with_qr():
  641. print '[ERROR] Login and init failed !'
  642. return
  643. else:
  644. print '[INFO Restore login succeed .'
  645. self.msg_thread = threading.Thread(target=self.msg_thread_proc)
  646. self.msg_thread.setDaemon(True)
  647. self.msg_thread.start()
  648. self.schedule_thread = threading.Thread(target=self.schedule_thread_proc)
  649. self.schedule_thread.setDaemon(True)
  650. self.schedule_thread.start()
  651. self.inner_proc_thread = threading.Thread(target=self.run_inner)
  652. self.inner_proc_thread.setDaemon(True)
  653. self.inner_proc_thread.start()
  654. self.inner_proc_thread.join()
  655. while True:
  656. if self.login_and_init_with_restore():
  657. self.inner_proc_thread = threading.Thread(target=self.run_inner)
  658. self.inner_proc_thread.setDaemon(True)
  659. self.inner_proc_thread.start()
  660. self.inner_proc_thread.join()
  661. else:
  662. print '[ERROR] Try to restore from file failed !'
  663. return
  664. def apply_useradd_requests(self,RecommendInfo):
  665. url = self.base_uri + '/webwxverifyuser?r='+str(int(time.time()))+'&lang=zh_CN'
  666. params = {
  667. "BaseRequest": self.base_request,
  668. "Opcode": 3,
  669. "VerifyUserListSize": 1,
  670. "VerifyUserList": [
  671. {
  672. "Value": RecommendInfo['UserName'],
  673. "VerifyUserTicket": RecommendInfo['Ticket'] }
  674. ],
  675. "VerifyContent": "",
  676. "SceneListCount": 1,
  677. "SceneList": [
  678. 33
  679. ],
  680. "skey": self.skey
  681. }
  682. headers = {'content-type': 'application/json; charset=UTF-8'}
  683. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  684. try:
  685. r = self.session.post(url, data=data, headers=headers)
  686. except (ConnectionError, ReadTimeout):
  687. return False
  688. dic = r.json()
  689. return dic['BaseResponse']['Ret'] == 0
  690. def add_groupuser_to_friend_by_uid(self, uid, VerifyContent):
  691. """
  692. 主动向群内人员打招呼,提交添加好友请求
  693. uid-群内人员得uid VerifyContent-好友招呼内容
  694. 慎用此接口!封号后果自负!慎用此接口!封号后果自负!慎用此接口!封号后果自负!
  695. """
  696. if self.is_contact(uid):
  697. return True
  698. url = self.base_uri + '/webwxverifyuser?r='+str(int(time.time()))+'&lang=zh_CN'
  699. params ={
  700. "BaseRequest": self.base_request,
  701. "Opcode": 2,
  702. "VerifyUserListSize": 1,
  703. "VerifyUserList": [
  704. {
  705. "Value": uid,
  706. "VerifyUserTicket": ""
  707. }
  708. ],
  709. "VerifyContent": VerifyContent,
  710. "SceneListCount": 1,
  711. "SceneList": [
  712. 33
  713. ],
  714. "skey": self.skey
  715. }
  716. headers = {'content-type': 'application/json; charset=UTF-8'}
  717. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  718. try:
  719. r = self.session.post(url, data=data, headers=headers)
  720. except (ConnectionError, ReadTimeout):
  721. return False
  722. dic = r.json()
  723. return dic['BaseResponse']['Ret'] == 0
  724. def add_friend_to_group(self,uid,group_name):
  725. """
  726. 将好友加入到群聊中
  727. """
  728. gid = ''
  729. #通过群名获取群id,群没保存到通讯录中的话无法添加哦
  730. for group in self.group_list:
  731. if group['NickName'] == group_name:
  732. gid = group['UserName']
  733. if gid == '':
  734. return False
  735. #通过群id判断uid是否在群中
  736. for user in self.group_members[gid]:
  737. if user['UserName'] == uid:
  738. #已经在群里面了,不用加了
  739. return True
  740. url = self.base_uri + '/webwxupdatechatroom?fun=addmember&pass_ticket=%s' % self.pass_ticket
  741. params ={
  742. "AddMemberList": uid,
  743. "ChatRoomName": gid,
  744. "BaseRequest": self.base_request
  745. }
  746. headers = {'content-type': 'application/json; charset=UTF-8'}
  747. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  748. try:
  749. r = self.session.post(url, data=data, headers=headers)
  750. except (ConnectionError, ReadTimeout):
  751. return False
  752. dic = r.json()
  753. return dic['BaseResponse']['Ret'] == 0
  754. def delete_user_from_group(self,uname,gid):
  755. """
  756. 将群用户从群中剔除,只有群管理员有权限
  757. """
  758. uid = ""
  759. for user in self.group_members[gid]:
  760. if user['NickName'] == uname:
  761. uid = user['UserName']
  762. if uid == "":
  763. return False
  764. url = self.base_uri + '/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % self.pass_ticket
  765. params ={
  766. "DelMemberList": uid,
  767. "ChatRoomName": gid,
  768. "BaseRequest": self.base_request
  769. }
  770. headers = {'content-type': 'application/json; charset=UTF-8'}
  771. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  772. try:
  773. r = self.session.post(url, data=data, headers=headers)
  774. except (ConnectionError, ReadTimeout):
  775. return False
  776. dic = r.json()
  777. return dic['BaseResponse']['Ret'] == 0
  778. def send_msg_by_uid(self, word, dst='filehelper'):
  779. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  780. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  781. word = self.to_unicode(word)
  782. params = {
  783. 'BaseRequest': self.base_request,
  784. 'Msg': {
  785. "Type": 1,
  786. "Content": word,
  787. "FromUserName": self.my_account['UserName'],
  788. "ToUserName": dst,
  789. "LocalID": msg_id,
  790. "ClientMsgId": msg_id
  791. }
  792. }
  793. headers = {'content-type': 'application/json; charset=UTF-8'}
  794. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  795. try:
  796. r = self.session.post(url, data=data, headers=headers)
  797. except (ConnectionError, ReadTimeout):
  798. return False
  799. dic = r.json()
  800. return dic['BaseResponse']['Ret'] == 0
  801. def upload_media(self, fpath, is_img=False):
  802. if not os.path.exists(fpath):
  803. print '[ERROR] File not exists.'
  804. return None
  805. url_1 = 'https://file.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
  806. url_2 = 'https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
  807. flen = str(os.path.getsize(fpath))
  808. ftype = mimetypes.guess_type(fpath)[0] or 'application/octet-stream'
  809. files = {
  810. 'id': (None, 'WU_FILE_%s' % str(self.file_index)),
  811. 'name': (None, os.path.basename(fpath)),
  812. 'type': (None, ftype),
  813. 'lastModifiedDate': (None, time.strftime('%m/%d/%Y, %H:%M:%S GMT+0800 (CST)')),
  814. 'size': (None, flen),
  815. 'mediatype': (None, 'pic' if is_img else 'doc'),
  816. 'uploadmediarequest': (None, json.dumps({
  817. 'BaseRequest': self.base_request,
  818. 'ClientMediaId': int(time.time()),
  819. 'TotalLen': flen,
  820. 'StartPos': 0,
  821. 'DataLen': flen,
  822. 'MediaType': 4,
  823. })),
  824. 'webwx_data_ticket': (None, self.session.cookies['webwx_data_ticket']),
  825. 'pass_ticket': (None, self.pass_ticket),
  826. 'filename': (os.path.basename(fpath), open(fpath, 'rb'),ftype.split('/')[1]),
  827. }
  828. self.file_index += 1
  829. try:
  830. r = self.session.post(url_1, files=files)
  831. if json.loads(r.text)['BaseResponse']['Ret'] != 0:
  832. # 当file返回值不为0时则为上传失败,尝试第二服务器上传
  833. r = self.session.post(url_2, files=files)
  834. if json.loads(r.text)['BaseResponse']['Ret'] != 0:
  835. print '[ERROR] Upload media failure.'
  836. return None
  837. mid = json.loads(r.text)['MediaId']
  838. return mid
  839. except Exception,e:
  840. return None
  841. def send_file_msg_by_uid(self, fpath, uid):
  842. mid = self.upload_media(fpath)
  843. if mid is None or not mid:
  844. return False
  845. url = self.base_uri + '/webwxsendappmsg?fun=async&f=json&pass_ticket=' + self.pass_ticket
  846. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  847. data = {
  848. 'BaseRequest': self.base_request,
  849. 'Msg': {
  850. 'Type': 6,
  851. 'Content': ("<appmsg appid='wxeb7ec651dd0aefa9' sdkver=''><title>%s</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>%s</totallen><attachid>%s</attachid><fileext>%s</fileext></appattach><extinfo></extinfo></appmsg>" % (os.path.basename(fpath).encode('utf-8'), str(os.path.getsize(fpath)), mid, fpath.split('.')[-1])).encode('utf8'),
  852. 'FromUserName': self.my_account['UserName'],
  853. 'ToUserName': uid,
  854. 'LocalID': msg_id,
  855. 'ClientMsgId': msg_id, }, }
  856. try:
  857. r = self.session.post(url, data=json.dumps(data))
  858. res = json.loads(r.text)
  859. if res['BaseResponse']['Ret'] == 0:
  860. return True
  861. else:
  862. return False
  863. except Exception,e:
  864. return False
  865. def send_img_msg_by_uid(self, fpath, uid):
  866. mid = self.upload_media(fpath, is_img=True)
  867. if mid is None:
  868. return False
  869. url = self.base_uri + '/webwxsendmsgimg?fun=async&f=json'
  870. data = {
  871. 'BaseRequest': self.base_request,
  872. 'Msg': {
  873. 'Type': 3,
  874. 'MediaId': mid,
  875. 'FromUserName': self.my_account['UserName'],
  876. 'ToUserName': uid,
  877. 'LocalID': str(time.time() * 1e7),
  878. 'ClientMsgId': str(time.time() * 1e7), }, }
  879. if fpath[-4:] == '.gif':
  880. url = self.base_uri + '/webwxsendemoticon?fun=sys'
  881. data['Msg']['Type'] = 47
  882. data['Msg']['EmojiFlag'] = 2
  883. try:
  884. r = self.session.post(url, data=json.dumps(data))
  885. res = json.loads(r.text)
  886. if res['BaseResponse']['Ret'] == 0:
  887. return True
  888. else:
  889. return False
  890. except Exception,e:
  891. return False
  892. def get_user_id(self, name):
  893. if name == '':
  894. return None
  895. name = self.to_unicode(name)
  896. for contact in self.contact_list:
  897. if 'RemarkName' in contact and contact['RemarkName'] == name:
  898. return contact['UserName']
  899. elif 'NickName' in contact and contact['NickName'] == name:
  900. return contact['UserName']
  901. elif 'DisplayName' in contact and contact['DisplayName'] == name:
  902. return contact['UserName']
  903. for group in self.group_list:
  904. if 'RemarkName' in group and group['RemarkName'] == name:
  905. return group['UserName']
  906. if 'NickName' in group and group['NickName'] == name:
  907. return group['UserName']
  908. if 'DisplayName' in group and group['DisplayName'] == name:
  909. return group['UserName']
  910. return ''
  911. def send_msg(self, name, word, isfile=False):
  912. uid = self.get_user_id(name)
  913. if uid is not None:
  914. if isfile:
  915. with open(word, 'r') as f:
  916. result = True
  917. for line in f.readlines():
  918. line = line.replace('\n', '')
  919. print '-> ' + name + ': ' + line
  920. if self.send_msg_by_uid(line, uid):
  921. pass
  922. else:
  923. result = False
  924. time.sleep(1)
  925. return result
  926. else:
  927. word = self.to_unicode(word)
  928. if self.send_msg_by_uid(word, uid):
  929. return True
  930. else:
  931. return False
  932. else:
  933. if self.DEBUG:
  934. print '[ERROR] This user does not exist .'
  935. return True
  936. @staticmethod
  937. def search_content(key, content, fmat='attr'):
  938. if fmat == 'attr':
  939. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  940. if pm:
  941. return pm.group(1)
  942. elif fmat == 'xml':
  943. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  944. if pm:
  945. return pm.group(1)
  946. return 'unknown'
  947. def get_uuid(self):
  948. url = 'https://login.weixin.qq.com/jslogin'
  949. params = {
  950. 'appid': 'wx782c26e4c19acffb',
  951. 'fun': 'new',
  952. 'lang': 'zh_CN',
  953. '_': int(time.time()) * 1000 + random.randint(1, 999),
  954. }
  955. r = self.session.get(url, params=params)
  956. r.encoding = 'utf-8'
  957. data = r.text
  958. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  959. pm = re.search(regx, data)
  960. if pm:
  961. code = pm.group(1)
  962. self.uuid = pm.group(2)
  963. return code == '200'
  964. return False
  965. def gen_qr_code(self, qr_file_path):
  966. string = 'https://login.weixin.qq.com/l/' + self.uuid
  967. qr = pyqrcode.create(string)
  968. if self.conf['qr'] == 'png':
  969. qr.png(qr_file_path, scale=8)
  970. show_image(qr_file_path)
  971. # img = Image.open(qr_file_path)
  972. # img.show()
  973. elif self.conf['qr'] == 'tty':
  974. print(qr.terminal(quiet_zone=1))
  975. def do_request(self, url):
  976. r = self.session.get(url)
  977. r.encoding = 'utf-8'
  978. data = r.text
  979. param = re.search(r'window.code=(\d+);', data)
  980. code = param.group(1)
  981. return code, data
  982. def wait4login(self):
  983. """
  984. http comet:
  985. tip=1, 等待用户扫描二维码,
  986. 201: scaned
  987. 408: timeout
  988. tip=0, 等待用户确认登录,
  989. 200: confirmed
  990. """
  991. LOGIN_TEMPLATE = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s'
  992. tip = 1
  993. try_later_secs = 1
  994. MAX_RETRY_TIMES = 10
  995. code = UNKONWN
  996. retry_time = MAX_RETRY_TIMES
  997. while retry_time > 0:
  998. url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time()))
  999. code, data = self.do_request(url)
  1000. if code == SCANED:
  1001. print '[INFO] Please confirm to login .'
  1002. tip = 0
  1003. elif code == SUCCESS: # 确认登录成功
  1004. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  1005. redirect_uri = param.group(1) + '&fun=new'
  1006. self.redirect_uri = redirect_uri
  1007. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  1008. return code
  1009. elif code == TIMEOUT:
  1010. print '[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,)
  1011. tip = 1 # 重置
  1012. retry_time -= 1
  1013. time.sleep(try_later_secs)
  1014. else:
  1015. print ('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
  1016. (code, try_later_secs))
  1017. tip = 1
  1018. retry_time -= 1
  1019. time.sleep(try_later_secs)
  1020. return code
  1021. def save_dict_to_file(self, dic, fname):
  1022. with open(os.path.join(self.temp_pwd, fname), 'w') as f:
  1023. f.write(json.dumps(dic))
  1024. def restore_dict_from_file(self, fname):
  1025. with open(os.path.join(self.temp_pwd, fname), 'r') as f:
  1026. fstr = f.read()
  1027. return json.loads(fstr)
  1028. def save_login_result(self):
  1029. result = {}
  1030. result['skey'] = self.skey
  1031. result['sid'] = self.sid
  1032. result['uin'] = self.uin
  1033. result['pass_ticket'] = self.pass_ticket
  1034. result['base_request'] = self.base_request
  1035. result['redirect_uri'] = self.redirect_uri
  1036. result['base_uri'] = self.base_uri
  1037. result['sync_key'] = self.sync_key
  1038. result['sync_key_str'] = self.sync_key_str
  1039. result['my_account'] = self.my_account
  1040. result['sync_host'] = self.sync_host
  1041. with open(os.path.join(self.temp_pwd, "login_result.json"), 'w') as f:
  1042. f.write(json.dumps(result))
  1043. self.save_dict_to_file(self.contact_list, 'contact_list.json')
  1044. self.save_dict_to_file(self.special_list, 'special_list.json')
  1045. self.save_dict_to_file(self.group_list, 'group_list.json')
  1046. self.save_dict_to_file(self.public_list, 'public_list.json')
  1047. self.save_dict_to_file(self.member_list, 'member_list.json')
  1048. self.save_dict_to_file(self.group_members, 'group_members.json')
  1049. self.save_dict_to_file(self.account_info, 'account_info.json')
  1050. self.save_dict_to_file(self.encry_chat_room_id_list, 'encry_chat_room_id_list.json')
  1051. def restore_login_result(self):
  1052. try:
  1053. with open(os.path.join(self.temp_pwd, "login_result.json"), 'r') as f:
  1054. login_str = f.read()
  1055. result = json.loads(login_str)
  1056. self.skey = result['skey']
  1057. self.sid = result['sid']
  1058. self.uin = result['uin']
  1059. self.pass_ticket = result['pass_ticket']
  1060. self.base_request = result['base_request']
  1061. self.redirect_uri = result['redirect_uri']
  1062. self.base_uri = result['base_uri']
  1063. self.sync_key = result['sync_key']
  1064. self.sync_key_str = result['sync_key_str']
  1065. self.my_account = result['my_account']
  1066. self.sync_host = result['sync_host']
  1067. self.contact_list = self.restore_dict_from_file('contact_list.json')
  1068. self.special_list = self.restore_dict_from_file('special_list.json')
  1069. self.group_list = self.restore_dict_from_file('group_list.json')
  1070. self.public_list = self.restore_dict_from_file('public_list.json')
  1071. self.member_list = self.restore_dict_from_file('member_list.json')
  1072. self.group_members = self.restore_dict_from_file('group_members.json')
  1073. self.account_info = self.restore_dict_from_file('account_info.json')
  1074. self.encry_chat_room_id_list = self.restore_dict_from_file('encry_chat_room_id_list.json')
  1075. return True
  1076. except Exception, e:
  1077. print format_exc()
  1078. def login(self):
  1079. if len(self.redirect_uri) < 4:
  1080. print '[ERROR] Login failed due to network problem, please try again.'
  1081. return False
  1082. r = self.session.get(self.redirect_uri)
  1083. r.encoding = 'utf-8'
  1084. data = r.text
  1085. doc = xml.dom.minidom.parseString(data)
  1086. root = doc.documentElement
  1087. for node in root.childNodes:
  1088. if node.nodeName == 'skey':
  1089. self.skey = node.childNodes[0].data
  1090. elif node.nodeName == 'wxsid':
  1091. self.sid = node.childNodes[0].data
  1092. elif node.nodeName == 'wxuin':
  1093. self.uin = node.childNodes[0].data
  1094. elif node.nodeName == 'pass_ticket':
  1095. self.pass_ticket = node.childNodes[0].data
  1096. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  1097. return False
  1098. self.base_request = {
  1099. 'Uin': self.uin,
  1100. 'Sid': self.sid,
  1101. 'Skey': self.skey,
  1102. 'DeviceID': self.device_id,
  1103. }
  1104. return True
  1105. def init(self):
  1106. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  1107. params = {
  1108. 'BaseRequest': self.base_request
  1109. }
  1110. r = self.session.post(url, data=json.dumps(params))
  1111. r.encoding = 'utf-8'
  1112. dic = json.loads(r.text)
  1113. self.sync_key = dic['SyncKey']
  1114. self.my_account = dic['User']
  1115. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  1116. for keyVal in self.sync_key['List']])
  1117. return dic['BaseResponse']['Ret'] == 0
  1118. def status_notify(self):
  1119. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  1120. self.base_request['Uin'] = int(self.base_request['Uin'])
  1121. params = {
  1122. 'BaseRequest': self.base_request,
  1123. "Code": 3,
  1124. "FromUserName": self.my_account['UserName'],
  1125. "ToUserName": self.my_account['UserName'],
  1126. "ClientMsgId": int(time.time())
  1127. }
  1128. r = self.session.post(url, data=json.dumps(params))
  1129. r.encoding = 'utf-8'
  1130. dic = json.loads(r.text)
  1131. return dic['BaseResponse']['Ret'] == 0
  1132. def test_sync_check(self):
  1133. for host in ['webpush', 'webpush2']:
  1134. self.sync_host = host
  1135. retcode = self.sync_check()[0]
  1136. if retcode == '0':
  1137. return True
  1138. return False
  1139. def sync_check(self):
  1140. params = {
  1141. 'r': int(time.time()),
  1142. 'sid': self.sid,
  1143. 'uin': self.uin,
  1144. 'skey': self.skey,
  1145. 'deviceid': self.device_id,
  1146. 'synckey': self.sync_key_str,
  1147. '_': int(time.time()),
  1148. }
  1149. url = 'https://' + self.sync_host + '.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  1150. try:
  1151. r = self.session.get(url, timeout=60)
  1152. r.encoding = 'utf-8'
  1153. data = r.text
  1154. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  1155. retcode = pm.group(1)
  1156. selector = pm.group(2)
  1157. return [retcode, selector]
  1158. except:
  1159. return [-1, -1]
  1160. def sync(self):
  1161. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  1162. % (self.sid, self.skey, self.pass_ticket)
  1163. params = {
  1164. 'BaseRequest': self.base_request,
  1165. 'SyncKey': self.sync_key,
  1166. 'rr': ~int(time.time())
  1167. }
  1168. try:
  1169. r = self.session.post(url, data=json.dumps(params), timeout=60)
  1170. r.encoding = 'utf-8'
  1171. dic = json.loads(r.text)
  1172. if dic['BaseResponse']['Ret'] == 0:
  1173. self.sync_key = dic['SyncKey']
  1174. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  1175. for keyVal in self.sync_key['List']])
  1176. return dic
  1177. except:
  1178. return None
  1179. def get_icon(self, uid, gid=None):
  1180. """
  1181. 获取联系人或者群聊成员头像
  1182. :param uid: 联系人id
  1183. :param gid: 群id,如果为非None获取群中成员头像,如果为None则获取联系人头像
  1184. """
  1185. if gid is None:
  1186. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  1187. else:
  1188. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (
  1189. uid, self.skey, self.encry_chat_room_id_list[gid])
  1190. r = self.session.get(url)
  1191. data = r.content
  1192. fn = 'icon_' + uid + '.jpg'
  1193. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1194. f.write(data)
  1195. return fn
  1196. def get_head_img(self, uid):
  1197. """
  1198. 获取群头像
  1199. :param uid: 群uid
  1200. """
  1201. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  1202. r = self.session.get(url)
  1203. data = r.content
  1204. fn = 'head_' + uid + '.jpg'
  1205. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1206. f.write(data)
  1207. return fn
  1208. def get_msg_img_url(self, msgid):
  1209. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  1210. def get_msg_img(self, msgid):
  1211. """
  1212. 获取图片消息,下载图片到本地
  1213. :param msgid: 消息id
  1214. :return: 保存的本地图片文件路径
  1215. """
  1216. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  1217. r = self.session.get(url)
  1218. data = r.content
  1219. fn = 'img_' + msgid + '.jpg'
  1220. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1221. f.write(data)
  1222. return fn
  1223. def get_voice_url(self, msgid):
  1224. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  1225. def get_voice(self, msgid):
  1226. """
  1227. 获取语音消息,下载语音到本地
  1228. :param msgid: 语音消息id
  1229. :return: 保存的本地语音文件路径
  1230. """
  1231. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  1232. r = self.session.get(url)
  1233. data = r.content
  1234. fn = 'voice_' + msgid + '.mp3'
  1235. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1236. f.write(data)
  1237. return fn
  1238. def set_remark_name(self, uid, name): # 设置联系人的备注名
  1239. url = self.base_uri + '/webwxoplog?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  1240. remark_name = self.to_unicode(name)
  1241. params = {
  1242. 'BaseRequest': self.base_request,
  1243. 'CmdId': 2,
  1244. 'RemarkName': remark_name,
  1245. 'UserName': uid
  1246. }
  1247. try:
  1248. r = self.session.post(url, data=json.dumps(params), timeout=60)
  1249. r.encoding = 'utf-8'
  1250. dic = json.loads(r.text)
  1251. return dic['BaseResponse']['ErrMsg']
  1252. except:
  1253. return None