Search code examples
pythonwebsocket

websocket connection closing after sometime


So i was trying to implement discord's WS to join a VC as per their documentations. But the connection closes itself after sometime for no reason/error

Here is my code ->

import json
import time
from websocket import WebSocket
from websocket import WebSocketApp

class ConnectWebSocket(WebSocketApp):
    """Class Inherited From `WebSocketApp`"""
    def __init__(
            self,
            token: str,
            guild_id: str,
            channel_id: str
        ):
        super().__init__(
            header=[
                "Accept-Language: en-US",
                "Connection: Upgrade",
                "Host: gateway.discord.gg",
                "Sec-Websocket-Extensions: permessage-deflate; client_max_window_bits",
                "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) discord/1.0.9153 Chrome/124.0.6367.243 Electron/30.1.0 Safari/537.36"
            ],
            url="wss://gateway.discord.gg/?v=9&encoding=json",
            on_open=self.on_connection,
            on_message=self.on_message
        )
        self._token = token
        self._guild = guild_id
        self._channel = channel_id

    def on_connection(self, ws):
        print("Opened a connection...")
        ws.send(json.dumps({
            "op": 2,
            "d": {
                "token": self._token,
                "intents": 513,
                "properties": {
                "os": "windows 10",
                "browser": "Google Chrome",
                "device": "Windows"
                }
            }
        }))
        print("First Payload Sent")
        ws.send(json.dumps({
                "op": 4,
                "d": {
                    "guild_id": self._guild,
                    "channel_id": self._channel,
                    "self_mute": False,
                    "self_deaf": False
                }
            }
        ))
        print("Second Payload Sent")

    def on_message(self, ws, message):
        print(f"Received message")

    def run_forever(self, proxy):
        username_password, proxy_address_port = proxy.split('@')
        username, password = username_password.split(':')
        proxy_address, port = proxy_address_port.split(':')
        return super().run_forever(
            reconnect=5,
            ping_interval=10,
            proxy_type="http",
            http_proxy_host=proxy_address,
            http_proxy_port=int(port),
            http_proxy_auth=(username, password),
            ping_payload={"op": 6, "d": int(time.time() * 1000)},
        )
    
    def on_error(self, ws, error):
        print(error)

    def on_close(self, ws, close_status_code, close_msg):
        print("Closed con")

The account joins the vc for sometime and then disconnects after 30-40 seconds. But why? i have set the ping payload and interval to send a recon request every 10 seconds but that doesn't seem to work. I tried searching up but got nothing.

Im pretty new to websockets any help will be appreciated...!


Solution

  • try to not use the built in ping in the websocket package, instead set a while loop and manually send ping every 5 seconds, sometimes it works