wxbot.py 56 KB

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