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

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.cookiejar
import urllib.request
import json
class 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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bwlab

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值