四个平台接入

This commit is contained in:
jjz
2025-09-13 19:54:30 +08:00
parent 22122660df
commit 08613313d3
5 changed files with 1250 additions and 768 deletions

View File

@@ -44,7 +44,6 @@ class BackendClient:
if self.loop and self.loop.is_running():
asyncio.run_coroutine_threadsafe(self._close(), self.loop)
if self.thread and self.thread.is_alive():
self.thread.join(timeout=3)
@@ -388,7 +387,7 @@ class BackendClient:
if recv_pin and store_id:
# 根据store_id动态确定平台类型
platform_type = self._get_platform_by_store_id(store_id)
if platform_type == "京东":
self._forward_to_jd(store_id, recv_pin, content)
elif platform_type == "抖音":
@@ -430,16 +429,17 @@ class BackendClient:
if not entry:
print(f"[JD Forward] 未找到连接: {shop_key}")
return
platform_info = (entry or {}).get('platform') or {}
ws = platform_info.get('ws')
aid = platform_info.get('aid')
pin_zj = platform_info.get('pin_zj')
vender_id = platform_info.get('vender_id')
loop = platform_info.get('loop')
print(f"[JD Forward] shop_key={shop_key} has_ws={bool(ws)} aid={aid} pin_zj={pin_zj} vender_id={vender_id} has_loop={bool(loop)} recv_pin={recv_pin}")
print(
f"[JD Forward] shop_key={shop_key} has_ws={bool(ws)} aid={aid} pin_zj={pin_zj} vender_id={vender_id} has_loop={bool(loop)} recv_pin={recv_pin}")
if ws and aid and pin_zj and vender_id and loop and content:
async def _send():
import hashlib as _hashlib
@@ -463,7 +463,7 @@ class BackendClient:
}
}
await ws.send(_json.dumps(msg))
import asyncio as _asyncio
_future = _asyncio.run_coroutine_threadsafe(_send(), loop)
try:
@@ -487,17 +487,18 @@ class BackendClient:
dy_mgr = DouYinWebsocketManager()
shop_key = f"抖音:{store_id}"
entry = dy_mgr.get_connection(shop_key)
if not entry:
print(f"[DY Forward] 未找到连接: {shop_key}")
return
platform_info = entry.get('platform', {})
douyin_bot = platform_info.get('douyin_bot')
message_handler = platform_info.get('message_handler')
print(f"[DY Forward] shop_key={shop_key} has_bot={bool(douyin_bot)} has_handler={bool(message_handler)} recv_pin={recv_pin}")
print(
f"[DY Forward] shop_key={shop_key} has_bot={bool(douyin_bot)} has_handler={bool(message_handler)} recv_pin={recv_pin}")
if douyin_bot and message_handler and content:
# 在消息处理器的事件循环中发送消息
def send_in_loop():
@@ -523,17 +524,17 @@ class BackendClient:
print(f"[DY Forward] 事件循环不可用")
except Exception as e:
print(f"[DY Forward] 发送过程异常: {e}")
# 在新线程中执行发送操作
import threading
send_thread = threading.Thread(target=send_in_loop, daemon=True)
send_thread.start()
else:
print("[DY Forward] 条件不足,未转发:",
{
'has_bot': bool(douyin_bot),
'has_handler': bool(message_handler),
'has_bot': bool(douyin_bot),
'has_handler': bool(message_handler),
'has_content': bool(content)
})
except Exception as e:
@@ -543,7 +544,8 @@ class BackendClient:
"""转发消息到千牛平台"""
try:
# TODO: 实现千牛平台的消息转发逻辑
print(f"[QN Forward] 千牛平台消息转发功能待实现: store_id={store_id}, recv_pin={recv_pin}, content={content}")
print(
f"[QN Forward] 千牛平台消息转发功能待实现: store_id={store_id}, recv_pin={recv_pin}, content={content}")
except Exception as e:
print(f"[QN Forward] 转发失败: {e}")
@@ -554,17 +556,18 @@ class BackendClient:
pdd_mgr = PDDWSManager()
shop_key = f"拼多多:{store_id}"
entry = pdd_mgr.get_connection(shop_key)
if not entry:
print(f"[PDD Forward] 未找到连接: {shop_key}")
return
platform_info = entry.get('platform', {})
pdd_instance = platform_info.get('pdd_instance')
loop = platform_info.get('loop')
print(f"[PDD Forward] shop_key={shop_key} has_pdd_instance={bool(pdd_instance)} has_loop={bool(loop)} recv_pin={recv_pin}")
print(
f"[PDD Forward] shop_key={shop_key} has_pdd_instance={bool(pdd_instance)} has_loop={bool(loop)} recv_pin={recv_pin}")
if pdd_instance and loop and content:
# 在拼多多实例的事件循环中发送消息
def send_in_loop():
@@ -585,17 +588,17 @@ class BackendClient:
print(f"[PDD Forward] 转发执行失败: {fe}")
except Exception as e:
print(f"[PDD Forward] 发送过程异常: {e}")
# 在新线程中执行发送操作
import threading
send_thread = threading.Thread(target=send_in_loop, daemon=True)
send_thread.start()
else:
print("[PDD Forward] 条件不足,未转发:",
{
'has_pdd_instance': bool(pdd_instance),
'has_loop': bool(loop),
'has_pdd_instance': bool(pdd_instance),
'has_loop': bool(loop),
'has_content': bool(content)
})
except Exception as e:
@@ -608,24 +611,24 @@ class BackendClient:
pdd_mgr = PDDWSManager()
shop_key = f"拼多多:{store_id}"
entry = pdd_mgr.get_connection(shop_key)
if not entry:
print(f"[PDD Transfer] 未找到拼多多连接: {shop_key}")
return
platform_info = entry.get('platform', {})
pdd_instance = platform_info.get('pdd_instance')
loop = platform_info.get('loop')
print(f"[PDD Transfer] 找到拼多多连接,准备执行转接: user_id={user_id}, cs_id={customer_service_id}")
if pdd_instance and loop:
# 设置目标客服ID并执行转接
def transfer_in_loop():
try:
# 设置目标客服ID
pdd_instance.csid = customer_service_id
# 在事件循环中执行转接
future = asyncio.run_coroutine_threadsafe(
pdd_instance.handle_transfer_message({
@@ -634,7 +637,7 @@ class BackendClient:
}),
loop
)
# 等待转接结果
try:
result = future.result(timeout=15) # 转接可能需要更长时间
@@ -646,77 +649,24 @@ class BackendClient:
print(f"[PDD Transfer] 转接执行失败: {fe}")
except Exception as e:
print(f"[PDD Transfer] 转接过程异常: {e}")
# 在新线程中执行转接操作
import threading
transfer_thread = threading.Thread(target=transfer_in_loop, daemon=True)
transfer_thread.start()
else:
print(f"[PDD Transfer] 条件不足: has_pdd_instance={bool(pdd_instance)}, has_loop={bool(loop)}")
except Exception as e:
print(f"[PDD Transfer] 拼多多转接失败: {e}")
def _transfer_to_jd(self, customer_service_id: str, user_id: str, store_id: str):
"""执行京东平台转接操作"""
def _transfer_to_qianniu(self, customer_service_id: str, user_id: str, store_id: str):
"""执行千牛平台转接操作"""
try:
from Utils.JD.JdUtils import WebsocketManager as JDWSManager
jd_mgr = JDWSManager()
shop_key = f"京东:{store_id}"
entry = jd_mgr.get_connection(shop_key)
if not entry:
print(f"[JD Transfer] 未找到京东连接: {shop_key}")
return
platform_info = entry.get('platform', {})
ws = platform_info.get('ws')
aid = platform_info.get('aid')
pin_zj = platform_info.get('pin_zj')
loop = platform_info.get('loop')
print(f"[JD Transfer] 找到京东连接,准备执行转接: user_id={user_id}, cs_id={customer_service_id}")
print(f"[JD Transfer] 连接参数: has_ws={bool(ws)}, aid={aid}, pin_zj={pin_zj}, has_loop={bool(loop)}")
if ws and aid and pin_zj and loop:
# 在事件循环中执行转接
def transfer_in_loop():
try:
# 导入FixJdCookie类来调用转接方法
from Utils.JD.JdUtils import FixJdCookie
jd_utils = FixJdCookie()
# 在事件循环中执行转接
future = asyncio.run_coroutine_threadsafe(
jd_utils.transfer_customer(ws, aid, user_id, pin_zj, customer_service_id),
loop
)
# 等待转接结果
try:
result = future.result(timeout=10) # 京东转接超时时间
if result:
print(f"[JD Transfer] ✅ 转接成功: user_id={user_id} -> cs_id={customer_service_id}")
else:
print(f"[JD Transfer] ❌ 转接失败: user_id={user_id}")
except Exception as fe:
print(f"[JD Transfer] 转接执行失败: {fe}")
except Exception as e:
print(f"[JD Transfer] 转接过程异常: {e}")
# 在新线程中执行转接操作
import threading
transfer_thread = threading.Thread(target=transfer_in_loop, daemon=True)
transfer_thread.start()
else:
print("[JD Transfer] 条件不足,未转接:",
{
'has_ws': bool(ws), 'has_aid': bool(aid), 'has_pin_zj': bool(pin_zj),
'has_loop': bool(loop)
})
# TODO: 实现千牛平台转接逻辑
print(f"[QN Transfer] 千牛平台转接功能待实现: user_id={user_id}, cs_id={customer_service_id}")
except Exception as e:
print(f"[JD Transfer] 京东转接失败: {e}")
print(f"[QN Transfer] 千牛转接失败: {e}")
def _handle_transfer(self, message: Dict[str, Any]):
"""处理转接消息"""
@@ -731,15 +681,16 @@ class BackendClient:
# 根据店铺ID确定平台类型并执行转接
try:
platform_type = self._get_platform_by_store_id(store_id)
if platform_type == "京东":
self._transfer_to_jd(customer_service_id, user_id, store_id)
# 京东转接逻辑 - 待实现
print(f"[JD Transfer] 京东平台转接功能待实现")
elif platform_type == "抖音":
# 抖音转接逻辑 - 待实现
print(f"[DY Transfer] 抖音平台转接功能待实现")
elif platform_type == "千牛":
# 千牛转接逻辑 - 待实现
print(f"[QN Transfer] 千牛平台转接功能待实现")
# 千牛转接逻辑
self._transfer_to_qianniu(customer_service_id, user_id, store_id)
elif platform_type == "拼多多":
self._transfer_to_pdd(customer_service_id, user_id, store_id)
else:
@@ -777,7 +728,7 @@ class BackendClient:
platform_name = message.get('platform_name', '')
content = message.get('content', '')
data = message.get('data', {})
# 判断是拼多多登录参数还是普通Cookie
if platform_name == "拼多多" and content == "pdd_login_params" and data.get('login_params'):
# 拼多多登录参数模式
@@ -809,7 +760,7 @@ class BackendClient:
nickname = staff.get('nickname', '')
print(f" - {nickname} ({pin})")
if self.customers_callback: # 假设客服列表更新也触发客服列表回调
if self.customers_callback: # 假设客服列表更新也触发客服列表回调
self.customers_callback(staff_list, store_id)
# ==================== 辅助方法 ====================

