Files
tw/core/websocket_send_flow.py

72 lines
2.4 KiB
Python

import json
import websockets
async def send_text_flow(client, cy_id, acc_type, content):
"""主动发送文本消息。"""
message = {
"msg_id": "",
"acc_id": "",
"msg": content,
"from_id": client.reply_id,
"from_name": client.reply_id,
"cy_id": cy_id,
"acc_type": acc_type,
"msg_type": 0,
"cy_name": "",
}
await client.send_message(message)
async def send_image_flow(client, cy_id, acc_type, image_path):
"""主动发送图片消息。"""
message = {
"msg_id": "",
"acc_id": "",
"msg": image_path,
"from_id": client.reply_id,
"from_name": client.reply_id,
"cy_id": cy_id,
"acc_type": acc_type,
"msg_type": 1,
"cy_name": "",
}
await client.send_message(message)
async def send_message_flow(client, message):
"""发送消息到服务器。"""
if client.websocket and client.websocket.state == websockets.protocol.State.OPEN:
try:
msg_json = json.dumps(message, ensure_ascii=False)
await client.websocket.send(msg_json)
pretty = json.dumps(message, ensure_ascii=False, indent=2)
client.logger.info(f"[{client.get_time()}] 发送成功:\n{pretty}")
data = message.get("data", {}) if isinstance(message, dict) else {}
client._activity_log(
"send_message_success",
trace_id=message.get("_trace_id", "") if isinstance(message, dict) else "",
acc_id=data.get("acc_id", ""),
customer_id=data.get("cy_id", ""),
msg_type=data.get("msg_type", 0),
msg=data.get("msg", ""),
)
except Exception as e:
client.logger.info(f"[{client.get_time()}] 发送失败: {e}")
client._activity_log(
"send_message_error",
trace_id=message.get("_trace_id", ""),
acc_id=message.get("acc_id", ""),
customer_id=message.get("from_id", ""),
error=str(e),
)
else:
client.logger.info(f"[{client.get_time()}] 错误: 连接未打开")
client._activity_log(
"send_message_skipped",
trace_id=message.get("_trace_id", ""),
reason="socket_not_open",
acc_id=message.get("acc_id", ""),
customer_id=message.get("from_id", ""),
)