3 handle.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import config
  2. import logging
  3. import os
  4. from feishu_client import FeishuClient
  5. from coze_client import CozeClient
  6. # 配置日志
  7. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  8. def process_feishu_data_with_coze_flow(
  9. feishu_app_id: str,
  10. feishu_app_secret: str,
  11. feishu_base_id: str,
  12. feishu_table_id: str,
  13. feishu_input_field_name: str,
  14. feishu_output_field_name: str,
  15. coze_api_key: str,
  16. coze_bot_id: str,
  17. coze_prompt_template: str,
  18. max_records_to_process: int = 50, # 每次处理的记录数
  19. overwrite_existing_output: bool = True # 是否覆盖已有的输出字段内容
  20. ) -> None:
  21. """
  22. 从飞书多维表格读取数据,调用Coze API进行处理,并将结果写入多维表格。
  23. 这是整个业务流程的协调函数。
  24. Args:
  25. feishu_app_id (str): 飞书应用的 App ID。
  26. feishu_app_secret (str): 飞书应用的 App Secret。
  27. feishu_base_id (str): 飞书多维表格的 Base ID (应用 Token)。
  28. feishu_table_id (str): 多维表格中要操作的表的 Table ID。
  29. feishu_input_field_name (str): 多维表格中用于输入给Coze的字段名称。
  30. feishu_output_field_name (str): 多维表格中用于存储Coze返回结果的字段名称。
  31. coze_api_key (str): Coze API 密钥。
  32. coze_bot_id (str): Coze 机器人的 Bot ID。
  33. coze_prompt_template (str): Coze API的提示模板字符串,需要包含 '{input_data}' 占位符。
  34. 例如: "请总结以下文本的关键信息: {input_data}"
  35. max_records_to_process (int): 每次函数调用最多从飞书读取并处理的记录数。
  36. overwrite_existing_output (bool): 如果输出字段已有内容,是否覆盖。True为覆盖,False为跳过。
  37. """
  38. logging.info("--- 🚀 开始执行飞书数据与Coze交互流程 🚀 ---")
  39. try:
  40. # 初始化客户端
  41. feishu_client = FeishuClient(feishu_app_id, feishu_app_secret)
  42. # 1. 从飞书多维表格读取数据
  43. logging.info("阶段 1/3: 从飞书多维表格读取数据...")
  44. read_field_names = [feishu_input_field_name, feishu_output_field_name]
  45. raw_records = feishu_client.read_records(
  46. feishu_base_id,
  47. feishu_table_id,
  48. read_field_names,
  49. page_size=max_records_to_process # 限制读取数量,防止一次性处理过多
  50. )
  51. records_to_process = []
  52. for record in raw_records:
  53. record_id = record.get("record_id")
  54. fields = record.get("fields", {})
  55. input_value = fields.get(feishu_input_field_name)
  56. output_value_existing = fields.get(feishu_output_field_name)
  57. # 筛选需要处理的记录
  58. if input_value is None or str(input_value).strip() == "":
  59. logging.debug(f"记录 {record_id} 的输入字段 '{feishu_input_field_name}' 为空,跳过。")
  60. continue
  61. if not overwrite_existing_output and output_value_existing is not None and str(output_value_existing).strip() != "":
  62. logging.info(f"记录 {record_id} 的输出字段 '{feishu_output_field_name}' 已有内容且设置为不覆盖,跳过。")
  63. continue
  64. records_to_process.append({
  65. "record_id": record_id,
  66. "input_data": input_value
  67. })
  68. if not records_to_process:
  69. logging.info("没有符合条件的记录需要处理,流程结束。")
  70. return
  71. logging.info(f"共筛选出 {len(records_to_process)} 条记录待Coze处理。")
  72. # 2. 调用 Coze API 处理数据
  73. logging.info("阶段 2/3: 调用Coze API处理数据...")
  74. updated_feishu_records = []
  75. for i, record_info in enumerate(records_to_process):
  76. record_id = record_info["record_id"]
  77. input_data = record_info["input_data"]
  78. logging.info(f"正在处理第 {i+1}/{len(records_to_process)} 条记录 (ID: {record_id})...")
  79. try:
  80. coze_output = coze_client.send_message(
  81. coze_bot_id,
  82. coze_prompt_template,
  83. str(input_data) # 确保输入是字符串
  84. )
  85. if coze_output:
  86. updated_feishu_records.append({
  87. "record_id": record_id,
  88. "fields": {
  89. feishu_output_field_name: coze_output
  90. }
  91. })
  92. else:
  93. logging.warning(f"Coze API 返回空结果给记录 {record_id},不更新此记录。")
  94. except Exception as e:
  95. logging.error(f"处理记录 {record_id} 时调用Coze API失败: {e}。该记录将被跳过。")
  96. # 可以在这里记录到单独的错误日志或错误字段
  97. if not updated_feishu_records:
  98. logging.info("没有记录成功通过 Coze API 处理并准备更新,无需写入飞书。流程结束。")
  99. return
  100. # 3. 将结果写入飞书多维表格
  101. logging.info("阶段 3/3: 将处理结果写回飞书多维表格...")
  102. feishu_client.update_records(
  103. feishu_base_id,
  104. feishu_table_id,
  105. updated_feishu_records
  106. )
  107. logging.info("--- ✅ 流程执行完毕 ✅ ---")
  108. except Exception as e:
  109. logging.critical(f"主流程执行过程中发生致命错误: {e}")
  110. logging.critical("请检查配置信息、网络连接、API权限以及日志中的详细错误信息。")
  111. if __name__ == "__main__":
  112. # --- 环境变量/配置信息加载 ---
  113. # 推荐使用环境变量加载敏感信息,而不是硬编码。
  114. # 例如:export FEISHU_APP_ID="your_id"
  115. # 或者从配置文件 (如 config.ini, .env 文件) 中加载
  116. # 飞书配置
  117. FEISHU_APP_ID = config.FEISHU_APP_ID
  118. FEISHU_APP_SECRET = config.FEISHU_APP_SECRET
  119. FEISHU_BASE_ID = config.FEISHU_BASE_ID
  120. FEISHU_TABLE_ID = config.FEISHU_TABLE_ID
  121. FEISHU_INPUT_FIELD = config.FEISHU_INPUT_FIELD # 你的飞书表格中用于输入的列名
  122. FEISHU_OUTPUT_FIELD = config.FEISHU_OUTPUT_FIELD # 你的飞书表格中用于输出的列名
  123. # Coze 配置
  124. COZE_API_KEY = config.COZE_API_KEY
  125. COZE_BOT_ID = config.COZE_BOT_ID # 例如: "7343685511394590740"
  126. # Coze 提示模板,请确保包含 {input_data} 占位符
  127. # 这是一个示例,你可以根据你的机器人功能设计更复杂的提示
  128. COZE_PROMPT_TEMPLATE = os.getenv("COZE_PROMPT_TEMPLATE", "请作为一位专业的编辑,总结以下文章的核心内容,要求言简意赅,200字以内: {input_data}")
  129. # --- 执行流程 ---
  130. if "YOUR_" in FEISHU_APP_ID or "YOUR_" in COZE_API_KEY:
  131. logging.error("⛔️ 请检查 main.py 或环境变量,确保所有 'YOUR_' 占位符都已替换为您的实际配置信息!⛔️")
  132. logging.error("流程未执行。")
  133. else:
  134. process_feishu_data_with_coze_flow(
  135. feishu_app_id=FEISHU_APP_ID,
  136. feishu_app_secret=FEISHU_APP_SECRET,
  137. feishu_base_id=FEISHU_BASE_ID,
  138. feishu_table_id=FEISHU_TABLE_ID,
  139. feishu_input_field_name=FEISHU_INPUT_FIELD,
  140. feishu_output_field_name=FEISHU_OUTPUT_FIELD,
  141. coze_api_key=COZE_API_KEY,
  142. coze_bot_id=COZE_BOT_ID,
  143. coze_prompt_template=COZE_PROMPT_TEMPLATE,
  144. max_records_to_process=10, # 每次运行最多处理10条记录
  145. overwrite_existing_output=True # 总是覆盖输出字段
  146. )