wxbot.py 59 KB

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