Skip to content

回复消息嵌套时,Element解析缺少ReplyElement类型 #157

@HadeonYu

Description

@HadeonYu

发送文本消息A,用消息B回复消息A,再用消息C回复消息B:

Image

消息C中消息B的 Elements 数组只有 TextElement ,没有对消息A的 ReplyElement

Image

这就导致需要向上寻找最终被回复的根消息(场景中的消息A)时不方便,目前我的方案是用函数 func (c *QQClient) GetPrivateMessages(uin, timestamp, count uint32) ([]*message2.PrivateMessage, error) ,用Time字段迭代找到root消息:

func findReplyRootMsg(msg *message.PrivateMessage) (*message.PrivateMessage, error) {
	var root *message.PrivateMessage // 根消息
	replyMsg, ok := msg.Elements[0].(*message.ReplyElement)
	if !ok {
		return nil, fmt.Errorf("first element is Reply but type assertion failed")
	}
	for {
		// 用Time迭代寻找根message
		msgs, err := qqClient.GetPrivateMessages(replyMsg.SenderUin, replyMsg.Time, 1)
		if err != nil {
			return nil, fmt.Errorf("fail to get messages (uin=%v, time=%v): %w", replyMsg.SenderUin, replyMsg.Time, err)
		}
		if len(msgs) == 0 {
			return nil, fmt.Errorf("no message returned for (uin=%v, time=%v)", replyMsg.SenderUin, replyMsg.Time)
		}

		m := msgs[0]
		if len(m.Elements) == 0 {
			return nil, fmt.Errorf("empty message")
		}

		// 仍是回复消息,继续迭代
		if m.Elements[0].Type() == message.Reply {
			if next, ok := m.Elements[0].(*message.ReplyElement); ok {
				replyMsg = next
				continue
			}
		}

		// 第一条非 Reply 的消息 => 根消息
		root = m
		break
	}
	return root, nil
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions