首页 > 解决方案 > 在heroku上部署电报机器人

问题描述

我想学习如何创建电报机器人,但在云上部署它时遇到了麻烦。我一直在 Heroku 日志上收到此错误

2021-11-01T16:51:38.071120+00:00 heroku[router]: at=info method=POST path="/2xxxxxXXxx:AAAAAAAAxxxx-xxx" host=xxxx-Xxxx-xxxx.herokuapp.com request_id=ed02154c-af96-44b7-af50-0ad1d8891f8f fwd="91.108.6.83" dyno=web.1 connect=0ms service=1ms status=500 bytes=404 protocol=https

2021-11-01T16:51:38.076047+00:00 app[web.1]: TypeError: bot.processUpdate is not a function

2021-11-01T16:51:38.076210+00:00 app[web.1]:     at /app/index.js:18:6

这是我的 index.js

// DEPENDENCIES
const express = require('express');
require('dotenv').config();

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

const app = express();

const port = process.env.PORT || 5000;

app.use(express.json());

app.get('/', (req, res) => {
    res.status(200).json({ message: 'Hello from the Bot API.' });
});
// TELEGRAM WEBHOOK - https://core.telegram.org/bots/api#setwebhook
app.post(`/${process.env.TELEGRAM_TOKEN}`, (req, res) => {
    bot.processUpdate(req.body);
    res.status(200).json({ message: 'ok' });
});

app.listen(port, () => {
    console.log(`\n\nServer running on port ${port}.\n\n`);
});

这是我的 bot.js

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

//bot token
const token = process.env.TELEGRAM_TOKEN;
//initialize bot
var bot;

// if production env, we use webhooks
// https://core.telegram.org/bots/api#setwebhook
// https://github.com/yagop/node-telegram-bot-api/blob/release/doc/api.md#TelegramBot+setWebHook
if (process.env.NODE_ENV === 'production') {
    bot = new TelegramBot(token);
    bot.setWebHook(process.env.HEROKU_URL + bot.token);
    console.log('**** BOT initiated ***** ');
} else {
    // otherwise, we use polling
    // differences between webhooks and polling:
    // https://core.telegram.org/bots/webhooks
    // https://stackoverflow.com/questions/40033150/telegram-bot-getupdates-vs-setwebhook
    bot = new TelegramBot(token, { polling: true });
}

console.log(`Bot started in the ${process.env.NODE_ENV} mode`);


bot.onText(/^\/say_hello (.+)$/, function (msg, match) {
    var name = match[1];
    bot.sendMessage(msg.chat.id, 'Hello ' + name + '!').then(function () {
        // reply sent!
    });
});

bot.onText(/^\/sum((\s+\d+)+)$/, function (msg, match) {
    var result = 0;
    match[1].trim().split(/\s+/).forEach(function (i) {
        result += (+i || 0);
    })
    bot.sendMessage(msg.chat.id, result).then(function () {
        // reply sent!
    });
});

一切都在本地完美运行。起初我认为问题出在 webhook URL 上,但花了几个小时后,我才意识到日志中还有其他内容。我正在使用https://github.com/yagop/node-telegram-bot-api并且文档肯定仍然编写了 processUpdate 但我不知道如何测试它。由于在本地工作上部署,问题可能出在我不知道的其他地方。

标签: node.jsherokutelegram-bot

解决方案


您需要将botbot.js 中定义的导出添加到该模块的下一行

module.exports = bot

推荐阅读