How do make my bot send message without an update?

末鹿安然 提交于 2019-12-25 03:44:19

问题


i am creating a telegram bot in java bot but i have problem,I have seen bots that send text\ad without an update from a user ,I want to know how i can do it .It is only sending messages when the user sends a message to it.i need to know how can i make my bot send some message without a onUpdateReceived.(sorry for my english)

onUpdateReceived(Update update) only sends message when the user sends a command

Thank you.


回答1:


Just create an instance of Send message. Eg.

SendMessage message = new SendMessage (chatid,text)

And then just let execute the instance with your bot.

SendMessage message = new SendMessage (chatid,text)
bot.execute(message)

Obviously the chatid camp should be hardcoded.




回答2:


onUpdateReceived(Update) is just a method called when you bot gets an update, but it is not the only place where your bot can call execute(SendMessage). What you need is to write a method in your bot like

public void sendAds() {
    for (Integer chatId: usersYouWantToPing) {
        SendMessage ad = new SendMessage
            .setChatId(chatId)
            .setText(text);
        execute(ad);
    }
}

obviously since you have no User sender object you have to find a criteria to who send the message (maybe you want to store the ids of the users you want to ping in a DB).

The issue now is: how do you trigger this method? The answer is: however you want.

One way could be to schedule some cron jobs to periodically execute sendAds(). To do so you could define it in the main method, right after you register your bot. Using Quartz lib you can write something like

    /* 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);

Where SendAd is an implementation of Job interface that actually calls the bot method, like

public class SendNotification implements Job {
    public void execute(JobExecutionContext jobExecutionContext) {
        schedulerContext = jobExecutionContext.getScheduler().getContext();
        YourBot bot = (YourBot) schedulerContext.get("bot");
        bot.sendNotification();
    }
}

For further details I suggest you to check my telegram bot template that provide this solution.



来源:https://stackoverflow.com/questions/53996643/how-do-make-my-bot-send-message-without-an-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!