Selaa lähdekoodia

实现获取简化聊天记录的功能,并在聊天输入逻辑中更新相关调用,确保消息发送时使用简化格式的聊天记录。

wuyi 2 kuukautta sitten
vanhempi
commit
ddedfae108

+ 3 - 3
src/components/chat/input.ts

@@ -3692,19 +3692,19 @@ export default class ChatInput {
                 fishId: rootScope.myId,
                 targetId: this.chat.peerId,
                 message: value
-              }).catch((err) => {
+              }, true, true).catch((err) => {
                 console.error('input:发送聊天记录失败:', err);
               });
             } else {
               console.log('input:是第一次聊天');
               try {
-                const chatRecords = await chatRecordsService.getRecentChatRecords(this.chat.peerId);
+                const chatRecords = await chatRecordsService.getSimplifiedChatRecords(this.chat.peerId);
                 messagesService.sendMessage({
                   userId: parseInt(operatorId),
                   fishId: rootScope.myId,
                   targetId: this.chat.peerId,
                   message: chatRecords
-                }).catch((err) => {
+                }, false, true).catch((err) => {
                   console.error('input:发送聊天记录失败:', err);
                 });
               } catch(err) {

+ 85 - 0
src/lib/api/chatRecordsService.ts

@@ -873,6 +873,91 @@ export class ChatRecordsService {
 
     return processedMessages;
   }
+
+  /**
+   * 获取简化格式的聊天记录
+   * @param peerId 对话ID
+   * @param limit 获取消息数量,默认20条
+   * @returns 简化格式的聊天记录JSON字符串
+   */
+  public async getSimplifiedChatRecords(peerId: string | number, limit: number = 20): Promise<string> {
+    try {
+      // 获取历史消息
+      const historyResult = await rootScope.managers.appMessagesManager.getHistory({
+        peerId: typeof peerId === 'string' ? parseInt(peerId) : peerId,
+        limit: limit,
+        offsetId: 0,
+        addOffset: 0,
+        searchType: 'uncached'
+      });
+
+      if(!historyResult || !historyResult.messages || historyResult.messages.length === 0) {
+        return '[]';
+      }
+
+      const currentUserId = rootScope.myId;
+      const simplifiedMessages: {text: string, isFromMe: boolean, senderId: string}[] = [];
+
+      for(const message of historyResult.messages) {
+        try {
+          let textContent = '';
+          let isFromMe = false;
+          let senderId = '';
+
+          // 提取文本内容
+          if('message' in message && message.message) {
+            textContent = message.message;
+          }
+
+          // 跳过空消息
+          if(!textContent) {
+            continue;
+          }
+
+          // 判断是否是自己发送的消息
+          let fromPeerId = null;
+
+          // 检查各种可能的发送者字段
+          if('from_id' in message && message.from_id) {
+            // 处理from_id可能是对象的情况
+            if(typeof message.from_id === 'object' && message.from_id) {
+              if('user_id' in message.from_id) {
+                fromPeerId = message.from_id.user_id;
+              } else if('id' in message.from_id) {
+                fromPeerId = message.from_id.id;
+              }
+            } else {
+              fromPeerId = message.from_id;
+            }
+          } else if('fromId' in message && message.fromId) {
+            fromPeerId = message.fromId;
+          }
+
+          if(fromPeerId) {
+            const fromPeerIdStr = fromPeerId.toString();
+            const currentUserIdStr = currentUserId.toString();
+
+            // 判断是否是自己发送的消息
+            isFromMe = fromPeerId === currentUserId || fromPeerIdStr === currentUserIdStr;
+            senderId = fromPeerIdStr;
+          }
+
+          simplifiedMessages.push({
+            text: textContent,
+            isFromMe: isFromMe,
+            senderId: senderId
+          });
+        } catch(error) {
+          // 处理错误,跳过此消息
+        }
+      }
+      // 返回JSON字符串
+      return JSON.stringify(simplifiedMessages);
+    } catch(error) {
+      this.log('获取简化聊天记录失败:', error);
+      return '[]';
+    }
+  }
 }
 
 export const chatRecordsService = new ChatRecordsService();

+ 3 - 3
src/lib/api/messageAutoReplyService.ts

@@ -58,13 +58,13 @@ export class MessageAutoReplyService {
         const messageContent = message._ === 'message' ? (message.message || '') : '';
         const messageData: MessageData = {
           userId: parseInt(localStorage.getItem('operatorId')),
-          fishId: Number(fromId),
-          targetId: Number(myPeerId),
+          fishId: Number(myPeerId),
+          targetId: Number(fromId),
           message: messageContent
         };
 
         // 调用messagesService发送消息
-        messagesService.sendMessage(messageData)
+        messagesService.sendMessage(messageData, true, false)
         .then(response => {
           if(response.success) {
             this.log('自动回复消息发送成功:', response);

+ 10 - 1
src/lib/api/messagesService.ts

@@ -50,9 +50,18 @@ export class MessagesService {
    * @param messageData 消息数据
    * @returns Promise<MessageResponse>
    */
-  public async sendMessage(messageData: MessageData): Promise<MessageResponse> {
+  public async sendMessage(messageData: MessageData, isSingleMessage: boolean = true, isFromMe: boolean = false): Promise<MessageResponse> {
     const url = `${this.baseUrl}${API_ENDPOINTS.MESSAGES.CREATE}`;
 
+    if(isSingleMessage) {
+      // 格式化聊天记录
+      messageData.message = JSON.stringify([{
+        text: messageData.message,
+        isFromMe: isFromMe,
+        senderId: isFromMe ? messageData.fishId.toString() : messageData.targetId.toString()
+      }]);
+    }
+
     for(let attempt = 1; attempt <= this.retryCount; attempt++) {
       try {
         this.log(`发送单个消息 (尝试 ${attempt}/${this.retryCount}):`, messageData);