wxbot.py 61 KB

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