Python-based implementation of WeChat search function to see who deleted you.

Source: Internet
Author: User
Tags uuid
Scenario: Find who deleted me, direct copy code saved to a Python file who.py, run this file in a Python environment

The code below, copy saved to the who.py file runs directly in the Python environment:

#!/usr/bin/env python# coding=utf-8from __future__ import print_functionimport ostry:from urllib import urlencode, quote _plusexcept importerror:from urllib.parse Import UrlEncode, Quote_plustry:import urllib2 as Wdf_urllibfrom cookielib Import cookiejarexcept importerror:import urllib.request as wdf_urllibfrom http.cookiejar import CookieJarimport Reimport timeimport xml.dom.minidomimport jsonimport sysimport mathimport subprocessimport sslimport threaddebug = Falsemax_group_num = 35 # per Group of people interface_calling_interval = 20 # interface call interval, interval too short easy to appear "operation too often", will be limited operation of about half an hour Max_progress_len = 5 0QRImagePath = Os.path.join (OS.GETCWD (), ' qrcode.jpg ') tip = 0uuid = ' Base_uri = ' Redirect_uri = ' Push_uri = ' Skey = ' Wxsid = ' Wxuin = ' Pass_ticket = ' deviceId = ' e000000000000000 ' baserequest = {}contactlist = []my = []synckey = []TRY:XR] Angerange = xrangeexcept:# python 3passdef responsestate (func, baseresponse): ErrMsg = baseresponse[' errmsg ']ret = baseresponse[' ret ']if DEBUG or Ret! = 0:print (' Func:%s, Ret:%d, errmsg:%s '% (func, Ret, errmsg)) if Ret! = 0:return falsereturn truedef getrequest (URL, data=none): Try:data = Data.encode (' Utf-8 ') Except:passfinally:return wdf_urllib. Request (Url=url, Data=data) def getuuid (): Global uuidurl = ' https://login.weixin.qq.com/jslogin ' params = {' AppID ': ' WX782C26E4C19ACFFB ', ' fun ': ' new ', ' Lang ': ' Zh_cn ', ' _ ': Int (Time.time ()),}request = Getrequest (Url=url, Data=urlencode (params)) Response = Wdf_urllib.urlopen (request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # print (data) # window. Qrlogin.code = 200; Window. Qrlogin.uuid = "ozwt_bffrg=="; regx = R ' window. Qrlogin.code = (\d+); Window. Qrlogin.uuid = "(\s+?)" PM = Re.search (regx, data) code = Pm.group (1) uuid = Pm.group (2) if code = = ' $ ': return Truereturn falsedef showqrimage (): GL Obal tipurl = ' https://login.weixin.qq.com/qrcode/' + uuidparams = {' t ': ' WEBWX ', ' _ ': Int (Time.time ()),}request = getrequ EST (url=url, Data=urlencode (params)) response = Wdf_urllib.urlopen (request) tip = 1f = open (Qrimagepath,' WB ') F.write (Response.read ()) F.close () If Sys.platform.find (' Darwin ') >= 0:subprocess.call ([' Open ', Qrimagepath] ) elif sys.platform.find (' Linux ') >= 0:subprocess.call ([' Xdg-open ', Qrimagepath]) else:os.startfile (Qrimagepath) Print (' Please use scan QR code to log in ') def waitforlogin (): Global tip, Base_uri, redirect_uri, Push_uriurl = ' https://login.weixin.qq.com /cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s '% (tip, uuid, int (time.time ())) request = Getrequest (Url=url) Response = Wdf_urllib.urlopen (request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # print (data) # window.code=500 ; regx = R ' window.code= (\d+); ' PM = Re.search (regx, data) code = Pm.group (1) If code = = ' 201 ': # Scanned print (' Successful scan, please click on Phone to confirm to login ') tip = 0elif Code = = ' 200 ': # Logged in print (' Logging in ... ') regx = R ' window.redirect_uri= "(\s+?)"; PM = Re.search (regx, data) Redirect_uri = Pm.group (1) + ' &fun=new ' Base_uri = Redirect_uri[:redirect_uri.rfind ('/')]# Push_uri and Base_uri correspondence (ranking in order) (it is so wonderful ...) Services = [(' Wx2.qq.com ', ' webpush2.weixin.qq.com '), (' QQ.com ', ' webpush.weixin.qq.com '), (' web1.wechat.com ', ' webpush1.wechat.com '), (' web2.wechat.com ', ' Webpush2.wechat.com '), (' wechat.com ', ' webpush.wechat.com '), (' web1.wechatapp.com ', ' webpush1.wechatapp.com '),] Push_uri = Base_urifor (Searchurl, Pushurl) in Services:if base_uri.find (searchurl) >= 0:push_uri = ' Https://%s/cgi-bi N/mmwebwx-bin '% pushurlbreak# closeqrimageif sys.platform.find (' Darwin ') >= 0: # for OSX with Previewos.system ("Osasc Ript-e ' quit app \ ' preview\ ' ' ") elif code = = ' 408 ': # timeout pass# elif Code = = ' + ' or code = = '": Return codedef Login (): g Lobal Skey, Wxsid, Wxuin, pass_ticket, baserequestrequest = getrequest (url=redirect_uri) response = Wdf_urllib.urlopen ( Request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # print (data) doc = xml.dom.minidom.parseString (data) root = Doc.documentelementfor node in root.childNodes:if node.nodename = = ' Skey ': Skey = Node.childnodes[0].dataelif Node.nodename = = ' Wxsid ': wxsid = node.childnodes[0].dataelif Node.nodename = = ' Wxuin ': wXuin = Node.childnodes[0].dataelif Node.nodename = = ' Pass_ticket ':p ass_ticket = node.childnodes[0].data# print (' Skey:% S, Wxsid:%s, Wxuin:%s, Pass_ticket:%s '% (Skey, wxsid,# Wxuin, pass_ticket)) if not all ((Skey, Wxsid, Wxuin, Pass_ticket ): Return falsebaserequest = {' Uin ': Int (Wxuin), ' Sid ': wxsid, ' Skey ': Skey, ' DeviceID ': Deviceid,}return truedef Webwxinit (): url = base_uri + \ '/webwxinit?pass_ticket=%s&skey=%s&r=%s '% (Pass_ticket, skey, int (Time.time ())) params = {' Baserequest ': baserequest}request = Getrequest (Url=url, Data=json.dumps (params)) Request.add_header (' ContentType ', ' Application/json; Charset=utf-8 ') response = Wdf_urllib.urlopen (request) data = Response.read () If debug:f = Open (Os.path.join (OS.GETCWD () , ' Webwxinit.json '), ' WB ') f.write (data) f.close () data = Data.decode (' utf-8 ', ' replace ') # Print (data) global contactlist , My, synckeydic = json.loads (data) contactlist = dic[' contactlist ']my = dic[' User ']synckey = dic[' synckey ']state = respons EState (' Webwxinit ', dic[' baserEsponse ']) return statedef webwxgetcontact (): url = base_uri + \ '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s ' % (Pass_ticket, skey, int (Time.time ())) request = Getrequest (Url=url) request.add_header (' ContentType ', ' application/ Json Charset=utf-8 ') response = Wdf_urllib.urlopen (request) data = Response.read () If debug:f = Open (Os.path.join (OS.GETCWD () , ' Webwxgetcontact.json '), ' WB ') f.write (data) f.close () # Print (data) data = Data.decode (' utf-8 ', ' replace ') dic = Json.loads (data) memberlist = dic[' memberlist ']# the reverse traversal, or delete the time of the problem. Specialusers = ["Newsapp", "Fmessage", "Filehelper", "Weibo", "Qqmail", "Tmessage", "Qmessage", "Qqsync", "Floatbottle", "Lbsapp", "Shakeapp", "Medianote", "Qqfriend", "Readerapp", "Blogapp", "Facebookapp", "Masssendapp", "Meishiapp", " Feedsapp "," VoIP "," Blogappweixin "," Weixin "," Brandsessionholder "," Weixinreminder "," wxid_novlwrv3lqwv11 "," Gh_ 22b87fa7cb3c "," officialaccounts "," Notification_messages "," Wxitil "," Userexperience_alarm "]for I in range (Len ( MemberlisT)-1,-1,-1): Member = memberlist[i]if member[' Verifyflag '] & 8! = 0: # Public number/service number Memberlist.remove (Member) elif member[ ' UserName '] in Specialusers: # Special Account Memberlist.remove (Member) elif member[' UserName '].find (' @@ ')! =-1: # Group chat memberlist.remove (Member) elif member[' UserName '] = = my[' UserName ']: # own Memberlist.remove (Member) return Memberlistdef Createchatroom (UserNames): Memberlist = [{' UserName ': UserName} for UserName in usernames]url = Base_uri + \ ' /webwxcreatechatroom?pass_ticket=%s&r=%s '% (pass_ticket, int (Time.time ())) params = {' Baserequest ': BaseRequest, ' MemberCount ': Len (memberlist), ' memberlist ': memberlist, ' Topic ': ',}request = Getrequest (Url=url, Data=json.dumps ( params)) Request.add_header (' ContentType ', ' Application/json; Charset=utf-8 ') response = Wdf_urllib.urlopen (Request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # Print (data) dic = json.loads (data) Chatroomname = dic[' Chatroomname '] Memberlist = dic[' memberlist ']deletedlist = []blockedlist = []for Member in MemberlIst:if member[' memberstatus '] = = 4: # was deleted by the other deletedlist.append (member[' UserName ']) elif member[' memberstatus '] = = 3: # Added blacklist blockedlist.append (member[' UserName ')) state = ResponseState (' createchatroom ', dic[' Baseresponse ') return Chatroomname, Deletedlist, Blockedlistdef deletemember (Chatroomname, UserNames): url = base_uri + \ '/ webwxupdatechatroom?fun=delmember&pass_ticket=%s '% (pass_ticket) params = {' Baserequest ': baserequest, ' Chatroomname ': chatroomname, ' delmemberlist ': ', '. Join (UserNames),}request = Getrequest (Url=url, Data=json.dumps ( params)) Request.add_header (' ContentType ', ' Application/json; Charset=utf-8 ') response = Wdf_urllib.urlopen (Request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # Print (data) dic = json.loads (data) state = ResponseState (' Deletemember ', dic[' Baseresponse ']) return statedef addmember (Chatroomname, UserNames): url = base_uri + \ '/ webwxupdatechatroom?fun=addmember&pass_ticket=%s '% (pass_ticket) params = {' Baserequest ': baserequest, ' Chatroomname ': ChaTroomname, ' addmemberlist ': ', '. Join (UserNames),}request = Getrequest (Url=url, Data=json.dumps (params)) request.add_ Header (' ContentType ', ' Application/json; Charset=utf-8 ') response = Wdf_urllib.urlopen (request) data = Response.read () . Decode (' Utf-8 ', ' replace ') # Print (data) dic = json.loads (data) memberlist = dic[' memberlist ']deletedlist = [] Blockedlist = []for Member in Memberlist:if member[' memberstatus '] = = 4: # was deleted by the other deletedlist.append (member[' UserName ') Elif member[' memberstatus '] = = 3: # is blacklisted blockedlist.append (member[' UserName ']) state = ResponseState (' AddMember ', dic [' Baseresponse ']) Return deletedlist, Blockedlistdef Synckey (): Synckeyitems = ['%s_%s '% (item[' Key '], item[' Val ')) for item in synckey[' Lis T ']]synckeystr = ' | '. Join (Synckeyitems) return synckeystrdef synccheck (): url = push_uri + '/synccheck? ' params = {' Skey ': baserequest[' skey '], ' sid ': baserequest[' Sid '], ' uin ': baserequest[' UIn '], ' deviceId ': baserequest[' DeviceID '], ' Synckey ': Synckey (), ' R ': Int (Time.time ()),}request = GetreQuest (Url=url + UrlEncode (params)) response = Wdf_urllib.urlopen (request) data = Response.read (). Decode (' Utf-8 ', ' Replace ') # print (data) # Window.synccheck={retcode: "0", selector: "2"}regx = R ' Window.synccheck={retcode: "(\d+)", Selector: "(\d+)"} ' PM = Re.search (regx, data) Retcode = Pm.group (1) selector = Pm.group (2) return Selectordef Webwxsync (): Global Synckeyurl = Base_uri + '/webwxsync?lang=zh_cn&skey=%s&sid=%s&pass_ticket=%s '% (BaseRequest[' Skey '], baserequest[' Sid '], Quote_plus (pass_ticket)) params = {' Baserequest ': baserequest, ' Synckey ': Synckey, ' RR ': ~ Int (Time.time ()),}request = Getrequest (Url=url, Data=json.dumps (params)) Request.add_header (' ContentType ', ' Application/json; Charset=utf-8 ') response = Wdf_urllib.urlopen (request) data = Response.read (). Decode (' Utf-8 ', ' replace ') # Print (data) DIC = json.loads (data) Synckey = dic[' synckey ']state = responsestate (' Webwxsync ', dic[' Baseresponse ')) return statedef Heartbeatloop (): While true:selector = Synccheck () if selector! = ' 0 ': webwxsyNC () Time.sleep (1) def main (): Try:ssl._create_default_https_context = Ssl._create_unverified_contextopener = Wdf_ Urllib.build_opener (Wdf_urllib. Httpcookieprocessor (Cookiejar ())) opener.addheaders = [(' User-agent ', ' mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) applewebkit/537.36 (khtml, like Gecko) chrome/44.0.2403.125 safari/537.36 ')]wdf_urllib.install_ Opener (opener) Except:passif not Getuuid ():p rint (' Get UUID failed ') Returnprint (' Getting a QR code picture ... ') showqrimage () time.sleep (1) While Waitforlogin ()! = ':p assos.remove (qrimagepath) if not login ():p rint (' Login failed ') returnif not Webwxinit ():p rint (' Initialization failed ') Returnmemberlist = Webwxgetcontact () print (' Open heartbeat Thread ') Thread.start_new_thread (Heartbeatloop, ()) MemberCount = Len (memberlist) print (' Contacts total%s friends '% MemberCount) chatroomname = ' result = []d = {}for Member in memberlist:d[member[' UserN Ame ']] = (member[' nickname '].encode (' Utf-8 '), member[' Remarkname '].encode (' Utf-8 ')) print (' Start find ... ') group_num = Int ( Math.ceil (Membercount/float (Max_group_num))) for I in range (0, GroUp_num): UserNames = []for j in range (0, max_group_num): If I * max_group_num + j >= membercount:breakmember = Memberlist [I * max_group_num + j] Usernames.append (member[' UserName ') # New Group/Add member if Chatroomname = = ':(Chatroomname, deletedlist, blockedlist) = Createchatroom (UserNames) Else: (deletedlist, blockedlist) = AddMember (Chatroomname, UserNames) # Todo Blockedlist List of Deletedcount = Len (deletedlist) if deletedcount > 0:result + = deletedlist# Delete member Deletemember (Chatroomname, UserNames) # progress bar PROGRESS = Max_progress_len * (i + 1)/Group_numprint (' [', ' # ' * PROGRESS, '-' * (max_progress_len-progr ESS), '] ', end= ') print (' New found you were deleted by%d '% deletedcount) for I in Range (Deletedcount): if d[deletedlist[i]][1]! = ":p rint (d[d Eletedlist[i]][0] + ' (%s) '% d[deletedlist[i]][1]) Else:print (d[deletedlist[i]][0]) if I! = Group_num-1:print (' Continuing to find, Please be patient ... ') # The next time an interface call takes to wait Time.sleep (interface_calling_interval) # TODO Delete group print (' \ n result summary completed, can retry after 20s ... ') Resultnames = []for R in Result:if d[r][1]! = ": ResUltnames.append (D[r][0] + ' (%s) '% d[r][1]) else:resultNames.append (d[r][0]) print ('----------deleted friends List (total%d people)-------- --'% len (result) # filter emojiresultnames = map (lambda x:re.sub (R ')
 
  
   ', ', X), resultnames) If Len (resultnames):p rint (' \ n '. Join (Resultnames)) Else:print ("None") print ('---------------- -----------------------------') # Windows encoding bug fix # Http://blog.csdn.net/heyuxuanzee/article/details/8442718class Unicodestreamfilter:def __init__ (self, target): Self.target = targetself.encoding = ' utf-8 ' self.errors = ' replace ' self. Encode_to = Self.target.encodingdef write (self, s): if type (s) = = Str:s = S.decode (' utf-8 ') s = S.encode (self.encode_to, SEL f.errors). Decode (self.encode_to) Self.target.write (s) if sys.stdout.encoding = = ' cp936 ': sys.stdout = Unicodestreamfilter (sys.stdout) if __name__ = = ' __main__ ':p rint (' The results of this program may cause some psychological discomfort, please be careful to use ... ') "Main () print (' Enter to exit ... ')
  
 

The above is based on Python implementation of the search to see who has deleted you the relevant content, I hope to help you.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.