python利用微信订阅号报警

利用python模拟登录到微信公众平台订阅号,给用户列表中的用户发送微信。

说明:用户列表中的每个用户都有一个tofakeid,为微信用户的唯一标识,本来是做一个微信报警的,可是腾讯没有对外提供这方面的接口,这样模拟登录的话也有一个48小时的互动时间的限制。学习爬虫的时候试着写的。

# coding=utf-8
import urllib
import urllib2
import cookielib
import json
import sys
data={'username':'yaokuaile-99',
      'pwd':'f4bb2d8abe7a799ad62495a912ae3363',
      'imgcode':'',
      'f':'json'
      }
cj=cookielib.LWPCookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
def getToken():
    headers = {'Accept': 'application/json, text/javascript, */*; q=0.01',
               'Accept-Encoding': 'gzip,deflate,sdch',
               'Accept-Language': 'zh-CN,zh;q=0.8',
               'Connection': 'keep-alive',
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
               'Content-Length': '74',
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
               'Host': 'mp.weixin.qq.com',
               'Origin': 'https://mp.weixin.qq.com',
               'Referer': 'https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36',
               'X-Requested-With': 'XMLHttpRequest',
              }
    req = urllib2.Request('https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN',urllib.urlencode(data),headers)
    ret = urllib2.urlopen(req)
    retread= ret.read()
    token = json.loads(retread)
    token=token['redirect_url'][44:]
    return token
### send msg
def sendWeixin(msg,token,tofakeid):
    msg = msg
    token = token
    data1 = {'type':'1','content':msg,'imgcode':'','imgcode':'','tofakeid':tofakeid,'f':'json','token':token,'ajax':'1'}
    headers = {'Accept':'*/*',
               'Accept-Encoding': 'gzip,deflate,sdch',
               'Accept-Language': 'zh-CN,zh;q=0.8',
               'Connection': 'keep-alive',
               'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
               'Host': 'mp.weixin.qq.com',
               'Origin': 'https://mp.weixin.qq.com',
               'Referer': 'https://mp.weixin.qq.com/cgi-bin/singlemsgpage?msgid=&source=&count=20&t=wxm-singlechat&fromfakeid=150890&token=%s&lang=zh_CN',
               'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36',
               'X-Requested-With':'XMLHttpRequest',
               }
    req2 = urllib2.Request('https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&lang=zh_CN',urllib.urlencode(data1),headers)
    ret2=urllib2.urlopen(req2)

if __name__=='__main__':
    '''
    useage: ./send_wx.py msg
    '''
    token = getToken()
    msg = sys.argv[1:]
    msg = '\n'.join(msg)
    tofakeid = '2443746922'
    sendWeixin(msg, token, tofakeid)

运行:python send_wx.py msg


你可能感兴趣的:(JavaScript,python,用户)