自动化测试企业微信推送:群机器人(三)

前言:此文章主要讲解python通过群机器人发送文件

前置条件:群机器人已创建

代码逻辑:

1、通过企业微信的API文档,获取文件上传的media_id

2、获取到ID之后,发送群消息

代码:

import os
import time
import requests
import json



def send_file_to_wechat_group(file_path):
    """
    通过企业微信群机器人发送文件
    :param webhook_url: 企业微信群机器人的 webhook URL
    :param file_path: 要发送的文件路径
    """
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ae34a1b6-0d57-4468-990c-24b238344cc5"
    upload_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=ae34a1b6-0d57-4468-990c-24b238344cc5&type=file"
    with open(file_path, 'rb') as file:
        response = requests.post(upload_url, files={'file': file}, timeout=10)
        media_id =response.json().get('media_id')           # 获取上传文件的media_id
        data = {
            "msgtype": "file",
            "file": {
                "media_id": media_id
            }
        }
    result = requests.post(url, json=data, timeout=10)       # 发送文件
    print(result.text)
    if "ok"==result.json().get('errmsg'):
        print("文件发送成功")
    else:
        print("文件发送失败")



# 示例调用
if __name__ == '__main__':
    file_path = r'D:\python_project\performance\repoet\test1.txt'
    send_file_to_wechat_group(file_path)

验证结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值