How to use telegraf webhook?
Asked Answered
A

2

6

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();
Alarise answered 13/1, 2021 at 11:53 Comment(0)
B
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.

Behka answered 18/1, 2021 at 21:17 Comment(0)
G
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.

Gabon answered 9/11, 2021 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.