本教程均已发送到指定群聊为例
开发之前首先需进入飞书开放平台注册应用
飞书开放平台
拿到应用的 APP_ID 和 APP_SECRET
def get_access_token(APP_ID, APP_SECRET):
url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal'
headers = {
'Content-Type': "application/json; charset=utf-8"
}
data = {
'app_id': APP_ID,
'app_secret': APP_SECRET
}
res = requests.post(url, headers=headers, json=data).json()
return res['tenant_access_token']
可选择根据用户邮箱或者手机号查找,也可同时使用
def get_user_id(token):
url = 'https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id?user_id_type=union_id'
headers = {
'Authorization': "Bearer " + token,
'Content-Type': "application/json; charset=utf-8"
}
# data = {
# 'user_id_type': 'union_id',
# }
json = {
# "emails": [
# "[email protected]", "[email protected]"
# ],
"mobiles": [
"13372947224",
]
}
res = requests.post(url, headers=headers, json=json).json()
return res
获取之前开启应用的机器人能力,并把机器人拉入相关群聊
# 该函数会返回机器人所在的所有群聊
def get_chat_id(token):
url = 'https://open.feishu.cn/open-apis/im/v1/chats'
headers = {
'Authorization': "Bearer " + token,
'Content-Type': "application/json; charset=utf-8"
}
res = requests.get(url, headers=headers).json()
return res
本例发送消息可采用两种方式
def send_text(content, receive_id='', token='', bot='', types=1):
# 发送消息
if types == 1:
url = 'https://open.feishu.cn/open-apis/bot/v2/hook/' + bot
headers = {"Content-Type": "text/plain"}
data = {
"msg_type": "text",
"content": {
"text": content
}
}
r = requests.post(url, headers=headers, json=data)
return r.text
# 发送消息
elif types == 2:
url = 'https://open.feishu.cn/open-apis/im/v1/messages/'
params = {
'receive_id_type': 'chat_id'
}
headers = {
'Authorization': "Bearer {}".format(token),
"Content-Type": "application/json; charset=utf-8"
}
data = {
"receive_id": receive_id,
"msg_type": "text",
"content": content,
}
r = requests.post(url=url, params=params, headers=headers, data=json.dumps(data))
# 发送消息卡片
elif types == 3:
# open_id user_id union_id email chat_id
url = 'https://open.feishu.cn/open-apis/im/v1/messages/'
params = {
'receive_id_type': 'chat_id'
}
headers = {
'Authorization': "Bearer {}".format(token),
"Content-Type": "application/json; charset=utf-8"
}
data = {
"receive_id": receive_id,
"msg_type": "interactive",
"content": content,
}
r = requests.post(url=url, params=params, headers=headers, data=json.dumps(data))
print('res', r, r.text)
return r.text
有时候会有涉及到文件上传,比如消息卡片中嵌套的图片,此时通过创建的应用即可
def upload_img(img_path, token):
resp = requests.post(
url='https://open.feishu.cn/open-apis/image/v4/put/',
headers={'Authorization': "Bearer " + token},
files={
"image": open(img_path, "rb")
},
data={
"image_type": "message"
},
stream=True)
resp.raise_for_status()
content = resp.json()
if content.get("code") == 0:
return content['data']['image_key']
else:
return Exception("Call Api Error, errorCode is %s" % content["code"])