python 飞书发送文件
时间: 2023-08-31 17:02:44 浏览: 113
要使用Python发送文件到飞书,可以使用飞书开放平台提供的API。下面是一个简单的示例代码:
```python
import requests
# 飞书应用的请求URL
url = 'https://open.feishu.cn/open-apis/im/v1/messages/send'
# 飞书应用的访问令牌
access_token = 'your_access_token'
# 要发送的文件路径
file_path = 'path_to_your_file'
# 以二进制读取文件内容
with open(file_path, 'rb') as file:
file_data = file.read()
# 构建请求参数
payload = {
'open_id': 'user_open_id',
'msg_type': 'post',
'content': {
'title': 'File',
'text': 'This is a file',
'post': {
'zh_cn': {
'title': 'File',
'content': [
[
{
'tag': 'file',
'file_key': 'file_key',
}
]
]
}
}
}
}
# 发起POST请求
response = requests.post(url, headers={'Authorization': 'Bearer ' + access_token}, json=payload, files={'file': file_data})
# 打印发送结果
print(response.json())
```
在代码中,首先需要替换`url`变量的值为您创建的飞书应用的请求URL,`access_token`变量的值为您的飞书应用的访问令牌,以及`file_path`变量的值为您要发送的文件的路径。
然后,使用`open`函数打开文件,并以二进制模式读取文件内容到`file_data`变量中。
接下来,根据飞书的消息格式构建请求参数`payload`,其中`open_id`变量为接收者用户的Open ID。`file_key`是用来标识文件附件的唯一键值,可以自定义。
最后,使用`requests.post`方法发起POST请求,将请求参数`payload`和文件内容`file_data`作为参数传递。根据请求结果,您可以获取发送结果的JSON数据。
以上是一个简单的示例代码,您可以根据您的实际需求进行修改和扩展。请确保已正确安装`requests`库。