View File

@@ -9,6 +9,7 @@ from WebSocket.BackendClient import BackendClient
from Utils.JD.JdUtils import JDListenerForGUI as JDListenerForGUI_WS
from Utils.Dy.DyUtils import DouYinListenerForGUI as DYListenerForGUI_WS
from Utils.Pdd.PddUtils import PddListenerForGUI as PDDListenerForGUI_WS
from Utils.QianNiu.QianNiuUtils import QianNiuListenerForGUI as QNListenerForGUI_WS
_backend_client = None
@@ -123,20 +124,50 @@ class WebSocketManager:
return False
def _handle_platform_login(self, platform_name: str, store_id: str, cookies: str):
"""处理平台登录逻辑"""
"""处理平台登录请求"""
try:
if platform_name == "京东" and store_id and cookies:
self._start_jd_listener(store_id, cookies)
elif platform_name == "抖音" and store_id and cookies:
self._start_douyin_listener(store_id, cookies)
elif platform_name == "千牛" and store_id and cookies:
# 平台名称映射
platform_map = {
"淘宝": "千牛",
"QIANNIU": "千牛",
"京东": "京东",
"JD": "京东",
"抖音": "抖音",
"DY": "抖音",
"DOUYIN": "抖音",
"拼多多": "拼多多",
"PDD": "拼多多",
"PINDUODUO": "拼多多"
}
# 标准化平台名称
normalized_platform = platform_map.get(platform_name.upper(), platform_name)
self._log(f"处理平台登录: {platform_name} -> {normalized_platform}, 店铺={store_id}", "INFO")
# 🔧 关键修改:确保每个平台都能独立处理自己的登录请求
if normalized_platform == "千牛":
if cookies == "login_success":
self._log("⚠️ 千牛平台收到空cookies但允许启动监听器", "WARNING")
cookies = "" # 清空cookies千牛不需要真实cookies
self._start_qianniu_listener(store_id, cookies)
elif platform_name == "拼多多" and store_id and cookies:
elif normalized_platform == "京东":
self._start_jd_listener(store_id, cookies)
elif normalized_platform == "抖音":
self._start_douyin_listener(store_id, cookies)
elif normalized_platform == "拼多多":
self._start_pdd_listener(store_id, cookies)
else:
self._log(f"不支持的平台或参数不全: {platform_name}", "WARNING")
self._log(f"不支持的平台: {platform_name}", "ERROR")
except Exception as e:
self._log(f"启动平台监听失败: {e}", "ERROR")
self._log(f"处理平台登录失败: {e}", "ERROR")
import traceback
self._log(f"错误详情: {traceback.format_exc()}", "DEBUG")
def _start_jd_listener(self, store_id: str, cookies: str):
"""启动京东平台监听"""
@@ -199,7 +230,7 @@ class WebSocketManager:
except json.JSONDecodeError as e:
self._log(f"❌ Cookie JSON解析失败: {e}", "ERROR")
return False
result = asyncio.run(listener.start_with_cookies(store_id=store_id, cookie_dict=cookie_dict))
return result
except Exception as e:
@@ -250,13 +281,64 @@ class WebSocketManager:
self._log(f"失败状态下报抖音平台连接状态也失败: {send_e}", "ERROR")
def _start_qianniu_listener(self, store_id: str, cookies: str):
"""启动千牛平台监听"""
"""启动千牛平台监听(单连接多店铺架构)"""
try:
# 这里可以添加千牛监听逻辑
self._log("千牛平台监听功能待实现", "INFO")
# 获取用户token从后端客户端获取
exe_token = None
if self.backend_client:
exe_token = getattr(self.backend_client, 'token', None)
if not exe_token:
self._log("❌ 缺少exe_token无法启动千牛监听器", "ERROR")
return
def _runner():
try:
listener = QNListenerForGUI_WS()
# 千牛平台使用新架构传递store_id和exe_token
asyncio.run(listener.start_listening_with_store(store_id, exe_token))
except Exception as e:
self._log(f"千牛监听器运行异常: {e}", "ERROR")
# 在新线程中启动监听器
thread = Thread(target=_runner, daemon=True)
thread.start()
# 保存监听器引用
self.platform_listeners[f"千牛:{store_id}"] = {
'thread': thread,
'platform': '千牛',
'store_id': store_id,
'exe_token': exe_token
}
# 上报连接状态给后端
if self.backend_client:
try:
self.backend_client.send_message({
"type": "connect_message",
"store_id": store_id,
"status": True
})
except Exception as e:
self._log(f"上报连接状态失败: {e}", "WARNING")
self._log("已启动千牛平台监听(单连接多店铺架构)", "SUCCESS")
except Exception as e:
self._log(f"启动千牛平台监听失败: {e}", "ERROR")
# 确保失败时也上报状态
if self.backend_client:
try:
self.backend_client.send_message({
"type": "connect_message",
"store_id": store_id,
"status": False
})
except Exception as send_e:
self._log(f"失败状态下报千牛平台连接状态也失败: {send_e}", "ERROR")
def _start_pdd_listener(self, store_id: str, data: str):
"""启动拼多多平台监听"""
try: