yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.31k stars 1.51k forks source link

Stop at given function #559

Closed siyavash4812 closed 2 years ago

siyavash4812 commented 6 years ago

Feature Request

I have:

Introduction

So in my code I have a variable called isFetchingData which is type boolean. Whenever user sends a message this variable will be set to true until the data has been fetched and sent to user. I want to check to see if the variable is true at this function and if it is then stop the request and send a message to back to user. If it is not true then allow the message to go through the other methods and find a method that matches the message.

bot.onText(/(.+)/, (msg, match) => {
    const chatId = msg.chat.id;

    if (isFetchingData){
        bot.sendMessage(chatId, 'Please Wait', optKeyboard);
        //Stop going to other methods
    } else {
        //Continue
    }
});

Example

User -> Sends a request to fetch some data Bot -> Sets the isFetchingData to true and starts fetching data User -> Sends another request immediately Bot -> Checks to see if isFetchingData is true and if it is then stops the request from going to its method

sidelux commented 6 years ago

This is a problem of this library. You can't do a middleware so easy, try to read here.

Anyway there is a method (a bit ugly but the only i think).

var isFetchingData = [];

function checkIfBusy(from_id){
    if (isFetchingData[from_id] == undefined)
        isFetchingData[from_id] = 0;
    else if (isFetchingData[from_id] == 1){
        bot.sendMessage(from_id, 'Please Wait...');
        return 1;
    }
    return 0;
}

bot.onText(/command1/, (msg) => {
    if (checkIfBusy(msg.from.id))
        return;
    isFetchingData[msg.from.id] = 1;
    // things... and when is done:
    isFetchingData[msg.from.id] = 0;
});

bot.onText(/command2/, (msg) => {
    if (checkIfBusy(msg.from.id))
        return;
    isFetchingData[msg.from.id] = 1;
    // things... and when is done:
    isFetchingData[msg.from.id] = 0;
});

// same with all other functions...
siyavash4812 commented 6 years ago

@sidelux Thank you for the link. I actually installed it and looked at it but I thought there might be a way to just do it once and whenever a new message arrives it goes through that function and then if I allow it, it would continue to go to the other functions and not it would just stop there and send a message to user.