如何使用电报网络钩子?

时间:2021-01-13 11:53:51

标签: node.js telegraf.js

我想在 Telegraf 中使用 webHook,但我不知道如何正确使用它。

这是我的简单代码。 但它仍然使用轮询。

    const Telegraf = require('telegraf');
    const bot = new Telegraf('123:ABC');

    bot.telegram.setWebhook('https://myaddress.com');
    bot.startWebhook(`/`, null, 4000);



    bot.use(function(ctx, next){
        try{
            if(ctx.chat == undefined) return;
            console.log("Hello World");
        }catch (e){
            console.log("Error");
        }
    });


    bot.launch();

1 个答案:

答案 0 :(得分:4)

bot.startWebhook() 被称为 Telegraf will start listening to the provided webhook url 时,因此您不需要在此之后调用 bot.launch()

如果没有在您的情况下指定选项,则还 bot.launch() will start the bot in polling mode by default

删除 bot.launch(),机器人应以 webhook 模式启动。

Telegraf.js ^4.0.0

如果您使用的是 Telegraf.js 4.0 或更高版本,changelog 声明:

<块引用>

机器人现在应该总是使用 bot.launch 和相应的长轮询(默认)或 webhooks 配置启动。

因此您也可以尝试删除 bot.telegram.setWebhook()bot.startWebhook(),改为添加以下代码:

bot.launch({
  webhook: {
    domain: 'https://myaddress.com',
    port: 4000
  }
})

请参阅文档中的 this example 以供参考。