I’m new to JavaScript and Node.js. Working on a Telegram bot as a learning project and running into a weird issue with message handlers.
I have a registration flow that starts with /start command showing gender selection buttons:
bot.onText(/\/register/, async message => {
db.get("SELECT * FROM accounts WHERE account_id = ?", [message.chat.id], async (err, result) => {
result ?
console.log('found')
: await bot.sendMessage(message.chat.id, message.chat.first_name + ', ' + 'welcome! 🎉\n\n' +
'You are not registered yet! Please choose your gender to continue:', createKeyboard(genderOptions));
});
});
Helper function for keyboard creation:
const createKeyboard = (options) => {
return {
reply_markup: JSON.stringify({
inline_keyboard: options
})
}
};
Gender selection buttons:
const genderOptions = [
[
{
text: '🚹 Male',
callback_data: 'register_male'
},
{
text: '🚺 Female',
callback_data: 'register_female'
}
]
];
Callback handler:
bot.on('callback_query', async callback => {
switch (callback.data) {
case 'register_male':
await bot.sendMessage(callback.message.chat.id, 'Please enter your age (18-80)');
bot.on('message', async message => {
if (message.text >= 18 && message.text <= 80) {
return await bot.sendMessage(message.chat.id, 'age saved successfully');
} else {
bot.sendMessage(message.chat.id, 'Age must be between 18-80');
}
});
break;
case 'register_female':
bot.sendMessage(callback.message.chat.id, 'Great choice! Now please enter your age as numbers');
break;
}
});
The problem happens when multiple users interact with the bot simultaneously. Each user gets duplicate messages equal to the number of active users. With one user everything works fine, but with multiple users the message handler seems to trigger for all of them.
What am I doing wrong here? How can I fix this behavior so each user only gets their own responses?