Skip to content

Commit 8457cdc

Browse files
authored
Update readme (#145). Closes #138
1 parent 1568c0f commit 8457cdc

File tree

1 file changed

+148
-44
lines changed

1 file changed

+148
-44
lines changed

README.md

Lines changed: 148 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
1-
# Java API for [Telegram Bots and Gaming Platform](https://core.telegram.org/bots)
1+
# Java Telegram Bot API
22
[![Maven Central](https://img.shields.io/maven-central/v/com.github.pengrad/java-telegram-bot-api.svg)](https://search.maven.org/artifact/com.github.pengrad/java-telegram-bot-api)
33
[![Build Status](https://travis-ci.org/pengrad/java-telegram-bot-api.svg?branch=master)](https://travis-ci.org/pengrad/java-telegram-bot-api)
4+
<!--
45
[![codecov](https://codecov.io/gh/pengrad/java-telegram-bot-api/branch/master/graph/badge.svg)](https://codecov.io/gh/pengrad/java-telegram-bot-api)
6+
-->
57

6-
Full support of all Bot API 4.1 methods with [Telegram Passport](https://telegram.org/blog/passport) and Decryption API
8+
Java library for interacting with [Telegram Bot API](https://core.telegram.org/bots/api)
9+
- Full support of all Bot API 4.1 methods
10+
- Telegram [Passport](https://core.telegram.org/passport) and Decryption API
11+
- Bot [Payments](https://core.telegram.org/bots/payments)
12+
- [Gaming Platform](https://telegram.org/blog/games)
713

814
## Download
915

1016
Gradle:
1117
```groovy
12-
compile 'com.github.pengrad:java-telegram-bot-api:4.1.0'
18+
implementation 'com.github.pengrad:java-telegram-bot-api:4.1.0'
1319
```
1420
Maven:
1521
```xml
@@ -19,45 +25,50 @@ Maven:
1925
<version>4.1.0</version>
2026
</dependency>
2127
```
22-
JAR-file:
2328
[JAR with all dependencies on release page](https://github.com/pengrad/java-telegram-bot-api/releases)
2429

25-
## Contents
30+
## Usage
31+
```java
32+
// Create your bot passing the token received from @BotFather
33+
TelegramBot bot = new TelegramBot("BOT_TOKEN");
34+
35+
// Register for updates
36+
bot.setUpdatesListener(updates -> {
37+
// ... process updates
38+
// return id of last processed update or confirm them all
39+
return UpdatesListener.CONFIRMED_UPDATES_ALL;
40+
});
41+
42+
// Send messages
43+
long chatId = update.message().chat().id();
44+
SendResponse response = bot.execute(new SendMessage(chatId, "Hello!"));
45+
```
2646

47+
## Documentation
2748
- [Creating your bot](#creating-your-bot)
2849
- [Making requests](#making-requests)
2950
- [Getting updates](#getting-updates)
30-
- [Get Updates](#get-updates)
31-
- [Webhook](#webhook)
32-
- [Updates Listener](#updates-listener)
3351
- [Available types](#available-types)
34-
- [Keyboards](#keyboards)
35-
- [Chat Action](#chat-action)
3652
- [Available methods](#available-methods)
37-
- [Send message](#send-message)
38-
- [Formatting options](#formatting-options)
39-
- [Get file](#get-file)
40-
- [Other requests](#other-requests)
4153
- [Updating messages](#updating-messages)
54+
- [Stickers](#stickers)
4255
- [Inline mode](#inline-mode)
43-
- [Inline query result](#inline-query-result)
44-
- [Answer inline query](#answer-inline-query)
45-
- [Payments](#payments)
56+
- [Payments](#payments)
57+
- [Telegram Passport](#telegram-passport)
4658
- [Games](#games)
47-
- [Test Telegram Bot API](#test-telegram-bot-api)
4859

49-
## Creating your bot
60+
### Creating your bot
5061

5162
```java
5263
TelegramBot bot = new TelegramBot("BOT_TOKEN");
5364
```
54-
Network operations based on OkHttp library.
65+
Network operations based on [OkHttp](https://github.com/square/okhttp) library.
5566
You can build bot with custom OkHttpClient, for specific timeouts or interceptors.
5667
```java
5768
TelegramBot bot = new TelegramBot.Builder("BOT_TOKEN").okHttpClient(client).build();
5869
```
5970

60-
## Making requests
71+
### Making requests
6172

6273
Synchronous
6374
```java
@@ -83,7 +94,7 @@ Request [in response to update](https://core.telegram.org/bots/faq#how-can-i-mak
8394
String response = request.toWebhookResponse();
8495
```
8596

86-
## Getting updates
97+
### Getting updates
8798

8899
You can use **getUpdates** request, parse incoming **Webhook** request, or set listener to receive updates.
89100
Update object just copies Telegram's response.
@@ -99,7 +110,7 @@ class Update {
99110
}
100111
```
101112

102-
### Get updates
113+
#### Get updates
103114

104115
Building request
105116
```java
@@ -133,7 +144,7 @@ bot.execute(getUpdates, new Callback<GetUpdates, GetUpdatesResponse>() {
133144
});
134145
```
135146

136-
### Webhook
147+
#### Webhook
137148

138149
Building request
139150
```java
@@ -170,7 +181,7 @@ Update update = BotUtils.parseUpdate(reader); // or from java.io.Reader
170181
Message message = update.message();
171182
```
172183

173-
### Updates Listener
184+
#### Updates Listener
174185

175186
You can set listener to receiving incoming updates as if using Webhook.
176187
This will trigger executing getUpdates requests in a loop.
@@ -197,7 +208,7 @@ To stop receiving updates
197208
bot.removeGetUpdatesListener();
198209
```
199210

200-
## Available types
211+
### Available types
201212

202213
All types have the same name as original ones.
203214
Type's fields are methods in lowerCamelCase.
@@ -207,7 +218,7 @@ Types used in responses **(Update, Message, User, Document...)** are in `com.pen
207218
Types used in requests **(Keyboard, InlineQueryResult, ParseMode, InputMessageContent...)** are in `com.pengrad.telegrambot.model.request` package.
208219
When creating request's type required params should be passed in constructor, optional params can be added in chains.
209220

210-
### Keyboards
221+
#### Keyboards
211222

212223
ForceReply, ReplyKeyboardRemove
213224
```java
@@ -242,24 +253,24 @@ InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(
242253
new InlineKeyboardButton[]{
243254
new InlineKeyboardButton("url").url("www.google.com"),
244255
new InlineKeyboardButton("callback_data").callbackData("callback_data"),
245-
new InlineKeyboardButton("switch_inline_query").switchInlineQuery("switch_inline_query")
256+
new InlineKeyboardButton("Switch!").switchInlineQuery("switch_inline_query")
246257
});
247258
```
248259

249-
### Chat Action
260+
#### Chat Action
250261
```java
251262
ChatAction action = ChatAction.typing;
252263
ChatAction action = ChatAction.upload_photo;
253264
ChatAction action = ChatAction.find_location;
254265
```
255266

256-
## Available methods
267+
### Available methods
257268

258269
All request methods have the same names as original ones.
259270
Required params should be passed in constructor.
260271
Optional params can be added in chains.
261272

262-
### Send message
273+
#### Send message
263274

264275
All send requests **(SendMessage, SendPhoto, SendLocation...)** return **SendResponse** object that contains **Message**.
265276
```java
@@ -289,13 +300,13 @@ bot.execute(request, new Callback<SendMessage, SendResponse>() {
289300
});
290301
```
291302

292-
### Formatting options
303+
#### Formatting options
293304
```java
294305
ParseMode parseMode = ParseMode.Markdown;
295306
ParseMode parseMode = ParseMode.HTML;
296307
```
297308

298-
### Get file
309+
#### Get file
299310
```java
300311
GetFile request = new GetFile("fileId")
301312
GetFileResponse getFileResponse = bot.execute(request);
@@ -310,7 +321,7 @@ To get downloading link as `https://api.telegram.org/file/bot<token>/<file_path>
310321
String fullPath = bot.getFullFilePath(file); // com.pengrad.telegrambot.model.File
311322
```
312323

313-
### Other requests
324+
#### Other requests
314325

315326
All requests return BaseResponse if not mention here
316327
```java
@@ -363,7 +374,7 @@ class GetUserProfilePhotosResponse {
363374
}
364375
```
365376

366-
## Updating messages
377+
### Updating messages
367378

368379
Normal message
369380
```java
@@ -387,7 +398,30 @@ DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId);
387398
BaseResponse response = bot.execute(deleteMessage);
388399
```
389400

390-
## Inline mode
401+
### Stickers
402+
403+
Send sticker
404+
```java
405+
// File or byte[] or string fileId of existing sticker or string URL
406+
SendSticker sendSticker = new SendSticker(chatId, imageFile);
407+
SendResponse response = bot.execute(sendSticker);
408+
```
409+
410+
Get sticker set
411+
```java
412+
GetStickerSet getStickerSet = new GetStickerSet(stickerSet);
413+
GetStickerSetResponse response = bot.execute(getStickerSet);
414+
StickerSet stickerSet = response.stickerSet();
415+
```
416+
417+
Upload sticker file
418+
```java
419+
// File or byte[] or string URL
420+
UploadStickerFile uploadStickerFile = new UploadStickerFile(chatId, stickerFile);
421+
GetFileResponse response = bot.execute(uploadStickerFile);
422+
```
423+
424+
### Inline mode
391425

392426
Getting updates
393427
```java
@@ -407,7 +441,7 @@ Update update = BotUtils.parseUpdate(reader); // from java.io.Reader
407441
InlineQuery inlineQuery = update.inlineQuery();
408442
```
409443

410-
### Inline query result
444+
#### Inline query result
411445
```java
412446
InlineQueryResult r1 = new InlineQueryResultPhoto("id", "photoUrl", "thumbUrl");
413447
InlineQueryResult r2 = new InlineQueryResultArticle("id", "title", "message text").thumbUrl("url");
@@ -419,7 +453,7 @@ InlineQueryResult r5 = new InlineQueryResultVideo(
419453
.inputMessageContent(new InputLocationMessageContent(21.03f, 105.83f));
420454
```
421455

422-
### Answer inline query
456+
#### Answer inline query
423457
```java
424458
BaseResponse response = bot.execute(new AnswerInlineQuery(inlineQuery.id(), r1, r2, r3, r4, r5));
425459

@@ -452,14 +486,18 @@ SendResponse response = bot.execute(sendInvoice);
452486

453487
Answer shipping query
454488
```java
489+
LabeledPrice[] prices = new LabeledPrice[]{
490+
new LabeledPrice("delivery", 100),
491+
new LabeledPrice("tips", 50)
492+
};
455493
AnswerShippingQuery answerShippingQuery = new AnswerShippingQuery(shippingQueryId,
456-
new ShippingOption("1", "VNPT", new LabeledPrice("delivery", 100), new LabeledPrice("tips", 50)),
494+
new ShippingOption("1", "VNPT", prices),
457495
new ShippingOption("2", "FREE", new LabeledPrice("free delivery", 0))
458496
);
459497
BaseResponse response = bot.execute(answerShippingQuery);
460498

461499
// answer with error
462-
AnswerShippingQuery answerShippingError = new AnswerShippingQuery(shippingQueryId, "Can't delivery to your address");
500+
AnswerShippingQuery answerShippingError = new AnswerShippingQuery(id, "Can't deliver here!");
463501
BaseResponse response = bot.execute(answerShippingError);
464502
```
465503

@@ -469,10 +507,79 @@ AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(preCheckoutQu
469507
BaseResponse response = bot.execute(answerPreCheckoutQuery);
470508

471509
// answer with error
472-
AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(preCheckoutQueryId, "Sorry, item not available");
510+
AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(id, "Sorry, item not available");
473511
BaseResponse response = bot.execute(answerPreCheckoutQuery);
474512
```
475513

514+
### Telegram Passport
515+
516+
When the user confirms your request by pressing the ‘Authorize’ button, the Bot API sends an Update with the field passport_data to the bot that contains encrypted Telegram Passport data. [Telegram Passport Manual](https://core.telegram.org/passport#receiving-information)
517+
518+
#### Receiving information
519+
You can get encrypted Passport data from Update (via UpdatesListener or Webhook)
520+
```java
521+
PassportData passportData = update.message().passportData();
522+
```
523+
PassportData contains array of `EncryptedPassportElement` and `EncryptedCredentials`.
524+
You need to decrypt `Credentials` using private key (public key you uploaded to `@BotFather`)
525+
```java
526+
String privateKey = "...";
527+
EncryptedCredentials encryptedCredentials = passportData.credentials();
528+
Credentials credentials = encryptedCredentials.decrypt(privateKey);
529+
```
530+
These `Credentials` can be used to decrypt encrypted data in `EncryptedPassportElement`.
531+
```java
532+
EncryptedPassportElement[] encryptedPassportElements = passportData.data();
533+
for (EncryptedPassportElement element : encryptedPassportElements) {
534+
DecryptedData decryptedData = element.decryptData(credentials);
535+
// DecryptedData can be cast to specific type by checking instanceOf
536+
if (decryptedData instanceof PersonalDetails) {
537+
PersonalDetails personalDetails = (PersonalDetails) decryptedData;
538+
}
539+
// Or by checking type of passport element
540+
if (element.type() == EncryptedPassportElement.Type.address) {
541+
ResidentialAddress address = (ResidentialAddress) decryptedData;
542+
}
543+
}
544+
```
545+
`EncryptedPassportElement` also contains array of `PassportFile` (file uploaded to Telegram Passport).
546+
You need to download them 1 by 1 and decrypt content.
547+
This library supports downloading and decryption, returns decrypted byte[]
548+
```java
549+
EncryptedPassportElement element = ...
550+
551+
// Combine all files
552+
List<PassportFile> files = new ArrayList<PassportFile>();
553+
files.add(element.frontSide());
554+
files.add(element.reverseSide());
555+
files.add(element.selfie());
556+
if (element.files() != null) {
557+
files.addAll(Arrays.asList(element.files()));
558+
}
559+
if (element.translation() != null) {
560+
files.addAll(Arrays.asList(element.translation()));
561+
}
562+
563+
// Decrypt
564+
for (PassportFile file : files) {
565+
if (file == null) continue;
566+
byte[] data = element.decryptFile(file, credentials, bot); // GetFile request and decrypt content
567+
// save to file if needed
568+
new FileOutputStream("files/" + element.type()).write(data);
569+
}
570+
```
571+
572+
#### Set Passport data errors
573+
``` java
574+
SetPassportDataErrors setPassportDataErrors = new SetPassportDataErrors(chatId,
575+
new PassportElementErrorDataField("personal_details", "first_name", "dataHash",
576+
"Please enter a valid First name"),
577+
new PassportElementErrorSelfie("driver_license", "fileHash",
578+
"Can't see your face on photo")
579+
);
580+
bot.execute(setPassportDataErrors);
581+
```
582+
476583
### Games
477584

478585
Send game
@@ -490,6 +597,3 @@ Get game high scores
490597
GetGameHighScoresResponse response = bot.execute(new GetGameHighScores(userId, chatId, messageId));
491598
GameHighScore[] scores = response.result();
492599
```
493-
494-
### Test Telegram Bot API
495-
Test on [RapidAPI](https://rapidapi.com/package/TelegramBot/functions?utm_source=TelegramGitHub&utm_medium=button)

0 commit comments

Comments
 (0)