88import org .slf4j .Logger ;
99import org .slf4j .LoggerFactory ;
1010
11+ import java .time .LocalDateTime ;
12+ import java .time .temporal .ChronoUnit ;
13+
1114/**
1215 * Abstract bot to handle VK events.
1316 */
@@ -17,6 +20,13 @@ public abstract class LongPollBot extends VkBot {
1720 */
1821 private static final Logger LOGGER = LoggerFactory .getLogger (LongPollBot .class );
1922
23+ /**
24+ * Default session time.
25+ *
26+ * @see LongPollBot#sessionDuration
27+ */
28+ private static final long DEFAULT_SESSION_DURATION = 9 ;
29+
2030 /**
2131 * Group ID.
2232 */
@@ -37,6 +47,17 @@ public abstract class LongPollBot extends VkBot {
3747 */
3848 private boolean polling = true ;
3949
50+ /**
51+ * Last time when {@link LongPollBot#initialize()} was called.
52+ */
53+ private LocalDateTime initializedAt ;
54+
55+ /**
56+ * Long Poll session duration (in hours).
57+ * When time is expired, {@link LongPollBot#initialize()} method is called.
58+ */
59+ private long sessionDuration = DEFAULT_SESSION_DURATION ;
60+
4061 /**
4162 * Begins listening to VK updates.
4263 *
@@ -46,10 +67,13 @@ public void startPolling() throws VkApiException {
4667 initialize ();
4768 while (polling ) {
4869 try {
70+ if (isSessionExpired ()) {
71+ initialize ();
72+ }
4973 GetUpdates .ResponseBody updates = getUpdates .execute ();
5074 getUpdates .setTs (updates .getTs ());
5175 handle (updates .getEvents ());
52- } catch (VkApiHttpException | VkApiResponseException e ) {
76+ } catch (VkApiHttpException | VkApiResponseException e ) {
5377 LOGGER .warn ("Failed to get events from VK Long Poll Server." , e );
5478 if (e instanceof VkApiResponseException && !e .getMessage ().contains ("failed" )) {
5579 throw e ;
@@ -71,7 +95,9 @@ public void stopPolling() {
7195 *
7296 * @throws VkApiException if errors occur.
7397 */
74- private void initialize () throws VkApiException {
98+ public void initialize () throws VkApiException {
99+ initializedAt = LocalDateTime .now ();
100+
75101 if (groupId == null ) {
76102 groupId = vk .other .execute ()
77103 .setCode ("return API.groups.getById()@.id[0];" )
@@ -89,4 +115,22 @@ private void initialize() throws VkApiException {
89115 .setKey (longPollServer .getResponse ().getKey ())
90116 .setTs (longPollServer .getResponse ().getTs ());
91117 }
118+
119+ /**
120+ * Sets session duration (in hours).
121+ *
122+ * @param sessionDuration session duration (in hours).
123+ */
124+ public void setSessionDuration (long sessionDuration ) {
125+ this .sessionDuration = sessionDuration ;
126+ }
127+
128+ /**
129+ * Checks whether Long Poll session is expired.
130+ *
131+ * @return {@code true} if Long Poll session is expired, {@code false} otherwise.
132+ */
133+ private boolean isSessionExpired () {
134+ return ChronoUnit .HOURS .between (initializedAt , LocalDateTime .now ()) >= sessionDuration ;
135+ }
92136}
0 commit comments