wxbot.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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. elif mtype == 43:
  585. msg_content['type'] = 13
  586. msg_content['data'] = self.get_video_url(msg_id)
  587. if self.DEBUG:
  588. print ' %s[video] %s' % (msg_prefix, msg_content['data'])
  589. else:
  590. msg_content['type'] = 99
  591. msg_content['data'] = content
  592. if self.DEBUG:
  593. print ' %s[Unknown]' % msg_prefix
  594. return msg_content
  595. def handle_msg(self, r):
  596. """
  597. 处理原始微信消息的内部函数
  598. msg_type_id:
  599. 0 -> Init
  600. 1 -> Self
  601. 2 -> FileHelper
  602. 3 -> Group
  603. 4 -> Contact
  604. 5 -> Public
  605. 6 -> Special
  606. 99 -> Unknown
  607. :param r: 原始微信消息
  608. """
  609. for msg in r['AddMsgList']:
  610. user = {'id': msg['FromUserName'], 'name': 'unknown'}
  611. if msg['MsgType'] == 51 and msg['StatusNotifyCode'] == 4: # init message
  612. msg_type_id = 0
  613. user['name'] = 'system'
  614. #会获取所有联系人的username 和 wxid,但是会收到3次这个消息,只取第一次
  615. if self.is_big_contact and len(self.full_user_name_list) == 0:
  616. self.full_user_name_list = msg['StatusNotifyUserName'].split(",")
  617. self.wxid_list = re.search(r"username&gt;(.*?)&lt;/username", msg["Content"]).group(1).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(json.dumps(self.wxid_list))
  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. #获取群成员数量并判断邀请方式
  795. group_num=len(self.group_members[gid])
  796. print '[DEBUG] group_name:%s group_num:%s' % (group_name,group_num)
  797. #通过群id判断uid是否在群中
  798. for user in self.group_members[gid]:
  799. if user['UserName'] == uid:
  800. #已经在群里面了,不用加了
  801. return True
  802. if group_num<=100:
  803. url = self.base_uri + '/webwxupdatechatroom?fun=addmember&pass_ticket=%s' % self.pass_ticket
  804. params ={
  805. "AddMemberList": uid,
  806. "ChatRoomName": gid,
  807. "BaseRequest": self.base_request
  808. }
  809. else:
  810. url = self.base_uri + '/webwxupdatechatroom?fun=invitemember'
  811. params ={
  812. "InviteMemberList": uid,
  813. "ChatRoomName": gid,
  814. "BaseRequest": self.base_request
  815. }
  816. headers = {'content-type': 'application/json; charset=UTF-8'}
  817. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  818. try:
  819. r = self.session.post(url, data=data, headers=headers)
  820. except (ConnectionError, ReadTimeout):
  821. return False
  822. dic = r.json()
  823. return dic['BaseResponse']['Ret'] == 0
  824. def invite_friend_to_group(self,uid,group_name):
  825. """
  826. 将好友加入到群中。对人数多的群,需要调用此方法。
  827. 拉人时,可以先尝试使用add_friend_to_group方法,当调用失败(Ret=1)时,再尝试调用此方法。
  828. """
  829. gid = ''
  830. # 通过群名获取群id,群没保存到通讯录中的话无法添加哦
  831. for group in self.group_list:
  832. if group['NickName'] == group_name:
  833. gid = group['UserName']
  834. if gid == '':
  835. return False
  836. # 通过群id判断uid是否在群中
  837. for user in self.group_members[gid]:
  838. if user['UserName'] == uid:
  839. # 已经在群里面了,不用加了
  840. return True
  841. url = self.base_uri + '/webwxupdatechatroom?fun=invitemember&pass_ticket=%s' % self.pass_ticket
  842. params = {
  843. "InviteMemberList": uid,
  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 delete_user_from_group(self,uname,gid):
  856. """
  857. 将群用户从群中剔除,只有群管理员有权限
  858. """
  859. uid = ""
  860. for user in self.group_members[gid]:
  861. if user['NickName'] == uname:
  862. uid = user['UserName']
  863. if uid == "":
  864. return False
  865. url = self.base_uri + '/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % self.pass_ticket
  866. params ={
  867. "DelMemberList": uid,
  868. "ChatRoomName": gid,
  869. "BaseRequest": self.base_request
  870. }
  871. headers = {'content-type': 'application/json; charset=UTF-8'}
  872. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  873. try:
  874. r = self.session.post(url, data=data, headers=headers)
  875. except (ConnectionError, ReadTimeout):
  876. return False
  877. dic = r.json()
  878. return dic['BaseResponse']['Ret'] == 0
  879. def set_group_name(self,gid,gname):
  880. """
  881. 设置群聊名称
  882. """
  883. url = self.base_uri + '/webwxupdatechatroom?fun=modtopic&pass_ticket=%s' % self.pass_ticket
  884. params ={
  885. "NewTopic": gname,
  886. "ChatRoomName": gid,
  887. "BaseRequest": self.base_request
  888. }
  889. headers = {'content-type': 'application/json; charset=UTF-8'}
  890. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  891. try:
  892. r = self.session.post(url, data=data, headers=headers)
  893. except (ConnectionError, ReadTimeout):
  894. return False
  895. dic = r.json()
  896. return dic['BaseResponse']['Ret'] == 0
  897. def send_msg_by_uid(self, word, dst='filehelper'):
  898. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  899. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  900. word = self.to_unicode(word)
  901. params = {
  902. 'BaseRequest': self.base_request,
  903. 'Msg': {
  904. "Type": 1,
  905. "Content": word,
  906. "FromUserName": self.my_account['UserName'],
  907. "ToUserName": dst,
  908. "LocalID": msg_id,
  909. "ClientMsgId": msg_id
  910. }
  911. }
  912. headers = {'content-type': 'application/json; charset=UTF-8'}
  913. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  914. try:
  915. r = self.session.post(url, data=data, headers=headers)
  916. except (ConnectionError, ReadTimeout):
  917. return False
  918. dic = r.json()
  919. return dic['BaseResponse']['Ret'] == 0
  920. def upload_media(self, fpath, is_img=False):
  921. if not os.path.exists(fpath):
  922. print '[ERROR] File not exists.'
  923. return None
  924. url_1 = 'https://file.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
  925. url_2 = 'https://file2.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
  926. flen = str(os.path.getsize(fpath))
  927. ftype = mimetypes.guess_type(fpath)[0] or 'application/octet-stream'
  928. files = {
  929. 'id': (None, 'WU_FILE_%s' % str(self.file_index)),
  930. 'name': (None, os.path.basename(fpath)),
  931. 'type': (None, ftype),
  932. 'lastModifiedDate': (None, time.strftime('%m/%d/%Y, %H:%M:%S GMT+0800 (CST)')),
  933. 'size': (None, flen),
  934. 'mediatype': (None, 'pic' if is_img else 'doc'),
  935. 'uploadmediarequest': (None, json.dumps({
  936. 'BaseRequest': self.base_request,
  937. 'ClientMediaId': int(time.time()),
  938. 'TotalLen': flen,
  939. 'StartPos': 0,
  940. 'DataLen': flen,
  941. 'MediaType': 4,
  942. })),
  943. 'webwx_data_ticket': (None, self.session.cookies['webwx_data_ticket']),
  944. 'pass_ticket': (None, self.pass_ticket),
  945. 'filename': (os.path.basename(fpath), open(fpath, 'rb'),ftype.split('/')[1]),
  946. }
  947. self.file_index += 1
  948. try:
  949. r = self.session.post(url_1, files=files)
  950. if json.loads(r.text)['BaseResponse']['Ret'] != 0:
  951. # 当file返回值不为0时则为上传失败,尝试第二服务器上传
  952. r = self.session.post(url_2, files=files)
  953. if json.loads(r.text)['BaseResponse']['Ret'] != 0:
  954. print '[ERROR] Upload media failure.'
  955. return None
  956. mid = json.loads(r.text)['MediaId']
  957. return mid
  958. except Exception,e:
  959. return None
  960. def send_file_msg_by_uid(self, fpath, uid):
  961. mid = self.upload_media(fpath)
  962. if mid is None or not mid:
  963. return False
  964. url = self.base_uri + '/webwxsendappmsg?fun=async&f=json&pass_ticket=' + self.pass_ticket
  965. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  966. data = {
  967. 'BaseRequest': self.base_request,
  968. 'Msg': {
  969. 'Type': 6,
  970. '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'),
  971. 'FromUserName': self.my_account['UserName'],
  972. 'ToUserName': uid,
  973. 'LocalID': msg_id,
  974. 'ClientMsgId': msg_id, }, }
  975. try:
  976. r = self.session.post(url, data=json.dumps(data))
  977. res = json.loads(r.text)
  978. if res['BaseResponse']['Ret'] == 0:
  979. return True
  980. else:
  981. return False
  982. except Exception,e:
  983. return False
  984. def send_img_msg_by_uid(self, fpath, uid):
  985. mid = self.upload_media(fpath, is_img=True)
  986. if mid is None:
  987. return False
  988. url = self.base_uri + '/webwxsendmsgimg?fun=async&f=json'
  989. data = {
  990. 'BaseRequest': self.base_request,
  991. 'Msg': {
  992. 'Type': 3,
  993. 'MediaId': mid,
  994. 'FromUserName': self.my_account['UserName'],
  995. 'ToUserName': uid,
  996. 'LocalID': str(time.time() * 1e7),
  997. 'ClientMsgId': str(time.time() * 1e7), }, }
  998. if fpath[-4:] == '.gif':
  999. url = self.base_uri + '/webwxsendemoticon?fun=sys'
  1000. data['Msg']['Type'] = 47
  1001. data['Msg']['EmojiFlag'] = 2
  1002. try:
  1003. r = self.session.post(url, data=json.dumps(data))
  1004. res = json.loads(r.text)
  1005. if res['BaseResponse']['Ret'] == 0:
  1006. return True
  1007. else:
  1008. return False
  1009. except Exception,e:
  1010. return False
  1011. def get_user_id(self, name):
  1012. if name == '':
  1013. return None
  1014. name = self.to_unicode(name)
  1015. for contact in self.contact_list:
  1016. if 'RemarkName' in contact and contact['RemarkName'] == name:
  1017. return contact['UserName']
  1018. elif 'NickName' in contact and contact['NickName'] == name:
  1019. return contact['UserName']
  1020. elif 'DisplayName' in contact and contact['DisplayName'] == name:
  1021. return contact['UserName']
  1022. for group in self.group_list:
  1023. if 'RemarkName' in group and group['RemarkName'] == name:
  1024. return group['UserName']
  1025. if 'NickName' in group and group['NickName'] == name:
  1026. return group['UserName']
  1027. if 'DisplayName' in group and group['DisplayName'] == name:
  1028. return group['UserName']
  1029. return ''
  1030. def send_msg(self, name, word, isfile=False):
  1031. uid = self.get_user_id(name)
  1032. if uid is not None:
  1033. if isfile:
  1034. with open(word, 'r') as f:
  1035. result = True
  1036. for line in f.readlines():
  1037. line = line.replace('\n', '')
  1038. print '-> ' + name + ': ' + line
  1039. if self.send_msg_by_uid(line, uid):
  1040. pass
  1041. else:
  1042. result = False
  1043. time.sleep(1)
  1044. return result
  1045. else:
  1046. word = self.to_unicode(word)
  1047. if self.send_msg_by_uid(word, uid):
  1048. return True
  1049. else:
  1050. return False
  1051. else:
  1052. if self.DEBUG:
  1053. print '[ERROR] This user does not exist .'
  1054. return True
  1055. @staticmethod
  1056. def search_content(key, content, fmat='attr'):
  1057. if fmat == 'attr':
  1058. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  1059. if pm:
  1060. return pm.group(1)
  1061. elif fmat == 'xml':
  1062. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  1063. if pm:
  1064. return pm.group(1)
  1065. return 'unknown'
  1066. def run(self):
  1067. self.get_uuid()
  1068. self.gen_qr_code(os.path.join(self.temp_pwd,'wxqr.png'))
  1069. print '[INFO] Please use WeChat to scan the QR code .'
  1070. result = self.wait4login()
  1071. if result != SUCCESS:
  1072. print '[ERROR] Web WeChat login failed. failed code=%s' % (result,)
  1073. return
  1074. if self.login():
  1075. print '[INFO] Web WeChat login succeed .'
  1076. else:
  1077. print '[ERROR] Web WeChat login failed .'
  1078. return
  1079. if self.init():
  1080. print '[INFO] Web WeChat init succeed .'
  1081. else:
  1082. print '[INFO] Web WeChat init failed'
  1083. return
  1084. self.status_notify()
  1085. if self.get_contact():
  1086. print '[INFO] Get %d contacts' % len(self.contact_list)
  1087. print '[INFO] Start to process messages .'
  1088. self.proc_msg()
  1089. def get_uuid(self):
  1090. url = 'https://login.weixin.qq.com/jslogin'
  1091. params = {
  1092. 'appid': 'wx782c26e4c19acffb',
  1093. 'fun': 'new',
  1094. 'lang': 'zh_CN',
  1095. '_': int(time.time()) * 1000 + random.randint(1, 999),
  1096. }
  1097. r = self.session.get(url, params=params)
  1098. r.encoding = 'utf-8'
  1099. data = r.text
  1100. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  1101. pm = re.search(regx, data)
  1102. if pm:
  1103. code = pm.group(1)
  1104. self.uuid = pm.group(2)
  1105. return code == '200'
  1106. return False
  1107. def gen_qr_code(self, qr_file_path):
  1108. string = 'https://login.weixin.qq.com/l/' + self.uuid
  1109. qr = pyqrcode.create(string)
  1110. if self.conf['qr'] == 'png':
  1111. qr.png(qr_file_path, scale=8)
  1112. show_image(qr_file_path)
  1113. # img = Image.open(qr_file_path)
  1114. # img.show()
  1115. elif self.conf['qr'] == 'tty':
  1116. print(qr.terminal(quiet_zone=1))
  1117. def do_request(self, url):
  1118. r = self.session.get(url)
  1119. r.encoding = 'utf-8'
  1120. data = r.text
  1121. param = re.search(r'window.code=(\d+);', data)
  1122. code = param.group(1)
  1123. return code, data
  1124. def wait4login(self):
  1125. """
  1126. http comet:
  1127. tip=1, 等待用户扫描二维码,
  1128. 201: scaned
  1129. 408: timeout
  1130. tip=0, 等待用户确认登录,
  1131. 200: confirmed
  1132. """
  1133. LOGIN_TEMPLATE = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s'
  1134. tip = 1
  1135. try_later_secs = 1
  1136. MAX_RETRY_TIMES = 10
  1137. code = UNKONWN
  1138. retry_time = MAX_RETRY_TIMES
  1139. while retry_time > 0:
  1140. url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time()))
  1141. code, data = self.do_request(url)
  1142. if code == SCANED:
  1143. print '[INFO] Please confirm to login .'
  1144. tip = 0
  1145. elif code == SUCCESS: # 确认登录成功
  1146. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  1147. redirect_uri = param.group(1) + '&fun=new'
  1148. self.redirect_uri = redirect_uri
  1149. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  1150. temp_host = self.base_uri[8:]
  1151. self.base_host = temp_host[:temp_host.find("/")]
  1152. return code
  1153. elif code == TIMEOUT:
  1154. print '[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,)
  1155. tip = 1 # 重置
  1156. retry_time -= 1
  1157. time.sleep(try_later_secs)
  1158. else:
  1159. print ('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
  1160. (code, try_later_secs))
  1161. tip = 1
  1162. retry_time -= 1
  1163. time.sleep(try_later_secs)
  1164. return code
  1165. def login(self):
  1166. if len(self.redirect_uri) < 4:
  1167. print '[ERROR] Login failed due to network problem, please try again.'
  1168. return False
  1169. r = self.session.get(self.redirect_uri)
  1170. r.encoding = 'utf-8'
  1171. data = r.text
  1172. doc = xml.dom.minidom.parseString(data)
  1173. root = doc.documentElement
  1174. for node in root.childNodes:
  1175. if node.nodeName == 'skey':
  1176. self.skey = node.childNodes[0].data
  1177. elif node.nodeName == 'wxsid':
  1178. self.sid = node.childNodes[0].data
  1179. elif node.nodeName == 'wxuin':
  1180. self.uin = node.childNodes[0].data
  1181. elif node.nodeName == 'pass_ticket':
  1182. self.pass_ticket = node.childNodes[0].data
  1183. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  1184. return False
  1185. self.base_request = {
  1186. 'Uin': self.uin,
  1187. 'Sid': self.sid,
  1188. 'Skey': self.skey,
  1189. 'DeviceID': self.device_id,
  1190. }
  1191. return True
  1192. def init(self):
  1193. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  1194. params = {
  1195. 'BaseRequest': self.base_request
  1196. }
  1197. r = self.session.post(url, data=json.dumps(params))
  1198. r.encoding = 'utf-8'
  1199. dic = json.loads(r.text)
  1200. self.sync_key = dic['SyncKey']
  1201. self.my_account = dic['User']
  1202. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  1203. for keyVal in self.sync_key['List']])
  1204. return dic['BaseResponse']['Ret'] == 0
  1205. def status_notify(self):
  1206. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  1207. self.base_request['Uin'] = int(self.base_request['Uin'])
  1208. params = {
  1209. 'BaseRequest': self.base_request,
  1210. "Code": 3,
  1211. "FromUserName": self.my_account['UserName'],
  1212. "ToUserName": self.my_account['UserName'],
  1213. "ClientMsgId": int(time.time())
  1214. }
  1215. r = self.session.post(url, data=json.dumps(params))
  1216. r.encoding = 'utf-8'
  1217. dic = json.loads(r.text)
  1218. return dic['BaseResponse']['Ret'] == 0
  1219. def test_sync_check(self):
  1220. for host1 in ['webpush.', 'webpush2.']:
  1221. self.sync_host = host1+self.base_host
  1222. try:
  1223. retcode = self.sync_check()[0]
  1224. except:
  1225. retcode = -1
  1226. if retcode == '0':
  1227. return True
  1228. return False
  1229. def sync_check(self):
  1230. params = {
  1231. 'r': int(time.time()),
  1232. 'sid': self.sid,
  1233. 'uin': self.uin,
  1234. 'skey': self.skey,
  1235. 'deviceid': self.device_id,
  1236. 'synckey': self.sync_key_str,
  1237. '_': int(time.time()),
  1238. }
  1239. url = 'https://' + self.sync_host + '/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  1240. try:
  1241. r = self.session.get(url, timeout=60)
  1242. r.encoding = 'utf-8'
  1243. data = r.text
  1244. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  1245. retcode = pm.group(1)
  1246. selector = pm.group(2)
  1247. return [retcode, selector]
  1248. except:
  1249. return [-1, -1]
  1250. def sync(self):
  1251. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  1252. % (self.sid, self.skey, self.pass_ticket)
  1253. params = {
  1254. 'BaseRequest': self.base_request,
  1255. 'SyncKey': self.sync_key,
  1256. 'rr': ~int(time.time())
  1257. }
  1258. try:
  1259. r = self.session.post(url, data=json.dumps(params), timeout=60)
  1260. r.encoding = 'utf-8'
  1261. dic = json.loads(r.text)
  1262. if dic['BaseResponse']['Ret'] == 0:
  1263. self.sync_key = dic['SyncKey']
  1264. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  1265. for keyVal in self.sync_key['List']])
  1266. return dic
  1267. except:
  1268. return None
  1269. def get_icon(self, uid, gid=None):
  1270. """
  1271. 获取联系人或者群聊成员头像
  1272. :param uid: 联系人id
  1273. :param gid: 群id,如果为非None获取群中成员头像,如果为None则获取联系人头像
  1274. """
  1275. if gid is None:
  1276. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  1277. else:
  1278. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (
  1279. uid, self.skey, self.encry_chat_room_id_list[gid])
  1280. r = self.session.get(url)
  1281. data = r.content
  1282. fn = 'icon_' + uid + '.jpg'
  1283. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1284. f.write(data)
  1285. return fn
  1286. def get_head_img(self, uid):
  1287. """
  1288. 获取群头像
  1289. :param uid: 群uid
  1290. """
  1291. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  1292. r = self.session.get(url)
  1293. data = r.content
  1294. fn = 'head_' + uid + '.jpg'
  1295. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1296. f.write(data)
  1297. return fn
  1298. def get_msg_img_url(self, msgid):
  1299. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  1300. def get_msg_img(self, msgid):
  1301. """
  1302. 获取图片消息,下载图片到本地
  1303. :param msgid: 消息id
  1304. :return: 保存的本地图片文件路径
  1305. """
  1306. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  1307. r = self.session.get(url)
  1308. data = r.content
  1309. fn = 'img_' + msgid + '.jpg'
  1310. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1311. f.write(data)
  1312. return fn
  1313. def get_voice_url(self, msgid):
  1314. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  1315. def get_voice(self, msgid):
  1316. """
  1317. 获取语音消息,下载语音到本地
  1318. :param msgid: 语音消息id
  1319. :return: 保存的本地语音文件路径
  1320. """
  1321. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  1322. r = self.session.get(url)
  1323. data = r.content
  1324. fn = 'voice_' + msgid + '.mp3'
  1325. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1326. f.write(data)
  1327. return fn
  1328. def get_video_url(self, msgid):
  1329. return self.base_uri + '/webwxgetvideo?msgid=%s&skey=%s' % (msgid, self.skey)
  1330. def get_video(self, msgid):
  1331. """
  1332. 获取视频消息,下载视频到本地
  1333. :param msgid: 视频消息id
  1334. :return: 保存的本地视频文件路径
  1335. """
  1336. url = self.base_uri + '/webwxgetvideo?msgid=%s&skey=%s' % (msgid, self.skey)
  1337. headers = {'Range': 'bytes=0-'}
  1338. r = self.session.get(url, headers=headers)
  1339. data = r.content
  1340. fn = 'video_' + msgid + '.mp4'
  1341. with open(os.path.join(self.temp_pwd,fn), 'wb') as f:
  1342. f.write(data)
  1343. return fn
  1344. def set_remarkname(self,uid,remarkname):#设置联系人的备注名
  1345. url = self.base_uri + '/webwxoplog?lang=zh_CN&pass_ticket=%s' \
  1346. % (self.pass_ticket)
  1347. remarkname = self.to_unicode(remarkname)
  1348. params = {
  1349. 'BaseRequest': self.base_request,
  1350. 'CmdId': 2,
  1351. 'RemarkName': remarkname,
  1352. 'UserName': uid
  1353. }
  1354. try:
  1355. r = self.session.post(url, data=json.dumps(params), timeout=60)
  1356. r.encoding = 'utf-8'
  1357. dic = json.loads(r.text)
  1358. return dic['BaseResponse']['ErrMsg']
  1359. except:
  1360. return None