skip to Main Content

I am making a Telegram bot with Telegraf framework in JavaScript with nodeJS. I want to send a message to the user every Monday morning at 9.00 AM. How can I make this time based trigger in telegraf js?

2

Answers


  1. Telegraf doesn’t provide you with such abilities out-of-the-box since it’s a bot framework with the goal of abstracting API calls. You should instead schedule the task with task scheduling libraries (like node-cron).

    An example with node-cron

    const Telegraf = require('telegraf')
    
    const bot = new Telegraf(process.env.BOT_TOKEN)
    
    const cron = require('node-cron');
    
    cron.schedule('0 9 * * MON', () => {
      // send the message here
      bot.telegram.sendMessage(12345678, "scheduled message");
    });
    
    bot.launch()
    

    If you want to learn a bit more about it, please refer this tutorial

    Login or Signup to reply.
  2. If you don’t want to use any other libraries, try using Date object.

    let goalTime = new Date(December 17, 2020 13:24:00)
    

    And use if to check Date.now() :

    let currentTime = Date.now()
    if (currentTime == goalTime) {
        ctx.reply("your message")
    }
    

    For sending message weekly (below code is just an example, you can also use hour and minute to specify time):

    const goalTime = new Date(December 17, 2020 13:24:00)
    const weekday = goalTime.getDay()
    let currentTime = Date.now
    let currentDay = currentTime.getDay()
    if (currentDay == weekday) {
    ctx.reply("your message")
    }
    

    You can refer to this link for more details on Date.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search