from 抖音直播间弹幕.extractors.douyin_pb2 import PushFrame, Response, ChatMessage
import binascii
import gzip


def 解析直播间广播数据(content):
    # 将16进制转换成原始字节
    res_bytes = binascii.unhexlify(content)

    # 转成PushFrame数据对象
    frame = PushFrame()
    frame.ParseFromString(res_bytes)

    # 对PushFrame的 payload 内容进行gzip解压
    origin_bytes = gzip.decompress(frame.payload)

    # 根据Response+gzip解压数据，生成Response数据对象
    response = Response()
    response.ParseFromString(origin_bytes)

    msg_list = []
    for item in response.messagesList:
        if item.method != "WebcastChatMessage":
            continue
        # 生成ChatMessage数据对象
        message = ChatMessage()
        message.ParseFromString(item.payload)
        webcast_chat_message = {
            'user_id': message.user.id,
            'user_nickName': message.user.nickName,
            'content': message.content
        }
        msg_list.append(webcast_chat_message)
    return msg_list


if __name__ == '__main__':
    content = '[encoded data, 4210 characters]'
    res = 解析直播间广播数据(content)
    print(res)
