Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

可否提供python获取直播弹幕的示例代码? #44

Open
xuan06zyx opened this issue Jun 6, 2024 · 0 comments
Open

可否提供python获取直播弹幕的示例代码? #44

xuan06zyx opened this issue Jun 6, 2024 · 0 comments

Comments

@xuan06zyx
Copy link

xuan06zyx commented Jun 6, 2024

我用gpt生成的代码反复修改测试报错永远是 websockets.exceptions.ConnectionClosedError: no close frame received or sent
目前我的代码是以下

import json
import base64
import asyncio

import websockets
from urllib.parse import quote


async def send_heartbeat(websocket):
    while True:
        await websocket.send("ping")
        await asyncio.wait_for(websocket.recv(), timeout=5)
        print("发送心跳包")
        await asyncio.sleep(30)  # 每30秒发送一次心跳包


async def connect_and_print(url):
    async with websockets.connect(url) as websocket:
        start = json.dumps({"roomid": 465244,
                            "protover": 2,
                            "platform": "web",
                            "type": 2
                            })
        await websocket.send(start)
        print(start)
        print("加入房间")
        await asyncio.sleep(5)
        await websocket.send("ping")
        print("发送心跳包")
        await asyncio.sleep(5)
        await asyncio.wait_for(websocket.recv(), timeout=5)
        print('接收消息')

        # await asyncio.sleep(5)
        # print("发送心跳包")
        # await websocket.send("ping")
        # await asyncio.sleep(5)

        while True:
            # 接收消息
            message = await asyncio.wait_for(websocket.recv(), timeout=5)
            print(f"Received message: {message}")


# 替换为你的 WebSocket 服务器地址
websocket_server_url = "wss://broadcastlv.chat.bilibili.com/sub"

# 使用 asyncio 运行协程
asyncio.run(connect_and_print(websocket_server_url))

大概是在进房以后无论是心跳还是进房消息都可以发送 后续不论是接收消息还是再次发送心跳都会报错

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant