Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 557
developer Avatar asked Sep 01 '26 21:09

developer


1 Answers

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.

like image 122
robcss Avatar answered Sep 04 '26 12:09

robcss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!