当前位置:首页 >> 脚本专栏

python模仿网页版微信发送消息功能

这个微信版网页版虽然繁琐,但是不是很难,全程不带加密的。有兴趣的可以试着玩一玩,如果有兴趣的话,可以完善一下,做一些比较有意思的东西。

开发环境:Windows10
开发语言:Python3.6
开发工具:pycharm
抓包工具:fiddler

抓的包如下:

python模仿网页版微信发送消息功能

import requests
import time
import re
from bs4 import BeautifulSoup
import json
import random
from copyheaders import headers_raw_to_dict
DEFAULT_HEADERS={
  b'Host': b'wx.qq.com',
  b'Connection': b'keep-alive',
  b'Cache-Control': b'max-age=0',
  b'User-Agent': b'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
  b'Upgrade-Insecure-Requests': b'1',
  b'Accept': b'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  b'Accept-Language': b'zh-CN,zh;q=0.9',
  }
def get_13_time():
  return str(int(time.time()*1000))
class WXRobot(object):
  def __init__(self):
    self.s = requests.session()
    self.s.verify = False
    self.s.headers = DEFAULT_HEADERS
    self.DeviceID='e'+str(random.random())[2:17]
  def visit_index(self):
    url = 'https://wx.qq.com/'
    self.s.get(url)

  def visit_jslogin(self):
    url='https://login.wx.qq.com/jslogin"(.*";',text)[0]
    uuid=str(maths)
    self.uuid=uuid
  def visit_vcode(self):
    #获取验证码
    url='https://login.weixin.qq.com/qrcode/{}'.format(self.uuid)
    r=self.s.get(url)

    with open('qrcode.jpg','wb') as f:
      f.write(r.content)
      f.flush()
      f.close()
      print('等待扫描验证码。。。')
  def visit_login(self):
    url='https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login"(.*"''', text)[0]
      self.redirect_uri=maths
      print('redirect_uri获取完成...',self.redirect_uri)

  #得到一些关键字
  def visit_newloginpage(self):
    r=self.s.get(self.redirect_uri,allow_redirects=False)
    text=r.text
    bs=BeautifulSoup(text,'lxml')
    self.skey = bs.find('skey').text
    self.wxsid = bs.find('wxsid').text
    self.wxuin = bs.find('wxuin').text
    self.pass_ticket = bs.find('pass_ticket').text
    self.isgrayscale = bs.find('isgrayscale').text
    # print(self.skey,self.wxsid,self.wxuin,self.pass_ticket)


  #得到初始化信息
  def visit_webwxinit(self):
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit"BaseRequest":{"Uin":self.wxuin ,"Sid":self.wxsid,"Skey":self.skey,"DeviceID":self.DeviceID}
    }
    r=self.s.post(url,json=data)
    r.encoding='utf-8'

    jsontext=r.json()
    # =json.loads(text)
    print('登录用户为:',jsontext["User"]["NickName"])
    self.FromUserName=jsontext["User"]["UserName"]
    self.group_list=jsontext['ContactList'] #
    SyncKey=jsontext["SyncKey"]["List"]
    ChatSet=jsontext["ChatSet"]
    ChatSetlist=str(ChatSet).split(',')
    self.ChatSet =[{"UserName":name ,"EncryChatRoomId":""} for name in ChatSetlist if name.startswith('@')]


  def visit_notify(self):
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxstatusnotify"BaseRequest": {"Uin": self.wxuin, "Sid": self.wxsid,
               "Skey": self.skey,
               "DeviceID": self.DeviceID},
      "Code": 3,
      "FromUserName": self.FromUserName,
      "ToUserName": self.FromUserName,
      "ClientMsgId": int(get_13_time())
    }
    r=self.s.post(url=url,json=data)
    r.encoding='utf-8'
    self.MsgID=r.json()['MsgID']
    print(r.json()['MsgID'],'消息id')
  #获取所有好友列表
  def getcontact(self):
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact"MemberList"]
    for name in self.MemberList:
      print(name['NickName'],name['UserName'])

  # 聊天列表
  def batchgetcontact(self):
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact"BaseRequest": {"Uin":self.wxuin,
               "Sid": self.wxsid,
               "Skey": self.skey,
               "DeviceID": self.DeviceID},
       "Count": len(self.ChatSet),
       "List": self.ChatSet
       }
    r=self.s.post(url=url,json=data)
    r.encoding='utf-8'
    ContactList=r.json()["ContactList"]
    for i in ContactList:
      print('聊天窗口----',i.get('NickName'))

  def get_local(self):
    return str(time.time())+str(random.random())[2:9]
  def send_msg(self):

    ToUserName=input('你要发送给谁?')
    msg = input('请输入你要发送的信息内容')
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg"BaseRequest": {"Uin":self.wxuin,
               "Sid": self.wxsid,
               "Skey": self.skey,
               "DeviceID": self.DeviceID},
      "Msg": {"Type": 1,
          "Content": msg,
          "FromUserName": self.FromUserName,
          "ToUserName": ToUserName,
          "LocalID": self.get_local(),
          "ClientMsgId": self.get_local()
          },
      "Scene": 0
    }
    r=self.s.post(url=url,json=data)
    json_data=r.json()
    if 0 == json_data['BaseResponse']['Ret']:
      print('消息发送成功')
    else:
      print('消息发送失败')
if __name__ == '__main__':
  wx=WXRobot()
  wx.visit_index()
  wx.visit_jslogin()
  wx.visit_vcode()
  wx.visit_login()
  wx.visit_newloginpage()
  wx.visit_webwxinit()
  wx.visit_notify()
  wx.getcontact()
  wx.batchgetcontact()
  while True:
    wx.send_msg()
  # wx.x() #心跳包
  # time.sleep(50)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。