I’ve noticed a weird behaviour lately with GramJs, according to the documentation here, it should be quite straightforward but as I have come to find out that my event handler takes about 5-10 seconds approximately to be established, and I have no idea why this is the case.
here’s my code
webSocketServer.on("connection", async (wsConnection, user) => {
console.log(`User Connected`);
wsConnection.isAlive = true;
const me = {
userId: user.entityId,
username: user.entityFields.username._value,
firstName: user.entityFields.firstName._value,
phoneNumber: user.entityFields.phoneNumber._value,
lastName: user.entityFields.lastName._value,
};
const telegramSelf = JSON.parse(
await redisHelper.getKey(`${me.userId}:telegram`)
);
if (
telegramSelf?.telegramSession &&
(await telegramService.checkSession(telegramSelf.telegramSession))
) {
const telegramClient = await quickConnect(telegramSelf.telegramSession);
console.log(`${me.username} Connected To Telegram`);
telegramClient.addEventHandler(
(event) => telegramService.eventHandler(event, wsConnection),
new NewMessage({})
);
}
wsConnection.on("pong", function () {
this.isAlive = true;
});
wsConnection.on("message", async (raw) => {
const stringMessage = Buffer.from(raw).toString("utf8");
const message = JSON.parse(stringMessage);
if (message.event === "one-to-one-message") {
if (
!(await redisHelper.getKey(`${me.userId}:telegram`)) &&
message.to === "Telegram"
) {
wsConnection.send(
JSON.stringify({
event: "client-error",
status: 403,
message: "You are not linked to Telegram yet",
})
);
return;
}
if (
!(await redisHelper.getKey(`${me.username}:whatsApp`)) &&
message.to === "WhatsApp"
) {
wsConnection.send(
JSON.stringify({
event: "client-error",
status: 403,
message: "You are not linked to WhatsApp yet",
})
);
return;
}
}
events.eventHandler(message.event)(message, wsConnection, me);
});
wsConnection.on("close", async () => {
// await redisHelper.deleteKey(`${me.username}:telegram`);
console.log(`${me.username} Disconnected`);
});
});
so as it appears I’m triggering the message handler when a connection to my WebSocket server is made, and when that happens I check my redis key to see if the user has any sessions, if so I check the validity of the session and if it’s valid then I’m triggering the quickConnect function which simply initialises the client and connects it to Telegram, after that I establish the Event handler.
I’d appreciate the help as I’ve been suffering from this problem for weeks
Note: I’ve debugged the code multiple times and the async requests never seem to be holding the process at all, it takes less that one second for the code executer to be at the line where the eventHandler function is being triggered.


