Python 企业微信应用文件发送教程:详细代码示例

本教程将带您了解如何使用 Python 代码实现企业微信应用文件发送功能,并提供详细代码示例和注意事项。

代码示例

import requests
import json

# 设置企业微信应用的相关参数
corpid = 'your_corpid'
corpsecret = 'your_corpsecret'
agentid = 'your_agentid'

# 获取access_token
url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
params = {'corpid': corpid, 'corpsecret': corpsecret}
response = requests.get(url, params=params)
access_token = json.loads(response.text)['access_token']

# 上传文件
url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
params = {'access_token': access_token, 'type': 'file'}
files = {'file': open('your_file_path', 'rb')}
response = requests.post(url, params=params, files=files)
media_id = json.loads(response.text)['media_id']

# 发送文件
url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send'
params = {'access_token': access_token}
data = {
    'touser': '@all',
    'agentid': agentid,
    'msgtype': 'file',
    'file': {
        'media_id': media_id
    }
}
response = requests.post(url, params=params, data=json.dumps(data))
print(response.text)

参数说明

  • your_corpid:企业微信的 corpid。
  • your_corpsecret:企业微信应用的 secret。
  • your_agentid:企业微信应用的 agentid。
  • your_file_path:待发送的文件路径。

注意事项

  1. 上传文件的接口要求文件大小不超过 20MB。
  2. 发送文件的接口要求文件类型为 doc、docx、xls、xlsx、ppt、pptx、pdf、txt、zip、rar。
  3. 发送文件的接口的 msgtype 参数必须为 file。
Python 企业微信应用文件发送教程:详细代码示例