This repository has been archived by the owner on Jan 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathTelegramBot.java
541 lines (475 loc) · 22.6 KB
/
TelegramBot.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package co.vandenham.telegram.botapi;
import co.vandenham.telegram.botapi.requests.*;
import co.vandenham.telegram.botapi.types.Message;
import co.vandenham.telegram.botapi.types.Update;
import co.vandenham.telegram.botapi.types.User;
import co.vandenham.telegram.botapi.types.UserProfilePhotos;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class represents a TelegramBot.
* <p/>
* To use it, use any of the available subclasses or subclass it yourself.
*/
abstract public class TelegramBot {
private static final Logger logger = Logger.getLogger(TelegramBot.class.getName());
private TelegramApi api;
private Thread pollThread;
private AtomicBoolean running = new AtomicBoolean();
private int lastUpdateId = 0;
private ApiRequestExecutor requestExecutor;
private ExecutorService executorService;
private HandlerNotifier handlerNotifier;
private boolean sendAsync = true;
/**
* Convenience constructor for {@code TelegramBot(botToken, true)}
*/
public TelegramBot(String botToken) {
this(botToken, true);
}
/**
* Constructs a TelegramBot using the provided {@code botToken}, If {@code sendAsync} is {@code true},
* the bot invokes all {@code sendXXX} methods asynchronously.
*
* @param botToken The token provided by @BotFather
* @param sendAsync Whether this bot should invoke {@code sendXXX} methods asynchronously.
*/
public TelegramBot(String botToken, boolean sendAsync) {
api = new TelegramApi(botToken);
handlerNotifier = new HandlerNotifier(this);
this.sendAsync = sendAsync;
}
/**
* Starts the bot.
* <p/>
* First, it instantiates a {@link java.util.concurrent.ExecutorService} by calling {@link TelegramBot#provideExecutorService()}.
* If this instance is constructed with {@code sendAsync} set to {@code true}, it instantiates a asynchronous {@link ApiRequestExecutor},
* otherwise a synchronous version is used.
* <p/>
* After this, a polling {@link java.lang.Thread} is instantiated and the bot starts polling the Telegram API.
*/
public final void start() {
logger.info("Starting");
executorService = provideExecutorService();
requestExecutor = sendAsync ?
ApiRequestExecutor.getAsynchronousExecutor() : ApiRequestExecutor.getSynchronousExecutor();
running.set(true);
pollThread = new Thread(new UpdatePoller());
pollThread.start();
onStart();
}
protected void onStart() {
}
/**
* Stops the bot and joins the polling {@link Thread}.
*/
public final void stop() {
running.set(false);
try {
pollThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
onStop();
}
protected void onStop() {
}
/**
* Instantiates and returns an {@link ExecutorService}.
* <p/>
* By default, {@link java.util.concurrent.Executors#newCachedThreadPool()} is used.
* This method can safely be overridden to adjust this behaviour.
* This method can safely be overridden to return null, but if you decide to do so, {@link TelegramBot#notifyNewMessages(List)}
* <b>must</b> be overridden to avoid a NPE.
*
* @return An instantiated {@link ExecutorService}
*/
protected ExecutorService provideExecutorService() {
return Executors.newCachedThreadPool();
}
/**
* Forwards a message with ID {@code messageId} from {@code fromChatId} to {@code chatId}.
*
* @param chatId Unique identifier for the message recipient — User or GroupChat id
* @param fromChatId Unique identifier for the chat where the original message was sent — User or GroupChat id
* @param messageId Unique message identifier
* @return An {@code ApiResponse} with the sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#forwardmessage">https://core.telegram.org/bots/api#forwardmessage</a>
*/
public final ApiResponse<Message> forwardMessage(int chatId, int fromChatId, int messageId) {
return requestExecutor.execute(api, new ForwardMessageRequest(chatId, fromChatId, messageId));
}
/**
* A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object.
*
* @return this bot's information, in the form of a {@code User} wrapped in a {@code ApiResponse}
* @see <a href="https://core.telegram.org/bots/api#getme">https://core.telegram.org/bots/api#getme</a>
*/
public final ApiResponse<User> getMe() {
return requestExecutor.execute(api, new GetMeRequest());
}
/**
* @see TelegramBot#getUserProfilePhotos(int, OptionalArgs)
*/
public final ApiResponse<UserProfilePhotos> getUserProfilePhotos(int userId) {
return requestExecutor.execute(api, new GetUserProfilePhotosRequest(userId));
}
/**
* Returns a {@link UserProfilePhotos} for a user.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param userId Unique identifier of the target user
* @param optionalArgs Any optional arguments for this method
* @return The requested {@link UserProfilePhotos}
* @see <a href="https://core.telegram.org/bots/api#getuserprofilephotos">https://core.telegram.org/bots/api#getuserprofilephotos</a>
* @see OptionalArgs
*/
public final ApiResponse<UserProfilePhotos> getUserProfilePhotos(int userId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new GetUserProfilePhotosRequest(userId, optionalArgs));
}
/**
* @see TelegramBot#sendAudio(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendAudio(int chatId, File audioFile) {
return requestExecutor.execute(api, new SendAudioRequest(chatId, audioFile));
}
/**
* Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
*
* For backward compatibility, when the fields title and performer are both empty and the mime-type of the file
* to be sent is not audio/mpeg, the file will be sent as a playable voice message.
* For this to work, the audio must be in an .ogg file encoded with OPUS.
* This behavior will be phased out in the future. For sending voice messages, use the sendVoice method instead.
*
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param audioFile Audio {@link File} to send
* @param optionalArgs Any optional arguments for this method
* @return The sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendaudio">https://core.telegram.org/bots/api#sendaudio</a>
*/
public final ApiResponse<Message> sendAudio(int chatId, File audioFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendAudioRequest(chatId, audioFile, optionalArgs));
}
/**
* @see TelegramBot#sendAudio(int, String, OptionalArgs)
*/
public final ApiResponse<Message> sendAudio(int chatId, String audioFileId) {
return requestExecutor.execute(api, new SendAudioRequest(chatId, audioFileId));
}
/**
* This version takes a file id instead of a {@link File}, as a {@code String} argument.
*
* @see TelegramBot#sendAudio(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendAudio(int chatId, String audioFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendAudioRequest(chatId, audioFileId, optionalArgs));
}
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id.
* @param chatAction The target {@link ChatAction}
* @return True if the request was successful
* @see <a href="https://core.telegram.org/bots/api#sendchataction">https://core.telegram.org/bots/api#sendchataction</a>
*/
public final ApiResponse<Boolean> sendChatAction(int chatId, ChatAction chatAction) {
return requestExecutor.execute(api, new SendChatActionRequest(chatId, chatAction));
}
/**
* @see TelegramBot#sendAudio(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendDocument(int chatId, File documentFile) {
return requestExecutor.execute(api, new SendDocumentRequest(chatId, documentFile));
}
/**
* Use this method to send general files. On success, the sent Message is returned.
* Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param documentFile File to send
* @param optionalArgs Any optional arguments
* @return The sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#senddocument">https://core.telegram.org/bots/api#senddocument</a>
*/
public final ApiResponse<Message> sendDocument(int chatId, File documentFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendDocumentRequest(chatId, documentFile, optionalArgs));
}
/**
* @see TelegramBot#sendDocument(int, String, OptionalArgs)
*/
public final ApiResponse<Message> sendDocument(int chatId, String documentFileId) {
return requestExecutor.execute(api, new SendDocumentRequest(chatId, documentFileId));
}
/**
* This version takes a file id instead of a {@link File}.
*
* @see TelegramBot#sendDocument(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendDocument(int chatId, String documentFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendDocumentRequest(chatId, documentFileId, optionalArgs));
}
/**
* @see TelegramBot#sendLocation(int, float, float, OptionalArgs)
*/
public final ApiResponse<Message> sendLocation(int chatId, float latitude, float longitude) {
return requestExecutor.execute(api, new SendLocationRequest(chatId, latitude, longitude));
}
/**
* Use this method to send point on the map.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param latitude Latitude of location
* @param longitude Longitude of location
* @param optionalArgs Any optional arguments
* @return the sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendlocation">https://core.telegram.org/bots/api#sendlocation</a>
*/
public final ApiResponse<Message> sendLocation(int chatId, float latitude, float longitude, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendLocationRequest(chatId, latitude, longitude, optionalArgs));
}
/**
* @see TelegramBot#sendMessage(int, String, OptionalArgs)
*/
public final ApiResponse<Message> sendMessage(int chatId, String text) {
return requestExecutor.execute(api, new SendMessageRequest(chatId, text));
}
/**
* Use this method to send text messages.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param text Text of the message to be sent
* @param optionalArgs Any optional arguments
* @return the sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendmessage">https://core.telegram.org/bots/api#sendmessage</a>
*/
public final ApiResponse<Message> sendMessage(int chatId, String text, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendMessageRequest(chatId, text, optionalArgs));
}
/**
* @see TelegramBot#sendPhoto(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendPhoto(int chatId, File photoFile) {
return requestExecutor.execute(api, new SendPhotoRequest(chatId, photoFile));
}
/**
* Use this method to send photos.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param photoFile Photo to send
* @param optionalArgs Any optional arguments
* @return The sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendphoto">https://core.telegram.org/bots/api#sendphoto</a>
*/
public final ApiResponse<Message> sendPhoto(int chatId, File photoFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendPhotoRequest(chatId, photoFile, optionalArgs));
}
/**
* @see TelegramBot#sendPhoto(int, String, OptionalArgs)
*/
public final ApiResponse<Message> sendPhoto(int chatId, String photoFileId) {
return requestExecutor.execute(api, new SendPhotoRequest(chatId, photoFileId));
}
/**
* This version takes a file id instead of a {@link File}
*
* @see TelegramBot#sendPhoto(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendPhoto(int chatId, String photoFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendPhotoRequest(chatId, photoFileId, optionalArgs));
}
/**
* @see TelegramBot#sendSticker(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendSticker(int chatId, File stickerFile) {
return requestExecutor.execute(api, new SendStickerRequest(chatId, stickerFile));
}
/**
* Use this method to send .webp stickers.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param stickerFile Sticker to send.
* @param optionalArgs Any optional arguments
* @return The sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendsticker">https://core.telegram.org/bots/api#sendsticker</a>
*/
public final ApiResponse<Message> sendSticker(int chatId, File stickerFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendStickerRequest(chatId, stickerFile, optionalArgs));
}
/**
* @see TelegramBot#sendSticker(int, String, OptionalArgs)
*/
public final ApiResponse<Message> sendSticker(int chatId, String stickerFileId) {
return requestExecutor.execute(api, new SendStickerRequest(chatId, stickerFileId));
}
/**
* This version takes a file id instead of a {@link File}.
*
* @see TelegramBot#sendSticker(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendSticker(int chatId, String stickerFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendStickerRequest(chatId, stickerFileId, optionalArgs));
}
/**
* @see TelegramBot#sendVideo(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVideo(int chatId, File videoFile) {
return requestExecutor.execute(api, new SendVideoRequest(chatId, videoFile));
}
/**
* Use this method to send video files,
* Telegram clients support mp4 videos (other formats may be sent as Document ({@link TelegramBot#sendDocument(int, File, OptionalArgs)})).
* Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
* <p/>
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient - {@link User} or {@link co.vandenham.telegram.botapi.types.GroupChat} id
* @param videoFile Video to send
* @param optionalArgs Any optional arguments.
* @return The sent {@link Message}
* @see <a href="https://core.telegram.org/bots/api#sendvideo">https://core.telegram.org/bots/api#sendvideo</a>
*/
public final ApiResponse<Message> sendVideo(int chatId, File videoFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendVideoRequest(chatId, videoFile, optionalArgs));
}
/**
* @see TelegramBot#sendVideo(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVideo(int chatId, String videoFileId) {
return requestExecutor.execute(api, new SendVideoRequest(chatId, videoFileId));
}
/**
* This version uses a file id rather than a {@link File}
*
* @see TelegramBot#sendVideo(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVideo(int chatId, String videoFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendVideoRequest(chatId, videoFileId, optionalArgs));
}
/**
* @see TelegramBot#sendVoice(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVoice(int chatId, File voiceFile) {
return requestExecutor.execute(api, new SendVoiceRequest(chatId, voiceFile));
}
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
* For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
* On success, the sent Message is returned.
* Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
*
* For any optional arguments, refer to the Telegram documentation.
*
* @param chatId Unique identifier for the message recipient — User or GroupChat id
* @param voiceFile Audio file to send. You can either pass a file_id as String to resend an audio
* that is already on the Telegram servers, or upload a new audio file using multipart/form-data.
* @param optionalArgs Any optional arguments
* @return the sent {@link Message}
*/
public final ApiResponse<Message> sendVoice(int chatId, File voiceFile, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendVoiceRequest(chatId, voiceFile, optionalArgs));
}
/**
* This version uses a String rather than a File.
*
* @see TelegramBot#sendVoice(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVoice(int chatId, String voiceFileId) {
return requestExecutor.execute(api, new SendVoiceRequest(chatId, voiceFileId));
}
/**
* This version uses a String rather than a File
*
* @see TelegramBot#sendVoice(int, File, OptionalArgs)
*/
public final ApiResponse<Message> sendVoice(int chatId, String voiceFileId, OptionalArgs optionalArgs) {
return requestExecutor.execute(api, new SendVoiceRequest(chatId, voiceFileId, optionalArgs));
}
/**
* Convenience method for {@code sendMessage(message.getChat().getId(), text, new OptionalArgs().replyToMessageId(message.getMessageId()))}
*/
public final ApiResponse<Message> replyTo(Message message, String text) {
OptionalArgs optionalArgs = new OptionalArgs().replyToMessageId(message.getMessageId());
return sendMessage(message.getChat().getId(), text, optionalArgs);
}
/**
* This method is called when a new message has arrived.
* It can safely be overridden by subclasses.
*
* @param message The newly arrived {@link Message}
*/
protected void onMessage(Message message) {
// Can be overridden by subclasses.
}
/**
* This method is called by this class to process all new {@link Message}s asynchronously.
* It <b>must</b> be overridden if {@link TelegramBot#provideExecutorService()} is overridden to return null, otherwise
* a {@link NullPointerException} may be thrown.
*
* @param messages The newly arrived {@link Message}s
*/
protected void notifyNewMessages(List<Message> messages) {
for (final Message message : messages) {
executorService.submit(new Runnable() {
@Override
public void run() {
onMessage(message);
}
});
executorService.submit(new Runnable() {
@Override
public void run() {
handlerNotifier.notifyHandlers(message);
}
});
}
}
private class UpdatePoller implements Runnable {
@Override
public void run() {
while (running.get()) {
try {
poll();
} catch (ApiException e) {
logger.log(Level.SEVERE, "An exception occurred while polling Telegram.", e);
running.set(false);
}
}
}
public void poll() {
OptionalArgs optionalArgs = new OptionalArgs().offset(lastUpdateId + 1).timeout(3);
GetUpdatesRequest request = new GetUpdatesRequest(optionalArgs);
List<Update> updates = requestExecutor.execute(api, request).getResult();
if (updates.size() > 0) {
List<Message> newMessages = processUpdates(updates);
notifyNewMessages(newMessages);
}
}
private List<Message> processUpdates(List<Update> updates) {
List<Message> newMessages = new ArrayList<Message>();
for (Update update : updates) {
if (update.getUpdateId() > lastUpdateId)
lastUpdateId = update.getUpdateId();
newMessages.add(update.getMessage());
}
return newMessages;
}
}
}