Ardil Mc
Ardil Mc

Reputation: 19

Discord bot connect websocket python

I have this code that connect to discord gateway websocket and it did what it suppose to do but after around 1 minute it went offline what should I do to prevent it from going offline. Please give suggestions or advice.

Edit* I am not using discord.py module because it does not support self bot in the version 2.0+ and I am going to run around 1000++++ tokens at the same time so using websocket is a better choice for me

code:

import json
import threading
import time
import websocket
from concurrent.futures import ThreadPoolExecutor 
with open("tokens.txt") as f:
    token = f.readlines()
    tokens = [x.strip() for x in token] 

def connect(token):
    ws = websocket.WebSocket()
    ws.connect("wss://gateway.discord.gg/?v=9&encoding=json")
    RECV = json.loads(ws.recv())
    heartbeat_interval = RECV['d']['heartbeat_interval']
    while True:
        try:
            ws.send(json.dumps({"op":2,"d": {"token":token, "properties": {"$os":"windows","$browser":"Discord","$device": "desktop" }}}))
            time.sleep(heartbeat_interval/1000)
        
        except Exception as e:
            print(e)

threads_create = [] 
with ThreadPoolExecutor(max_workers=len(tokens)) as executor:
    for token in tokens:
        threads_create.append(executor.submit(connect,token))

ERROR: enter image description here

Upvotes: 0

Views: 1813

Answers (1)

Spider-Man
Spider-Man

Reputation: 50

I had the same issue, except discord disconnected me after a few hours.

You can try to run ws.connect("wss://gateway.discord.gg/?v=9&encoding=json") again when it faces an exception to reconnect to the gateway, that worked fine for me, so the code would be something like:

import json
import threading
import time
import websocket
from concurrent.futures import ThreadPoolExecutor 
with open("tokens.txt") as f:
    token = f.readlines()
    tokens = [x.strip() for x in token] 

def connect(token):
    ws = websocket.WebSocket()
    ws.connect("wss://gateway.discord.gg/?v=9&encoding=json")
    RECV = json.loads(ws.recv())
    heartbeat_interval = RECV['d']['heartbeat_interval']
    while True:
        try:
            ws.send(json.dumps({"op":2,"d": {"token":token, "properties": {"$os":"windows","$browser":"Discord","$device": "desktop" }}}))
            time.sleep(heartbeat_interval/1000)
        
        except Exception as e:
            print(e)
            ws.connect("wss://gateway.discord.gg/?v=9&encoding=json")

threads_create = [] 
with ThreadPoolExecutor(max_workers=len(tokens)) as executor:
    for token in tokens:
        threads_create.append(executor.submit(connect,token))

Upvotes: 1

Related Questions