python-消息推送(企业微信)

目录

消息类型

文本

markdown

图片

图文

文件

卡片消息

发送请求


接口文档:发送应用消息 - 接口文档 - 企业微信开发者中心

消息类型

文本

## qywx_data.py

def text():  # 发送文本
    textmessage_body = {
        "msgtype": "text",
        "text": {
            "content": "羔裘豹祛,自我人居居。岂无他人?维子之故。\n羔裘豹褎,自我人究究。岂无他人?维子之好。",
            "mentioned_list": ["张三", '@all'],
            "mentioned_mobile_list": ["18793149370"]
        },
        "at": {
            "atMobiles": [],
            "isAtAll": False
        }
    }
    return textmessage_body

参数

是否必填

说明

msgtype

消息类型,此时固定为text

content

文本内容,最长不超过2048个字节,必须是utf8编码

mentioned_list

userid的列表,提醒群中的指定成员(@某个成员),@all表示提醒所有人,如果开发者获取不到userid,可以使用mentioned_mobile_list

mentioned_mobile_list

手机号列表,提醒手机号对应的群成员(@某个成员),@all表示提醒所有人

markdown

## qywx_data.py
def markdown():  # 发送markdown
    markdownmessage_body = {
        "msgtype": "markdown",
        "markdown": {
            "content": "# <font color='info'>**《诗经·羔裘》**</font>\n" +
                       "> ### <font color='warning'>羔裘豹祛,自我人居居。岂无他人?维子之故。</font>\n" +
                       "> #### <font color='warning'>羔裘豹褎,自我人究究。岂无他人?维子之好。</font>\n" +
                       "[点击访问](https://hanyu.baidu.com/shici/detail?pid=c79ce4bc0cf64ad3acfb8f69449ace1e)",
            "mentioned_list": ["贾宝瑞"],
            "mentioned_mobile_list": ["18793149370"]
        },
        "at": {
            "atMobiles": [],
            "isAtAll": False
        }
    }
    return markdownmessage_body

参数

是否必填

说明

msgtype

消息类型,此时固定为markdown

content

markdown内容,最长不超过4096个字节,必须是utf8编码

样式说明:

