mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-08-30 22:27:13 +00:00
feat: add download image port configuration and improve image retrieval process
This commit is contained in:
@@ -23,6 +23,7 @@ class GewechatConfigMigration(migration.Migration):
|
|||||||
"adapter": "gewechat",
|
"adapter": "gewechat",
|
||||||
"enable": False,
|
"enable": False,
|
||||||
"gewechat_url": "http://your-gewechat-server:2531",
|
"gewechat_url": "http://your-gewechat-server:2531",
|
||||||
|
"gewechat_downloadImage_port": 2532,
|
||||||
"port": 2286,
|
"port": 2286,
|
||||||
"callback_url": "http://your-callback-url:2286/gewechat/callback",
|
"callback_url": "http://your-callback-url:2286/gewechat/callback",
|
||||||
"app_id": "",
|
"app_id": "",
|
||||||
|
|||||||
@@ -89,8 +89,8 @@ class GewechatMessageConverter(adapter.MessageConverter):
|
|||||||
app_id=self.config["app_id"],
|
app_id=self.config["app_id"],
|
||||||
xml_content=image_xml,
|
xml_content=image_xml,
|
||||||
token=self.config["token"],
|
token=self.config["token"],
|
||||||
data_dir=self.config.get("data_dir", "/root/docker/gewechat/data/download"),
|
image_type=2,
|
||||||
image_type=2
|
download_image_port=self.config["gewechat_downloadImage_port"]
|
||||||
)
|
)
|
||||||
|
|
||||||
return platform_message.MessageChain([
|
return platform_message.MessageChain([
|
||||||
@@ -107,20 +107,15 @@ class GewechatMessageConverter(adapter.MessageConverter):
|
|||||||
elif message["Data"]["MsgType"] == 49:
|
elif message["Data"]["MsgType"] == 49:
|
||||||
# 支持微信聊天记录的消息类型,将 XML 内容转换为 MessageChain 传递
|
# 支持微信聊天记录的消息类型,将 XML 内容转换为 MessageChain 传递
|
||||||
try:
|
try:
|
||||||
# 首先确保内容是字符串
|
|
||||||
content = message["Data"]["Content"]["string"]
|
content = message["Data"]["Content"]["string"]
|
||||||
|
|
||||||
# 如果内容已经是base64编码,尝试解码
|
|
||||||
try:
|
try:
|
||||||
# 先将字符串编码为UTF-8字节
|
|
||||||
content_bytes = content.encode('utf-8')
|
content_bytes = content.encode('utf-8')
|
||||||
# 然后进行base64解码
|
|
||||||
decoded_content = base64.b64decode(content_bytes)
|
decoded_content = base64.b64decode(content_bytes)
|
||||||
return platform_message.MessageChain(
|
return platform_message.MessageChain(
|
||||||
[platform_message.Unknown(content=decoded_content)]
|
[platform_message.Unknown(content=decoded_content)]
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# 如果解码失败,直接返回原始内容
|
|
||||||
return platform_message.MessageChain(
|
return platform_message.MessageChain(
|
||||||
[platform_message.Plain(text=content)]
|
[platform_message.Plain(text=content)]
|
||||||
)
|
)
|
||||||
@@ -175,7 +170,7 @@ class GewechatEventConverter(adapter.EventConverter):
|
|||||||
time=event["Data"]["CreateTime"],
|
time=event["Data"]["CreateTime"],
|
||||||
source_platform_object=event,
|
source_platform_object=event,
|
||||||
)
|
)
|
||||||
elif 'wxid_' in event["Data"]["FromUserName"]["string"]:
|
else:
|
||||||
return platform_events.FriendMessage(
|
return platform_events.FriendMessage(
|
||||||
sender=platform_entities.Friend(
|
sender=platform_entities.Friend(
|
||||||
id=event["Data"]["FromUserName"]["string"],
|
id=event["Data"]["FromUserName"]["string"],
|
||||||
@@ -221,7 +216,7 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
@self.quart_app.route('/gewechat/callback', methods=['POST'])
|
@self.quart_app.route('/gewechat/callback', methods=['POST'])
|
||||||
async def gewechat_callback():
|
async def gewechat_callback():
|
||||||
data = await quart.request.json
|
data = await quart.request.json
|
||||||
# print(json.dumps(data, indent=4, ensure_ascii=False))
|
print(json.dumps(data, indent=4, ensure_ascii=False))
|
||||||
|
|
||||||
if 'testMsg' in data:
|
if 'testMsg' in data:
|
||||||
return 'ok'
|
return 'ok'
|
||||||
|
|||||||
@@ -17,6 +17,13 @@ spec:
|
|||||||
type: string
|
type: string
|
||||||
required: true
|
required: true
|
||||||
default: ""
|
default: ""
|
||||||
|
- name: gewechat_downloadImage_port
|
||||||
|
label:
|
||||||
|
en_US: GeWeChat download image port
|
||||||
|
zh_CN: GeWeChat 下载图片的端口
|
||||||
|
type: int
|
||||||
|
required: true
|
||||||
|
default: 2532
|
||||||
- name: port
|
- name: port
|
||||||
label:
|
label:
|
||||||
en_US: Port
|
en_US: Port
|
||||||
@@ -45,13 +52,6 @@ spec:
|
|||||||
type: string
|
type: string
|
||||||
required: true
|
required: true
|
||||||
default: ""
|
default: ""
|
||||||
- name: data_dir
|
|
||||||
label:
|
|
||||||
en_US: Data Directory
|
|
||||||
zh_CN: 数据目录
|
|
||||||
type: string
|
|
||||||
required: true
|
|
||||||
default: "/root/docker/gewechat/data/download"
|
|
||||||
execution:
|
execution:
|
||||||
python:
|
python:
|
||||||
path: ./gewechat.py
|
path: ./gewechat.py
|
||||||
|
|||||||
+64
-38
@@ -11,6 +11,7 @@ import httpx
|
|||||||
import os
|
import os
|
||||||
import aiofiles
|
import aiofiles
|
||||||
import pathlib
|
import pathlib
|
||||||
|
import asyncio
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
@@ -19,69 +20,94 @@ async def get_gewechat_image_base64(
|
|||||||
app_id: str,
|
app_id: str,
|
||||||
xml_content: str,
|
xml_content: str,
|
||||||
token: str,
|
token: str,
|
||||||
data_dir: str = "/root/docker/gewechat/data/download", # gewechat数据目录
|
image_type: int = 2,
|
||||||
image_type: int = 2
|
download_image_port: int = 2532,
|
||||||
) -> typing.Tuple[str, str]:
|
) -> typing.Tuple[str, str]:
|
||||||
"""从gewechat本地文件系统获取图片并转换为base64格式
|
"""从gewechat服务器获取图片并转换为base64格式
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
gewechat_url (str): gewechat服务器地址(用于获取图片URL)
|
gewechat_url (str): gewechat服务器地址(用于获取图片URL)
|
||||||
app_id (str): gewechat应用ID
|
app_id (str): gewechat应用ID
|
||||||
xml_content (str): 图片的XML内容
|
xml_content (str): 图片的XML内容
|
||||||
token (str): Gewechat API Token
|
token (str): Gewechat API Token
|
||||||
data_dir (str): gewechat数据目录
|
|
||||||
image_type (int, optional): 图片类型. Defaults to 2.
|
image_type (int, optional): 图片类型. Defaults to 2.
|
||||||
|
download_image_port (int, optional): 图片下载服务端口. Defaults to 2532.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
typing.Tuple[str, str]: (base64编码, 图片格式)
|
typing.Tuple[str, str]: (base64编码, 图片格式)
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
aiohttp.ClientTimeout: 请求超时(15秒)或连接超时(2秒)
|
||||||
|
Exception: 其他错误
|
||||||
"""
|
"""
|
||||||
headers = {
|
headers = {
|
||||||
'X-GEWE-TOKEN': token,
|
'X-GEWE-TOKEN': token,
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
# 设置超时
|
||||||
# 获取图片下载链接
|
timeout = aiohttp.ClientTimeout(
|
||||||
async with session.post(
|
total=15.0, # 总超时时间15秒
|
||||||
f"{gewechat_url}/v2/api/message/downloadImage",
|
connect=2.0, # 连接超时2秒
|
||||||
headers=headers,
|
sock_connect=2.0, # socket连接超时2秒
|
||||||
json={
|
sock_read=15.0 # socket读取超时15秒
|
||||||
"appId": app_id,
|
)
|
||||||
"type": image_type,
|
|
||||||
"xml": xml_content
|
|
||||||
}
|
|
||||||
) as response:
|
|
||||||
if response.status != 200:
|
|
||||||
raise Exception(f"获取gewechat图片下载失败: {await response.text()}")
|
|
||||||
|
|
||||||
resp_data = await response.json()
|
try:
|
||||||
if resp_data.get("ret") != 200:
|
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||||
raise Exception(f"获取gewechat图片下载链接失败: {resp_data}")
|
# 获取图片下载链接
|
||||||
|
try:
|
||||||
|
async with session.post(
|
||||||
|
f"{gewechat_url}/v2/api/message/downloadImage",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"appId": app_id,
|
||||||
|
"type": image_type,
|
||||||
|
"xml": xml_content
|
||||||
|
}
|
||||||
|
) as response:
|
||||||
|
if response.status != 200:
|
||||||
|
raise Exception(f"获取gewechat图片下载失败: {await response.text()}")
|
||||||
|
|
||||||
# 从URL中解析文件路径
|
resp_data = await response.json()
|
||||||
file_url = resp_data['data']['fileUrl']
|
if resp_data.get("ret") != 200:
|
||||||
parsed_url = urlparse(file_url)
|
raise Exception(f"获取gewechat图片下载链接失败: {resp_data}")
|
||||||
path_parts = parsed_url.path.strip('/').split('/')
|
|
||||||
|
|
||||||
# 构建本地文件路径
|
file_url = resp_data['data']['fileUrl']
|
||||||
# URL格式: /20250224/wx_U48cqQsdtqedi4Cak7MnN/35f6240a-c778-4579-93ee-d8002f91a8ed.png
|
except asyncio.TimeoutError:
|
||||||
local_path = os.path.join(data_dir, *path_parts)
|
raise Exception("获取图片下载链接超时")
|
||||||
|
except aiohttp.ClientError as e:
|
||||||
|
raise Exception(f"获取图片下载链接网络错误: {str(e)}")
|
||||||
|
|
||||||
# 确保文件存在
|
# 解析原始URL并替换端口
|
||||||
if not os.path.exists(local_path):
|
parsed_url = urlparse(gewechat_url)
|
||||||
raise Exception(f"图片文件不存在: {local_path}")
|
base_url = f"http://{parsed_url.hostname}:{download_image_port}"
|
||||||
|
download_url = f"{base_url}/download/{file_url}"
|
||||||
|
|
||||||
# 读取本地文件
|
# 下载图片
|
||||||
async with aiofiles.open(local_path, 'rb') as f:
|
try:
|
||||||
image_data = await f.read()
|
async with session.get(download_url) as img_response:
|
||||||
|
if img_response.status != 200:
|
||||||
|
raise Exception(f"下载图片失败: {await img_response.text()}, URL: {download_url}")
|
||||||
|
|
||||||
# 获取图片格式
|
image_data = await img_response.read()
|
||||||
image_format = pathlib.Path(local_path).suffix.lstrip('.')
|
|
||||||
|
|
||||||
# 转换为base64
|
content_type = img_response.headers.get('Content-Type', '')
|
||||||
base64_str = base64.b64encode(image_data).decode('utf-8')
|
if content_type:
|
||||||
|
image_format = content_type.split('/')[-1]
|
||||||
|
else:
|
||||||
|
image_format = file_url.split('.')[-1]
|
||||||
|
|
||||||
|
base64_str = base64.b64encode(image_data).decode('utf-8')
|
||||||
|
|
||||||
|
return base64_str, image_format
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
raise Exception(f"下载图片超时, URL: {download_url}")
|
||||||
|
except aiohttp.ClientError as e:
|
||||||
|
raise Exception(f"下载图片网络错误: {str(e)}, URL: {download_url}")
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception(f"获取图片失败: {str(e)}") from e
|
||||||
|
|
||||||
return base64_str, image_format
|
|
||||||
|
|
||||||
async def get_wecom_image_base64(pic_url: str) -> tuple[str, str]:
|
async def get_wecom_image_base64(pic_url: str) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -64,6 +64,7 @@
|
|||||||
"adapter": "gewechat",
|
"adapter": "gewechat",
|
||||||
"enable": false,
|
"enable": false,
|
||||||
"gewechat_url": "http://your-gewechat-server:2531",
|
"gewechat_url": "http://your-gewechat-server:2531",
|
||||||
|
"gewechat_downloadImage_port": 2532,
|
||||||
"port": 2286,
|
"port": 2286,
|
||||||
"callback_url": "http://your-callback-url:2286/gewechat/callback",
|
"callback_url": "http://your-callback-url:2286/gewechat/callback",
|
||||||
"app_id": "",
|
"app_id": "",
|
||||||
|
|||||||
@@ -325,6 +325,11 @@
|
|||||||
"default": "",
|
"default": "",
|
||||||
"description": "gewechat 的 url"
|
"description": "gewechat 的 url"
|
||||||
},
|
},
|
||||||
|
"gewechat_downloadImage_port": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 2532,
|
||||||
|
"description": "gewechat 下载图片的端口"
|
||||||
|
},
|
||||||
"port": {
|
"port": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"default": 2286,
|
"default": 2286,
|
||||||
|
|||||||
Reference in New Issue
Block a user