当前位置: 首页 > 科技观察

仅需三步,如何用Python给微信发送通知?

时间:2023-03-20 15:29:45 科技观察

1.通知方式有哪些?大家好,我是菜鸟小弟。常见的通知方式有:邮件、电话、短信、微信。短信和电话:通常收费,很少使用;email:适合文件类的通知,比较正式,有存档性;微信:适合报警类通知,更方便。这里所说的微信是企业微信。本文目的:通过企业微信应用向企业会员发送消息。2、如何实现企业微信通知?1、新建应用,登录网页版企业微信(https://work.weixin.qq.com),点击应用管理→应用→创建应用上传应用logo,进入应用名称(新债券),然后选择可见范围。成功创建报警应用2.获取Secret使用Python发送报警请求。其实只用到两个接口:获取Token:https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}发送请求:https://qyapi.weixin...就会知道你要发送corpid给哪个企业的应用。您可以通过我的企业→企业信息→企业ID获取秘钥。可以点击新建的应用(Newbond)→查看secret→发送获取,最后在下面的常量中填写corporateid和secret。3.代码实现importjsonimporttimeimportrequests'''本文档主要实现通过企业微信应用向企业会员发送消息'''CORP_ID="xxxx"SECRET="xxxx"classWeChatPub:s=requests.session()def__init__(self):self.token=self.get_token()defget_token(self):url=f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={CORP_ID}&corpsecret={SECRET}"rep=self.s.get(url)ifrep.status_code!=200:print("requestfailed.")returnreturnjson.loads(rep.content)['access_token']defsend_msg(self,content):url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+self.tokenheader={"Content-Type":"application/json"}form_data={"touser":"凤仙梅",#receiver"toparty":"1",#接收部门"totag":"TagID1|TagID2",#通讯录标签id"msgtype":"textcard","agentid":1000002,#ApplicationID"textcard":{"title":"新债提醒","description":content,"url":"URL","btntxt":"more"},"safe":0}rep=self.s.post(url,data=json.dumps(form_data).encode('utf-8'),headers=header)ifrep.status_code!=200:print("requestfailed.")returnreturnjson.loads(rep.content)if__name__=="__main__":wechat=WeChatPub()timenow=time.strftime("%Y-%m-%d%H:%M:%S",time.localtime())wechat.send_msg(f"{timenow}

注意!
今天有新债,继续欠债!
")print('消息已发送!')4.实现效果: