skip to Main Content

I would like to create a Telegram bot based on Telegraf. I want the bot to schedule and send messages to users by launching a command.

For instance, I want it to work as a course: once you select a course, you get lessons every day.

I tried using node-cron (see the example below), but it starts sending messages by initiating the bot.

const cron = require('node-cron');

const schedule = cron.schedule('*/5 * * * * *', async () => {
  bot.telegram.sendMessage(chatId, 'Hello World');
});

bot.command('/launch', ctx => {
  schedule.launch();
});

bot.command('/stop', ctx => {
  schedule.stop();
});

Please suggest ways to implement a bot like this.
If you know an existing telegraf bot like this with source code, please let me know.

2

Answers


  1. If this were my project I would write a standalone program (in nodejs or some other language) to run every so often invoked by the OS’s cron subsystem, not nodejs’s. This program would not run as a web server, but just standalone.

    The standalone program would connect to your database of users, retrieve the list of messages it needs to send, and then use telegram to send them.

    When done sending it would exit, knowing that the OS’s cron will start it again when the time comes.

    Login or Signup to reply.
  2. There are two options you can do this.

    1. Use setInterval() function and check date in function body. I check seconds, but you can check hours or days.
    let timer = null;
    
    bot.onText(//start/, message => {
        timer = setInterval(() => {
            if(new Date().getSeconds() === 1) {
                bot.sendMessage(message.chat.id, "responce");    
            }
        }, 1000)    
    });
    
    bot.onText(//stop/, message => {
        clearInterval(timer);
    })
    
    1. Use external npm package node-schedule or something like that.
    import schedule from "node-schedule";
    let job;
    
    bot.onText(//start/, message => {
        job = schedule.scheduleJob('1 * * * * *', () => {
            bot.sendMessage(message.chat.id, "responce");
        });
    });
    
    bot.onText(//stop/, message => {
        if (job) {
            job.cancel()
        }
    });
    

    I prefer second option because it’s more flexible.

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