I created a Telegram bot using Node.js and Telegraf that I deployed on Vercel. This bot features a referral system that verifies a user’s registration status through my backend API.
Currently, I am encountering a major issue where the first invocation of the /start command, after the bot has been idle, results in a significant delay in response. Subsequent commands are processed swiftly and without delay.
This initial lag disrupts my referral registration process because:
- A user activates the referral link and sends the /start command.
- The bot takes a long time to reply.
- The user is registered while waiting for the response.
- When the bot eventually processes the /start command, the referral association is lost.
const { Telegraf } = require('telegraf');
const fetch = require('node-fetch');
require('dotenv').config();
const botInstance = new Telegraf(process.env.BOT_TOKEN);
botInstance.start(async (context) => {
const inviterCode = context.startPayload;
const userId = context.from.id.toString();
const displayName = context.from.username || 'Anonymous';
const hasPremium = context.from.is_premium || false;
if (!inviterCode) {
await context.replyWithPhoto(
{ url: 'https://example.com/welcome.jpg' },
{
caption: '🎉 **Join Our Community** 🎉',
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [
[{ text: 'Follow Channel', url: 'https://t.me/mychannel' }],
[{
text: 'Open App',
web_app: { url: 'https://myapp.vercel.app' }
}]
]
}
}
);
return;
}
try {
const checkUser = await fetch(
`${process.env.API_BASE}/users/${userId}`
);
if (!checkUser.ok) {
await fetch(
`${process.env.API_BASE}/invite`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newUserId: userId,
inviterCode: inviterCode,
premium: hasPremium,
name: displayName
})
}
);
}
} catch (err) {
console.log('Registration failed:', err);
}
await context.replyWithPhoto(
{ url: 'https://example.com/success.jpg' },
{
caption: '✅ **Welcome Aboard** ✅',
parse_mode: 'Markdown',
reply_markup: {
inline_keyboard: [
[{ text: 'Join Channel', url: 'https://t.me/updates' }],
[{
text: 'Start App',
web_app: { url: 'https://webapp.vercel.app' }
}]
]
}
}
);
});
const initializeBot = async (expressApp) => {
const webhook = await botInstance.telegram.getWebhookInfo();
if (!webhook.url) {
await botInstance.telegram.setWebhook(
`${process.env.DOMAIN}/webhook/${process.env.BOT_TOKEN}`
);
}
expressApp.post(`/webhook/${process.env.BOT_TOKEN}`, (request, response) => {
botInstance.handleUpdate(request.body, response);
});
};
module.exports = initializeBot;
After the first slow response, the bot functions well. I suspect this delay may be due to Vercel’s serverless architecture entering a sleep state, but I am unsure how to resolve the timing issue for referrals. Has anyone else experienced similar challenges with their Telegram bots on Vercel?