telegram bot on heroku doesn't work with webhook

63 Views Asked by At

My telegram bot doesn't work in production mode. It fails to respond to the commands /start and /echo; Heroku logs also remain silent. The only working feature is the purchase of goods, which is processed in app.post (bot.answerWebAppQuery). Most likely, the issue lies in app.port, as in the development mode that employs polling instead of a webhook, everything works fine, except for bot.answerWebAppQuery, of course.

All this can be seen visually in the telegram: @ReactWebAppBot

GitHub repository

index.js

const express = require('express');
const cors = require('cors');
require('dotenv').config();

const bot = require('./bot');
const app = express();

app.use(express.json());
app.use(cors());

app.post('/web-data', async (req, res) => {
    const { queryId, products, totalPrice } = req.body;

    try {
        await bot.answerWebAppQuery(queryId, {
            type: 'article',
            id: queryId,
            title: 'Успешна покупка!',
            input_message_content: {
                message_text: `Поздравляю с покупкой, вы приобрели товар на сумму $${totalPrice}
                "${products.map(item => item.title).join(', ')}"`
            }
        });
        bot.processUpdate(req.body);
        res.status(200).json({ message: 'Ok' });
    } catch (e) {
        await bot.answerWebAppQuery(queryId, {
            type: 'article',
            id: queryId,
            title: 'Не удалось приобрести товар :(',
            input_message_content: { 
                message_text: 'Не удалось приобрести товар :(' 
            }
        });
        res.status(500).json({ message: 'Error' });
    }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log('Server started on PORT ' + PORT));

bot.js

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

const token = process.env.BOT_TOKEN;
const webAppUrl = 'https://tg-webapp-react.netlify.app';

let bot;
  
const initPolling = () => {
    bot = new TelegramBot(token, { polling: true });
    
    console.log('Bot started in the dev mode with polling.');
}

const initWebhook = () => {
    bot = new TelegramBot(token);

    const webhookUrl = process.env.HEROKU_URL + bot.token;
    console.log('Webhook URL:', webhookUrl);
    bot.setWebHook(webhookUrl);

    console.log('Bot started in the prod mode with webhook.');
};

if (process.env.NODE_ENV === 'production') {
    initWebhook();
} else {
    initPolling();
}

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

    if (text === '/start') {
        await bot.sendMessage(chatId, 'Заполни форму', {
            reply_markup: {
                keyboard: [
                    [{ text: 'Заполнить форму', web_app: { url: webAppUrl + '/form' } }]
                ]
            }
        });
        await bot.sendMessage(chatId, 'Заходи сюда', {
            reply_markup: {
                inline_keyboard: [
                    [{ text: 'Сделать заказ', web_app: { url: webAppUrl } }]
                ]
            }
        });
    }
    if (msg.web_app_data?.data) {
        try {
            const data = JSON.parse(msg.web_app_data?.data);

            await bot.sendMessage(chatId, 'Спасибо за обратную связь!');
            await bot.sendMessage(chatId, 'Ваша страна: ' + data?.country);
            await bot.sendMessage(chatId, 'Ваша улица: ' + data?.street);
        } catch (e) {
            console.log(e);
        }
    }
});

module.exports = bot;

Heroku logs:

2023-12-25T14:55:09.324439+00:00 app[web.1]: > [email protected] start
2023-12-25T14:55:09.324439+00:00 app[web.1]: > node index.js
2023-12-25T14:55:09.324439+00:00 app[web.1]:
2023-12-25T14:55:09.600098+00:00 app[web.1]: Webhook URL: https://<app-name>.herokuapp.com/<bot-token>
2023-12-25T14:55:09.604960+00:00 app[web.1]: Bot started in the prod mode with webhook.
2023-12-25T14:55:09.608718+00:00 app[web.1]: Server started on PORT 11228
2023-12-25T14:55:10.054273+00:00 heroku[web.1]: State changed from starting to up
2023-12-25T14:55:43.228297+00:00 heroku[router]: at=info method=POST path="/6712623296:AAHGTjFF0m9TgkFLwe7vtke-Q2MQJ57xdUo" host=web-app-bot-fbadb4b5a054.herokuapp.com request_id=b778f8aa-6af0-4078-b6fd-fe702ea37a63 fwd="91.108.6.73" dyno=web.1 connect=0ms service=10ms status=404 bytes=462 protocol=https
0

There are 0 best solutions below