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

发布时间:2020-10-25 12:03:51 作者:赵韶晖_
来源:脚本之家 阅读:207

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

开发环境: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?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_={}'.format(get_13_time())
    r=self.s.get(url)
    text=r.text
    maths=re.findall(r'window.QRLogin.code = 200; window.QRLogin.uuid = "(.*?)";',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?loginicon=true&uuid={}&tip=0&_={}'.format(self.uuid,get_13_time())
    r=self.s.get(url)
    text=r.text
    code=re.findall(r'''window.code=(.*?);''',text)[0]
    # print('获取状态码', code)
    if str(code)!='200':
      # print('两秒后重新调用')
      time.sleep(2)
      self.visit_login()
    elif str(code)=='200':
      maths = re.findall(r'''redirect_uri="(.*?)"''', 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?pass_ticket={}'.format(self.pass_ticket)
    data={
      "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?pass_ticket={}'.format(self.pass_ticket)
    data={
      "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?pass_ticket={}&r={}&seq=0&skey=@{}'.format(self.pass_ticket,get_13_time(),self.skey)
    r=self.s.get(url)
    r.encoding='utf=8'
    contactjson=r.json()
    # print(contactjson)
    self.MemberList=contactjson["MemberList"]
    for name in self.MemberList:
      print(name['NickName'],name['UserName'])

  # 聊天列表
  def batchgetcontact(self):
    url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r={}&pass_ticket={}'.format(get_13_time(),self.pass_ticket)
    data={
      "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?pass_ticket={}'.format(self.pass_ticket)
    data={
      "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)

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

推荐阅读:
  1. 微信网页授权
  2. 微信小程序实现蒙版弹出窗功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 发送消息

上一篇:微信网页开发如何完成签名校验

下一篇:Linux使用NetworkManager随机生成你的MAC地址

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》