Search code examples
node.jstelegraf.js

How to use telegraf webhook?


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();

Solution

  • 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.