I'm trying to use Bun to create an app that can interact with the Discord gateway. I tried the same code in node.js and it works properly, but in bun it only works sometimes. What I am doing is:
- Declare a paylod for identification.
- When the websocket connects, Discord sends the opcode
10
(hello) - On the
onmessage
event, I properly receive the opcode10
, which is theHello
one, so I use theping
function to keep the connection alive and send the identification. - The
t
in thepayload
is the gateway event name, and when the message is a payload in which thet
isREADY
, that means that the app is working properly.
The problem is that sometimes it works and sometimes it doesn't. Sometimes printing t
returns READY
, sometimes it's not even printing out. I have no idea on why this happens. Here's the code:
const ws = new WebSocket("wss://gateway.discord.gg/?v=10&encoding=json");
const payload = {
op: 2,
d: {
token: TOKEN,
intents: 513,
properties: {
os: "linux",
browser: "chrome",
device: "chrome",
},
},
};
ws.on("open", (e) => {
console.log("open");
});
ws.on("message", (e) => {
const p = JSON.parse(e);
const { t, d, op } = p;
if (op == 10) {
ping(d.heartbeat_interval);
console.log("interval started");
ws.send(JSON.stringify(payload));
}
console.log(op);
console.log(t);
});
function ping(ms) {
return setInterval(() => {
ws.send(JSON.stringify({ op: 1, d: 251 }));
}, ms);
}
Please keep in mind that I'm working with the bun environment! Thanks!