Writing Telegram Bots On Java
Writing Telegram Bots On Java
of Contents
Introduction 1.1
Lesson 1. Simple echo bot 1.2
Lesson 2. PhotoBot 1.3
Lesson 3. Logging 1.4
Lesson 4. Emoji 1.5
Lesson 5. Deploy your bot 1.6
Lesson 6. Inline keyboards and editing message's text 1.7
Lesson 7. Creating users database with MongoDB 1.8
Lesson 8. Integrating with Redis 1.9
1
Introduction
Hello everyone! This course is for those, who wants to learn how to code bots for
Telegram's Bot Platform.
Table of contents
Lesson 1. Simple "echo" bot
Lesson 2. PhotoBot
Lesson 3. Logging
Lesson 4. Emoji
Lesson 5. Deploy your bot
Lesson 6. Inline keyboards and editing message's text
Lesson 7. Creating users database with MongoDB
Lesson 8. Integrating with Redis
Credits
Rubenlagus for his amazing library and support
Clevero for his amazing HOWTO guide
MasterGroosha for his amazing Python book
2
Lesson 1. Simple echo bot
Prepare to launch
Bot API is based on HTTP-requests, but in this book I will use Rubenlagus' library
for Java.
Using Maven:
<dependency>
<groupId>org.telegram</groupId>
<artifactId>telegrambots</artifactId>
<version>Latest</version>
</dependency>
Using Jitpack
Or just download .jar file with dependencies from here
Lets go to code!
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
3
Lesson 1. Simple echo bot
install TelegramBots library with preffered method. I think, that it is most easy to
just download .jar from here
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:
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
public class MyAmazingBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// TODO
}
@Override
public String getBotUsername() {
// TODO
return null;
}
@Override
public String getBotToken() {
// TODO
return null;
}
}
4
Lesson 1. Simple echo bot
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
public class MyAmazingBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// TODO
}
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "MyAmazingBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
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.
5
Lesson 1. Simple echo bot
@Override
public void onUpdateReceived(Update update) {
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:
6
Lesson 1. Simple echo bot
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
public class Main {
public static void main(String[] args) {
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
7
Lesson 1. Simple echo bot
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
8
Lesson 1. Simple echo bot
src/Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiExcepti
on;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
src/MyAmazingBot.java
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
public class MyAmazingBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
9
Lesson 1. Simple echo bot
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "MyAmazingBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
Well done! Now we can pack our project into runnable .jar file and run it on
our computer/server!
10
Lesson 1. Simple echo bot
11
Lesson 2. PhotoBot
12
Lesson 2. PhotoBot
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
try {
botsApi.registerBot(new PhotoBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("PhotoBot successfully started!");
}
}
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.
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
13
Lesson 2. PhotoBot
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
SendMessage message = new SendMessage() // Create a
message object object
.setChatId(chat_id)
.setText(message_text);
try {
sendMessage(message); // Sending our message obj
ect to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "PhotoBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
14
Lesson 2. PhotoBot
@Override
public void onUpdateReceived(Update update) {
We want our bot to send file_id of the photo. Well, lets do this:
15
Lesson 2. PhotoBot
ileSize).reversed())
.findFirst()
.orElse(null).getFileId();
// Know photo width
int f_width = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
ileSize).reversed())
.findFirst()
.orElse(null).getWidth();
// Know photo height
int f_height = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
ileSize).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 = new SendPhoto()
.setChatId(chat_id)
.setPhoto(f_id)
.setCaption(caption);
try {
sendPhoto(msg); // Call method to send the photo with ca
ption
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
16
Lesson 2. PhotoBot
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 .
17
Lesson 2. PhotoBot
18
Lesson 2. PhotoBot
Well, you already now how to make our bot recognise command. Lets make
another if for command /markup .
19
Lesson 2. PhotoBot
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
20
Lesson 2. PhotoBot
else if (message_text.equals("/markup")) {
SendMessage message = new SendMessage() // Create a message
object object
.setChatId(chat_id)
.setText("Here is your keyboard");
// Create ReplyKeyboardMarkup object
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup
();
// Create the keyboard (list of keyboard rows)
List<KeyboardRow> keyboard = new ArrayList<>();
// Create a keyboard row
KeyboardRow row = new KeyboardRow();
// Set each button, you can also use KeyboardButton objects
if you need something else than text
row.add("Row 1 Button 1");
row.add("Row 1 Button 2");
row.add("Row 1 Button 3");
// Add the first row to the keyboard
keyboard.add(row);
// Create another keyboard row
row = new KeyboardRow();
// Set each button for the second line
row.add("Row 2 Button 1");
row.add("Row 2 Button 2");
row.add("Row 2 Button 3");
// Add the second row to the keyboard
keyboard.add(row);
// Set the keyboard to the markup
keyboardMarkup.setKeyboard(keyboard);
// Add it to the message
message.setReplyMarkup(keyboardMarkup);
try {
sendMessage(message); // Sending our message object to u
ser
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
21
Lesson 2. PhotoBot
Now, when user press button with "Row 1 Button 1" text on it, bot will send picture
by file_id to user:
And lets add "Hide keyboard" function when user send /hide command to bot.
This can be done with ReplyMarkupRemove .
22
Lesson 2. PhotoBot
else if (message_text.equals("/hide")) {
SendMessage msg = new SendMessage()
.setChatId(chat_id)
.setText("Keyboard hidden");
ReplyKeyboardRemove keyboardMarkup = new ReplyKeyboardRemove
();
msg.setReplyMarkup(keyboardMarkup);
try {
sendMessage(msg); // Call method to send the photo
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
Here is code of our files. You can also find all sources at GitHub repository.
src/Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
try {
botsApi.registerBot(new PhotoBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("PhotoBot successfully started!");
}
}
23
Lesson 2. PhotoBot
src/PhotoBot.java
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.methods.send.SendPhoto;
import org.telegram.telegrambots.api.objects.PhotoSize;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.Reply
KeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.Reply
KeyboardRemove;
import org.telegram.telegrambots.api.objects.replykeyboard.butto
ns.KeyboardRow;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
24
Lesson 2. PhotoBot
e.printStackTrace();
}
} else if (message_text.equals("/pic")) {
SendPhoto msg = new SendPhoto()
.setChatId(chat_id)
.setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8G
ecvSw0ABGvTl7ObQNPNX7UEAAEC")
.setCaption("Photo");
try {
sendPhoto(msg); // Call method to send the p
hoto
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (message_text.equals("/markup")) {
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText("Here is your keyboard");
// Create ReplyKeyboardMarkup object
ReplyKeyboardMarkup keyboardMarkup = new ReplyKe
yboardMarkup();
// Create the keyboard (list of keyboard rows)
List<KeyboardRow> keyboard = new ArrayList<>();
// Create a keyboard row
KeyboardRow row = new KeyboardRow();
// Set each button, you can also use KeyboardBut
ton objects if you need something else than text
row.add("Row 1 Button 1");
row.add("Row 1 Button 2");
row.add("Row 1 Button 3");
// Add the first row to the keyboard
keyboard.add(row);
// Create another keyboard row
row = new KeyboardRow();
// Set each button for the second line
row.add("Row 2 Button 1");
row.add("Row 2 Button 2");
row.add("Row 2 Button 3");
// Add the second row to the keyboard
25
Lesson 2. PhotoBot
keyboard.add(row);
// Set the keyboard to the markup
keyboardMarkup.setKeyboard(keyboard);
// Add it to the message
message.setReplyMarkup(keyboardMarkup);
try {
sendMessage(message); // Sending our message
object to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (message_text.equals("Row 1 Button 1")) {
SendPhoto msg = new SendPhoto()
.setChatId(chat_id)
.setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8G
ecvSw0ABGvTl7ObQNPNX7UEAAEC")
.setCaption("Photo");
try {
sendPhoto(msg); // Call method to send the p
hoto
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (message_text.equals("/hide")) {
SendMessage msg = new SendMessage()
.setChatId(chat_id)
.setText("Keyboard hidden");
ReplyKeyboardRemove keyboardMarkup = new ReplyKe
yboardRemove();
msg.setReplyMarkup(keyboardMarkup);
try {
sendMessage(msg); // Call method to send the
photo
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else {
SendMessage message = new SendMessage() // Creat
e a message object object
26
Lesson 2. PhotoBot
.setChatId(chat_id)
.setText("Unknown command");
try {
sendMessage(message); // Sending our message
object to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
} else if (update.hasMessage() && update.getMessage().ha
sPhoto()) {
// Message contains photo
// Set variables
long chat_id = update.getMessage().getChatId();
27
Lesson 2. PhotoBot
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "PhotoBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "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:)
28
Lesson 3. Logging
Lesson 3. Logging.
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!
Creating project
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:
src/LoggingTestBot.java
29
Lesson 3. Logging
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "LoggingTestBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
30
Lesson 3. Logging
src/Main.java
31
Lesson 3. Logging
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
32
Lesson 3. Logging
33
Lesson 3. Logging
Our files:
src/Main.java
34
Lesson 3. Logging
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
src/LoggingTestBot.java
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
35
Lesson 3. Logging
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
36
Lesson 3. Logging
return "LoggingTestBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
private void log(String first_name, String last_name, String
user_id, String txt, String bot_answer) {
System.out.println("\n ----------------------------");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd
HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Message from " + first_name + " " +
last_name + ". (id = " + user_id + ") \n Text - " + txt);
System.out.println("Bot answer: \n Text - " + bot_answer
);
}
}
Well, thats all for now. In the next lesson we will learn how to make your
messages more beautiful with unicode emojis:).
37
Lesson 4. Emoji
Lesson 4. Emoji
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. I
think you know what is emoji, so let's move forward.
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:
src/Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
src/EmojiTestBot.java
38
Lesson 4. Emoji
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
39
Lesson 4. Emoji
}
}
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "EmojiTestBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
private void log(String first_name, String last_name, String
user_id, String txt, String bot_answer) {
System.out.println("\n ----------------------------");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd
HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Message from " + first_name + " " +
last_name + ". (id = " + user_id + ") \n Text - " + txt);
System.out.println("Bot answer: \n Text - " + bot_answer
);
}
}
Via Maven :
40
Lesson 4. Emoji
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>3.1.3</version>
</dependency>
Via Gradle :
compile 'com.vdurmont:emoji-java:3.1.3'
import com.vdurmont.emoji.EmojiParser;
Now you can view list of emojis at EmojiPedia or Emoji Cheat Sheet. To insert
emoji, do this:
Where :smile: or :alien: is emoji alias or emoji short code. You can also
view them at EmojiPedia or Emoji Cheat Sheet.
src/Main.java
41
Lesson 4. Emoji
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
src/EmojiTestBot.java
import com.vdurmont.emoji.EmojiParser;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
42
Lesson 4. Emoji
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "EmojiTestBot";
43
Lesson 4. Emoji
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
private void log(String first_name, String last_name, String
user_id, String txt, String bot_answer) {
System.out.println("\n ----------------------------");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd
HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Message from " + first_name + " " +
last_name + ". (id = " + user_id + ") \n Text - " + txt);
System.out.println("Bot answer: \n Text - " + bot_answer
);
}
}
Our lesson came to an end. Thank you for reading this. See you soon!
44
Lesson 5. Deploy your bot
Creating droplet
Firstly, you need to create account on DigitalOcean. Open this link to get 10$ as
gift from me, enter your email and password and click "Create an account"
45
Lesson 5. Deploy your bot
Then, follow register insctructions. Once you are in your control panel, create a
new droplet.
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:
When you install it, open PuTTY and write server IP and port (default 22).
46
Lesson 5. Deploy your bot
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:
Type java -version to check installation. You will see something like that:
47
Lesson 5. Deploy your bot
screen
cd FOLDER_NAME
48
Lesson 5. Deploy your bot
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 .
49
Lesson 6. Inline keyboards and editing message's text
On April 9, 2016, Telegram released Bot API 2.0 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:
src/BotApi20.java
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
50
Lesson 6. Inline keyboards and editing message's text
}
}
@Override
public String getBotUsername() {
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "BotApi20Bot";
51
Lesson 6. Inline keyboards and editing message's text
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
src/Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
I recommend you always look in the Bot API description so you know every
method and type. Okey, lets make bot answer to the /start command:
52
Lesson 6. Inline keyboards and editing message's text
} else if (update.hasCallbackQuery()) {}
}
53
Lesson 6. Inline keyboards and editing message's text
if (update.getMessage().getText().equals("/start"))
{
} else if (update.hasCallbackQuery()) {}
}
54
Lesson 6. Inline keyboards and editing message's text
We want to edit message text right? Let's do it when user press our button. Add a
Callback Query handler to your bot:
else if (update.hasCallbackQuery()) {}
So if update has Callback query, it call this else if operator. Moving forward:
else if (update.hasCallbackQuery()) {
// Set variables
String call_data = update.getCallbackQuery().getData
();
long message_id = update.getCallbackQuery().getMessa
ge().getMessageId();
long chat_id = update.getCallbackQuery().getMessage(
).getChatId();
if (call_data.equals("update_msg_text")) {
String answer = "Updated message text";
EditMessageText new_message = new EditMessageTex
t()
.setChatId(chat_id)
.setMessageId(toIntExact(message_id))
.setText(answer);
try {
execute(new_message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
55
Lesson 6. Inline keyboards and editing message's text
Now when user press our button it will change it's text:
Source:
src/Main.java
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
src/BotApi20.java
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.methods.updatingmessages.Ed
itMessageText;
import org.telegram.telegrambots.api.objects.Update;
56
Lesson 6. Inline keyboards and editing message's text
import org.telegram.telegrambots.api.objects.replykeyboard.Inlin
eKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.butto
ns.InlineKeyboardButton;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException
;
import java.util.ArrayList;
import java.util.List;
57
Lesson 6. Inline keyboards and editing message's text
rowsInline.add(rowInline);
// Add it to the message
markupInline.setKeyboard(rowsInline);
message.setReplyMarkup(markupInline);
try {
execute(message); // Sending our message obj
ect to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else {
} else if (update.hasCallbackQuery()) {
// Set variables
String call_data = update.getCallbackQuery().getData
();
long message_id = update.getCallbackQuery().getMessa
ge().getMessageId();
long chat_id = update.getCallbackQuery().getMessage(
).getChatId();
if (call_data.equals("update_msg_text")) {
String answer = "Updated message text";
EditMessageText new_message = new EditMessageTex
t()
.setChatId(chat_id)
.setMessageId(toIntExact(message_id))
.setText(answer);
try {
execute(new_message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
}
@Override
public String getBotUsername() {
58
Lesson 6. Inline keyboards and editing message's text
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
You can also find all source code to all of my lessons at GitHub.
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!
59
Lesson 7. Creating users database with MongoDB
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONObject;
11:01:25.174 [cluster-ClusterId{value='554dbecb1b554f11e86c3a69'
, description='null'}-localhost:27017] DEBUG org.mongodb.driver.
cluster - Checking status of localhost:27017
60
Lesson 7. Creating users database with MongoDB
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.
61
Lesson 7. Creating users database with MongoDB
Replace host:port with your Mongo's host and port. You can find how to setup
MongoDB server for Ubuntu here. Then we set our database and collection.
Replace this names with your own.
if (found == 0) {
Document doc = new Document("first_name", first_name
)
.append("last_name", last_name)
.append("id", user_id)
.append("username", username);
collection.insertOne(doc);
mongoClient.close();
System.out.println("User not exists in database. Wri
tten.");
return "no_exists";
} else {
System.out.println("User exists in database.");
mongoClient.close();
return "exists";
}
62
Lesson 7. Creating users database with MongoDB
Just check if user exists in database by calling this function when user sends
/start :
63
Lesson 7. Creating users database with MongoDB
// Set variables
String user_first_name = update.getMessage().getChat().getFirstN
ame();
String user_last_name = update.getMessage().getChat().getLastNam
e();
String user_username = update.getMessage().getChat().getUserName
();
long user_id = update.getMessage().getChat().getId();
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
try {
sendMessage(message);
check(user_first_name, user_last_name, toIntExact(user_id),
user_username);
} catch (TelegramApiException e) {
e.printStackTrace();
}
MonsterDeveloper
64
Lesson 8. Integrating with Redis
search: keywords: ['lesson 8', '8', 'redis', 'database', 'fast database', 'lettuce']
Library
For driver I chose Lettuce because of its popularity and good documentation. You
can download it here or install with Maven:
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>Latest</version>
</dependency>
Establish connection
Then, you need to connect to Redis:
RedisClient redisClient;
StatefulRedisConnection<String, String> redisConnection;
RedisCommands<String, String> syncCommands;
redisClient = RedisClient.create("redis://localhost:6379/0"); //
Format: redis://ip:post/dbNumber
redisConnection = redisClient.connect();
syncCommands = this.redisConnection.sync();
65
Lesson 8. Integrating with Redis
Connection established
And thats all! Now you can execute commands like that:
syncCommands.get("key");
syncCommands.set("key", "value");
syncCommands.lrange("key", 0, -1);
Also, don't forget to close connection with Redis when you done your work:
redisConnection.close();
redisClient.shutdown();
Very short lesson, but I think useful :D Thanks for your time, hope to see you
soon!
66