通过python实现企业微信公众号链接+图文推送

背景:通过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
    
)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值