wxbot.py 58 KB

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