onUpdateReceived(Update) 只是当你的机器人获得更新时调用的一个方法,但它不是你的机器人可以调用execute(SendMessage) 的唯一地方。
您需要的是在您的机器人中编写一个方法,例如
public void sendAds() {
for (Integer chatId: usersYouWantToPing) {
SendMessage ad = new SendMessage
.setChatId(chatId)
.setText(text);
execute(ad);
}
}
显然,由于您没有 User 发件人对象,因此您必须找到发送消息的标准(也许您希望将要 ping 的用户的 ID 存储在数据库中)。
现在的问题是:如何触发这个方法?答案是:随心所欲。
一种方法是安排一些cron 作业 定期执行sendAds()。为此,您可以在注册机器人后立即在 main 方法中定义它。使用Quartz lib 你可以写类似
/* Instantiate the job that will call the bot function */
JobDetail jobSendAd = JobBuilder.newJob(SendAd.class)
.withIdentity("sendAd")
.build();
/* Define a trigger for the call */
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("everyMorningAt8")
.withSchedule(CronScheduleBuilder.dailyAtHourAndMinute(8, 0))
.build();
/* Create a scheduler to manage triggers */
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.getContext().put("bot", bot);
scheduler.start();
scheduler.scheduleJob(jobSendAd, trigger);
其中SendAd 是Job 接口的实现,它实际上调用了bot 方法,比如
public class SendNotification implements Job {
public void execute(JobExecutionContext jobExecutionContext) {
schedulerContext = jobExecutionContext.getScheduler().getContext();
YourBot bot = (YourBot) schedulerContext.get("bot");
bot.sendNotification();
}
}
有关更多详细信息,我建议您查看我提供此解决方案的telegram bot template。