简体   繁体   中英

Is it possible to get periodical responses from telegram bot?

I want to make a simple bot that will send me some reminders periodically, like once an hour. I tried using

TimeUnit.MINUTES.sleep(60);

but it makes my simple bot non-responsive to any incoming messages during this time. I couldn't find any example of such functionality, but I believe it is possible and not that hard to do.

Btw, my bot is simple, I basically use org.telegram.telegrambots.bots.TelegramLongPollingBot and tried to mess with its onUpdateReceived method.

When you do things like TimeUnit.MINUTES.sleep(60); , you will suspend the current thread running the line of code. This probably is your main thread. So you will pause your whole bot, and thus make it unresponsive to any interaction until the thread is awoken out of its sleep.

You should try using cron or scheduled jobs. Or create another thread in your application. But i think its a better design choice to go for something like a cron job. This will fire an event or call an endpoint of your bot to send you an update scheduled at certain times.

You can do several things but one easy way can be adding a Timer to you project with 1 second interval and on your timer's each tick check wether the second is equal to 60 or not. if it was send the message our do what ever you need.

You can use a code like below:

int seconds = 0;
private void timer1_Tick(object sender, EventArgs e)
{
   seconds++;
   if(seconds == 60)
   {
    await Bot.SendTextMessageAsync(ChatID, "Text");
    seconds == 0;
   }
}

Note that the sample code that I provided is written in C#, you should convert it to Java cause you've mentioned that your bot is Telegram Java Bot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM