wxbot.py 60 KB

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