import config import logging import os from feishu_client import FeishuClient from coze_client import CozeClient # 配置日志 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def process_feishu_data_with_coze_flow( feishu_app_id: str, feishu_app_secret: str, feishu_base_id: str, feishu_table_id: str, feishu_input_field_name: str, feishu_output_field_name: str, coze_api_key: str, coze_bot_id: str, coze_prompt_template: str, max_records_to_process: int = 50, # 每次处理的记录数 overwrite_existing_output: bool = True # 是否覆盖已有的输出字段内容 ) -> None: """ 从飞书多维表格读取数据,调用Coze API进行处理,并将结果写入多维表格。 这是整个业务流程的协调函数。 Args: feishu_app_id (str): 飞书应用的 App ID。 feishu_app_secret (str): 飞书应用的 App Secret。 feishu_base_id (str): 飞书多维表格的 Base ID (应用 Token)。 feishu_table_id (str): 多维表格中要操作的表的 Table ID。 feishu_input_field_name (str): 多维表格中用于输入给Coze的字段名称。 feishu_output_field_name (str): 多维表格中用于存储Coze返回结果的字段名称。 coze_api_key (str): Coze API 密钥。 coze_bot_id (str): Coze 机器人的 Bot ID。 coze_prompt_template (str): Coze API的提示模板字符串,需要包含 '{input_data}' 占位符。 例如: "请总结以下文本的关键信息: {input_data}" max_records_to_process (int): 每次函数调用最多从飞书读取并处理的记录数。 overwrite_existing_output (bool): 如果输出字段已有内容,是否覆盖。True为覆盖,False为跳过。 """ logging.info("--- 🚀 开始执行飞书数据与Coze交互流程 🚀 ---") try: # 初始化客户端 feishu_client = FeishuClient(feishu_app_id, feishu_app_secret) # 1. 从飞书多维表格读取数据 logging.info("阶段 1/3: 从飞书多维表格读取数据...") read_field_names = [feishu_input_field_name, feishu_output_field_name] raw_records = feishu_client.read_records( feishu_base_id, feishu_table_id, read_field_names, page_size=max_records_to_process # 限制读取数量,防止一次性处理过多 ) records_to_process = [] for record in raw_records: record_id = record.get("record_id") fields = record.get("fields", {}) input_value = fields.get(feishu_input_field_name) output_value_existing = fields.get(feishu_output_field_name) # 筛选需要处理的记录 if input_value is None or str(input_value).strip() == "": logging.debug(f"记录 {record_id} 的输入字段 '{feishu_input_field_name}' 为空,跳过。") continue if not overwrite_existing_output and output_value_existing is not None and str(output_value_existing).strip() != "": logging.info(f"记录 {record_id} 的输出字段 '{feishu_output_field_name}' 已有内容且设置为不覆盖,跳过。") continue records_to_process.append({ "record_id": record_id, "input_data": input_value }) if not records_to_process: logging.info("没有符合条件的记录需要处理,流程结束。") return logging.info(f"共筛选出 {len(records_to_process)} 条记录待Coze处理。") # 2. 调用 Coze API 处理数据 logging.info("阶段 2/3: 调用Coze API处理数据...") updated_feishu_records = [] for i, record_info in enumerate(records_to_process): record_id = record_info["record_id"] input_data = record_info["input_data"] logging.info(f"正在处理第 {i+1}/{len(records_to_process)} 条记录 (ID: {record_id})...") try: coze_output = coze_client.send_message( coze_bot_id, coze_prompt_template, str(input_data) # 确保输入是字符串 ) if coze_output: updated_feishu_records.append({ "record_id": record_id, "fields": { feishu_output_field_name: coze_output } }) else: logging.warning(f"Coze API 返回空结果给记录 {record_id},不更新此记录。") except Exception as e: logging.error(f"处理记录 {record_id} 时调用Coze API失败: {e}。该记录将被跳过。") # 可以在这里记录到单独的错误日志或错误字段 if not updated_feishu_records: logging.info("没有记录成功通过 Coze API 处理并准备更新,无需写入飞书。流程结束。") return # 3. 将结果写入飞书多维表格 logging.info("阶段 3/3: 将处理结果写回飞书多维表格...") feishu_client.update_records( feishu_base_id, feishu_table_id, updated_feishu_records ) logging.info("--- ✅ 流程执行完毕 ✅ ---") except Exception as e: logging.critical(f"主流程执行过程中发生致命错误: {e}") logging.critical("请检查配置信息、网络连接、API权限以及日志中的详细错误信息。") if __name__ == "__main__": # --- 环境变量/配置信息加载 --- # 推荐使用环境变量加载敏感信息,而不是硬编码。 # 例如:export FEISHU_APP_ID="your_id" # 或者从配置文件 (如 config.ini, .env 文件) 中加载 # 飞书配置 FEISHU_APP_ID = config.FEISHU_APP_ID FEISHU_APP_SECRET = config.FEISHU_APP_SECRET FEISHU_BASE_ID = config.FEISHU_BASE_ID FEISHU_TABLE_ID = config.FEISHU_TABLE_ID FEISHU_INPUT_FIELD = config.FEISHU_INPUT_FIELD # 你的飞书表格中用于输入的列名 FEISHU_OUTPUT_FIELD = config.FEISHU_OUTPUT_FIELD # 你的飞书表格中用于输出的列名 # Coze 配置 COZE_API_KEY = config.COZE_API_KEY COZE_BOT_ID = config.COZE_BOT_ID # 例如: "7343685511394590740" # Coze 提示模板,请确保包含 {input_data} 占位符 # 这是一个示例,你可以根据你的机器人功能设计更复杂的提示 COZE_PROMPT_TEMPLATE = os.getenv("COZE_PROMPT_TEMPLATE", "请作为一位专业的编辑,总结以下文章的核心内容,要求言简意赅,200字以内: {input_data}") # --- 执行流程 --- if "YOUR_" in FEISHU_APP_ID or "YOUR_" in COZE_API_KEY: logging.error("⛔️ 请检查 main.py 或环境变量,确保所有 'YOUR_' 占位符都已替换为您的实际配置信息!⛔️") logging.error("流程未执行。") else: process_feishu_data_with_coze_flow( feishu_app_id=FEISHU_APP_ID, feishu_app_secret=FEISHU_APP_SECRET, feishu_base_id=FEISHU_BASE_ID, feishu_table_id=FEISHU_TABLE_ID, feishu_input_field_name=FEISHU_INPUT_FIELD, feishu_output_field_name=FEISHU_OUTPUT_FIELD, coze_api_key=COZE_API_KEY, coze_bot_id=COZE_BOT_ID, coze_prompt_template=COZE_PROMPT_TEMPLATE, max_records_to_process=10, # 每次运行最多处理10条记录 overwrite_existing_output=True # 总是覆盖输出字段 )