I’m just starting my journey with JavaScript and Node.js, and I’m creating a Telegram bot to enhance my understanding of these technologies. However, I’ve encountered a problem with the bot’s event handling when several users are interacting at the same time.
Here’s how my registration process works: When a user sends the /start command, it triggers a registration flow:
bot.onText(/\/start/, async msg => {
db.get("SELECT * FROM users WHERE user_id = ?", [msg.chat.id], async (err, res) => {
res ?
console.log('user exists')
: await bot.sendMessage(msg.chat.id, msg.chat.first_name + ', welcome! 🙈
' + 'You are not registered! Please select your gender for continuing the registration:', createKeyboard(genderButtons));
});
});
The function I use to create keyboards is:
const createKeyboard = (buttons) => {
return {
reply_markup: JSON.stringify({
inline_keyboard: buttons
})
}
};
Here are the gender selection buttons:
const genderButtons = [
[
{
text: '👨 I'm a man',
callback_data: 'signup_male'
},
{
text: '👩 I'm a woman',
callback_data: 'signup_female'
}
]
];
And here’s the event handler for button clicks:
bot.on('callback_query', async query => {
switch (query.data) {
case 'signup_male':
await bot.sendMessage(query.message.chat.id, 'Please enter your age between 16 and 90');
bot.on('message', async msg => {
if (msg.text >= 16 && msg.text <= 90) {
return await bot.sendMessage(msg.chat.id, 'Your age has been accepted');
} else {
bot.sendMessage(msg.chat.id, 'Age must be between 16 and 90');
}
});
break;
case 'signup_female':
bot.sendMessage(query.message.chat.id, 'Nice to have you here! Now, please provide your age in the chat as numbers.');
break;
}
});
Here’s where it gets tricky: when I run the bot from one account, everything works smoothly. However, when I use multiple accounts at once, each user gets multiple messages sent to their chat whenever they enter their age. This happens based on how many accounts are using the bot at the same time and triggering responses. I’m trying to figure out why this is occurring and how to resolve it. Any insights would be appreciated!