Issue with the logic of a Telegram bot using the node-telegram-bot-api

Currently delving into the world of JS and NodeJs to broaden my knowledge and gain experience. Working on a Telegram bot project as a way to practice and learn more about JavaScript, particularly focusing on event handling aspects. Encountered an issue with the event handler: I have a registration window with inline keyboard functionality triggered by the /start command which displays several buttons for gender selection.

bot.onText(/\/start/, async msg => {
db.get("SELECT * FROM users WHERE user_id = ?", [msg.chat.id], async (no, yes) => {
    yes ? 
    console.log('ss')
    : await bot.sendMessage(msg.chat.id, msg.chat.first_name + ',' + ' ' + 'добро пожаловать! 🙈\n\n' + 
    'You are not registered yet! Please select your gender to proceed with registration:', keyboardName(signup));
}); });

The database is in place, but the focus here is on the keyboard implementation for code readability purposes:

    const keyboardName = (name) => {
    return {
        reply_markup: JSON.stringify ({
            inline_keyboard: name
        })
    }
};

Here are the gender selection buttons:

const signup = [
    [  
      {
        text: '👨 I am a guy',
        callback_data: 'signup_man'
      },
      {
        text: '👩 I am a girl',
        callback_data: 'signup_woman'
      }
    ]
];

And here is the button click event handler:

bot.on('callback_query', async query => {
    switch (query.data) {
        case 'signup_man':
            await bot.sendMessage(query.message.chat.id, 'Enter your age from 16 to 90');
            bot.on('message', async msg => {
                if (msg.text >= 1 && msg.text <= 90) {
                    return await bot.sendMessage(msg.chat.id, 'This is a test message');
                } else
                bot.sendMessage(msg.chat.id, 'Age must be between 16 and 90');
            })

            break;
        case 'signup_woman':
            bot.sendMessage(msg.chat.id, 'Nice dealing with you! Now, please enter your age in digits in the chat :)');
            break;
    }
});

The issue arises when using the bot with multiple accounts simultaneously. When entering the age (chat.id) during the signup process, multiple messages are sent to the chat, corresponding to the number of active accounts. Seeking insight into why this occurs and what might be causing it.

Tried various troubleshooting steps, but struggling to grasp the underlying logic behind this behavior.

Answer №1

The reason behind this issue is that every button click adds another handler, which can create complications when trying to use handlers selectively.

One way to address this is by creating an "array" to store user ids and their respective stages. You can take a look at my implementation of this approach here.

For practical guidance, check out this example of usage: USING EXAMPLE IMAGE

In your situation, ensure that you initialize your bot.on('message') handler on the same level as bot.on('callback_query'). Then, in your bot.on('message') handler, include an if condition to determine if a user has clicked any buttons.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

How do reading query variables differ from reading body variables?

Currently, I am utilizing node.js restify for my project. I have discovered that there are two methods to retrieve parameters from HTTP GET requests. The first method involves reading query variables. https://i.sstatic.net/kQla6.png On the other hand ...

How can I align images at the center of a div?

My div can hold up to four images, with a minimum of one. Currently, the images are aligned to the left within the container. I am looking to center align them regardless of how many images there are in the div. This is the code snippet that I currently h ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

Attempting to access the 'name' field from an input element in an HTML document using AngularJS, and also introducing a static field named 'likes' with a value

Currently, I am in the process of developing an application that retrieves a list of Beers from an API. Each beer in the JSON response contains the fields {name: "beer", id: number, likes: number}. However, I am facing a challenge while attempting to add ...

Learn about Angular8's prototype inheritance when working with the Date object

In my search for a way to extend the Date prototype in Angular (Typescript), I stumbled upon a solution on GitHub that has proven to be effective. date.extensions.ts // DATE EXTENSIONS // ================ declare global { interface Date { addDa ...

Is it necessary for the key in JSON syntax to be enclosed in quotes?

I am facing an issue with converting a specific string to JSON format. Here is the string: '{clientId: "1239268108.1505087088", userId: "0.4744496956388684", "url": "http://boomfix.es/", "pageUrl": "1", "timer": "15", "clickCount": "4", "mouseMax": " ...

The error message "npm ERR! enoent" indicates that npm is unable to locate a specific file

How do I troubleshoot this issue? After attempting the master version, I encountered a similar error. My operating system is OSX Yosemite: bash-3.2$ yo meanjs You're utilizing the official MEAN.JS generator. ? Which version of mean.js would you like ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Understanding the functionality of scope in AngularJS is essential for mastering the framework

Why does this code work? app.controller("ctrl", function($scope){ $scope.From = "Santa"; $scope.To = "Claus"; }); And why doesn't this one work? app.controller("ctrl", function(scope){ scope.From = "Santa"; scope.To = "Claus"; }); ...

Invoke the function defined within a modal when dismissing a ui-bootstrap modal

Inside my ui-bootstrap modal controller, I have a $watch function set up for a variable. The code snippet looks like this: main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', function ($sc ...

What is the process by which HTML strings are being attached to an output variable and how does the join function affect the map method?

I am encountering some difficulty grasping the significance of this section of code. I have included a large portion of the code to provide context and aid in understanding what the original author intended with this code snippet. Within the replaceTempla ...

Ensure that a component does not receive a value if the string is equal to an empty string

When passing values to my component, I encountered an issue where some values were empty (""). This resulted in a visual container appearing empty on my view. To resolve this, I need the value not to pass at all if it equals "". <AddIntel initialValues ...

What is the reason for the directional light shining on the box from behind?

I have inserted a DirectionalLightHelper into my code to provide lighting for a box. The light source is positioned at coordinates (2,2,1), and there are two boxes located at (0,0,0) and (3,3,3) respectively. Surprisingly, the box at (3,3,3) is also being ...

use the abstract function(req, res, next) in a Node environment

Imagine a scenario where I have a route: app.get(abc, (req, res, next) => { if (req.params.ID === undefined) { res.status(400); res.end(); } next(); }); Now, the question arises - would it function in the same way if I w ...

Conceal div when clicked in Vue.js

Could you provide the Vue.js equivalent for this jQuery code snippet? $('.btn').click(function(){ $('.hideMe').hide() }); ...

A sophisticated approach to implementing a search functionality within a complex JSON structure containing nested arrays using JavaScript

Searching for data in JSON format: { "results": { "key1": [ { "step": "step1", "result": "pass" } , { "step": "step2", "result": "pending" } ...

How can I obtain the MAC address of a tablet (iPad or Android)?

Synopsis: My project involves creating a HTML5 web app designed for tablets like iPad or Droid to log in to a server and perform various tasks. The client has requested a way to retrieve the device's MAC address during the login process. Most solution ...

Continually receiving the error message: "tsc.exe" has exited with an error code of 1

After I include a tsconfig.json file in my Visual Studio 2015 web solution, I encounter the error mentioned above. Furthermore, this prevents the compiler from generating js files again even when the "compileOnSave": true option is set. When I click on t ...