Python 如何在Discord网关Websocket上发送JSON有效负载标识
我正在使用此Python代码连接到discord网关,基本上我需要发送一个操作码2标识,以便能够在带有discord API的通道上发送消息Python 如何在Discord网关Websocket上发送JSON有效负载标识,python,websocket,discord,Python,Websocket,Discord,我正在使用此Python代码连接到discord网关,基本上我需要发送一个操作码2标识,以便能够在带有discord API的通道上发送消息 import websocket import json import pprint ws = websocket.WebSocket() # Connect to host url ws.connect("wss://gateway.discord.gg/?v=6&encoding=json") # Use ws.send() to send d
import websocket
import json
import pprint
ws = websocket.WebSocket()
# Connect to host url
ws.connect("wss://gateway.discord.gg/?v=6&encoding=json")
# Use ws.send() to send data to server
# Use ws.recv() to get the data sent from server
result = ws.recv()
print "Received: ",result
heartbeat = '{"op": 1,"d": 251}'
p = '{"token": "MY_BOT_TOKEN","properties": {"$os": "linux","$browser": "disco","$device": "disco" },"compress": false, "large_threshold": 250,"shard": [0, 1],"presence": {"game": {},"status": "online","since": null,"afk": false}}'
h = json.loads(heartbeat)
h_json = json.dumps(h)
p_load = json.loads(p)
p_json = json.dumps(p_load)
print(h_json)
ws.send(h_json)
# Use ws.close() to close the WebSocket handshake
result = ws.recv()
print "Received: ",result
ws.send(p_json)
result = ws.recv()
print "Received: ",result
这段代码的作用是:在操作码10之后发送心跳信号,从服务器接收操作码11,为操作码2发送json对象
但结果是:
Received: {"t":null,"s":null,"op":10,"d":{"heartbeat_interval":41250,"_trace":["gateway-prd-main-rskw"]}}
{"d": 251, "op": 1}
Received: {"t":null,"s":null,"op":11,"d":null}
Received:
问题是在发送json后连接被关闭,我无法收到响应,我的请求中是否有任何错误?我在第一次尝试时遇到了相同的问题,因此我仔细阅读了文档,找到了下面的部分
从客户端发送到网关API的数据包被封装在网关有效负载对象中,并且必须设置正确的操作码和数据对象。然后可以将有效负载对象序列化为所选格式(请参阅ETF/JSON),并通过websocket发送。向网关发送的有效负载限制为最多4096字节,超过此限制将导致连接终止,错误代码为4002
好的,那是什么意思? 发送到网关API的每个数据包都需要遵循请求模型
{
"op": 0,
"d": {},
"s": 42,
"t": "GATEWAY_EVENT_NAME"
}
此请求模型中的每个对象是什么?
op
:告诉网关API您的有效负载类型的代码。您可以找到op
的列表
d
:有效负载本身。下面是您试图发送的json(您的p
变量)
s
和t
:仅对op
0是必需的,因此您可以将其作为null传递给IDENTIFY
您的请求应该是什么样子的
我认为你发送的心跳有效载荷是错误的 内部d键是客户端收到的最后一个序列号。如果您尚未收到序列号,请发送null。 我不太确定,但您可以尝试将
d
的值更改为null
{
"op": 2,
"d": {
"token": "YOUR_TOKEN_HERE",
"properties": {
"$os": "linux",
"$browser": "disco",
"$device": "disco"
}
},
"s": null,
"t": null
}