背景:通过python实现企业微信公众号链接+图文推送
目的:实现点击即看到内容,用更符合用户查看公众号消息的习惯推送消息
步骤:
1、创建企业微信公众号(应用)
2、确定推送内容(BI报表链接)+标题+说明
3、通过编写python代码实现推送
4、其他自动化需求(比如固定时间推送)
import json
import datetime
import requests
class WeChatPub:
s = requests.session()
def __init__(self):
self.corpid='企业id'
self.secret='公众号Secret'#企业微信应用后台查看
self.token = self.get_token()
#print('init_token',self.token)
def get_token(self):
url=f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={self.secret}&debug=1"
rep = self.s.get(url)
print('rep_token',rep.content)
if rep.status_code !=200:
print('get token failed')
return
return json.loads(rep.content)['access_token']
def send_news(self,title,description,to_url,picurl,btntxt='阅读全文'):
url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+self.token
header = {
"Content-Type":"application/json"
}
# python 字典若要转json,千万不能用单引号,要用双引号~@@双引号~~~!!!
form_data ={
"touser":"工号,以|隔开",
#全员推送@all#
"msgtype":"news",
"agentid":"应用ID",
"news":{
"articles":[
{
"title":title,
"description":description,
"url":to_url,
"picurl":picurl,
"btntxt":btntxt
}
]
},
"enable_id_trans": 0,
"enable_duplicate_check": 0,
"duplicate_check_interval": 1800
}
print(form_data,type(form_data))
rep = self.s.post(url,data=json.dumps(form_data).encode('utf-8'),headers=header)
if rep.status_code != 200:
print("request failed")
return
return json.loads(rep.content)
print('functions ready now!')
# 图片消息
# title,description,url,picurl,btntxt='阅读全文'
wechat = WeChatPub()
wechat.send_news(
title = '标题',
description ='说明文案',
to_url = r"链接",
picurl = r"图片"
#btntxt = '此处跳转' https://www.picgo.net/image/ymwTq
)