Skip to content

Commit

Permalink
/add feishu tables
Browse files Browse the repository at this point in the history
  • Loading branch information
HSPK committed May 22, 2024
1 parent c64631a commit d1ee12c
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 62 deletions.
10 changes: 8 additions & 2 deletions api/core/tools/provider/builtin/feishu/tools/feishu_get_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,19 @@ def _invoke(
table_url = tool_parameters.get("table_url", "")
if not table_url:
return self.create_text_message("Invalid parameter table_url")

output_format = tool_parameters.get("output_format", "markdown")
try:
df = get_feishu_table(
self.runtime.credentials["app_id"],
self.runtime.credentials["app_secret"],
table_url,
)
return self.create_text_message(df.to_markdown(index=False))
if output_format == "csv":
ret = df.to_csv(index=False)
elif output_format == "markdown":
ret = df.to_markdown(index=False)
else:
assert False, "Invalid output format"
return self.create_text_message(ret)
except Exception as e:
return self.create_text_message("Failed to get table. {}".format(e))
21 changes: 21 additions & 0 deletions api/core/tools/provider/builtin/feishu/tools/feishu_get_table.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,24 @@ parameters:
pt_BR: table url
llm_description: table url
form: llm
- name: output_format
type: select
required: false
default: markdown
options:
- label:
en_US: markdown
value: markdown
- label:
en_US: csv
value: csv
label:
en_US: output format
zh_Hans: 输出格式
pt_BR: output format
human_description:
en_US: output format
zh_Hans: 输出格式
pt_BR: output format
llm_description: output format
form: llm
101 changes: 59 additions & 42 deletions api/core/tools/provider/builtin/feishu/tools/feishu_write_table.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,67 @@
import re
from typing import Any, Union

import httpx
import pandas as pd
from feishuconnector import FeishuConnector

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.utils.uuid_utils import is_valid_uuid


class FeishuGetTableTool(BuiltinTool):
def _invoke(self, user_id: str, tool_parameters: dict[str, Any]
) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
"""
invoke tools
API document: https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
"""

url = "https://open.feishu.cn/open-apis/bot/v2/hook"

content = tool_parameters.get('content', '')
if not content:
return self.create_text_message('Invalid parameter content')

hook_key = tool_parameters.get('hook_key', '')
if not is_valid_uuid(hook_key):
return self.create_text_message(
f'Invalid parameter hook_key ${hook_key}, not a valid UUID')

msg_type = 'text'
api_url = f'{url}/{hook_key}'
headers = {
'Content-Type': 'application/json',
}
params = {}
payload = {
"msg_type": msg_type,
"content": {
"text": content,
}
}


def extract_table(md_text):
if not md_text:
raise ValueError("The Markdown text is empty.")
lines = md_text.split("\n")
table_elements = []
delimeter = "|"
for line in lines:
if line.startswith(delimeter) and line.endswith(delimeter):
cells = [cell.strip() for cell in line.strip(delimeter).split(delimeter)]
if set(cells[0]) == set("-"):
continue
table_elements.append(cells)
assert table_elements, "No tables found in the Markdown text."
assert (
len(table_elements) > 1
), "At least two table lines must be present in the Markdown text."
for cells in table_elements[1:]:
assert len(cells) == len(
table_elements[0]
), "All tables must have the same number of columns."
df = pd.DataFrame(table_elements[1:], columns=table_elements[0])
return df


def write_feishu_table(app_id, app_secret, table_url, table_data):
fc = FeishuConnector({"default": None})
fc.init(app_id=app_id, app_secret=app_secret)
assert "sheet" in table_url, "Only Wiki sheet is supported currently"
match = re.findall(r"wiki/(.*)\?sheet=(.*)", table_url)
assert match, "Invalid parameter table_url"
assert len(match[0]) == 2, "Invalid parameter table_url"
df = extract_table(table_data)
return fc.write_sheet_data(
match[0][0], match[0][1], [df.columns.tolist()] + df.values.tolist()
)


class FeishuWriteTableTool(BuiltinTool):
def _invoke(
self, user_id: str, tool_parameters: dict[str, Any]
) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
table_url = tool_parameters.get("table_url", "")
if not table_url:
return self.create_text_message("Invalid parameter table_url")
table_data = tool_parameters.get("table_data", "")
if not table_data:
return self.create_text_message("Invalid parameter table_data")
try:
res = httpx.post(api_url, headers=headers, params=params, json=payload)
if res.is_success:
return self.create_text_message("Text message sent successfully")
else:
return self.create_text_message(
f"Failed to send the text message, status code: {res.status_code}, response: {res.text}")
ret = write_feishu_table(
self.runtime.credentials["app_id"],
self.runtime.credentials["app_secret"],
table_url,
table_data,
)
return self.create_text_message(str(ret))
except Exception as e:
return self.create_text_message("Failed to send message to group chat bot. {}".format(e))
return self.create_text_message("Failed to get table. {}".format(e))
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,31 @@ description:
en_US: Write table on Feishu via group bot
zh_Hans: 通过飞书的群机器人写入表格
pt_BR: Write table on Feishu via group bot
llm: A tool for write table to Feishu(飞书) .
llm: A tool for write table from Feishu(飞书) .
parameters:
- name: hook_key
type: secret-input
- name: table_url
type: string
required: true
label:
en_US: Feishu Group bot webhook key
zh_Hans: 群机器人webhook的key
pt_BR: Feishu Group bot webhook key
en_US: table url
zh_Hans: 表格 url
pt_BR: table url
human_description:
en_US: Feishu Group bot webhook key
zh_Hans: 群机器人webhook的key
pt_BR: Feishu Group bot webhook key
form: form
- name: content
en_US: table url
zh_Hans: 表格 url
pt_BR: table url
llm_description: table url
form: llm
- name: table_data
type: string
required: true
label:
en_US: content
zh_Hans: 消息内容
pt_BR: content
en_US: table data
zh_Hans: 表格 数据
pt_BR: table data
human_description:
en_US: Content to sent to the group.
zh_Hans: 群消息文本
pt_BR: Content to sent to the group.
llm_description: Content of the message
en_US: table data
zh_Hans: 表格 数据
pt_BR: table data
llm_description: table data
form: llm

0 comments on commit d1ee12c

Please sign in to comment.