├── media
├── info.md
├── mdrobot.png
├── Bot_Reply.jpg
├── Bot_emoji.png
├── do_email.png
├── do_pytty.png
├── chat_voting.png
├── do_register.png
├── java_version.png
├── Bot_Logging_1.png
├── Bot_Logging_2.png
├── do_fingerprint.png
├── Bot_sends_photo.png
├── bot_updated_text.png
├── bot_inline_keyboard.png
├── bot_unknown_command.png
├── Bot_sends_photo_command.png
├── custom_keyboard_preview.png
└── Bot_custom_keyboard_photo.png
├── .gitignore
├── book.json
├── SUMMARY.md
├── Lesson 2
└── src
│ ├── Main.java
│ └── PhotoBot.java
├── Lesson 6
└── src
│ ├── Main.java
│ └── BotApi20.java
├── Lesson 1
└── src
│ ├── Main.java
│ └── MyAmazingBot.java
├── Lesson 4
└── src
│ ├── Main.java
│ └── EmojiTestBot.java
├── Lesson 3
└── src
│ ├── Main.java
│ └── LoggingTestBot.java
├── README.md
├── lesson-8-integrating-with-redis.md
├── Lesson 7
└── src
│ └── database.java
├── lesson-5.-deploy-your-bot.md
├── lesson-7.-creating-users-database-with-mongodb.md
├── lesson-4.-emoji.md
├── lesson-3.-logging.md
├── chapter1.md
├── lesson-6.-inline-keyboards-and-editing-messages-text.md
└── lesson-2.-photobot.md
/media/info.md:
--------------------------------------------------------------------------------
1 | # Media folder
2 | This folder will contain photos for my book
3 |
--------------------------------------------------------------------------------
/media/mdrobot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/mdrobot.png
--------------------------------------------------------------------------------
/media/Bot_Reply.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_Reply.jpg
--------------------------------------------------------------------------------
/media/Bot_emoji.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_emoji.png
--------------------------------------------------------------------------------
/media/do_email.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/do_email.png
--------------------------------------------------------------------------------
/media/do_pytty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/do_pytty.png
--------------------------------------------------------------------------------
/media/chat_voting.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/chat_voting.png
--------------------------------------------------------------------------------
/media/do_register.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/do_register.png
--------------------------------------------------------------------------------
/media/java_version.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/java_version.png
--------------------------------------------------------------------------------
/media/Bot_Logging_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_Logging_1.png
--------------------------------------------------------------------------------
/media/Bot_Logging_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_Logging_2.png
--------------------------------------------------------------------------------
/media/do_fingerprint.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/do_fingerprint.png
--------------------------------------------------------------------------------
/media/Bot_sends_photo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_sends_photo.png
--------------------------------------------------------------------------------
/media/bot_updated_text.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/bot_updated_text.png
--------------------------------------------------------------------------------
/media/bot_inline_keyboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/bot_inline_keyboard.png
--------------------------------------------------------------------------------
/media/bot_unknown_command.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/bot_unknown_command.png
--------------------------------------------------------------------------------
/media/Bot_sends_photo_command.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_sends_photo_command.png
--------------------------------------------------------------------------------
/media/custom_keyboard_preview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/custom_keyboard_preview.png
--------------------------------------------------------------------------------
/media/Bot_custom_keyboard_photo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MonsterDeveloper/java-telegram-bot-tutorial/HEAD/media/Bot_custom_keyboard_photo.png
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Node rules:
2 | ## Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
3 | .grunt
4 |
5 | ## Dependency directory
6 | ## Commenting this out is preferred by some people, see
7 | ## https://docs.npmjs.com/misc/faq#should-i-check-my-node_modules-folder-into-git
8 | node_modules
9 |
10 | # Book build output
11 | _book
12 |
13 | # eBook build output
14 | *.epub
15 | *.mobi
16 | *.pdf
--------------------------------------------------------------------------------
/book.json:
--------------------------------------------------------------------------------
1 | {
2 | "plugins": [
3 | "disqus",
4 | "back-to-top-button",
5 | "asciinema",
6 | "copy-code-button",
7 | "algolia"
8 | ],
9 | "pluginsConfig": {
10 | "disqus": {
11 | "shortName": "writing-telegram-bots",
12 | "useIdentifier": true
13 | }, "algolia": {
14 | "index": "lessons",
15 | "applicationID": "C3LVYDULT2",
16 | "publicKey": "8b200bec152be76f39dbb40d6da98ac0",
17 | "freeAccount": "true"
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/SUMMARY.md:
--------------------------------------------------------------------------------
1 | # Table of contents
2 |
3 | * [Introduction](README.md)
4 | * [Lesson 1. Simple echo bot](chapter1.md)
5 | * [Lesson 2. PhotoBot](lesson-2.-photobot.md)
6 | * [Lesson 3. Logging](lesson-3.-logging.md)
7 | * [Lesson 4. Emoji](lesson-4.-emoji.md)
8 | * [Lesson 5. Deploy your bot](lesson-5.-deploy-your-bot.md)
9 | * [Lesson 6. Inline keyboards and editing message's text](lesson-6.-inline-keyboards-and-editing-messages-text.md)
10 | * [Lesson 7. Creating users database with MongoDB](lesson-7.-creating-users-database-with-mongodb.md)
11 | * [Lesson 8. Integrating with Redis](lesson-8-integrating-with-redis.md)
12 |
13 |
--------------------------------------------------------------------------------
/Lesson 2/src/Main.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.ApiContextInitializer;
2 | import org.telegram.telegrambots.TelegramBotsApi;
3 | import org.telegram.telegrambots.exceptions.TelegramApiException;
4 |
5 |
6 | public class Main {
7 | public static void main(String[] args) {
8 | ApiContextInitializer.init();
9 |
10 | TelegramBotsApi botsApi = new TelegramBotsApi();
11 |
12 | try {
13 | botsApi.registerBot(new PhotoBot());
14 | } catch (TelegramApiException e) {
15 | e.printStackTrace();
16 | }
17 | System.out.println("PhotoBot successfully started!");
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Lesson 6/src/Main.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.ApiContextInitializer;
2 | import org.telegram.telegrambots.TelegramBotsApi;
3 | import org.telegram.telegrambots.exceptions.TelegramApiException;
4 |
5 | public class Main {
6 | public static void main(String[] args) {
7 | // Initialize Api Context
8 | ApiContextInitializer.init();
9 |
10 | // Instantiate Telegram Bots API
11 | TelegramBotsApi botsApi = new TelegramBotsApi();
12 |
13 | // Register our bot
14 | try {
15 | botsApi.registerBot(new BotApi20());
16 | } catch (TelegramApiException e) {
17 | e.printStackTrace();
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Lesson 1/src/Main.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.ApiContextInitializer;
2 | import org.telegram.telegrambots.meta.TelegramBotsApi;
3 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
4 | public class Main {
5 | public static void main(String[] args) {
6 | // Initialize Api Context
7 | ApiContextInitializer.init();
8 |
9 | // Instantiate Telegram Bots API
10 | TelegramBotsApi botsApi = new TelegramBotsApi();
11 |
12 | // Register our bot
13 | try {
14 | botsApi.registerBot(new MyAmazingBot());
15 | } catch (TelegramApiException e) {
16 | e.printStackTrace();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Lesson 4/src/Main.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.ApiContextInitializer;
2 | import org.telegram.telegrambots.TelegramBotsApi;
3 | import org.telegram.telegrambots.exceptions.TelegramApiException;
4 |
5 | public class Main {
6 | public static void main(String[] args) {
7 | // Initialize Api Context
8 | ApiContextInitializer.init();
9 |
10 | // Instantiate Telegram Bots API
11 | TelegramBotsApi botsApi = new TelegramBotsApi();
12 |
13 | // Register our bot
14 | try {
15 | botsApi.registerBot(new EmojiTestBot());
16 | } catch (TelegramApiException e) {
17 | e.printStackTrace();
18 | }
19 | System.out.println("EmojiTestBot successfully started!");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/Lesson 3/src/Main.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.ApiContextInitializer;
2 | import org.telegram.telegrambots.TelegramBotsApi;
3 | import org.telegram.telegrambots.exceptions.TelegramApiException;
4 |
5 | public class Main {
6 | public static void main(String[] args) {
7 | // Initialize Api Context
8 | ApiContextInitializer.init();
9 |
10 | // Instantiate Telegram Bots API
11 | TelegramBotsApi botsApi = new TelegramBotsApi();
12 |
13 | // Register our bot
14 | try {
15 | botsApi.registerBot(new LoggingTestBot());
16 | } catch (TelegramApiException e) {
17 | e.printStackTrace();
18 | }
19 | System.out.println("LoggingTestBot successfully started!");
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - table of contents
5 | - getting started
6 | - readme
7 | ---
8 |
9 | * Note: this guide is not maintained. It's open for all contributions through GitHub.
10 |
11 | # Introduction
12 |
13 | [](https://www.gitbook.io/book/MonsterDeveloper/writing-telegram-bots-on-java/details)
14 |
15 | Hello everyone! While reading this book you will learn how to create Telegram Bots from start to finish. I assume you already know Java programming language.
16 |
17 | All sources are available at [GitHub repository](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial/).
18 |
19 | ## Table of contents
20 |
21 | * [Lesson 1. Simple "echo" bot](chapter1.md)
22 | * [Lesson 2. PhotoBot](lesson-2.-photobot.md)
23 | * [Lesson 3. Logging](lesson-3.-logging.md)
24 | * [Lesson 4. Emoji](lesson-4.-emoji.md)
25 | * [Lesson 5. Deploy your bot](lesson-5.-deploy-your-bot.md)
26 | * [Lesson 6. Inline keyboards and editing message's text](lesson-6.-inline-keyboards-and-editing-messages-text.md)
27 | * [Lesson 7. Creating users database with MongoDB](lesson-7.-creating-users-database-with-mongodb.md)
28 | * [Lesson 8. Integrating with Redis](lesson-8-integrating-with-redis.md)
29 |
30 | ## Credits
31 |
32 | * [Rubenlagus](https://github.com/rubenlagus/) for his amazing library and support
33 | * [Clevero](https://github.com/Clevero) for his amazing HOWTO guide
34 | * [MasterGroosha](https://github.com/MasterGroosha) for his amazing Python book
35 |
36 |
--------------------------------------------------------------------------------
/Lesson 1/src/MyAmazingBot.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
2 | import org.telegram.telegrambots.meta.api.objects.Update;
3 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
4 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
5 |
6 | public class MyAmazingBot extends TelegramLongPollingBot {
7 | @Override
8 | public void onUpdateReceived(Update update) {
9 |
10 | // We check if the update has a message and the message has text
11 | if (update.hasMessage() && update.getMessage().hasText()) {
12 | // Set variables
13 | String message_text = update.getMessage().getText();
14 | long chat_id = update.getMessage().getChatId();
15 |
16 | SendMessage message = new SendMessage() // Create a message object object
17 | .setChatId(chat_id)
18 | .setText(message_text);
19 | try {
20 | execute(message); // Sending our message object to user
21 | } catch (TelegramApiException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 | }
26 |
27 | @Override
28 | public String getBotUsername() {
29 | // Return bot username
30 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
31 | return "MyAmazingBot";
32 | }
33 |
34 | @Override
35 | public String getBotToken() {
36 | // Return bot token from BotFather
37 | return "12345:qwertyuiopASDGFHKMK";
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/lesson-8-integrating-with-redis.md:
--------------------------------------------------------------------------------
1 | # Lesson 8. Integrating with Redis
2 |
3 | search: keywords: \['lesson 8', '8', 'redis', 'database', 'fast database', 'lettuce'\]
4 |
5 | ## Lesson 8. Integrating with Redis
6 |
7 | Hi! Long time I haven't posted lessons. Sorry for that:\) Today we are integrating our ~~highload~~ bot with lighting fast database called [Redis](https://redis.io). I am using it for data that needs quick access.
8 |
9 | ### Library
10 |
11 | For driver I chose [Lettuce](https://lettuce.io) because of its popularity and good documentation. You can download it [here](https://lettuce.io/core/release/download/) or install with Maven:
12 |
13 | ```text
14 |
15 | io.lettuce
16 | lettuce-core
17 | Latest
18 |
19 | ```
20 |
21 | ### Establish connection
22 |
23 | Then, you need to connect to Redis:
24 |
25 | ```java
26 | RedisClient redisClient;
27 | StatefulRedisConnection redisConnection;
28 | RedisCommands syncCommands;
29 |
30 | redisClient = RedisClient.create("redis://localhost:6379/0"); // Format: redis://ip:post/dbNumber
31 | redisConnection = redisClient.connect();
32 | syncCommands = this.redisConnection.sync();
33 | ```
34 |
35 | ### Connection established
36 |
37 | And thats all! Now you can execute commands like that:
38 |
39 | ```java
40 | syncCommands.get("key");
41 | syncCommands.set("key", "value");
42 | syncCommands.lrange("key", 0, -1);
43 | ```
44 |
45 | Also, don't forget to close connection with Redis when you done your work:
46 |
47 | ```java
48 | redisConnection.close();
49 | redisClient.shutdown();
50 | ```
51 |
52 | Very short lesson, but I think useful :D Thanks for your time, hope to see you soon!
53 |
54 |
--------------------------------------------------------------------------------
/Lesson 7/src/database.java:
--------------------------------------------------------------------------------
1 | import com.mongodb.MongoClient;
2 | import com.mongodb.MongoClientURI;
3 | import com.mongodb.client.MongoCollection;
4 | import com.mongodb.client.MongoDatabase;
5 | import org.bson.Document;
6 | import org.json.JSONObject;
7 | import static java.lang.Math.toIntExact;
8 |
9 | // Set variables
10 | String user_first_name = update.getMessage().getChat().getFirstName();
11 | String user_last_name = update.getMessage().getChat().getLastName();
12 | String user_username = update.getMessage().getChat().getUserName();
13 | long user_id = update.getMessage().getChat().getId();
14 | String message_text = update.getMessage().getText();
15 | long chat_id = update.getMessage().getChatId();
16 |
17 | try {
18 | sendMessage(message);
19 | check(user_first_name, user_last_name, toIntExact(user_id), user_username);
20 | } catch (TelegramApiException e) {
21 | e.printStackTrace();
22 | }
23 |
24 | private String check(String first_name, String last_name, int user_id, String username) {
25 | // Set loggers
26 | java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);
27 | MongoClientURI connectionString = new MongoClientURI("mongodb://host:port");
28 | MongoClient mongoClient = new MongoClient(connectionString);
29 | MongoDatabase database = mongoClient.getDatabase("db_name");
30 | MongoCollection collection = database.getCollection("users");
31 | long found = collection.count(Document.parse("{id : " + Integer.toString(user_id) + "}"));
32 | if (found == 0) {
33 | Document doc = new Document("first_name", first_name)
34 | .append("last_name", last_name)
35 | .append("id", user_id)
36 | .append("username", username);
37 | collection.insertOne(doc);
38 | mongoClient.close();
39 | System.out.println("User not exists in database. Written.");
40 | return "no_exists";
41 | } else {
42 | System.out.println("User exists in database.");
43 | mongoClient.close();
44 | return "exists";
45 | }
46 |
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/Lesson 3/src/LoggingTestBot.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.api.methods.send.SendMessage;
2 | import org.telegram.telegrambots.api.objects.Update;
3 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
4 | import org.telegram.telegrambots.exceptions.TelegramApiException;
5 |
6 | import java.text.DateFormat;
7 | import java.text.SimpleDateFormat;
8 | import java.util.Date;
9 |
10 | public class LoggingTestBot extends TelegramLongPollingBot {
11 | @Override
12 | public void onUpdateReceived(Update update) {
13 |
14 | // We check if the update has a message and the message has text
15 | if (update.hasMessage() && update.getMessage().hasText()) {
16 | // Set variables
17 | String user_first_name = update.getMessage().getChat().getFirstName();
18 | String user_last_name = update.getMessage().getChat().getLastName();
19 | String user_username = update.getMessage().getChat().getUserName();
20 | long user_id = update.getMessage().getChat().getId();
21 | String message_text = update.getMessage().getText();
22 | long chat_id = update.getMessage().getChatId();
23 | String answer = message_text;
24 | SendMessage message = new SendMessage() // Create a message object object
25 | .setChatId(chat_id)
26 | .setText(answer);
27 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
28 | try {
29 | sendMessage(message); // Sending our message object to user
30 | } catch (TelegramApiException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 | }
35 |
36 |
37 |
38 | @Override
39 | public String getBotUsername() {
40 | // Return bot username
41 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
42 | return "LoggingTestBot";
43 | }
44 |
45 | @Override
46 | public String getBotToken() {
47 | // Return bot token from BotFather
48 | return "12345:qwertyuiopASDGFHKMK";
49 | }
50 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
51 | System.out.println("\n ----------------------------");
52 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
53 | Date date = new Date();
54 | System.out.println(dateFormat.format(date));
55 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
56 | System.out.println("Bot answer: \n Text - " + bot_answer);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Lesson 4/src/EmojiTestBot.java:
--------------------------------------------------------------------------------
1 | import com.vdurmont.emoji.EmojiParser;
2 | import org.telegram.telegrambots.api.methods.send.SendMessage;
3 | import org.telegram.telegrambots.api.objects.Update;
4 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
5 | import org.telegram.telegrambots.exceptions.TelegramApiException;
6 |
7 | import java.text.DateFormat;
8 | import java.text.SimpleDateFormat;
9 | import java.util.Date;
10 |
11 | public class EmojiTestBot extends TelegramLongPollingBot {
12 | @Override
13 | public void onUpdateReceived(Update update) {
14 |
15 | // We check if the update has a message and the message has text
16 | if (update.hasMessage() && update.getMessage().hasText()) {
17 | // Set variables
18 | String user_first_name = update.getMessage().getChat().getFirstName();
19 | String user_last_name = update.getMessage().getChat().getLastName();
20 | long user_id = update.getMessage().getChat().getId();
21 | String message_text = update.getMessage().getText();
22 | long chat_id = update.getMessage().getChatId();
23 | String answer = EmojiParser.parseToUnicode("Here is a smile emoji: :smile:\n\n Here is alien emoji: :alien:");
24 | SendMessage message = new SendMessage() // Create a message object object
25 | .setChatId(chat_id)
26 | .setText(answer);
27 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
28 | try {
29 | sendMessage(message); // Sending our message object to user
30 | } catch (TelegramApiException e) {
31 | e.printStackTrace();
32 | }
33 | }
34 | }
35 |
36 |
37 |
38 | @Override
39 | public String getBotUsername() {
40 | // Return bot username
41 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
42 | return "EmojiTestBot";
43 | }
44 |
45 | @Override
46 | public String getBotToken() {
47 | // Return bot token from BotFather
48 | return "12345:qwertyuiopASDGFHKMK";
49 | }
50 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
51 | System.out.println("\n ----------------------------");
52 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
53 | Date date = new Date();
54 | System.out.println(dateFormat.format(date));
55 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
56 | System.out.println("Bot answer: \n Text - " + bot_answer);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Lesson 6/src/BotApi20.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.api.methods.send.SendMessage;
2 | import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
3 | import org.telegram.telegrambots.api.objects.Update;
4 | import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
5 | import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;
6 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
7 | import org.telegram.telegrambots.exceptions.TelegramApiException;
8 |
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | import static java.lang.Math.toIntExact;
13 |
14 | public class BotApi20 extends TelegramLongPollingBot {
15 | @Override
16 | public void onUpdateReceived(Update update) {
17 |
18 | // We check if the update has a message and the message has text
19 | if (update.hasMessage() && update.getMessage().hasText()) {
20 | String message_text = update.getMessage().getText();
21 | long chat_id = update.getMessage().getChatId();
22 | if (update.getMessage().getText().equals("/start")) {
23 |
24 |
25 | SendMessage message = new SendMessage() // Create a message object object
26 | .setChatId(chat_id)
27 | .setText("You send /start");
28 | InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
29 | List> rowsInline = new ArrayList<>();
30 | List rowInline = new ArrayList<>();
31 | rowInline.add(new InlineKeyboardButton().setText("Update message text").setCallbackData("update_msg_text"));
32 | // Set the keyboard to the markup
33 | rowsInline.add(rowInline);
34 | // Add it to the message
35 | markupInline.setKeyboard(rowsInline);
36 | message.setReplyMarkup(markupInline);
37 | try {
38 | sendMessage(message); // Sending our message object to user
39 | } catch (TelegramApiException e) {
40 | e.printStackTrace();
41 | }
42 | } else {
43 |
44 | }
45 |
46 | } else if (update.hasCallbackQuery()) {
47 | // Set variables
48 | String call_data = update.getCallbackQuery().getData();
49 | long message_id = update.getCallbackQuery().getMessage().getMessageId();
50 | long chat_id = update.getCallbackQuery().getMessage().getChatId();
51 |
52 | if (call_data.equals("update_msg_text")) {
53 | String answer = "Updated message text";
54 | EditMessageText new_message = new EditMessageText()
55 | .setChatId(chat_id)
56 | .setMessageId(toIntExact(message_id))
57 | .setText(answer);
58 | try {
59 | editMessageText(new_message);
60 | } catch (TelegramApiException e) {
61 | e.printStackTrace();
62 | }
63 | }
64 | }
65 | }
66 | @Override
67 | public String getBotUsername() {
68 | // Return bot username
69 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
70 | return "BotApi20Bot";
71 | }
72 |
73 | @Override
74 | public String getBotToken() {
75 | // Return bot token from BotFather
76 | return "12345:qwertyuiopASDGFHKMK";
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/lesson-5.-deploy-your-bot.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - deploy
5 | - bot
6 | - telegram
7 | - do
8 | - digitalocean
9 | - '5'
10 | - hosting
11 | - jar
12 | - artifact
13 | ---
14 |
15 | # Lesson 5. Deploy your bot
16 |
17 | I think, when you are reading this, you have created your own bot with the help from my book. So now, its time to run it not on your home computer ~~with Intel Pentium II~~, but on professional server hardware. I will show how to deploy your bot on [DigitalOcean hosting](https://m.do.co/c/1a3a7fad419f).
18 |
19 | ## Creating droplet
20 |
21 | Firstly, you need to create account on DigitalOcean. Open [this link](https://m.do.co/c/1a3a7fad419f) to get 10$ as gift from me, enter your email and password and click "Create an account"
22 |
23 | 
24 |
25 | Then, follow register insctructions. Once you are in your control panel, create a new droplet.
26 |
27 | Select OS. I recommend using Ubuntu 16.04.01 x64. Then choose preffered plan. For Java bot, you can select 512-1GB RAM \(its enough for start\). Select datacenter's region \(I recommend to choose nearest city\), scroll down and click "Create". Check your email inbox for letter like this:
28 |
29 | 
30 |
31 | ## Connecting via SSH
32 |
33 | You will need next software for that:
34 |
35 | * [PuTTY SSH Client](http://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html)
36 | * [FileZilla FTP Client](https://filezilla-project.org/)
37 |
38 | When you install it, open PuTTY and write server IP and port \(default 22\).
39 |
40 | 
41 |
42 | And click "Open". You will see something like:
43 |
44 | 
45 |
46 | Click "Yes". Then login as "root" user and with password that you have recieved via email. Now we need to install Java on your server. Type following:
47 |
48 | ```bash
49 | sudo apt-get update
50 | sudo apt-get upgrade
51 | sudo apt-get install default-jre
52 | sudo apt-get install default-jdk
53 | sudo add-apt-repository ppa:webupd8team/java
54 | sudo apt-get update
55 | sudo apt-get install oracle-java8-installer
56 | ```
57 |
58 | Type `java -version` to check installation. You will see something like that:
59 |
60 | 
61 |
62 | ## Creating and uploading JAR
63 |
64 | Now, open `IntelliJ Idea` and go to File>Project Structure>Artifacts> + \(Add artifact\)>JAR>From modules with dependencies>Select main class \(`Main.java`\)>OK>Apply. Then Build>Build Artifacts>Build. Then in the `out/artifacts/` folder you will see your JAR.
65 |
66 | ### Uploading to the server
67 |
68 | Open FileZilla and enter IP address, username, password and port \(default 22\) and click "Connect". Create new folder on your server \(right window\), open it and upload you JAR by dragging it from left window \(local computer\) to right window \(server\). Open PuTTY and type:
69 |
70 | ```bash
71 | screen
72 | ```
73 |
74 | Press `ENTER` and then go to your folder:
75 |
76 | ```bash
77 | cd FOLDER_NAME
78 | ```
79 |
80 | And just run your JAR:
81 |
82 | ```bash
83 | java -jar FILE.jar
84 | ```
85 |
86 | Well done! You are now hosting your bot at DigitalOcean. To exit terminal, press `CTRL + A + D` and then type `exit`. To return, connect via SSH, type `screen -r` and you will be returned to your screen session. To stop the bot: `CTRL + C`.
87 |
88 | Well, that's all for now. See you soon!
89 |
90 |
--------------------------------------------------------------------------------
/lesson-7.-creating-users-database-with-mongodb.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - lesson 7
5 | - '7'
6 | - mongodb
7 | - database
8 | - users database
9 | - statistics
10 | ---
11 |
12 | # Lesson 7. Creating users database with MongoDB
13 |
14 | Hey! As you're reading this, you know that I returned from Italy. It was very nice, but okey - you want to create users database for your bot. Disputes about what DB is better can live very long time, but I will choose MongoDB. It is [high-performance, schema-free document-oriented database](https://mongodb.com). Let's create actual 'body' of our bot. Well, as always. I will skip this step as I know you have your own bot and there is no need to pollute the great lesson unnecessary amount of code. If not, you can find all sources at [GitHub repo](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial/). Now, import MongoDB's driver for Java. You can download it [here](http://mongodb.github.io/mongo-java-driver/) or import it from Maven. With IntelliJ Idea it is easier than you expect. Just go to **File < Project Structure... < Libraries < + < From Maven** and search for `org.mongodb:mongo-java-driver`. That's all. Import it in your bot file:
15 |
16 | ```java
17 | import com.mongodb.MongoClient;
18 | import com.mongodb.MongoClientURI;
19 | import com.mongodb.client.MongoCollection;
20 | import com.mongodb.client.MongoDatabase;
21 |
22 | import org.bson.Document;
23 | import org.json.JSONObject;
24 | ```
25 |
26 | You will also need `org.slf4j:slf4j-nop` library to disable additional logging, like this:
27 |
28 | ```text
29 | 11:01:15.406 [pool-1-thread-1] DEBUG org.mongodb.driver.protocol.query - Query completed
30 |
31 | 11:01:25.174 [cluster-ClusterId{value='554dbecb1b554f11e86c3a69', description='null'}-localhost:27017] DEBUG org.mongodb.driver.cluster - Checking status of localhost:27017
32 | ```
33 |
34 | Install it from Maven as you did with MongoDB Java Driver. Let's write our "check" function, that will check if user exists in database. If not, write it.
35 |
36 | ```java
37 | private String check(String first_name, String last_name, int user_id, String username) {
38 | MongoClientURI connectionString = new MongoClientURI("mongodb://host:port");
39 | MongoClient mongoClient = new MongoClient(connectionString);
40 | MongoDatabase database = mongoClient.getDatabase("db_name");
41 | MongoCollection collection = database.getCollection("users");
42 | long found = collection.count(Document.parse("{id : " + Integer.toString(user_id) + "}"));
43 | if (found == 0) {
44 | Document doc = new Document("first_name", first_name)
45 | .append("last_name", last_name)
46 | .append("id", user_id)
47 | .append("username", username);
48 | collection.insertOne(doc);
49 | mongoClient.close();
50 | System.out.println("User not exists in database. Written.");
51 | return "no_exists";
52 | } else {
53 | System.out.println("User exists in database.");
54 | mongoClient.close();
55 | return "exists";
56 | }
57 |
58 |
59 | }
60 | ```
61 |
62 | Don't do [kernel panic](https://en.wikipedia.org/wiki/Kernel_panic), I will explain everything now.
63 |
64 | Here we set new connection to MongoDB's server:
65 |
66 | ```java
67 | MongoClientURI connectionString = new MongoClientURI("mongodb://host:port");
68 | ```
69 |
70 | Replace `host:port` with your Mongo's host and port. You can find how to setup MongoDB server for Ubuntu [here](https://www.digitalocean.com/community/tutorials/how-to-install-mongodb-on-ubuntu-16-04). Then we set our database and collection. Replace this names with your own.
71 |
72 | ```java
73 | MongoClient mongoClient = new MongoClient(connectionString);
74 | MongoDatabase database = mongoClient.getDatabase("db_name");
75 | MongoCollection collection = database.getCollection("users");
76 | ```
77 |
78 | We search users like this:
79 |
80 | ```java
81 | long found = collection.count(Document.parse("{id : " + Integer.toString(user_id) + "}"));
82 | ```
83 |
84 | And just check if user exists or not.
85 |
86 | ```java
87 | if (found == 0) {
88 | Document doc = new Document("first_name", first_name)
89 | .append("last_name", last_name)
90 | .append("id", user_id)
91 | .append("username", username);
92 | collection.insertOne(doc);
93 | mongoClient.close();
94 | System.out.println("User not exists in database. Written.");
95 | return "no_exists";
96 | } else {
97 | System.out.println("User exists in database.");
98 | mongoClient.close();
99 | return "exists";
100 | }
101 | ```
102 |
103 | So now our full function looks like this:
104 |
105 | ```java
106 | private String check(String first_name, String last_name, int user_id, String username) {
107 | // Set loggers
108 | java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.OFF);
109 | MongoClientURI connectionString = new MongoClientURI("mongodb://host:port");
110 | MongoClient mongoClient = new MongoClient(connectionString);
111 | MongoDatabase database = mongoClient.getDatabase("db_name");
112 | MongoCollection collection = database.getCollection("users");
113 | long found = collection.count(Document.parse("{id : " + Integer.toString(user_id) + "}"));
114 | if (found == 0) {
115 | Document doc = new Document("first_name", first_name)
116 | .append("last_name", last_name)
117 | .append("id", user_id)
118 | .append("username", username);
119 | collection.insertOne(doc);
120 | mongoClient.close();
121 | System.out.println("User not exists in database. Written.");
122 | return "no_exists";
123 | } else {
124 | System.out.println("User exists in database.");
125 | mongoClient.close();
126 | return "exists";
127 | }
128 |
129 |
130 | }
131 | ```
132 |
133 | Just check if user exists in database by calling this function when user sends `/start`:
134 |
135 | ```java
136 | import static java.lang.Math.toIntExact;
137 |
138 | // Set variables
139 | String user_first_name = update.getMessage().getChat().getFirstName();
140 | String user_last_name = update.getMessage().getChat().getLastName();
141 | String user_username = update.getMessage().getChat().getUserName();
142 | long user_id = update.getMessage().getChat().getId();
143 | String message_text = update.getMessage().getText();
144 | long chat_id = update.getMessage().getChatId();
145 |
146 | try {
147 | sendMessage(message);
148 | check(user_first_name, user_last_name, toIntExact(user_id), user_username);
149 | } catch (TelegramApiException e) {
150 | e.printStackTrace();
151 | }
152 | ```
153 |
154 | Well, that's all for now. Hope to see you soon!
155 |
156 | > Thanks for reading this.
157 | >
158 | > _MonsterDeveloper_
159 |
160 |
--------------------------------------------------------------------------------
/Lesson 2/src/PhotoBot.java:
--------------------------------------------------------------------------------
1 | import org.telegram.telegrambots.api.methods.send.SendMessage;
2 | import org.telegram.telegrambots.api.methods.send.SendPhoto;
3 | import org.telegram.telegrambots.api.objects.PhotoSize;
4 | import org.telegram.telegrambots.api.objects.Update;
5 | import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;
6 | import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardRemove;
7 | import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;
8 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
9 | import org.telegram.telegrambots.exceptions.TelegramApiException;
10 |
11 | import java.util.ArrayList;
12 | import java.util.Comparator;
13 | import java.util.List;
14 |
15 | public class PhotoBot extends TelegramLongPollingBot {
16 | @Override
17 | public void onUpdateReceived(Update update) {
18 |
19 | // We check if the update has a message and the message has text
20 | if (update.hasMessage() && update.getMessage().hasText()) {
21 | // Set variables
22 | String message_text = update.getMessage().getText();
23 | long chat_id = update.getMessage().getChatId();
24 | if (message_text.equals("/start")) {
25 | SendMessage message = new SendMessage() // Create a message object object
26 | .setChatId(chat_id)
27 | .setText(message_text);
28 | try {
29 | execute(message); // Sending our message object to user
30 | } catch (TelegramApiException e) {
31 | e.printStackTrace();
32 | }
33 | } else if (message_text.equals("/pic")) {
34 | SendPhoto msg = new SendPhoto()
35 | .setChatId(chat_id)
36 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
37 | .setCaption("Photo");
38 | try {
39 | sendPhoto(msg); // Call method to send the photo
40 | } catch (TelegramApiException e) {
41 | e.printStackTrace();
42 | }
43 | } else if (message_text.equals("/markup")) {
44 | SendMessage message = new SendMessage() // Create a message object object
45 | .setChatId(chat_id)
46 | .setText("Here is your keyboard");
47 | // Create ReplyKeyboardMarkup object
48 | ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
49 | // Create the keyboard (list of keyboard rows)
50 | List keyboard = new ArrayList<>();
51 | // Create a keyboard row
52 | KeyboardRow row = new KeyboardRow();
53 | // Set each button, you can also use KeyboardButton objects if you need something else than text
54 | row.add("Row 1 Button 1");
55 | row.add("Row 1 Button 2");
56 | row.add("Row 1 Button 3");
57 | // Add the first row to the keyboard
58 | keyboard.add(row);
59 | // Create another keyboard row
60 | row = new KeyboardRow();
61 | // Set each button for the second line
62 | row.add("Row 2 Button 1");
63 | row.add("Row 2 Button 2");
64 | row.add("Row 2 Button 3");
65 | // Add the second row to the keyboard
66 | keyboard.add(row);
67 | // Set the keyboard to the markup
68 | keyboardMarkup.setKeyboard(keyboard);
69 | // Add it to the message
70 | message.setReplyMarkup(keyboardMarkup);
71 | try {
72 | execute(message); // Sending our message object to user
73 | } catch (TelegramApiException e) {
74 | e.printStackTrace();
75 | }
76 | } else if (message_text.equals("Row 1 Button 1")) {
77 | SendPhoto msg = new SendPhoto()
78 | .setChatId(chat_id)
79 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
80 | .setCaption("Photo");
81 |
82 | try {
83 | sendPhoto(msg); // Call method to send the photo
84 | } catch (TelegramApiException e) {
85 | e.printStackTrace();
86 | }
87 | } else if (message_text.equals("/hide")) {
88 | SendMessage msg = new SendMessage()
89 | .setChatId(chat_id)
90 | .setText("Keyboard hidden");
91 | ReplyKeyboardRemove keyboardMarkup = new ReplyKeyboardRemove();
92 | msg.setReplyMarkup(keyboardMarkup);
93 | try {
94 | sendPhoto(msg); // Call method to send the photo
95 | } catch (TelegramApiException e) {
96 | e.printStackTrace();
97 | }
98 | } else {
99 | SendMessage message = new SendMessage() // Create a message object object
100 | .setChatId(chat_id)
101 | .setText("Unknown command");
102 | try {
103 | execute(message); // Sending our message object to user
104 | } catch (TelegramApiException e) {
105 | e.printStackTrace();
106 | }
107 | }
108 | } else if (update.hasMessage() && update.getMessage().hasPhoto()) {
109 | // Message contains photo
110 | // Set variables
111 | long chat_id = update.getMessage().getChatId();
112 |
113 | List photos = update.getMessage().getPhoto();
114 | String f_id = photos.stream()
115 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
116 | .findFirst()
117 | .orElse(null).getFileId();
118 | int f_width = photos.stream()
119 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
120 | .findFirst()
121 | .orElse(null).getWidth();
122 | int f_height = photos.stream()
123 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
124 | .findFirst()
125 | .orElse(null).getHeight();
126 | String caption = "file_id: " + f_id + "\nwidth: " + Integer.toString(f_width) + "\nheight: " + Integer.toString(f_height);
127 | SendPhoto msg = new SendPhoto()
128 | .setChatId(chat_id)
129 | .setPhoto(f_id)
130 | .setCaption(caption);
131 | try {
132 | sendPhoto(msg); // Call method to send the message
133 | } catch (TelegramApiException e) {
134 | e.printStackTrace();
135 | }
136 | }
137 | }
138 |
139 | @Override
140 | public String getBotUsername() {
141 | // Return bot username
142 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
143 | return "PhotoBot";
144 | }
145 |
146 | @Override
147 | public String getBotToken() {
148 | // Return bot token from BotFather
149 | return "12345:qwertyuiopASDGFHKMK";
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/lesson-4.-emoji.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - emoji
5 | - bot
6 | - telegram
7 | - emojis
8 | - unicode
9 | - '4'
10 | ---
11 |
12 | # Lesson 4. Emoji
13 |
14 | Welcome back! Now your know, how to log messages from users. But how to make bot's messages more user-friendly and beautiful? The answer is - [emoji](https://en.wikipedia.org/wiki/Emoji). I think you know what is emoji, so let's move forward.
15 |
16 | Now, open `IntelliJ Idea` and create a new project. Create files `Main.java` and `EmojiTestBot.java` within the `src` directory. Here is first look of our files:
17 |
18 | > `src/Main.java`
19 |
20 | ```java
21 | import org.telegram.telegrambots.ApiContextInitializer;
22 | import org.telegram.telegrambots.TelegramBotsApi;
23 | import org.telegram.telegrambots.exceptions.TelegramApiException;
24 |
25 | public class Main {
26 | public static void main(String[] args) {
27 | // Initialize Api Context
28 | ApiContextInitializer.init();
29 |
30 | // Instantiate Telegram Bots API
31 | TelegramBotsApi botsApi = new TelegramBotsApi();
32 |
33 | // Register our bot
34 | try {
35 | botsApi.registerBot(new EmojiTestBot());
36 | } catch (TelegramApiException e) {
37 | e.printStackTrace();
38 | }
39 | System.out.println("EmojiTestBot successfully started!");
40 | }
41 | }
42 | ```
43 |
44 | > `src/EmojiTestBot.java`
45 |
46 | ```java
47 | import org.telegram.telegrambots.api.methods.send.SendMessage;
48 | import org.telegram.telegrambots.api.objects.Update;
49 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
50 | import org.telegram.telegrambots.exceptions.TelegramApiException;
51 |
52 | import java.text.DateFormat;
53 | import java.text.SimpleDateFormat;
54 | import java.util.Date;
55 |
56 | public class EmojiTestBot extends TelegramLongPollingBot {
57 | @Override
58 | public void onUpdateReceived(Update update) {
59 |
60 | // We check if the update has a message and the message has text
61 | if (update.hasMessage() && update.getMessage().hasText()) {
62 | // Set variables
63 | String user_first_name = update.getMessage().getChat().getFirstName();
64 | String user_last_name = update.getMessage().getChat().getLastName();
65 | long user_id = update.getMessage().getChat().getId();
66 | String message_text = update.getMessage().getText();
67 | long chat_id = update.getMessage().getChatId();
68 | String answer = message_text;
69 | SendMessage message = new SendMessage() // Create a message object object
70 | .setChatId(chat_id)
71 | .setText(answer);
72 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
73 | try {
74 | execute(message); // Sending our message object to user
75 | } catch (TelegramApiException e) {
76 | e.printStackTrace();
77 | }
78 | }
79 | }
80 |
81 |
82 |
83 | @Override
84 | public String getBotUsername() {
85 | // Return bot username
86 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
87 | return "EmojiTestBot";
88 | }
89 |
90 | @Override
91 | public String getBotToken() {
92 | // Return bot token from BotFather
93 | return "12345:qwertyuiopASDGFHKMK";
94 | }
95 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
96 | System.out.println("\n ----------------------------");
97 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
98 | Date date = new Date();
99 | System.out.println(dateFormat.format(date));
100 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
101 | System.out.println("Bot answer: \n Text - " + bot_answer);
102 | }
103 | }
104 | ```
105 |
106 | Okey. Now lets install [emoji library](https://github.com/vdurmont/emoji-java):
107 |
108 | * Via `Maven`:
109 |
110 | ```markup
111 |
112 | com.vdurmont
113 | emoji-java
114 | 3.1.3
115 |
116 | ```
117 |
118 | * Via `Gradle`:
119 |
120 | ```text
121 | compile 'com.vdurmont:emoji-java:3.1.3'
122 | ```
123 |
124 | * Or just download `.jar` from [here](https://github.com/vdurmont/emoji-java/releases/download/v3.1.3/emoji-java-3.1.3.jar)
125 |
126 | Once library is installed, import it to your bot class:
127 |
128 | ```java
129 | import com.vdurmont.emoji.EmojiParser;
130 | ```
131 |
132 | Now you can view list of emojis at [EmojiPedia](http://emojipedia.org/) or [Emoji Cheat Sheet](http://webpagefx.com/tools/emoji-cheat-sheet/). To insert emoji, do this:
133 |
134 | ```java
135 | String answer = EmojiParser.parseToUnicode("Here is a smile emoji: :smile:\n\n Here is alien emoji: :alien:");
136 | ```
137 |
138 | Where `:smile:` or `:alien:` is emoji alias or emoji short code. You can also view them at EmojiPedia or Emoji Cheat Sheet.
139 |
140 | Here is source code. You can also find it on [GitHub](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial).
141 |
142 | > `src/Main.java`
143 |
144 | ```java
145 | import org.telegram.telegrambots.ApiContextInitializer;
146 | import org.telegram.telegrambots.TelegramBotsApi;
147 | import org.telegram.telegrambots.exceptions.TelegramApiException;
148 |
149 | public class Main {
150 | public static void main(String[] args) {
151 | // Initialize Api Context
152 | ApiContextInitializer.init();
153 |
154 | // Instantiate Telegram Bots API
155 | TelegramBotsApi botsApi = new TelegramBotsApi();
156 |
157 | // Register our bot
158 | try {
159 | botsApi.registerBot(new EmojiTestBot());
160 | } catch (TelegramApiException e) {
161 | e.printStackTrace();
162 | }
163 | System.out.println("EmojiTestBot successfully started!");
164 | }
165 | }
166 | ```
167 |
168 | > `src/EmojiTestBot.java`
169 |
170 | ```java
171 | import com.vdurmont.emoji.EmojiParser;
172 | import org.telegram.telegrambots.api.methods.send.SendMessage;
173 | import org.telegram.telegrambots.api.objects.Update;
174 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
175 | import org.telegram.telegrambots.exceptions.TelegramApiException;
176 |
177 | import java.text.DateFormat;
178 | import java.text.SimpleDateFormat;
179 | import java.util.Date;
180 |
181 | public class EmojiTestBot extends TelegramLongPollingBot {
182 | @Override
183 | public void onUpdateReceived(Update update) {
184 |
185 | // We check if the update has a message and the message has text
186 | if (update.hasMessage() && update.getMessage().hasText()) {
187 | // Set variables
188 | String user_first_name = update.getMessage().getChat().getFirstName();
189 | String user_last_name = update.getMessage().getChat().getLastName();
190 | long user_id = update.getMessage().getChat().getId();
191 | String message_text = update.getMessage().getText();
192 | long chat_id = update.getMessage().getChatId();
193 | String answer = EmojiParser.parseToUnicode("Here is a smile emoji: :smile:\n\n Here is alien emoji: :alien:");
194 | SendMessage message = new SendMessage() // Create a message object object
195 | .setChatId(chat_id)
196 | .setText(answer);
197 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
198 | try {
199 | execute(message); // Sending our message object to user
200 | } catch (TelegramApiException e) {
201 | e.printStackTrace();
202 | }
203 | }
204 | }
205 |
206 |
207 |
208 | @Override
209 | public String getBotUsername() {
210 | // Return bot username
211 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
212 | return "EmojiTestBot";
213 | }
214 |
215 | @Override
216 | public String getBotToken() {
217 | // Return bot token from BotFather
218 | return "12345:qwertyuiopASDGFHKMK";
219 | }
220 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
221 | System.out.println("\n ----------------------------");
222 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
223 | Date date = new Date();
224 | System.out.println(dateFormat.format(date));
225 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
226 | System.out.println("Bot answer: \n Text - " + bot_answer);
227 | }
228 | }
229 | ```
230 |
231 | Now you can see our beautiful messages:
232 |
233 | 
234 |
235 | Our lesson came to an end. Thank you for reading this. See you soon!
236 |
237 |
--------------------------------------------------------------------------------
/lesson-3.-logging.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - logging
5 | - bot
6 | - telegram
7 | - log
8 | - logger
9 | - '3'
10 | ---
11 |
12 | # Lesson 3. Logging
13 |
14 | Good afternoon everyone! Did you look into console? Kinda empty ya? Now, we want to see something, isn't it? Let's make a logging function!
15 |
16 | ## Creating project
17 |
18 | As always, open `IntelliJ Idea` and create new project. Within the `src` folder create 2 files: `Main.java` and `LoggingTestBot.java`. Let's create a `body` of our bot:
19 |
20 | > src/LoggingTestBot.java
21 |
22 | ```java
23 | public class LoggingTestBot extends TelegramLongPollingBot {
24 | @Override
25 | public void onUpdateReceived(Update update) {
26 |
27 | // We check if the update has a message and the message has text
28 | if (update.hasMessage() && update.getMessage().hasText()) {
29 | // Set variables
30 | String message_text = update.getMessage().getText();
31 | long chat_id = update.getMessage().getChatId();
32 |
33 | SendMessage message = new SendMessage() // Create a message object object
34 | .setChatId(chat_id)
35 | .setText(message_text);
36 | try {
37 | execute(message); // Sending our message object to user
38 | } catch (TelegramApiException e) {
39 | e.printStackTrace();
40 | }
41 | }
42 | }
43 |
44 | @Override
45 | public String getBotUsername() {
46 | // Return bot username
47 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
48 | return "LoggingTestBot";
49 | }
50 |
51 | @Override
52 | public String getBotToken() {
53 | // Return bot token from BotFather
54 | return "12345:qwertyuiopASDGFHKMK";
55 | }
56 | }
57 | ```
58 |
59 | And our startup file:
60 |
61 | > src/Main.java
62 |
63 | ```java
64 | public class Main {
65 | public static void main(String[] args) {
66 | // Initialize Api Context
67 | ApiContextInitializer.init();
68 |
69 | // Instantiate Telegram Bots API
70 | TelegramBotsApi botsApi = new TelegramBotsApi();
71 |
72 | // Register our bot
73 | try {
74 | botsApi.registerBot(new LoggingTestBot());
75 | } catch (TelegramApiException e) {
76 | e.printStackTrace();
77 | }
78 | System.out.println("LoggingTestBot successfully started!");
79 | }
80 | }
81 | ```
82 |
83 | ## Logs, where are you?
84 |
85 | Lets set additional variables for logging:
86 |
87 | ```java
88 | public void onUpdateReceived(Update update) {
89 | // We check if the update has a message and the message has text
90 | if (update.hasMessage() && update.getMessage().hasText()) {
91 | // Set variables
92 | String user_first_name = update.getMessage().getChat().getFirstName();
93 | String user_last_name = update.getMessage().getChat().getLastName();
94 | String user_username = update.getMessage().getChat().getUserName();
95 | long user_id = update.getMessage().getChat().getId();
96 | String message_text = update.getMessage().getText();
97 | long chat_id = update.getMessage().getChatId();
98 |
99 | SendMessage message = new SendMessage() // Create a message object object
100 | .setChatId(chat_id)
101 | .setText(message_text);
102 | try {
103 | execute(message); // Sending our message object to user
104 | } catch (TelegramApiException e) {
105 | e.printStackTrace();
106 | }
107 | }
108 | }
109 | ```
110 |
111 | Create `logging` function:
112 |
113 | > Dont forget to import:
114 | >
115 | > ```java
116 | > import java.text.DateFormat;
117 | > import java.text.SimpleDateFormat;
118 | > import java.util.Date;
119 | > ```
120 |
121 | Add new `private` function:
122 |
123 | ```java
124 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
125 | System.out.println("\n ----------------------------");
126 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
127 | Date date = new Date();
128 | System.out.println(dateFormat.format(date));
129 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
130 | System.out.println("Bot answer: \n Text - " + bot_answer);
131 | }
132 | ```
133 |
134 | Now we need just call this function when we want to log
135 |
136 | ```java
137 | public void onUpdateReceived(Update update) {
138 | // We check if the update has a message and the message has text
139 | if (update.hasMessage() && update.getMessage().hasText()) {
140 | // Set variables
141 | String user_first_name = update.getMessage().getChat().getFirstName();
142 | String user_last_name = update.getMessage().getChat().getLastName();
143 | String user_username = update.getMessage().getChat().getUserName();
144 | long user_id = update.getMessage().getChat().getId();
145 | String message_text = update.getMessage().getText();
146 | long chat_id = update.getMessage().getChatId();
147 | String answer = message_text;
148 | SendMessage message = new SendMessage() // Create a message object object
149 | .setChatId(chat_id)
150 | .setText(answer);
151 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
152 | try {
153 | execute(message); // Sending our message object to user
154 | } catch (TelegramApiException e) {
155 | e.printStackTrace();
156 | }
157 | }
158 | }
159 | ```
160 |
161 | Our files:
162 |
163 | > src/Main.java
164 |
165 | ```java
166 | import org.telegram.telegrambots.ApiContextInitializer;
167 | import org.telegram.telegrambots.TelegramBotsApi;
168 | import org.telegram.telegrambots.exceptions.TelegramApiException;
169 |
170 | public class Main {
171 | public static void main(String[] args) {
172 | // Initialize Api Context
173 | ApiContextInitializer.init();
174 |
175 | // Instantiate Telegram Bots API
176 | TelegramBotsApi botsApi = new TelegramBotsApi();
177 |
178 | // Register our bot
179 | try {
180 | botsApi.registerBot(new LoggingTestBot());
181 | } catch (TelegramApiException e) {
182 | e.printStackTrace();
183 | }
184 | System.out.println("LoggingTestBot successfully started!");
185 | }
186 | }
187 | ```
188 |
189 | > src/LoggingTestBot.java
190 |
191 | ```java
192 | import org.telegram.telegrambots.api.methods.send.SendMessage;
193 | import org.telegram.telegrambots.api.objects.Update;
194 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
195 | import org.telegram.telegrambots.exceptions.TelegramApiException;
196 |
197 | import java.text.DateFormat;
198 | import java.text.SimpleDateFormat;
199 | import java.util.Date;
200 |
201 | public class LoggingTestBot extends TelegramLongPollingBot {
202 | @Override
203 | public void onUpdateReceived(Update update) {
204 |
205 | // We check if the update has a message and the message has text
206 | if (update.hasMessage() && update.getMessage().hasText()) {
207 | // Set variables
208 | String user_first_name = update.getMessage().getChat().getFirstName();
209 | String user_last_name = update.getMessage().getChat().getLastName();
210 | String user_username = update.getMessage().getChat().getUserName();
211 | long user_id = update.getMessage().getChat().getId();
212 | String message_text = update.getMessage().getText();
213 | long chat_id = update.getMessage().getChatId();
214 | String answer = message_text;
215 | SendMessage message = new SendMessage() // Create a message object object
216 | .setChatId(chat_id)
217 | .setText(answer);
218 | log(user_first_name, user_last_name, Long.toString(user_id), message_text, answer);
219 | try {
220 | execute(message); // Sending our message object to user
221 | } catch (TelegramApiException e) {
222 | e.printStackTrace();
223 | }
224 | }
225 | }
226 |
227 |
228 |
229 | @Override
230 | public String getBotUsername() {
231 | // Return bot username
232 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
233 | return "LoggingTestBot";
234 | }
235 |
236 | @Override
237 | public String getBotToken() {
238 | // Return bot token from BotFather
239 | return "12345:qwertyuiopASDGFHKMK";
240 | }
241 | private void log(String first_name, String last_name, String user_id, String txt, String bot_answer) {
242 | System.out.println("\n ----------------------------");
243 | DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
244 | Date date = new Date();
245 | System.out.println(dateFormat.format(date));
246 | System.out.println("Message from " + first_name + " " + last_name + ". (id = " + user_id + ") \n Text - " + txt);
247 | System.out.println("Bot answer: \n Text - " + bot_answer);
248 | }
249 | }
250 | ```
251 |
252 | You can also find all sources at [GitHub repository](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial/).
253 |
254 | Now it will do ~~ugly~~ log for us:\)
255 |
256 | 
257 |
258 | 
259 |
260 | Well, thats all for now. In the next lesson we will learn how to make your messages more beautiful with [unicode emojis:\)](https://en.wikipedia.org/wiki/Emoji).
261 |
262 |
--------------------------------------------------------------------------------
/chapter1.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - echo
5 | - bot
6 | - telegram
7 | - simple
8 | - getting started
9 | - '1'
10 | ---
11 |
12 | # Lesson 1. Simple echo bot
13 |
14 | Hello! If you want to know, how to code Telegram Bots on Java, you are on the right way!
15 |
16 | ## Prepare to launch
17 |
18 | Bot API is based on HTTP-requests, but in this book I will use [Rubenlagus' library for Java](https://github.com/rubenlagus/TelegramBots).
19 |
20 | ### Install the library
21 |
22 | You can install TelegramBots library with different methods:
23 |
24 | * Using Maven:
25 |
26 | ```markup
27 |
28 | org.telegram
29 | telegrambots
30 | Latest
31 |
32 | ```
33 |
34 | * Using [Jitpack](https://jitpack.io/#rubenlagus/TelegramBots/)
35 | * Or just download `.jar` file with dependencies from [here](https://github.com/rubenlagus/TelegramBots/releases/latest)
36 |
37 | In this tutorial I will use next machines:
38 |
39 | * Ubuntu 16.04 Server with 1GB of RAM
40 | * My home Windows 10 laptop with IntelliJ Idea pre-installed
41 |
42 | ## Lets go to code!
43 |
44 | Well, enough for words. Let's get down to buisness. In this lesson we will write simple bot that echoes everything we sent to him. Now, open `IntelliJ Idea` and create a new project. You can call it whatever you want. Then, dont forget to install `TelegramBots` library with preffered method. I think, that it is most easy to just download `.jar` from [here](https://github.com/rubenlagus/TelegramBots/releases/latest)
45 |
46 | Now, when you are in the project, create files `MyAmazingBot.java` and `Main.java` within the `src` directory. Open `MyAmazingBot.java` and lets write our actual bot:
47 |
48 | > Remember! The class must extends `TelegramLongPollingBot` and implement necessary methods
49 |
50 | ```java
51 | import org.telegram.telegrambots.api.methods.send.SendMessage;
52 | import org.telegram.telegrambots.api.objects.Update;
53 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
54 | import org.telegram.telegrambots.exceptions.TelegramApiException;
55 |
56 | public class MyAmazingBot extends TelegramLongPollingBot {
57 | @Override
58 | public void onUpdateReceived(Update update) {
59 | // TODO
60 | }
61 |
62 | @Override
63 | public String getBotUsername() {
64 | // TODO
65 | return null;
66 | }
67 |
68 | @Override
69 | public String getBotToken() {
70 | // TODO
71 | return null;
72 | }
73 | }
74 | ```
75 |
76 | As you can understand, `getBotUsername()` and `getBotToken()` must return bot's username and bot's token, obtained from [@BotFather](https://telegram.me/botfather). So now, our `MyAmazingBot.java` file will look like this:
77 |
78 | ```java
79 | import org.telegram.telegrambots.api.methods.send.SendMessage;
80 | import org.telegram.telegrambots.api.objects.Update;
81 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
82 | import org.telegram.telegrambots.exceptions.TelegramApiException;
83 |
84 | public class MyAmazingBot extends TelegramLongPollingBot {
85 | @Override
86 | public void onUpdateReceived(Update update) {
87 | // TODO
88 | }
89 |
90 | @Override
91 | public String getBotUsername() {
92 | // Return bot username
93 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
94 | return "MyAmazingBot";
95 | }
96 |
97 | @Override
98 | public String getBotToken() {
99 | // Return bot token from BotFather
100 | return "12345:qwertyuiopASDGFHKMK";
101 | }
102 | }
103 | ```
104 |
105 | Now, let's move on to the logic of our bot. As I said before, we want him to reply every text we send to him. `onUpdateReceived(Update update)` method is for us. When an update recieved, it will call this method.
106 |
107 | ```java
108 | @Override
109 | public void onUpdateReceived(Update update) {
110 |
111 | // We check if the update has a message and the message has text
112 | if (update.hasMessage() && update.getMessage().hasText()) {
113 | // Set variables
114 | String message_text = update.getMessage().getText();
115 | long chat_id = update.getMessage().getChatId();
116 |
117 | SendMessage message = new SendMessage() // Create a message object object
118 | .setChatId(chat_id)
119 | .setText(message_text);
120 | try {
121 | execute(message); // Sending our message object to user
122 | } catch (TelegramApiException e) {
123 | e.printStackTrace();
124 | }
125 | }
126 | }
127 | ```
128 |
129 | Good! But how do I run the bot? Well, its a good question. Lets save that file and open `Main.java`. This file will instantiate TelegramBotsApi and register our new bot. It will look like this:
130 |
131 | ```java
132 | import org.telegram.telegrambots.ApiContextInitializer;
133 | import org.telegram.telegrambots.TelegramBotsApi;
134 | import org.telegram.telegrambots.exceptions.TelegramApiException;
135 | public class Main {
136 | public static void main(String[] args) {
137 |
138 | // TODO Initialize Api Context
139 |
140 | // TODO Instantiate Telegram Bots API
141 |
142 | // TODO Register our bot
143 | }
144 | }
145 | ```
146 |
147 | Now, lets initialize Api Context
148 |
149 | ```java
150 | import org.telegram.telegrambots.ApiContextInitializer;
151 | import org.telegram.telegrambots.TelegramBotsApi;
152 | import org.telegram.telegrambots.exceptions.TelegramApiException;
153 | public class Main {
154 | public static void main(String[] args) {
155 | // Initialize Api Context
156 | ApiContextInitializer.init();
157 |
158 | // TODO Instantiate Telegram Bots API
159 |
160 | // TODO Register our bot
161 | }
162 | }
163 | ```
164 |
165 | Instantiate Telegram Bots API:
166 |
167 | ```java
168 | import org.telegram.telegrambots.ApiContextInitializer;
169 | import org.telegram.telegrambots.TelegramBotsApi;
170 | import org.telegram.telegrambots.exceptions.TelegramApiException;
171 | public class Main {
172 | public static void main(String[] args) {
173 | // Initialize Api Context
174 | ApiContextInitializer.init();
175 | // Instantiate Telegram Bots API
176 | TelegramBotsApi botsApi = new TelegramBotsApi();
177 |
178 | // TODO Register our bot
179 | }
180 | }
181 | ```
182 |
183 | And register our bot:
184 |
185 | ```java
186 | import org.telegram.telegrambots.ApiContextInitializer;
187 | import org.telegram.telegrambots.TelegramBotsApi;
188 | import org.telegram.telegrambots.exceptions.TelegramApiException;
189 | public class Main {
190 | public static void main(String[] args) {
191 | // Initialize Api Context
192 | ApiContextInitializer.init();
193 |
194 | // Instantiate Telegram Bots API
195 | TelegramBotsApi botsApi = new TelegramBotsApi();
196 |
197 | // Register our bot
198 | try {
199 | botsApi.registerBot(new MyAmazingBot());
200 | } catch (TelegramApiException e) {
201 | e.printStackTrace();
202 | }
203 | }
204 | }
205 | ```
206 |
207 | Here is all our files:
208 |
209 | > `src/Main.java`
210 |
211 | ```java
212 | import org.telegram.telegrambots.ApiContextInitializer;
213 | import org.telegram.telegrambots.TelegramBotsApi;
214 | import org.telegram.telegrambots.exceptions.TelegramApiException;
215 | public class Main {
216 | public static void main(String[] args) {
217 | // Initialize Api Context
218 | ApiContextInitializer.init();
219 |
220 | // Instantiate Telegram Bots API
221 | TelegramBotsApi botsApi = new TelegramBotsApi();
222 |
223 | // Register our bot
224 | try {
225 | botsApi.registerBot(new MyAmazingBot());
226 | } catch (TelegramApiException e) {
227 | e.printStackTrace();
228 | }
229 | }
230 | }
231 | ```
232 |
233 | > `src/MyAmazingBot.java`
234 |
235 | ```java
236 | import org.telegram.telegrambots.api.methods.send.SendMessage;
237 | import org.telegram.telegrambots.api.objects.Update;
238 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
239 | import org.telegram.telegrambots.exceptions.TelegramApiException;
240 |
241 | public class MyAmazingBot extends TelegramLongPollingBot {
242 | @Override
243 | public void onUpdateReceived(Update update) {
244 |
245 | // We check if the update has a message and the message has text
246 | if (update.hasMessage() && update.getMessage().hasText()) {
247 | // Set variables
248 | String message_text = update.getMessage().getText();
249 | long chat_id = update.getMessage().getChatId();
250 |
251 | SendMessage message = new SendMessage() // Create a message object object
252 | .setChatId(chat_id)
253 | .setText(message_text);
254 | try {
255 | execute(message); // Sending our message object to user
256 | } catch (TelegramApiException e) {
257 | e.printStackTrace();
258 | }
259 | }
260 | }
261 |
262 | @Override
263 | public String getBotUsername() {
264 | // Return bot username
265 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
266 | return "MyAmazingBot";
267 | }
268 |
269 | @Override
270 | public String getBotToken() {
271 | // Return bot token from BotFather
272 | return "12345:qwertyuiopASDGFHKMK";
273 | }
274 | }
275 | ```
276 |
277 | Well done! Now we can pack our project into runnable `.jar` file and run it on our computer/server!
278 |
279 | You can find all sources to this lesson in [GitHub repository](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial/).
280 |
281 | ```text
282 | java -jar MyAmazingBot.jar
283 | ```
284 |
285 | Now we can see our bot running:
286 |
287 | 
288 |
289 | Well, thats all for now. Hope to see you soon!:\)
290 |
291 |
--------------------------------------------------------------------------------
/lesson-6.-inline-keyboards-and-editing-messages-text.md:
--------------------------------------------------------------------------------
1 | # Lesson 6. Inline keyboards and editing message's text
2 |
3 | I published poll in our [Telegram chat](https://t.me/JavaBotsApi) about next lesson. So, as you are reading this, Bots API 2.0 won.
4 |
5 | 
6 |
7 | On April 9, 2016, Telegram released [Bot API 2.0](https://core.telegram.org/bots/api-changelog#april-9-2016) which allows you to edit message's text and send new Inline Keyboards. So, let's implement it to your bot and see how its beautiful. Now as always open `IntelliJ Idea`, within `src` folder create files `Main.java` and `BotApi20.java`. First look:
8 |
9 | > `src/BotApi20.java`
10 |
11 | ```java
12 | import org.telegram.telegrambots.api.methods.send.SendMessage;
13 | import org.telegram.telegrambots.api.objects.Update;
14 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
15 | import org.telegram.telegrambots.exceptions.TelegramApiException;
16 |
17 | public class BotApi20 extends TelegramLongPollingBot {
18 | @Override
19 | public void onUpdateReceived(Update update) {
20 |
21 | // We check if the update has a message and the message has text
22 | if (update.hasMessage() && update.getMessage().hasText()) {
23 | if (update.getMessage().getText().equals("/start")) {
24 | // Set variables
25 | String message_text = update.getMessage().getText();
26 | long chat_id = update.getMessage().getChatId();
27 |
28 | SendMessage message = new SendMessage() // Create a message object object
29 | .setChatId(chat_id)
30 | .setText(message_text);
31 | try {
32 | execute(message); // Sending our message object to user
33 | } catch (TelegramApiException e) {
34 | e.printStackTrace();
35 | }
36 | } else {
37 |
38 | }
39 |
40 | }
41 | }
42 |
43 | @Override
44 | public String getBotUsername() {
45 | // Return bot username
46 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
47 | return "BotApi20Bot";
48 | }
49 |
50 | @Override
51 | public String getBotToken() {
52 | // Return bot token from BotFather
53 | return "12345:qwertyuiopASDGFHKMK";
54 | }
55 | }
56 | ```
57 |
58 | > `src/Main.java`
59 |
60 | ```java
61 | import org.telegram.telegrambots.ApiContextInitializer;
62 | import org.telegram.telegrambots.TelegramBotsApi;
63 | import org.telegram.telegrambots.exceptions.TelegramApiException;
64 |
65 | public class Main {
66 | public static void main(String[] args) {
67 | // Initialize Api Context
68 | ApiContextInitializer.init();
69 |
70 | // Instantiate Telegram Bots API
71 | TelegramBotsApi botsApi = new TelegramBotsApi();
72 |
73 | // Register our bot
74 | try {
75 | botsApi.registerBot(new BotApi20());
76 | } catch (TelegramApiException e) {
77 | e.printStackTrace();
78 | }
79 | }
80 | }
81 | ```
82 |
83 | I recommend you always look in the [Bot API description](https://core.telegram.org/bots/api) so you know every method and type. Okey, lets make bot answer to the `/start` command:
84 |
85 | ```java
86 | public void onUpdateReceived(Update update) {
87 |
88 | // We check if the update has a message and the message has text
89 | if (update.hasMessage() && update.getMessage().hasText()) {
90 | String message_text = update.getMessage().getText();
91 | long chat_id = update.getMessage().getChatId();
92 | if (update.getMessage().getText().equals("/start")) {
93 |
94 |
95 | SendMessage message = new SendMessage() // Create a message object object
96 | .setChatId(chat_id)
97 | .setText("You send /start");
98 | try {
99 | execute(message); // Sending our message object to user
100 | } catch (TelegramApiException e) {
101 | e.printStackTrace();
102 | }
103 | } else {
104 |
105 | }
106 |
107 | } else if (update.hasCallbackQuery()) {}
108 | }
109 |
110 | ```
111 |
112 | And now lets add Inline Keyboard to this message:
113 |
114 | ```java
115 | public void onUpdateReceived(Update update) {
116 |
117 | // We check if the update has a message and the message has text
118 | if (update.hasMessage() && update.getMessage().hasText()) {
119 | String message_text = update.getMessage().getText();
120 | long chat_id = update.getMessage().getChatId();
121 | if (update.getMessage().getText().equals("/start")) {
122 |
123 |
124 | SendMessage message = new SendMessage() // Create a message object object
125 | .setChatId(chat_id)
126 | .setText("You send /start");
127 | InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
128 | List> rowsInline = new ArrayList<>();
129 | List rowInline = new ArrayList<>();
130 | rowInline.add(new InlineKeyboardButton().setText("Update message text").setCallbackData("update_msg_text"));
131 | // Set the keyboard to the markup
132 | rowsInline.add(rowInline);
133 | // Add it to the message
134 | markupInline.setKeyboard(rowsInline);
135 | message.setReplyMarkup(markupInline);
136 | try {
137 | execute(message); // Sending our message object to user
138 | } catch (TelegramApiException e) {
139 | e.printStackTrace();
140 | }
141 | } else {
142 |
143 | }
144 |
145 | } else if (update.hasCallbackQuery()) {}
146 | }
147 | ```
148 |
149 | It looks like this now:
150 |
151 | 
152 |
153 | We want to edit message text right? Let's do it when user press our button. Add a [Callback Query](https://core.telegram.org/bots/api#callbackquery) handler to your bot:
154 |
155 | ```java
156 | else if (update.hasCallbackQuery()) {}
157 | ```
158 |
159 | So if update has Callback query, it call this `else if` operator. Moving forward:
160 |
161 | ```java
162 | else if (update.hasCallbackQuery()) {
163 | // Set variables
164 | String call_data = update.getCallbackQuery().getData();
165 | long message_id = update.getCallbackQuery().getMessage().getMessageId();
166 | long chat_id = update.getCallbackQuery().getMessage().getChatId();
167 |
168 | if (call_data.equals("update_msg_text")) {
169 | String answer = "Updated message text";
170 | EditMessageText new_message = new EditMessageText()
171 | .setChatId(chat_id)
172 | .setMessageId(toIntExact(message_id))
173 | .setText(answer);
174 | try {
175 | execute(new_message);
176 | } catch (TelegramApiException e) {
177 | e.printStackTrace();
178 | }
179 | }
180 | }
181 | ```
182 |
183 | Now when user press our button it will change it's text:
184 |
185 | 
186 |
187 | Source:
188 |
189 | > `src/Main.java`
190 |
191 | ```java
192 | import org.telegram.telegrambots.ApiContextInitializer;
193 | import org.telegram.telegrambots.TelegramBotsApi;
194 | import org.telegram.telegrambots.exceptions.TelegramApiException;
195 |
196 | public class Main {
197 | public static void main(String[] args) {
198 | // Initialize Api Context
199 | ApiContextInitializer.init();
200 |
201 | // Instantiate Telegram Bots API
202 | TelegramBotsApi botsApi = new TelegramBotsApi();
203 |
204 | // Register our bot
205 | try {
206 | botsApi.registerBot(new BotApi20());
207 | } catch (TelegramApiException e) {
208 | e.printStackTrace();
209 | }
210 | }
211 | }
212 | ```
213 |
214 | > `src/BotApi20.java`
215 |
216 | ```java
217 | import org.telegram.telegrambots.api.methods.send.SendMessage;
218 | import org.telegram.telegrambots.api.methods.updatingmessages.EditMessageText;
219 | import org.telegram.telegrambots.api.objects.Update;
220 | import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
221 | import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;
222 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
223 | import org.telegram.telegrambots.exceptions.TelegramApiException;
224 |
225 | import java.util.ArrayList;
226 | import java.util.List;
227 |
228 | import static java.lang.Math.toIntExact;
229 |
230 | public class BotApi20 extends TelegramLongPollingBot {
231 | @Override
232 | public void onUpdateReceived(Update update) {
233 |
234 | // We check if the update has a message and the message has text
235 | if (update.hasMessage() && update.getMessage().hasText()) {
236 | String message_text = update.getMessage().getText();
237 | long chat_id = update.getMessage().getChatId();
238 | if (update.getMessage().getText().equals("/start")) {
239 |
240 |
241 | SendMessage message = new SendMessage() // Create a message object object
242 | .setChatId(chat_id)
243 | .setText("You send /start");
244 | InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
245 | List> rowsInline = new ArrayList<>();
246 | List rowInline = new ArrayList<>();
247 | rowInline.add(new InlineKeyboardButton().setText("Update message text").setCallbackData("update_msg_text"));
248 | // Set the keyboard to the markup
249 | rowsInline.add(rowInline);
250 | // Add it to the message
251 | markupInline.setKeyboard(rowsInline);
252 | message.setReplyMarkup(markupInline);
253 | try {
254 | execute(message); // Sending our message object to user
255 | } catch (TelegramApiException e) {
256 | e.printStackTrace();
257 | }
258 | } else {
259 |
260 | }
261 |
262 | } else if (update.hasCallbackQuery()) {
263 | // Set variables
264 | String call_data = update.getCallbackQuery().getData();
265 | long message_id = update.getCallbackQuery().getMessage().getMessageId();
266 | long chat_id = update.getCallbackQuery().getMessage().getChatId();
267 |
268 | if (call_data.equals("update_msg_text")) {
269 | String answer = "Updated message text";
270 | EditMessageText new_message = new EditMessageText()
271 | .setChatId(chat_id)
272 | .setMessageId(toIntExact(message_id))
273 | .setText(answer);
274 | try {
275 | execute(new_message);
276 | } catch (TelegramApiException e) {
277 | e.printStackTrace();
278 | }
279 | }
280 | }
281 | }
282 | @Override
283 | public String getBotUsername() {
284 | // Return bot username
285 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
286 | return "BotApi20Bot";
287 | }
288 |
289 | @Override
290 | public String getBotToken() {
291 | // Return bot token from BotFather
292 | return "12345:qwertyuiopASDGFHKMK";
293 | }
294 | }
295 |
296 | ```
297 |
298 | You can also find all source code to all of my lessons at [GitHub](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial).
299 |
300 | Thank you for reading this! Now you can send Inline Keyboards and edit message's text and extra: handle callback queries. I hope you liked this lesson. Next time I will show how to create users database using MongoDB. Bye!
301 |
--------------------------------------------------------------------------------
/lesson-2.-photobot.md:
--------------------------------------------------------------------------------
1 | ---
2 | search:
3 | keywords:
4 | - photo
5 | - bot
6 | - telegram
7 | - reply markup
8 | - keyboard markup
9 | - '2'
10 | ---
11 |
12 | # Lesson 2. PhotoBot
13 |
14 | Our today's mission - create a "photo" bot, that will send user a photo. It is just an example so there there will be no photos from online, no group chat support. Just local pics. But there is a good thing: we will learn how to create [custom keyboards](https://core.telegram.org/bots/api#replykeyboardmarkup), how to send [photos](https://core.telegram.org/bots/api#photosize) and create commands.
15 |
16 | ## Let's respect Telegram's servers
17 |
18 | Okey, for a start, let's prepare our pictures. Lets download 5 ~~completely unknown~~ photos. Just look: we will send same files to users many many times, so lets coast our traffic and disk space on Telegram Servers. It is amazing that we can upload our files at their server once and then just send files \(photos, audio files, documents, voice messages and [etc.](https://core.telegram.org/bots/api#available-types)\) by their unique `file_id`. Okey then. Now lets know photo's `file_id` when we will send it to our bot. As always, create a new project in `IntelliJ Idea` and create two files within the `src` directory: `Main.java` and `PhotoBot.java`. Open up first file and type next:
19 |
20 | > Dont forget to install [TelegramBots library](https://github.com/rubenlagus/TelegramBots)
21 |
22 | ```java
23 | import org.telegram.telegrambots.ApiContextInitializer;
24 | import org.telegram.telegrambots.TelegramBotsApi;
25 | import org.telegram.telegrambots.exceptions.TelegramApiException;
26 |
27 |
28 | public class Main {
29 | public static void main(String[] args) {
30 | ApiContextInitializer.init();
31 |
32 | TelegramBotsApi botsApi = new TelegramBotsApi();
33 |
34 | try {
35 | botsApi.registerBot(new PhotoBot());
36 | } catch (TelegramApiException e) {
37 | e.printStackTrace();
38 | }
39 | System.out.println("PhotoBot successfully started!");
40 | }
41 | }
42 | ```
43 |
44 | This code will register our bot print "PhotoBot successfully started!" when it is successfully started. Then, save it and open up `PhotoBot.java`. Paste the following code from previous lesson:
45 |
46 | > Dont forget to change `bot username` and `bot token` if you created another bot.
47 |
48 | ```java
49 | import org.telegram.telegrambots.api.methods.send.SendMessage;
50 | import org.telegram.telegrambots.api.objects.Update;
51 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
52 | import org.telegram.telegrambots.exceptions.TelegramApiException;
53 |
54 | public class PhotoBot extends TelegramLongPollingBot {
55 | @Override
56 | public void onUpdateReceived(Update update) {
57 |
58 | // We check if the update has a message and the message has text
59 | if (update.hasMessage() && update.getMessage().hasText()) {
60 | // Set variables
61 | String message_text = update.getMessage().getText();
62 | long chat_id = update.getMessage().getChatId();
63 | SendMessage message = new SendMessage() // Create a message object object
64 | .setChatId(chat_id)
65 | .setText(message_text);
66 | try {
67 | sendMessage(message); // Sending our message object to user
68 | } catch (TelegramApiException e) {
69 | e.printStackTrace();
70 | }
71 | }
72 | }
73 |
74 | @Override
75 | public String getBotUsername() {
76 | // Return bot username
77 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
78 | return "PhotoBot";
79 | }
80 |
81 | @Override
82 | public String getBotToken() {
83 | // Return bot token from BotFather
84 | return "12345:qwertyuiopASDGFHKMK";
85 | }
86 | }
87 | ```
88 |
89 | Now lets update our `onUpdateReceived` method. We want to send `file_id` of the picture we send to bot. Lets check if message contains photo object:
90 |
91 | ```java
92 | @Override
93 | public void onUpdateReceived(Update update) {
94 |
95 | // We check if the update has a message and the message has text
96 | if (update.hasMessage() && update.getMessage().hasText()) {
97 | // Set variables
98 | String message_text = update.getMessage().getText();
99 | long chat_id = update.getMessage().getChatId();
100 | SendMessage message = new SendMessage() // Create a message object object
101 | .setChatId(chat_id)
102 | .setText(message_text);
103 | try {
104 | sendMessage(message); // Sending our message object to user
105 | } catch (TelegramApiException e) {
106 | e.printStackTrace();
107 | }
108 | } else if (update.hasMessage() && update.getMessage().hasPhoto()) {
109 | // Message contains photo
110 | }
111 | }
112 | ```
113 |
114 | We want our bot to send `file_id` of the photo. Well, lets do this:
115 |
116 | ```java
117 | else if (update.hasMessage() && update.getMessage().hasPhoto()) {
118 | // Message contains photo
119 | // Set variables
120 | long chat_id = update.getMessage().getChatId();
121 |
122 | // Array with photo objects with different sizes
123 | // We will get the biggest photo from that array
124 | List photos = update.getMessage().getPhoto();
125 | // Know file_id
126 | String f_id = photos.stream()
127 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
128 | .findFirst()
129 | .orElse(null).getFileId();
130 | // Know photo width
131 | int f_width = photos.stream()
132 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
133 | .findFirst()
134 | .orElse(null).getWidth();
135 | // Know photo height
136 | int f_height = photos.stream()
137 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
138 | .findFirst()
139 | .orElse(null).getHeight();
140 | // Set photo caption
141 | String caption = "file_id: " + f_id + "\nwidth: " + Integer.toString(f_width) + "\nheight: " + Integer.toString(f_height);
142 | SendPhoto msg = new SendPhoto()
143 | .setChatId(chat_id)
144 | .setPhoto(f_id)
145 | .setCaption(caption);
146 | try {
147 | sendPhoto(msg); // Call method to send the photo with caption
148 | } catch (TelegramApiException e) {
149 | e.printStackTrace();
150 | }
151 | }
152 | ```
153 |
154 | Lets take a look:
155 |
156 | 
157 |
158 | Amazing! Now we know photo's file\_id so we can send them by file\_id. Lets make our bot answer with that photo when we send command `/pic`.
159 |
160 | ```java
161 | if (update.hasMessage() && update.getMessage().hasText()) {
162 | // Set variables
163 | String message_text = update.getMessage().getText();
164 | long chat_id = update.getMessage().getChatId();
165 | if (message_text.equals("/start")) {
166 | // User send /start
167 | SendMessage message = new SendMessage() // Create a message object object
168 | .setChatId(chat_id)
169 | .setText(message_text);
170 | try {
171 | sendMessage(message); // Sending our message object to user
172 | } catch (TelegramApiException e) {
173 | e.printStackTrace();
174 | }
175 | } else if (message_text.equals("/pic")) {
176 | // User sent /pic
177 | SendPhoto msg = new SendPhoto()
178 | .setChatId(chat_id)
179 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
180 | .setCaption("Photo");
181 | try {
182 | sendPhoto(msg); // Call method to send the photo
183 | } catch (TelegramApiException e) {
184 | e.printStackTrace();
185 | }
186 | } else {
187 | // Unknown command
188 | SendMessage message = new SendMessage() // Create a message object object
189 | .setChatId(chat_id)
190 | .setText("Unknown command");
191 | try {
192 | sendMessage(message); // Sending our message object to user
193 | } catch (TelegramApiException e) {
194 | e.printStackTrace();
195 | }
196 | }
197 | }
198 | ```
199 |
200 | Now bot sends photo like this:
201 |
202 | 
203 |
204 | And he can even reply to unknown command!
205 |
206 | 
207 |
208 | Now lets take a look at [ReplyKeyboardMarkup](https://core.telegram.org/bots/api#replykeyboardmarkup). We will now create custom keyboard like this:
209 |
210 | 
211 |
212 | Well, you already now how to make our bot recognise command. Lets make another `if` for command `/markup`.
213 |
214 | > Remember! When you press the button, it will send to bot the text on this button. For example, if I put "Hello" text on the button, when I press it, it will send "Hello" text for me
215 |
216 | ```java
217 | else if (message_text.equals("/markup")) {
218 | SendMessage message = new SendMessage() // Create a message object object
219 | .setChatId(chat_id)
220 | .setText("Here is your keyboard");
221 | // Create ReplyKeyboardMarkup object
222 | ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
223 | // Create the keyboard (list of keyboard rows)
224 | List keyboard = new ArrayList<>();
225 | // Create a keyboard row
226 | KeyboardRow row = new KeyboardRow();
227 | // Set each button, you can also use KeyboardButton objects if you need something else than text
228 | row.add("Row 1 Button 1");
229 | row.add("Row 1 Button 2");
230 | row.add("Row 1 Button 3");
231 | // Add the first row to the keyboard
232 | keyboard.add(row);
233 | // Create another keyboard row
234 | row = new KeyboardRow();
235 | // Set each button for the second line
236 | row.add("Row 2 Button 1");
237 | row.add("Row 2 Button 2");
238 | row.add("Row 2 Button 3");
239 | // Add the second row to the keyboard
240 | keyboard.add(row);
241 | // Set the keyboard to the markup
242 | keyboardMarkup.setKeyboard(keyboard);
243 | // Add it to the message
244 | message.setReplyMarkup(keyboardMarkup);
245 | try {
246 | sendMessage(message); // Sending our message object to user
247 | } catch (TelegramApiException e) {
248 | e.printStackTrace();
249 | }
250 | }
251 | ```
252 |
253 | Amazing! Now lets teach our bot to react on this buttons:
254 |
255 | ```java
256 | else if (message_text.equals("Row 1 Button 1")) {
257 | SendPhoto msg = new SendPhoto()
258 | .setChatId(chat_id)
259 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
260 | .setCaption("Photo");
261 | try {
262 | sendPhoto(msg); // Call method to send the photo
263 | } catch (TelegramApiException e) {
264 | e.printStackTrace();
265 | }
266 | }
267 | ```
268 |
269 | Now, when user press button with "Row 1 Button 1" text on it, bot will send picture by `file_id` to user:
270 |
271 | 
272 |
273 | And lets add "Hide keyboard" function when user send `/hide` command to bot. This can be done with `ReplyMarkupRemove`.
274 |
275 | ```java
276 | else if (message_text.equals("/hide")) {
277 | SendMessage msg = new SendMessage()
278 | .setChatId(chat_id)
279 | .setText("Keyboard hidden");
280 | ReplyKeyboardRemove keyboardMarkup = new ReplyKeyboardRemove();
281 | msg.setReplyMarkup(keyboardMarkup);
282 | try {
283 | sendMessage(msg); // Call method to send the photo
284 | } catch (TelegramApiException e) {
285 | e.printStackTrace();
286 | }
287 | }
288 | ```
289 |
290 | Here is code of our files. You can also find all sources at [GitHub repository](https://github.com/MonsterDeveloper/java-telegram-bot-tutorial/).
291 |
292 | > src/Main.java
293 |
294 | ```java
295 | import org.telegram.telegrambots.ApiContextInitializer;
296 | import org.telegram.telegrambots.TelegramBotsApi;
297 | import org.telegram.telegrambots.exceptions.TelegramApiException;
298 |
299 |
300 | public class Main {
301 | public static void main(String[] args) {
302 | ApiContextInitializer.init();
303 |
304 | TelegramBotsApi botsApi = new TelegramBotsApi();
305 |
306 | try {
307 | botsApi.registerBot(new PhotoBot());
308 | } catch (TelegramApiException e) {
309 | e.printStackTrace();
310 | }
311 | System.out.println("PhotoBot successfully started!");
312 | }
313 | }
314 | ```
315 |
316 | > src/PhotoBot.java
317 |
318 | ```java
319 | import org.telegram.telegrambots.api.methods.send.SendMessage;
320 | import org.telegram.telegrambots.api.methods.send.SendPhoto;
321 | import org.telegram.telegrambots.api.objects.PhotoSize;
322 | import org.telegram.telegrambots.api.objects.Update;
323 | import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;
324 | import org.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardRemove;
325 | import org.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;
326 | import org.telegram.telegrambots.bots.TelegramLongPollingBot;
327 | import org.telegram.telegrambots.exceptions.TelegramApiException;
328 |
329 | import java.util.ArrayList;
330 | import java.util.Comparator;
331 | import java.util.List;
332 |
333 | public class PhotoBot extends TelegramLongPollingBot {
334 | @Override
335 | public void onUpdateReceived(Update update) {
336 |
337 | // We check if the update has a message and the message has text
338 | if (update.hasMessage() && update.getMessage().hasText()) {
339 | // Set variables
340 | String message_text = update.getMessage().getText();
341 | long chat_id = update.getMessage().getChatId();
342 | if (message_text.equals("/start")) {
343 | SendMessage message = new SendMessage() // Create a message object object
344 | .setChatId(chat_id)
345 | .setText(message_text);
346 | try {
347 | sendMessage(message); // Sending our message object to user
348 | } catch (TelegramApiException e) {
349 | e.printStackTrace();
350 | }
351 | } else if (message_text.equals("/pic")) {
352 | SendPhoto msg = new SendPhoto()
353 | .setChatId(chat_id)
354 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
355 | .setCaption("Photo");
356 | try {
357 | sendPhoto(msg); // Call method to send the photo
358 | } catch (TelegramApiException e) {
359 | e.printStackTrace();
360 | }
361 | } else if (message_text.equals("/markup")) {
362 | SendMessage message = new SendMessage() // Create a message object object
363 | .setChatId(chat_id)
364 | .setText("Here is your keyboard");
365 | // Create ReplyKeyboardMarkup object
366 | ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
367 | // Create the keyboard (list of keyboard rows)
368 | List keyboard = new ArrayList<>();
369 | // Create a keyboard row
370 | KeyboardRow row = new KeyboardRow();
371 | // Set each button, you can also use KeyboardButton objects if you need something else than text
372 | row.add("Row 1 Button 1");
373 | row.add("Row 1 Button 2");
374 | row.add("Row 1 Button 3");
375 | // Add the first row to the keyboard
376 | keyboard.add(row);
377 | // Create another keyboard row
378 | row = new KeyboardRow();
379 | // Set each button for the second line
380 | row.add("Row 2 Button 1");
381 | row.add("Row 2 Button 2");
382 | row.add("Row 2 Button 3");
383 | // Add the second row to the keyboard
384 | keyboard.add(row);
385 | // Set the keyboard to the markup
386 | keyboardMarkup.setKeyboard(keyboard);
387 | // Add it to the message
388 | message.setReplyMarkup(keyboardMarkup);
389 | try {
390 | sendMessage(message); // Sending our message object to user
391 | } catch (TelegramApiException e) {
392 | e.printStackTrace();
393 | }
394 | } else if (message_text.equals("Row 1 Button 1")) {
395 | SendPhoto msg = new SendPhoto()
396 | .setChatId(chat_id)
397 | .setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC")
398 | .setCaption("Photo");
399 |
400 | try {
401 | sendPhoto(msg); // Call method to send the photo
402 | } catch (TelegramApiException e) {
403 | e.printStackTrace();
404 | }
405 | } else if (message_text.equals("/hide")) {
406 | SendMessage msg = new SendMessage()
407 | .setChatId(chat_id)
408 | .setText("Keyboard hidden");
409 | ReplyKeyboardRemove keyboardMarkup = new ReplyKeyboardRemove();
410 | msg.setReplyMarkup(keyboardMarkup);
411 | try {
412 | sendMessage(msg); // Call method to send the photo
413 | } catch (TelegramApiException e) {
414 | e.printStackTrace();
415 | }
416 | } else {
417 | SendMessage message = new SendMessage() // Create a message object object
418 | .setChatId(chat_id)
419 | .setText("Unknown command");
420 | try {
421 | sendMessage(message); // Sending our message object to user
422 | } catch (TelegramApiException e) {
423 | e.printStackTrace();
424 | }
425 | }
426 | } else if (update.hasMessage() && update.getMessage().hasPhoto()) {
427 | // Message contains photo
428 | // Set variables
429 | long chat_id = update.getMessage().getChatId();
430 |
431 | List photos = update.getMessage().getPhoto();
432 | String f_id = photos.stream()
433 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
434 | .findFirst()
435 | .orElse(null).getFileId();
436 | int f_width = photos.stream()
437 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
438 | .findFirst()
439 | .orElse(null).getWidth();
440 | int f_height = photos.stream()
441 | .sorted(Comparator.comparing(PhotoSize::getFileSize).reversed())
442 | .findFirst()
443 | .orElse(null).getHeight();
444 | String caption = "file_id: " + f_id + "\nwidth: " + Integer.toString(f_width) + "\nheight: " + Integer.toString(f_height);
445 | SendPhoto msg = new SendPhoto()
446 | .setChatId(chat_id)
447 | .setPhoto(f_id)
448 | .setCaption(caption);
449 | try {
450 | sendPhoto(msg); // Call method to send the message
451 | } catch (TelegramApiException e) {
452 | e.printStackTrace();
453 | }
454 | }
455 | }
456 |
457 | @Override
458 | public String getBotUsername() {
459 | // Return bot username
460 | // If bot username is @MyAmazingBot, it must return 'MyAmazingBot'
461 | return "PhotoBot";
462 | }
463 |
464 | @Override
465 | public String getBotToken() {
466 | // Return bot token from BotFather
467 | return "12345:qwertyuiopASDGFHKMK";
468 | }
469 | }
470 | ```
471 |
472 | Now you can create and remove custom `ReplyMarkup` keyboards, create custom commands and send photos by `file_id`! You are doing very well! Hope to see you soon:\)
473 |
474 |
--------------------------------------------------------------------------------