From 8b4684675eb3d82682e3f87f7adb3c50936f7b4a Mon Sep 17 00:00:00 2001 From: wangcham Date: Thu, 13 Mar 2025 10:41:21 -0400 Subject: [PATCH] fix: eliminate critical message queue blockage in wxoa --- libs/official_account_api/api.py | 31 ++++++++++++++++++------- pkg/platform/sources/officialaccount.py | 4 +++- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/libs/official_account_api/api.py b/libs/official_account_api/api.py index af427063..b777d626 100644 --- a/libs/official_account_api/api.py +++ b/libs/official_account_api/api.py @@ -27,6 +27,8 @@ xml_template = """ """ +user_msg_queue = {} + class OAClient(): def __init__(self,token:str,EncodingAESKey:str,AppID:str,Appsecret:str): @@ -224,9 +226,13 @@ class OAClientForLongerResponse(): if oa.msg_queue.get(from_user) and oa.msg_queue[from_user][0]["content"]: - queue_top = oa.msg_queue[from_user].pop(0) + queue_top = oa.msg_queue[from_user].pop(0) queue_content = queue_top["content"] + # 弹出用户消息 + if user_msg_queue.get(from_user) and user_msg_queue[from_user]: + user_msg_queue[from_user].pop(0) + response_xml = xml_template.format( to_user=from_user, from_user=to_user, @@ -242,14 +248,23 @@ class OAClientForLongerResponse(): create_time=int(time.time()), content="AI正在思考中,请发送任意内容获取回答。" ) + + if user_msg_queue.get(from_user) and user_msg_queue[from_user][0]["content"]: + return response_xml + else: + message_data = await self.get_message(xml_msg) + + if message_data: + event = OAEvent.from_payload(message_data) + if event: + user_msg_queue.setdefault(from_user,[]).append( + { + "content":event.message, + } + ) + await self._handle_message(event) - message_data = await self.get_message(xml_msg) - if message_data: - event = OAEvent.from_payload(message_data) - if event: - await self._handle_message(event) - - return response_xml + return response_xml except Exception as e: traceback.print_exc() diff --git a/pkg/platform/sources/officialaccount.py b/pkg/platform/sources/officialaccount.py index 3abc8c42..13a53038 100644 --- a/pkg/platform/sources/officialaccount.py +++ b/pkg/platform/sources/officialaccount.py @@ -101,13 +101,15 @@ class OfficialAccountAdapter(adapter.MessagePlatformAdapter): Appsecret=config['AppSecret'], AppID=config['AppID'], ) - if self.config['Mode'] == "passive": + elif self.config['Mode'] == "passive": self.bot = OAClientForLongerResponse( token=config['token'], EncodingAESKey=config['EncodingAESKey'], Appsecret=config['AppSecret'], AppID=config['AppID'], ) + else: + raise KeyError("请设置微信公众号通信模式") async def reply_message(self, message_source: platform_events.FriendMessage, message: platform_message.MessageChain, quote_origin: bool = False):