I'm trying to connect to Discord using the Gateway API in a React Native app. It connects normally on iOS and Web platforms, but on Android, it refuses to connect with the following error:
ERROR WebSocket error: {"isTrusted": false, "message": "Expected HTTP 101 response but was '403 Forbidden'"}
LOG WebSocket closed: {"code": 1006, "isTrusted": false, "reason": "Expected HTTP 101 response but was '403 Forbidden'"}
My code:
useEffect(() => {
const headers = {
Authorization: `Bot ${botToken}`,
"User-Agent": "DiscordBot/1.0 (https://example.com)",
};
fetch("https://discord.com/api/gateway/bot", { headers })
.then((response) => response.json())
.then((data) => {
const ws = new WebSocket(`${data.url}/?v=10&encoding=json`);
let payload = {
op: 2,
d: {
token: botToken,
intents: 33281,
properties: {
os: "foo",
browser: "f",
device: "foo",
},
},
};
ws.onopen = () => {
ws.send(JSON.stringify(payload));
console.log("WebSocket connected");
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
ws.onclose = (event) => {
console.log("WebSocket closed:", event);
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
const newMsg = data.d.content;
if (data.t === "MESSAGE_CREATE") {
console.log(newMsg);
}
};
})
.catch((error) => {
console.error(error);
});
}, []);
Expected it to work on all platforms but it connects only on Web (expo), iOS, and errors out on Android.