import asyncio
import requests
import websockets
import time
import json
from datetime import datetime

# 构建API请求链接
room_id = "17066184578990"
timestamp = int(time.time() * 1000)
api_url = f"https://live-api.immomo.com/open/m/room/profile?roomid={room_id}&momoid=&src=m50011&web_uid=11126216061Xazx3TgC&_= {timestamp}"

# 发起API请求
response = requests.get(api_url)
data = response.json()
ws_token = data["data"].get("ws_token", "")
umomoid = data["data"]["momoid"]

async def connect():
    uri = "wss://live-ws.immomo.com/ws/im"
    async with websockets.connect(uri) as websocket:
        print(f"链接websocket:[{uri}] 完成")

        momoid = umomoid
        roomid = room_id
        token = f"{ws_token}"

        data = '{{"msg_id":1,"client_time":{0},"type":"Sauth","data":{{"momoid":"{1}","roomid":"{2}","token":"{3}","barType":"NORMAL"}}}}'.format(
            timestamp, momoid, roomid, token)
        print(data)

        await websocket.send(data)

        print("Send Hello")

        while True:
            try:
                response = await websocket.recv()
                current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                #print(f"[{current_time}] 收到原始消息 => " + response)

                try:
                    json_data = json.loads(response)
                    #print(f"[{current_time}] 收到JSON消息 => ", json_data)

                    message_type = json_data['groups'][0]['units'][0]['type']

                    if message_type == "Message":
                        nick = json_data['groups'][0]['nick']
                        text = json_data['groups'][0]['units'][0]['Msg.Message.data']['text']
                        print(f"[{current_time}] {nick} : {text}")
                    elif message_type == "EnterRoom":
                        text = json_data['groups'][0]['units'][0]['Set.EnterRoom.data']['text']
                        print(f"[{current_time}] 有新人: {text}")
                    elif message_type == "BiliBili":
                        nick = json_data['groups'][0]['nick']
                        text = json_data['groups'][0]['units'][0]['Pay.BiliBili.data']['text']
                        print(f"[{current_time}] {nick} : {text}")
                    elif message_type == "GiftV3":
                        nick = json_data['groups'][0]['nick']
                        text = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['text']
                        product_id = json_data['groups'][0]['units'][0]['GiftV3.giftV3']['productId']
                        print(f"[{current_time}] 用户: {nick} 送出礼物,内容为: {text},产品ID为: {product_id}")
                    #else:
                        # 其他消息类型的处理
                        #print(f"[{current_time}] 收到未处理的消息类型: {message_type}")

                except KeyError as e:
                    print(f"[{current_time}] JSON数据中缺少必要的键:", e)
                except json.JSONDecodeError as e:
                    print(f"[{current_time}] 无法解析为JSON格式: ", e)

            except websockets.exceptions.ConnectionClosedError:
                print(f"[{current_time}] 与服务器断开链接")
                break

async def main():
    await connect()

asyncio.run(main())