1、标题(支持1至6级标题,注意#与文字中间要有空格)

        # 标题一

        ## 标题二

        ### 标题三

        #### 标题四

        ##### 标题五

        ###### 标题六

2、加粗:**bold**

3、行内代码段(暂不支持跨行):`code`

4、引用:> 引用文字

5、字体颜色(只支持3种内置颜色)

        <font color="info">绿色</font>

        <font color="comment">灰色</font>

        <font color="warning">橙红色</font>

 

图片

## qywx_data.py
def image(filename):  # 发送图片
    import base64, hashlib
    with open(filename, 'rb') as f:
        imagedata = f.read()
        encodestr = base64.b64encode(imagedata)
        image_data = str(encodestr, 'utf-8')

    with open(filename, 'rb') as f:
        md = hashlib.md5()
        md.update(f.read())
        image_md5 = md.hexdigest()

    imagemessage_body = {
        "touser": "UserID1|UserID2|UserID3",  # 指定接收消息的成员,成员ID列表(多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为"@all",则向该企业应用的全部成员发送
        "msgtype": 'image',
        "image": {
            "base64": image_data,
            "md5": image_md5,
            "mentioned_list": ["贾宝瑞"],
            "mentioned_mobile_list": ["18793149370"]
        }
    }
    return imagemessage_body

参数

是否必填

说明

msgtype

消息类型,此时固定为image

base64

图片内容的base64编码

md5

图片内容(base64编码前)的md5值

图文

def news():  # 图文消息
    newsmessage_body = {
        "msgtype": "news",
        "news": {
            "articles": [  # 图文消息,一个图文消息支持1到8条图文
                {
                    "title": "《邶风 ·式微》",  # 标题,不超过128个字节,超过会自动截断
                    "description": "式微,式微,胡不归?\n微君之故,胡为乎中露!\n式微,式微,胡不归?\n微君之躬,胡为乎泥中!",
                    # 描述,不超过512个字节,超过会自动截断
                    "url": "https://baike.baidu.com/item/%E9%82%B6%E9%A3%8E%C2%B7%E5%BC%8F%E5%BE%AE/19663937?fr=aladdin",
                    "picurl": "https://p2.itc.cn/q_70/images03/20210802/ec3f13a7216345968524b65787527a65.jpeg"
                },
                {
                    "title": "《邶风 ·北风》",
                    "description": "北风其凉,雨雪其雱。惠而好我,携手同行。其虚其邪?既亟只且!\n北风其喈,雨雪其霏。惠而好我,携手同归。其虚其邪?既亟只且!\n莫赤匪狐,莫黑匪乌。惠而好我,携手同车。其虚其邪?既亟只且!",
                    "url": "https://baike.baidu.com/item/%E9%82%B6%E9%A3%8E%C2%B7%E5%8C%97%E9%A3%8E/19666623?fromtitle=%E8%AF%97%E7%BB%8F%C2%B7%E9%82%B6%E9%A3%8E%C2%B7%E5%8C%97%E9%A3%8E&fromid=53819462&fr=aladdin",
                    "picurl": "https://img2.baidu.com/it/u=1970453247,2917096554&fm=253&fmt=auto&app=138&f=JPEG?w=650&h=447"
                }
            ]
        }
    }
    return newsmessage_body

参数

是否必填

说明

msgtype

消息类型,此时固定为news

articles

图文消息,一个图文消息支持1到8条图文

title

标题,不超过128个字节,超过会自动截断

description

描述,不超过512个字节,超过会自动截断

url

点击后跳转的链接。

picurl

图文消息的图片链接,支持JPG、PNG格式,较好的效果为大图 1068*455,小图150*150。

 

文件

def file(webHookUrl, filename):
    import requests
    headers = {"Accept": "application/json, text/plain, */*",
               "Accept-Encoding": "gzip, deflate",
               "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36"}
    with open(filename, 'rb') as f:
        filedata = f.read()
    upload_url = f'{webHookUrl}&type=file'
    response = requests.post(url=upload_url, headers=headers, files={'file': filedata})
    print(response.text)
    json_res = response.json()
    media_id = json_res['media_id']
    filemessage_body = {
        "msgtype": "file",
        "file": {
            "media_id": media_id
        }
    }
    return filemessage_body

参数

是否必填

说明

msgtype

消息类型,此时固定为file

media_id

文件id,通过下文的文件上传接口获取

卡片消息

def template_card():
    template_card_body = {
        "msgtype": "template_card",
        "template_card": {
            "card_type": "text_notice",  # 模板卡片类型,文本通知型卡片填写 "text_notice"
            # "source": {
            #     "icon_url": "https://www.baidu.com/img/flexible/logo/utouch.png",
            #     "desc": "企业微信",
            #     "desc_color": 3
            # # },  # 卡片来源样式信息,不需要来源样式可不填写
            # "action_menu": {
            #     "desc": "卡片副交互辅助文本说明",
            #     "action_list": [
            #         {"text": "接受推送", "key": "A"},
            #         {"text": "不再推送", "key": "B"}
            #     ]
            # },
            # "task_id": "task_id",  # 任务id,同一个应用任务id不能重复,只能由数字、字母和“_-@”组成,最长128字节,填了action_menu字段的话本字段必填
            "main_title": {
                "title": "欢迎使用企业微信",
                "desc": "您的好友正在邀请您加入企业微信"  # 标题辅助信息,建议不超过44个字,(支持id转译)
            },  # 一级标题,建议不超过36个字,文本通知型卡片本字段非必填,但不可本字段和sub_title_text都不填,(支持id转译)
            "emphasis_content": {
                "title": "关键数据内容",  # 关键数据样式的数据内容,建议不超过14个字
                "desc": "关键数据描述"  # 关键数据样式的数据描述内容,建议不超过22个字
            },  # 关键数据样式
            "quote_area": {
                "type": 1,  # 引用文献样式区域点击事件,0或不填代表没有点击事件,1 代表跳转url,2 代表跳转小程序
                "url": "https://baidu.com",  # 点击跳转的url,quote_area.type是1时必填
                "appid": "APPID",  # 点击跳转的小程序的appid,必须是与当前应用关联的小程序,quote_area.type是2时必填
                "pagepath": "PAGEPATH",  # 点击跳转的小程序的pagepath,quote_area.type是2时选填
                "title": "引用文本标题",
                "quote_text": "企业微信真的很好用~\nBalian:超级好的一款软件!"  # 引用文献的引用案例
            },  # 引用文献样式
            "sub_title_text": "这是一个二级普通文本!",  # 二级普通文本,建议不超过160个字,(支持id转译)
            "horizontal_content_list": [
                {
                    "keyname": "开发",
                    "value": "三毛"
                },
                {
                    "keyname": "企微官网",  # 二级标题,建议不超过5个字
                    "value": "点击访问",  # 二级文本,如果horizontal_content_list.type是2,该字段代表文件名称(要包含文件类型),建议不超过30个字,(支持id转译)
                    "type": 1,  # 链接类型,0或不填代表不是链接,1 代表跳转url,2 代表下载附件,3 代表点击跳转成员详情
                    "url": "https://developer.work.weixin.qq.com/document/path/90372"
                },
                {
                    "keyname": "企微下载",
                    "value": "企业微信.apk",
                    "type": 2,
                    "media_id": "MEDIAID"  # 附件的media_id,horizontal_content_list.type是2时必填
                }
            ],  # 二级标题+文本列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过6
            "jump_list": [
                {
                    "type": 1,  # 跳转链接类型,0或不填代表不是链接,1 代表跳转url,2 代表跳转小程序
                    "url": "https://work.weixin.qq.com/?from=openApi",
                    "title": "企业微信官网"  # 跳转链接样式的文案内容,建议不超过18个字
                },
                {
                    "type": 2,
                    "appid": "APPID",
                    "pagepath": "PAGEPATH",
                    "title": "跳转小程序"
                }
            ],  # 跳转指引样式的列表,该字段可为空数组,但有数据的话需确认对应字段是否必填,列表长度不超过3
            "card_action": {
                "type": 1,
                "url": "https://work.weixin.qq.com/?from=openApi",
                "appid": "APPID",  # 跳转事件的小程序的appid,必须是与当前应用关联的小程序,card_action.type是2时必填
                "pagepath": "PAGEPATH"  # 跳转事件的小程序的pagepath,card_action.type是2时选填
            }  # 整体卡片的点击跳转事件,text_notice必填本字段
        }
    }
    return template_card_body

更多类型可查看接口文档:更新模版卡片消息 - 文档 - 企业微信开发者中心 (qq.com) 

发送请求

import requests
import json
import qywx_data


def push_report(webHookUrl):
    header = {
        "Content-Type": "application/json"
    }

    # send_data = json.dumps(qywx_data.text)  # 将字典类型数据转化为json格式
    # send_data = json.dumps(qywx_data.markdown)
    # send_data = json.dumps(qywx_data.image(r'D:\zhuomian\test_file\33.png'))
    send_data = json.dumps(qywx_data.news())


    ChatBot = requests.post(url=webHookUrl, data=send_data, headers=header)
    opener = ChatBot.json()
    if opener["errmsg"] == "ok":
        print(u"%s 通知消息发送成功!" % opener)
    else:
        print(u"通知消息发送失败,原因:{}".format(opener))


if __name__ == '__main__':
    webHookUrl = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={qywx_data.user_key['交流群']}"
    push_report(webHookUrl)

猜你喜欢

转载自blog.csdn.net/JBY2020/article/details/129886505