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, how to send photos and create commands.
Let's respect Telegram's servers
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.) 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:
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:
Dont forget to change bot username and bot token if you created another bot.
importorg.telegram.telegrambots.api.methods.send.SendMessage;importorg.telegram.telegrambots.api.objects.Update;importorg.telegram.telegrambots.bots.TelegramLongPollingBot;importorg.telegram.telegrambots.exceptions.TelegramApiException;publicclassPhotoBotextendsTelegramLongPollingBot { @OverridepublicvoidonUpdateReceived(Update update) {// We check if the update has a message and the message has textif (update.hasMessage() &&update.getMessage().hasText()) {// Set variablesString message_text =update.getMessage().getText();long chat_id =update.getMessage().getChatId();SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText(message_text);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } } @OverridepublicStringgetBotUsername() {// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return"PhotoBot"; } @OverridepublicStringgetBotToken() {// Return bot token from BotFatherreturn"12345:qwertyuiopASDGFHKMK"; }}
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:
@OverridepublicvoidonUpdateReceived(Update update) {// We check if the update has a message and the message has textif (update.hasMessage() &&update.getMessage().hasText()) {// Set variablesString message_text =update.getMessage().getText();long chat_id =update.getMessage().getChatId();SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText(message_text);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (update.hasMessage() &&update.getMessage().hasPhoto()) {// Message contains photo }}
We want our bot to send file_id of the photo. Well, lets do this:
elseif (update.hasMessage() &&update.getMessage().hasPhoto()) {// Message contains photo// Set variableslong chat_id =update.getMessage().getChatId();// Array with photo objects with different sizes// We will get the biggest photo from that arrayList<PhotoSize> photos =update.getMessage().getPhoto();// Know file_idString f_id =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getFileId();// Know photo widthint f_width =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getWidth();// Know photo heightint f_height =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getHeight();// Set photo caption String caption = "file_id: " + f_id + "\nwidth: " + Integer.toString(f_width) + "\nheight: " + Integer.toString(f_height);
SendPhoto msg =newSendPhoto().setChatId(chat_id).setPhoto(f_id).setCaption(caption);try {sendPhoto(msg); // Call method to send the photo with caption } catch (TelegramApiException e) {e.printStackTrace(); }}
Lets take a look:
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.
if (update.hasMessage() &&update.getMessage().hasText()) {// Set variablesString message_text =update.getMessage().getText();long chat_id =update.getMessage().getChatId();if (message_text.equals("/start")) {// User send /startSendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText(message_text);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (message_text.equals("/pic")) {// User sent /picSendPhoto msg =newSendPhoto().setChatId(chat_id).setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC").setCaption("Photo");try {sendPhoto(msg); // Call method to send the photo } catch (TelegramApiException e) {e.printStackTrace(); } } else {// Unknown commandSendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText("Unknown command");try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } }}
Now bot sends photo like this:
And he can even reply to unknown command!
Now lets take a look at ReplyKeyboardMarkup. We will now create custom keyboard like this:
Well, you already now how to make our bot recognise command. Lets make another if for command /markup.
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
elseif (message_text.equals("/markup")) {SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText("Here is your keyboard");// Create ReplyKeyboardMarkup objectReplyKeyboardMarkup keyboardMarkup =newReplyKeyboardMarkup();// Create the keyboard (list of keyboard rows)List<KeyboardRow> keyboard =newArrayList<>();// Create a keyboard rowKeyboardRow row =newKeyboardRow();// Set each button, you can also use KeyboardButton objects if you need something else than textrow.add("Row 1 Button 1");row.add("Row 1 Button 2");row.add("Row 1 Button 3");// Add the first row to the keyboardkeyboard.add(row);// Create another keyboard row row =newKeyboardRow();// Set each button for the second linerow.add("Row 2 Button 1");row.add("Row 2 Button 2");row.add("Row 2 Button 3");// Add the second row to the keyboardkeyboard.add(row);// Set the keyboard to the markupkeyboardMarkup.setKeyboard(keyboard);// Add it to the messagemessage.setReplyMarkup(keyboardMarkup);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); }}
Amazing! Now lets teach our bot to react on this buttons:
importorg.telegram.telegrambots.api.methods.send.SendMessage;importorg.telegram.telegrambots.api.methods.send.SendPhoto;importorg.telegram.telegrambots.api.objects.PhotoSize;importorg.telegram.telegrambots.api.objects.Update;importorg.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardMarkup;importorg.telegram.telegrambots.api.objects.replykeyboard.ReplyKeyboardRemove;importorg.telegram.telegrambots.api.objects.replykeyboard.buttons.KeyboardRow;importorg.telegram.telegrambots.bots.TelegramLongPollingBot;importorg.telegram.telegrambots.exceptions.TelegramApiException;importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;publicclassPhotoBotextendsTelegramLongPollingBot { @OverridepublicvoidonUpdateReceived(Update update) {// We check if the update has a message and the message has textif (update.hasMessage() &&update.getMessage().hasText()) {// Set variablesString message_text =update.getMessage().getText();long chat_id =update.getMessage().getChatId();if (message_text.equals("/start")) {SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText(message_text);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (message_text.equals("/pic")) {SendPhoto msg =newSendPhoto().setChatId(chat_id).setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC").setCaption("Photo");try {sendPhoto(msg); // Call method to send the photo } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (message_text.equals("/markup")) {SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText("Here is your keyboard");// Create ReplyKeyboardMarkup objectReplyKeyboardMarkup keyboardMarkup =newReplyKeyboardMarkup();// Create the keyboard (list of keyboard rows)List<KeyboardRow> keyboard =newArrayList<>();// Create a keyboard rowKeyboardRow row =newKeyboardRow();// Set each button, you can also use KeyboardButton objects if you need something else than textrow.add("Row 1 Button 1");row.add("Row 1 Button 2");row.add("Row 1 Button 3");// Add the first row to the keyboardkeyboard.add(row);// Create another keyboard row row =newKeyboardRow();// Set each button for the second linerow.add("Row 2 Button 1");row.add("Row 2 Button 2");row.add("Row 2 Button 3");// Add the second row to the keyboardkeyboard.add(row);// Set the keyboard to the markupkeyboardMarkup.setKeyboard(keyboard);// Add it to the messagemessage.setReplyMarkup(keyboardMarkup);try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (message_text.equals("Row 1 Button 1")) {SendPhoto msg =newSendPhoto().setChatId(chat_id).setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0ABGvTl7ObQNPNX7UEAAEC").setCaption("Photo");try {sendPhoto(msg); // Call method to send the photo } catch (TelegramApiException e) {e.printStackTrace(); } } elseif (message_text.equals("/hide")) {SendMessage msg =newSendMessage().setChatId(chat_id).setText("Keyboard hidden");ReplyKeyboardRemove keyboardMarkup =newReplyKeyboardRemove();msg.setReplyMarkup(keyboardMarkup);try {sendMessage(msg); // Call method to send the photo } catch (TelegramApiException e) {e.printStackTrace(); } } else {SendMessage message =newSendMessage()// Create a message object object.setChatId(chat_id).setText("Unknown command");try {sendMessage(message); // Sending our message object to user } catch (TelegramApiException e) {e.printStackTrace(); } } } elseif (update.hasMessage() &&update.getMessage().hasPhoto()) {// Message contains photo// Set variableslong chat_id =update.getMessage().getChatId();List<PhotoSize> photos =update.getMessage().getPhoto();String f_id =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getFileId();int f_width =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getWidth();int f_height =photos.stream().sorted(Comparator.comparing(PhotoSize::getFileSize).reversed()).findFirst().orElse(null).getHeight(); String caption = "file_id: " + f_id + "\nwidth: " + Integer.toString(f_width) + "\nheight: " + Integer.toString(f_height);
SendPhoto msg =newSendPhoto().setChatId(chat_id).setPhoto(f_id).setCaption(caption);try {sendPhoto(msg); // Call method to send the message } catch (TelegramApiException e) {e.printStackTrace(); } } } @OverridepublicStringgetBotUsername() {// Return bot username// If bot username is @MyAmazingBot, it must return 'MyAmazingBot'return"PhotoBot"; } @OverridepublicStringgetBotToken() {// Return bot token from BotFatherreturn"12345:qwertyuiopASDGFHKMK"; }}
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:)