3

I want to use webHook in telegraf but i don't know how can i use it correctly.

Here is my simple code. But it still uses polling.

    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();
developer
  • 170
  • 2
  • 12

2 Answers2

12

When bot.startWebhook() is called Telegraf will start listening to the provided webhook url, so you don't need to call bot.launch() after that.

Also bot.launch() will start the bot in polling mode by default if no options are specified as in your case.

Remove bot.launch() and the bot should start in webhook mode.

Telegraf.js ^4.0.0

If you're using Telegraf.js version 4.0 or higher the changelog states that:

Bots should now always be started using bot.launch with the corresponding configuration for either long polling (default) or webhooks.

So you can also try removing bot.telegram.setWebhook() and bot.startWebhook(), adding the following code instead:

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

See this example from the documentation for reference.

robcss
  • 136
  • 1
  • 4
1

This is working for me:

  bot.startWebhook('/messages', null, 8443);
  bot.launch();

Second parameter are tlsOptions, it's optional.
I have read that Telegram only accepts webhooks on 80, 88, 443 and 8443.
Not sure if true, but is something important to consider since it's very difficult to troubleshoot webhooks.

julianm
  • 2,393
  • 1
  • 23
  • 24