生成 media_id
import os
from copy import copy
import requests
from urllib3 import encode_multipart_formdata
def upload_file(file_path, wx_upload_url):
file_name = file_path.split("/")[-1]
with open(file_path, 'rb') as f:
length = os.path.getsize(file_path)
data = f.read()
headers = {"Content-Type": "application/octet-stream"}
params = {
"filename": file_name,
"filelength": length,
}
file_data = copy(params)
file_data['file'] = (file_path.split('/')[-1:][0], data)
encode_data = encode_multipart_formdata(file_data)
file_data = encode_data[0]
headers['Content-Type'] = encode_data[1]
r = requests.post(wx_upload_url, data=file_data, headers=headers)
print(r.text)
media_id = r.json()['media_id']
return media_id
发送文件到微信群
def qi_ye_wei_xin_file(wx_url, media_id):
headers = {"Content-Type": "text/plain"}
data = {
"msgtype": "file",
"file": {
"media_id": media_id
}
}
r = requests.post(
url=wx_url,
headers=headers, json=data)
print(r.text)
发送消息实例:
test_report = '/root/data/demo.xlsx'
wx_api_key = "XXXX"
wx_upload_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={}&type=file".format(wx_api_key)
wx_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}'.format(wx_api_key)
media_id = upload_file(test_report, wx_upload_url)
qi_ye_wei_xin_file(wx_url, media_id)
在机器人配置页面看key
在消息中示例: