【问题标题】:Discord bot connect websocket pythonDiscord bot连接websocket python
【发布时间】:2021-10-16 13:08:19
【问题描述】:

我有这个连接到不和谐网关 websocket 的代码,它做了它应该做的事情,但是大约 1 分钟后它脱机了,我应该怎么做才能防止它脱机。请提出建议或意见。

Edit* 我没有使用 discord.py 模块,因为它在 2.0+ 版本中不支持 self bot,而且我将同时运行大约 1000++++ 个令牌,因此使用 websocket 是更好的选择我

代码:

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))

错误:

【问题讨论】:

  • 你为什么不直接使用bot.run('TOKEN')
  • 我愿意,我将同时运行大约 1000++++ 个令牌,并认为使用 websocket 会更好
  • 所以有什么答案吗?
  • 好吧,您计算机上的某些软件正在中止连接到 discord 网关的程序。

标签: python python-3.x websocket discord gateway


【解决方案1】:

我遇到了同样的问题,只是几个小时后不和谐断开了我的连接。

当遇到重新连接到网关的异常时,您可以尝试再次运行ws.connect("wss://gateway.discord.gg/?v=9&encoding=json"),这对我来说很好,所以代码如下:

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))

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2021-04-29
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多