yagop / node-telegram-bot-api

Telegram Bot API for NodeJS
MIT License
8.34k stars 1.52k forks source link

How can i listen for a specific user messages ?! #1104

Closed m0x61h0x64i closed 1 year ago

m0x61h0x64i commented 1 year ago

i want to listen for a specific user messages, bot.on('message', ...) this will listen for all users messages!

i only want to get user input, is there a better way to do this ?

m0x61h0x64i commented 1 year ago

@yagop please help

VDS13 commented 1 year ago

Hello, Can you give an example of what you want to do?

m0x61h0x64i commented 1 year ago

@VDS13 i want to check if the input is coming from a user that wanted to fill out phone number input then do the next step, but now when i console log msg.text under the bot.on('message'... it will receive any user input but how can i detect if the user that sent a number is the one that Im waiting for his/her number ?

derzhavets commented 1 year ago

I would suggest to use some king of "user states". I.e. when you prompt a user to enter phone number, you can set state that user with certain chatId (you can get chatId from .on('message')) is in state "entering_phone". So when next time the you get the message, you can check whether user with this chatId is sending you a phone number.

Here is basic example:

    const userStates = {}

    bot.on('message', (msg) => {

      const chatId = msg.chat.id

      if ( !userStates[chatId] ) {
        // let's assume empty state means you need to prompt user for phone number

        // send user prompt message and set user state
        bot.sendMessage( chatId, "Please enter your phone number")
        userStates[chatId] = "entering_phone"

      } else if ( userStates[chatId] == "entering_phone") {
        // based on "entering_phone" state, you know that user with this id is sending you phone number

        // do what you need with the number
        const phoneNumber = msg.text

        // also don't forget to reset user state, so the same user can ask you for something else
        userStates[chatId] = null

      }
    })
m0x61h0x64i commented 1 year ago

@derzhavets thanks a lot, was helpful

bluetyphoon77 commented 8 months ago

Hi @derzhavets Are you also using new_chat_members? Is it working for you? Cheers