

import requests
import json
class sent_message:
def __init__(self,app_id,app_serect,sent_text):# 初始接收APP的凭证信息和要输入的消息
self.app_id = app_id
self.app_serect = app_serect
self.sent_text = sent_text
def get_token(self): # 获取应用token
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
response = requests.post(url,json={
"app_id":self.app_id,
"app_secret": self.app_serect
})
data = response.json()
if data.get("code") == 0:
access_token = data["tenant_access_token"]
self.access_token = access_token
return self.access_token
else:
error_code = data.get("code") # 获取错误码
print(f"请求失败,错误码: {error_code}") # 打印错误码
raise RuntimeError(f"接口返回错误,错误码: {error_code}") # 抛出带错误码的异常
def get_user_openid(self,mobel:list): #获取open_id和user_id
url = "https://open.feishu.cn/open-apis/contact/v3/users/batch_get_id"
headers = {"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json"}
payload = {
"mobiles": mobel
}
resp = requests.post(url, headers=headers, json=payload)
data = resp.json()
print(data)
if data.get("code") == 0 and data.get("data", {}).get("user_list"):
user_info = data["data"]["user_list"][0]
open_id = user_info.get("user_id")
self.open_id = open_id
print(self.open_id)
return self.open_id
else:
raise Exception(f"Get open_id error: {data}")
def sent_massages(self, receive_id_type="open_id"):
print("=== 进入 sent_massages ===")
url = "https://open.feishu.cn/open-apis/im/v1/messages"
params = {
"receive_id_type": receive_id_type
}
headers = {
"Authorization": f"Bearer {self.access_token}",
"Content-Type": "application/json; charset=utf-8"
}
# content 应该是字符串格式的 JSON
content = json.dumps({"text": self.sent_text})
payload = {
"receive_id": self.open_id,
"msg_type": "text",
"content": content
}
print("发送的 payload:", payload) # 调试用
response = requests.post(
url=url,
params=params,
json=payload,
headers=headers,
timeout=10)
data = response.json()
print("返回结果:", data)
if data.get("code") == 0:
return data.get("message_id")
else:
raise Exception(f"发送消息失败: {data}")
def main(asgs):
APP_ID = ""
APP_Serect = ""
Sent_text = asgs
test = sent_message(APP_ID, APP_Serect, Sent_text)
test.get_token()
test.get_user_openid([""])
result = test.sent_massages()
print("发送结果:", result)
return result
这样就不用在业务电脑上配置飞书凭证了