javascriptnode.jstelegram-botnode-telegram-bot-api

Making a bot that checks to see if a message replied to is a photograph (node-telegram-bot-api 2024)


So I am making a simple telegram bot that replies with a message if the message replied to is a photograph, but the property of the node-telegram-bot library of the "message" object, reply_to_message, is undefined.

Here is the sample code I have written below:

const TelegramBot = require('node-telegram-bot-api');

const token = 'YOUR_TELEGRAM_BOT_TOKEN';

const bot = new TelegramBot(token, { polling: true });

bot.on('message', (msg) => {
    const chatId = msg.chat.id;

    if (msg.text && msg.text.toLowerCase() === '/meme') {
        if (msg.reply_to_message && msg.reply_to_message.photo) {
            bot.sendMessage(chatId, 'You have an image');
        }
    }
});

the bot does not reply with any message, if I go into debug mode, the object property "reply_to_message" is always undefined, even though the message replied to the image with the '/meme' command is defined as a message object.


Solution

  • Seems like the code is working pretty fine for my end. I've sent a photo to the bot, and send the message /meme as reply to the photo. Bot then replied with You have an image.

    Meanwhile, if you are sending message like /meme This is a meme it won't work. This is because, you're doing a strict equality check to match the message text to be "/meme". In this case if you want to accept text after the /meme command replace the following code:

    if (msg.text && msg.text.toLowerCase() === '/meme')
    

    With this:

    if (msg.text && msg.text.startsWith('/meme '))
    

    Hope this helps!