简体   繁体   中英

Maintain websocket connection with Discord - Node.js

I'm trying to create a Discord bot using raw api, but after some time, the bot doesn't works anymore.
I think is because I don't maintain websocket connection, so, how I can mantain it?
My current code:

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

Use this service 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);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM