|
@@ -0,0 +1,67 @@
|
|
|
+package in.ocsf.these.days.app.listener;/* kpmy 19.02.2017 */
|
|
|
+
|
|
|
+import com.pengrad.telegrambot.Callback;
|
|
|
+import com.pengrad.telegrambot.TelegramBot;
|
|
|
+import com.pengrad.telegrambot.TelegramBotAdapter;
|
|
|
+import com.pengrad.telegrambot.model.Update;
|
|
|
+import com.pengrad.telegrambot.request.GetUpdates;
|
|
|
+import com.pengrad.telegrambot.response.GetUpdatesResponse;
|
|
|
+import in.ocsf.these.days.app.object.UpdateState;
|
|
|
+import in.ocsf.these.days.app.repo.UpdateStateRepository;
|
|
|
+import org.apache.log4j.Logger;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.scheduling.annotation.Async;
|
|
|
+import org.springframework.scheduling.annotation.Scheduled;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.Optional;
|
|
|
+
|
|
|
+@Service
|
|
|
+public class ChatListener {
|
|
|
+
|
|
|
+ private final Logger log = Logger.getLogger(getClass());
|
|
|
+
|
|
|
+ @Value("${these-days.bot.token}")
|
|
|
+ private String token;
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ private UpdateStateRepository stateRepo;
|
|
|
+
|
|
|
+ @Async
|
|
|
+ protected void update(Update update) {
|
|
|
+ log.info(update.updateId());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Scheduled(fixedDelay = 500)
|
|
|
+ protected void doRequest() {
|
|
|
+ TelegramBot bot = TelegramBotAdapter.build(token);
|
|
|
+
|
|
|
+ final UpdateState state = Optional.ofNullable(stateRepo.findOne(UpdateState.defaultId)).orElse(new UpdateState());
|
|
|
+ GetUpdates request = new GetUpdates().limit(1024).offset(state.getUpdateId().intValue() + 1);
|
|
|
+
|
|
|
+ bot.execute(request, new Callback<GetUpdates, GetUpdatesResponse>() {
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onResponse(GetUpdates request, GetUpdatesResponse response) {
|
|
|
+ if (response.isOk()) {
|
|
|
+ if (response.updates() != null)
|
|
|
+ response.updates().stream().forEach(u -> {
|
|
|
+ update(u);
|
|
|
+ if (u.updateId() > state.getUpdateId())
|
|
|
+ state.setUpdateId(Long.valueOf(u.updateId()));
|
|
|
+ });
|
|
|
+ stateRepo.save(state);
|
|
|
+ } else {
|
|
|
+ throw new RuntimeException("response not ok");
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public void onFailure(GetUpdates request, IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ });
|
|
|
+ }
|
|
|
+}
|