基于python实现通过微信搜索功能查看谁把你删除了

场景:查找who删了我,直接copy代码保存到一个python文件who.py,在python环境下运行此文件

代码如下,copy保存到who.py文件在python环境直接运行:

#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import os
try:
from urllib import urlencode, quote_plus
except importerror:
from urllib.parse import urlencode, quote_plus
try:
import urllib2 as wdf_urllib
from cookielib import cookiejar
except importerror:
import urllib.request as wdf_urllib
from http.cookiejar import cookiejar
import re
import time
import xml.dom.minidom
import json
import sys
import math
import subprocess
import ssl
import thread
debug = false
max_group_num = 35 # 每组人数
interface_calling_interval = 20 # 接口调用时间间隔, 间隔太短容易出现”操作太频繁”, 会被限制操作半小时左右
max_progress_len = 50
qrimagepath = os.path.join(os.getcwd(), ‘qrcode.jpg’)
tip = 0
uuid = ”
base_uri = ”
redirect_uri = ”
push_uri = ”
skey = ”
wxsid = ”
wxuin = ”
pass_ticket = ”
deviceid = ‘e000000000000000’
baserequest = {}
contactlist = []
my = []
synckey = []
try:
xrange
range = xrange
except:
# python 3
pass
def 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 false
return true
def getrequest(url, data=none):
try:
data = data.encode(‘utf-8’)
except:
pass
finally:
return wdf_urllib.request(url=url, data=data)
def getuuid():
global uuid
url = ‘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 == ‘200’:
return true
return false
def showqrimage():
global tip
url = ‘https://login.weixin.qq.com/qrcode/’ + uuid
params = {
‘t’: ‘webwx’,
‘_’: int(time.time()),
}
request = getrequest(url=url, data=urlencode(params))
response = wdf_urllib.urlopen(request)
tip = 1
f = 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(‘请使用微信扫描二维码以登录’)
def waitforlogin():
global tip, base_uri, redirect_uri, push_uri
url = ‘https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uu % (
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’: # 已扫描
print(‘成功扫描,请在手机上点击确认以登录’)
tip = 0
elif code == ‘200’: # 已登录
print(‘正在登录…’)
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与base_uri对应关系(排名分先后)(就是这么奇葩..)
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_uri
for (searchurl, pushurl) in services:
if base_uri.find(searchurl) >= 0:
push_uri = ‘https://%s/cgi-bin/mmwebwx-bin’ % pushurl
break
# closeqrimage
if sys.platform.find(‘darwin’) >= 0: # for osx with preview
os.system(“osascript -e ‘quit app \”preview\”‘”)
elif code == ‘408’: # 超时
pass
# elif code == ‘400’ or code == ‘500’:
return code
def login():
global skey, wxsid, wxuin, pass_ticket, baserequest
request = 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.documentelement
for node in root.childnodes:
if node.nodename == ‘skey’:
skey = node.childnodes[0].data
elif node.nodename == ‘wxsid’:
wxsid = node.childnodes[0].data
elif node.nodename == ‘wxuin’:
wxuin = node.childnodes[0].data
elif node.nodename == ‘pass_ticket’:
pass_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 false
baserequest = {
‘uin’: int(wxuin),
‘sid’: wxsid,
‘skey’: skey,
‘deviceid’: deviceid,
}
return true
def 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, synckey
dic = json.loads(data)
contactlist = dic[‘contactlist’]
my = dic[‘user’]
synckey = dic[‘synckey’]
state = responsestate(‘webwxinit’, dic[‘baseresponse’])
return state
def 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’]
# 倒序遍历,不然删除的时候出问题..
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: # 公众号/服务号
memberlist.remove(member)
elif member[‘username’] in specialusers: # 特殊账号
memberlist.remove(member)
elif member[‘username’].find(‘@@’) != -1: # 群聊
memberlist.remove(member)
elif member[‘username’] == my[‘username’]: # 自己
memberlist.remove(member)
return memberlist
def 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: # 被对方删除了
deletedlist.append(member[‘username’])
elif member[‘memberstatus’] == 3: # 被加入黑名单
blockedlist.append(member[‘username’])
state = responsestate(‘createchatroom’, dic[‘baseresponse’])
return chatroomname, deletedlist, blockedlist
def 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 state
def 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: # 被对方删除了
deletedlist.append(member[‘username’])
elif member[‘memberstatus’] == 3: # 被加入黑名单
blockedlist.append(member[‘username’])
state = responsestate(‘addmember’, dic[‘baseresponse’])
return deletedlist, blockedlist
def synckey():
synckeyitems = [‘%s_%s’ % (item[‘key’], item[‘val’])
for item in synckey[‘list’]]
synckeystr = ‘|’.join(synckeyitems)
return synckeystr
def 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 selector
def webwxsync():
global synckey
url = base_uri + ‘/webwxsync?lang=zh_cn&skey=%s&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 state
def heartbeatloop():
while true:
selector = synccheck()
if selector != ‘0’:
webwxsync()
time.sleep(1)
def main():
try:
ssl._create_default_https_context = ssl._create_unverified_context
opener = 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:
pass
if not getuuid():
print(‘获取uuid失败’)
return
print(‘正在获取二维码图片…’)
showqrimage()
time.sleep(1)
while waitforlogin() != ‘200’:
pass
os.remove(qrimagepath)
if not login():
print(‘登录失败’)
return
if not webwxinit():
print(‘初始化失败’)
return
memberlist = webwxgetcontact()
print(‘开启心跳线程’)
thread.start_new_thread(heartbeatloop, ())
membercount = len(memberlist)
print(‘通讯录共%s位好友’ % membercount)
chatroomname = ”
result = []
d = {}
for member in memberlist:
d[member[‘username’]] = (member[‘nickname’].encode(
‘utf-8’), member[‘remarkname’].encode(‘utf-8’))
print(‘开始查找…’)
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:
break
member = memberlist[i * max_group_num + j]
usernames.append(member[‘username’])
# 新建群组/添加成员
if chatroomname == ”:
(chatroomname, deletedlist, blockedlist) = createchatroom(
usernames)
else:
(deletedlist, blockedlist) = addmember(chatroomname, usernames)
# todo blockedlist 被拉黑列表
deletedcount = len(deletedlist)
if deletedcount > 0:
result += deletedlist
# 删除成员
deletemember(chatroomname, usernames)
# 进度条
progress = max_progress_len * (i + 1) / group_num
print(‘[‘, ‘#’ * progress, ‘-‘ * (max_progress_len – progress), ‘]’, end=’ ‘)
print(‘新发现你被%d人删除’ % deletedcount)
for i in range(deletedcount):
if d[deletedlist[i]][1] != ”:
print(d[deletedlist[i]][0] + ‘(%s)’ % d[deletedlist[i]][1])
else:
print(d[deletedlist[i]][0])
if i != group_num – 1:
print(‘正在继续查找,请耐心等待…’)
# 下一次进行接口调用需要等待的时间
time.sleep(interface_calling_interval)
# todo 删除群组
print(‘\n结果汇总完毕,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(‘———- 被删除的好友列表(共%d人) ———-‘ % len(result))
# 过滤emoji
resultnames = map(lambda x: re.sub(r”, ”, x), resultnames)
if len(resultnames):
print(‘\n’.join(resultnames))
else:
print(“无”)
print(‘———————————————‘)
# windows下编码问题修复
# http://blog.csdn.net/heyuxuanzee/article/details/8442718
class unicodestreamfilter:
def __init__(self, target):
self.target = target
self.encoding = ‘utf-8’
self.errors = ‘replace’
self.encode_to = self.target.encoding
def write(self, s):
if type(s) == str:
s = s.decode(‘utf-8’)
s = s.encode(self.encode_to, self.errors).decode(self.encode_to)
self.target.write(s)
if sys.stdout.encoding == ‘cp936’:
sys.stdout = unicodestreamfilter(sys.stdout)
if __name__ == ‘__main__’:
print(‘本程序的查询结果可能会引起一些心理上的不适,请小心使用…’)
main()
print(‘回车键退出…’)

以上所述是基于python实现微信搜索查看谁把你删除了的相关内容,希望对大家有所帮助。

Posted in 未分类

发表评论