python实现微信提醒({“errcode”:41011,”errmsg”:”missing agentid”})

来源:互联网 发布:小满科技 数据怎么样 编辑:程序博客网 时间:2024/04/30 18:07
data = {   "touser": "monitor",   "toparty": "2",   "msgtype": "text",   "agentid": "1",   "text": {       "content": "test"   },   "safe":"0"}

post的数据格式我是这样写的
用的python3,原来是这样进行格式化的

post_data=urllib.parse.urlencode(data).encode(encoding='UTF8');

得到的post数据格式是这样的

b'text=%7B%27content%27%3A+%27test%27%7D&touser=monitor&safe=0&toparty=2&msgtype=text&agentid=1'

提交后就报错了

{“errcode”:41011,”errmsg”:”missing agentid”}

百度查后,有网友说必须是json格式,
然后我这样格式化

jdata = json.dumps(data).encode('UTF-8')

得到的数据是这样的

b'{"text": {"content": "test"}, "touser": "monitor", "safe": "0", "toparty": "2", "msgtype": "text", "agentid": "1"}'

这样就好了

上个完整版的

import http.cookiejarimport urllib.requestimport jsonclass sendMessage():    def __init__(self):        self.cookieJar = http.cookiejar.LWPCookieJar()         opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookieJar))        urllib.request.install_opener(opener)    def sendMessage(self,user,message):        getTokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx099c76afef3d1d6c&corpsecret=JDzPP2w7O1ijqV5WOrIHBB717Cii2Ln_ALjdvKIgb0UKU_mvNKqKmntP-nw28pHW"        request = urllib.request.Request(getTokenUrl)        request = urllib.request.urlopen(request)        pageHtml = request.read().decode('UTF-8')        token=pageHtml.split('"')[3]        request.close()        data = {   "touser": user,   "toparty": "2",   "msgtype": "text",   "agentid": "1",   "text": {       "content": message   },   "safe":"0"}        #data = "{   'touser': 'monitor',   'toparty': '2',   'msgtype': 'text',   'agentid': 1,   'text': {       'content': 'test send message' },   'safe':'0'}"        url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token        header = {'Content-Type':'application/x-www-form-urlencoded','charset':'utf-8'}        jdata = json.dumps(data).encode('UTF-8')        request = urllib.request.Request(url,data=jdata,headers=header)        request = urllib.request.urlopen(request)        pageHtml = request.read().decode('UTF-8')        print(pageHtml)        request.close()if __name__ == '__main__':    up = sendMessage();    up.sendMessage("monitor","test")
1 0