[Python] Why is connecting to a websocket in python returning a rejected websocket connection?

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    So im trying to connect to the TikTok websocket for chat messages. In the socket request made from the incognito browser, it connects and returns data in protobuf which represent the chat messages. When i connect in python to the websocket, it returns with websocket rejected. I dont think its anything to do with authentication cookies, because the incognito browser doesnt have any and the stream chat works. Does anyone know why? Would appreciate the help here! THanks

    import asyncio import websockets import datetime

    async def connect(cookies):
    uri = "wss://webcast16-ws-useast2a.tiktok.com/webcast/im/ws_proxy/ws_reuse_supplement/?version_code=180800&device_platform=web&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=en-US&browser_platform=Win32&browser_name=Mozilla&browser_version=5.0%20(Windows%20NT%2010.0;%20Win64;%20x64)%20AppleWebKit/537.36%20(KHTML,%20like%20Gecko)%20Chrome/136.0.0.0%20Safari/537.36%20Edg/136.0.0.0&browser_online=true&tz_name=Europe/London&app_name=tiktok_web&sup_ws_ds_opt=1&version_code=270000&update_version_code=2.0.0&compress=gzip&wrss=FQ6xeFgNFFOnt8GqF66yzNwx7NC_rWgR7vC6moobbjM&host=https://webcast.tiktok.com&aid=1988&live_id=12&debug=false&app_language=en&client_enter=1&room_id=7509146835937561366&identity=audience&history_comment_count=6&heartbeat_duration=0&last_rtt=281.400146484375&internal_ext=fetch_time:1748361800370|start_time:0|ack_ids:,,|flag:0|seq:1|next_cursor:1748361800370_7509156752575699652_1_1_7509156597956878851_0|wss_info:0-1748361800370-0-0&cursor=1748361800370_7509156752575699652_1_1_7509156597956878851_0&resp_content_type=protobuf&did_rule=3&webcast_language=en"
    headers = {
    "accept-encoding": "gzip, deflate, br, zstd",
    "accept-language": "en-US,en;q=0.9",
    # "cache-control": "no-cache",
    # "connection": "Upgrade",
    # "host": "im-ws.tiktok.com",
    "origin": "https://www.tiktok.com",
    # "pragma": "no-cache",
    # "sec-websocket-extensions": "permessage-deflate; client_max_window_bits",
    # "sec-websocket-key": "17q0Mjaeh07M/jOeU32fuA==",
    # "sec-websocket-version": "13",
    # "upgrade": "websocket",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0",
    "cookie": cookies
    }

    try:
    async with websockets.connect(uri) as websocket:
    async with websockets.connect(uri, additional_headers=headers) as websocket:
    response = await websocket.recv()
    print(response)
    # async for response in websocket:
    # print(response)
    except websockets.exceptions.ConnectionClosedError as e:
    print(f"Connection closed unexpectedly: {e}")
    except Exception as e:
    print(f"Other error: {e}")

    def json_list_to_concatenated_string(json_list):
    return ' '.join(
    f"{item['name']}={item['value']}" + (';' if i < len(json_list) - 1 else '')
    for i, item in enumerate(json_list)
    )

    result = json_list_to_concatenated_string(cookies)
    asyncio.run(connect(result))


    Server rejected websocket connection error

    Socket request from incognito browser

    Cookies present on incognito browser

    Continue reading...

Compartilhe esta Página