前言:此文章主要讲解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)
验证结果: