我有一个运行在cloudflare workers上的Discord bot,我想使用网关更新它的存在。下面的代码片段在我的浏览器控制台中工作,但在workers中不工作:
export function setPresence(token: string) {
return new Promise((resolve, reject) => {
const activities = [{
name: `you`,
type: 3
}];
const socket = new WebSocket("wss://gateway.discord.gg/?v=10&encoding=json");
function send(op, d) {
return socket.send(JSON.stringify({ op, d }));
}
socket.addEventListener("error", e => console.error(e) || reject(e));
socket.addEventListener("open", _ => console.log("websocket open"));
socket.addEventListener("close", _ => console.log("websocket closed") || resolve());
socket.addEventListener("message", event => {
const data = JSON.parse(event.data);
const { op, d } = data;
console.log({ data });
switch (op) {
case 1: // Heartbeat
case 10: { // Hello
send(1, null);
break;
};
case 11: { // Heartbeat ACK
send(2, {
token,
properties: {
os: "linux",
browser: "cloudflare workers",
device: "cloudflare workers"
},
intents: 0
});
break;
}
case 0: { // Ready
console.log("websocket ready");
send(3, {
activities: [activities[Math.floor(activities.length * Math.random())]],
status: "online",
since: 91879201,
afk: false
});
setTimeout(_ => socket.close(), 10000);
}
}
});
});
}
当我用wrangler dev --remote
在worker中运行它时,我没有得到websocket open
日志,只有一个错误事件和一个websocket closed
我已经尝试使用fetch("https://gateway.discord.gg/?v=10&encoding=json")
并访问响应的webSocket
属性,但它始终为null。
1条答案
按热度按时间ktca8awb1#
不幸的是,这是Discord故意阻止Cloudflare Workers连接到他们的网关。
是的-由于分层的安全方法,我们故意阻止CF工作人员连接到我们的网关套接字。1
您仍然可以使用Interactions,这是您的Worker的传出webhook,如https://discord.com/developers/docs/tutorials/hosting-on-cloudflare-workers所示。