Search code examples
node.jstelegramtelegram-bot

How do I implement the automatic reply feature with a telegram bot


So I am building a bot that will accept a date string with a command like this /add-date 1997.

I also want to handle it properly when users send the command without the date like this /add-date. I have been looking for a way to copy the strategy of some other bots like @vkmusic_bot that handle this case in the following way:

1, upon receiving the /song command, the bot will send this message

What song are you looking for? Blockquote

2, It will automatically prepare a reply at the bottom field tagged to the first reply of the bot.

enter image description here

Now given a song title, it will do the same thing that it would have had the user sent /song [song title]. Manually replying to the What song are you looking for? text has the same effect.

This only works in groups though.

I can't figure out how they're doing this. Would love to get any help on this 🙏

Also, I am building the bot on node.js with the node-telegram-bot-api


Solution

  • Your question is a bit unclear. I'm assuming you want to implement a similar behaviour on the bot such that it to handle the /date command in two ways:

    • If a date is provided (e.g., /date 08/05/2000), process it immediately.
    • If no date is given (just /date), ask the user for a date before processing.

    Here's the code for that:

    
    // Create RegEx for the format of your choice. The following will accept DD/MM/YYYY
    const dateRegex = /\d{1,2}\/\d{1,2}\/\d{2,4}/
    
    bot.on("message", (msg) => {
        /// Ignore if the message is not /date command
        if (!msg.text?.startsWith("/date")) return;
    
        // Checks if the command is exactly "/date" without the date specified.
        if (msg.text == "/date") {
            bot.sendMessage(msg.chat.id, "Send me a date to continue.", {
                reply_markup: {
                    force_reply: true, // Automatically goes to reply to this particular message
                }
            });
            return;
        }
    
        /// If the command contains a date, extract it with the specified regex and process it
        const match = dateRegex.match(msg.text);
        const date = match[0];
        if (date) {
            processDate(date);
        }
    });
    
    // Process incoming date message (this will be executed when the user sends the date alone - also as a reply to the bot's message)
    bot.onText(dateRegex, (msg) => {
        const match = dateRegex.match(msg.text);
        const date = match[0];
        processDate(date);
    })
    
    // A method to process the date
    function processDate(date) {
        // ...
    }
    

    Hope this helps!