使用Discord - Node.js维护WebSocket连接

jv2fixgn  于 2022-11-11  发布在  Node.js
关注(0)|答案(1)|浏览(208)

我试图创建一个不和谐的机器人使用原始API,但一段时间后,机器人不再工作。
我想是因为我不维护WebSocket连接,那么,我怎么才能维护它呢?
我的当前代码:

const ws = new WebSocket("wss://gateway.discord.gg/?v=6&encoding=json");

    let interval = 0;
    let payload = {
      op: 2,
      d: {
        token: botToken,
        intents: 32767,
        properties: {
          $os: "linux",
          $browser: "chrome",
          $device: "chrome",
        },
      },
    };

    ws.on("open", function open() {
      ws.send(JSON.stringify(payload));
    });

    ws.on("message", function incoming(data) {
      let response = JSON.parse(data);
      const { t, event, op, d } = response;

      switch (op) {
        case 10:
          const { heartbeat_interval } = d;
          interval = heartbeat(heartbeat_interval);
        break;
      }
    });

    const heartbeat = (ms) => {
      return setInterval(() => {
        ws.send(JSON.stringify({ op: 1, d: null }));
      }, ms);
    };
fcg9iug3

fcg9iug31#

使用此服务reconnecting-websocket
npm install --save reconnecting-websocket

const WS = require("ws");
const ReconnectingWebSocket = require("reconnecting-websocket");
const ws = new ReconnectingWebSocket("wss://gateway.discord.gg/?v=6&encoding=json", [], { WebSocket: WS });
let interval = 0;
let session_id;
let last_seq;
let payload = {
  op: 2,
  d: {
    token: botToken,
    intents: 32767,
    properties: {
      $os: "linux",
      $browser: "chrome",
      $device: "chrome",
    },
  },
};

ws.addEventListener('open', () => {
    ws.send(JSON.stringify(payload))
});

ws.addEventListener ('message', function incoming(rawdata){
let payload = JSON.parse(rawdata.data);
const {t, event, op, d, s}  = payload;
last_seq = s;
  switch (op) {
    case 10:
      const { heartbeat_interval } = d;
      interval = heartbeat(heartbeat_interval);
    break;
  }
});

const heartbeat = (ms) => {
  return setInterval(() => {
    ws.send(JSON.stringify({ op: 1, d: last_seq }));
  }, ms);
};

相关问题