Uploaded by Rustam Rahmatov

writing-telegram-bots-on-java

advertisement
Table 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
Writing bots for Telegram on Java
Hello everyone! This course is for those, who wants to learn how to code bots for
Telegram's Bot Platform.
You can always contact me at Telegram: @MonsterDeveloper
You can find all sources at GitHub repository.
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
Lesson 1. Writing your first "echo" bot
Hello! If you want to know, how to code Telegram Bots on Java, you are on the
right way!
Prepare to launch
Bot API is based on HTTP-requests, but in this book I will use Rubenlagus' library
for Java.
Install the library
You can install TelegramBots library with different methods:
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
In this tutorial I will use next machines:
Ubuntu 16.04 Server with 1GB of RAM
My home Windows 10 laptop with IntelliJ Idea pre-installed
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:
Remember! The class must extends TelegramLongPollingBot and
implement necessary methods
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;
}
}
As you can understand, getBotUsername() and getBotToken() must return
bot's username and bot's token, obtained from @BotFather. So now, our
MyAmazingBot.java file will look like this:
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) {
// We check if the update has a message and the message 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 mess
age object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message object to u
ser
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
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) {
// TODO Initialize Api Context
// TODO Instantiate Telegram Bots API
// TODO Register our bot
}
}
Now, lets initialize Api Context
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();
// TODO Instantiate Telegram Bots API
// TODO Register our bot
}
}
Instantiate Telegram Bots API:
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();
// TODO Register our bot
}
}
And register our 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();
// Register our bot
try {
botsApi.registerBot(new MyAmazingBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
8
Lesson 1. Simple echo bot
Here is all our files:
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();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new MyAmazingBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
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) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
9
Lesson 1. Simple echo bot
SendMessage message = new SendMessage() // Create a
message object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message object
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 "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!
You can find all sources to this lesson in GitHub repository.
java -jar MyAmazingBot.jar
Now we can see our bot running:
10
Lesson 1. Simple echo bot
Well, thats all for now. Hope to see you soon!:)
11
Lesson 2. PhotoBot
Lesson 2. Photo bot.
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:
Dont forget to install TelegramBots library
12
Lesson 2. PhotoBot
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) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
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
;
public class PhotoBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
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";
}
}
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:
14
Lesson 2. PhotoBot
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message 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 mess
age object object
.setChatId(chat_id)
.setText(message_text);
try {
sendMessage(message); // Sending our message object
to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (update.hasMessage() && update.getMessage().hasPho
to()) {
// Message contains photo
}
}
We want our bot to send file_id of the photo. Well, lets do this:
else if (update.hasMessage() && update.getMessage().hasPhoto())
{
// Message contains photo
// Set variables
long chat_id = update.getMessage().getChatId();
// Array with photo objects with different sizes
// We will get the biggest photo from that array
List<PhotoSize> photos = update.getMessage().getPhoto();
// Know file_id
String f_id = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
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();
}
}
Lets take a look:
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 .
if (update.hasMessage() && update.getMessage().hasText()) {
// Set variables
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
if (message_text.equals("/start")) {
// User send /start
SendMessage message = new SendMessage() // Create a mess
age object object
.setChatId(chat_id)
.setText(message_text);
try {
sendMessage(message); // Sending our message object
to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else if (message_text.equals("/pic")) {
17
Lesson 2. PhotoBot
// User sent /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 {
// Unknown command
SendMessage message = new SendMessage() // Create a mess
age 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:
18
Lesson 2. PhotoBot
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 .
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
Amazing! Now lets teach our bot to react on this buttons:
else if (message_text.equals("Row 1 Button 1")) {
SendPhoto msg = new SendPhoto()
.setChatId(chat_id)
.setPhoto("AgADAgAD6qcxGwnPsUgOp7-MvnQ8GecvSw0AB
GvTl7ObQNPNX7UEAAEC")
.setCaption("Photo");
try {
sendPhoto(msg); // Call method to send the photo
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
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
;
public class Main {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi botsApi = new TelegramBotsApi();
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;
public class PhotoBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
if (message_text.equals("/start")) {
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText(message_text);
try {
sendMessage(message); // Sending our message
object to user
} catch (TelegramApiException e) {
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();
List<PhotoSize> photos = update.getMessage().getPhot
o();
String f_id = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
ileSize).reversed())
.findFirst()
.orElse(null).getFileId();
int f_width = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
ileSize).reversed())
.findFirst()
.orElse(null).getWidth();
int f_height = photos.stream()
.sorted(Comparator.comparing(PhotoSize::getF
ileSize).reversed())
.findFirst()
.orElse(null).getHeight();
String caption = "file_id: " + f_id + "\nwidth: " +
Integer.toString(f_width) + "\nheight: " + Integer.toString(f_he
ight);
SendPhoto msg = new SendPhoto()
.setChatId(chat_id)
.setPhoto(f_id)
.setCaption(caption);
try {
27
Lesson 2. PhotoBot
sendPhoto(msg); // Call method to send the messa
ge
} 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";
}
}
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
public class LoggingTestBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
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 {
execute(message); // Sending our message object
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 "LoggingTestBot";
}
@Override
public String getBotToken() {
// Return bot token from BotFather
return "12345:qwertyuiopASDGFHKMK";
}
}
30
Lesson 3. Logging
And our startup file:
src/Main.java
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new LoggingTestBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("LoggingTestBot successfully started!"
);
}
}
Logs, where are you?
Lets set additional variables for logging:
31
Lesson 3. Logging
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message has
text
if (update.hasMessage() && update.getMessage().hasText()) {
// Set variables
String user_first_name = update.getMessage().getChat().g
etFirstName();
String user_last_name = update.getMessage().getChat().ge
tLastName();
String user_username = update.getMessage().getChat().get
UserName();
long user_id = update.getMessage().getChat().getId();
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
SendMessage message = new SendMessage() // Create a mess
age object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message object to u
ser
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
Create logging function:
Dont forget to import:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
Add new private function:
32
Lesson 3. Logging
private void log(String first_name, String last_name, String use
r_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
);
}
Now we need just call this function when we want to log
33
Lesson 3. Logging
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message has
text
if (update.hasMessage() && update.getMessage().hasText()) {
// Set variables
String user_first_name = update.getMessage().getChat().g
etFirstName();
String user_last_name = update.getMessage().getChat().ge
tLastName();
String user_username = update.getMessage().getChat().get
UserName();
long user_id = update.getMessage().getChat().getId();
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
String answer = message_text;
SendMessage message = new SendMessage() // Create a mess
age object object
.setChatId(chat_id)
.setText(answer);
log(user_first_name, user_last_name, Long.toString(user_
id), message_text, answer);
try {
execute(message); // Sending our message object to u
ser
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
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
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new LoggingTestBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("LoggingTestBot successfully started!"
);
}
}
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;
public class LoggingTestBot extends TelegramLongPollingBot {
@Override
35
Lesson 3. Logging
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String user_first_name = update.getMessage().getChat
().getFirstName();
String user_last_name = update.getMessage().getChat(
).getLastName();
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();
String answer = message_text;
SendMessage message = new SendMessage() // Create a
message object object
.setChatId(chat_id)
.setText(answer);
log(user_first_name, user_last_name, Long.toString(u
ser_id), message_text, answer);
try {
execute(message); // Sending our message object
to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
@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
);
}
}
You can also find all sources at GitHub repository.
Now it will do ugly log for us:)
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
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new EmojiTestBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("EmojiTestBot successfully started!")
;
}
}
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;
public class EmojiTestBot extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String user_first_name = update.getMessage().getChat
().getFirstName();
String user_last_name = update.getMessage().getChat(
).getLastName();
long user_id = update.getMessage().getChat().getId()
;
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
String answer = message_text;
SendMessage message = new SendMessage() // Create a
message object object
.setChatId(chat_id)
.setText(answer);
log(user_first_name, user_last_name, Long.toString(u
ser_id), message_text, answer);
try {
execute(message); // Sending our message object
to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
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
);
}
}
Okey. Now lets install emoji library:
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'
Or just download .jar from here
Once library is installed, import it to your bot class:
import com.vdurmont.emoji.EmojiParser;
Now you can view list of emojis at EmojiPedia or Emoji Cheat Sheet. To insert
emoji, do this:
String answer = EmojiParser.parseToUnicode("Here is a smile emoj
i: :smile:\n\n Here is alien emoji: :alien:");
Where :smile: or :alien: is emoji alias or emoji short code. You can also
view them at EmojiPedia or Emoji Cheat Sheet.
Here is source code. You can also find it on GitHub.
src/Main.java
41
Lesson 4. Emoji
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();
// Register our bot
try {
botsApi.registerBot(new EmojiTestBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
System.out.println("EmojiTestBot successfully started!")
;
}
}
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;
public class EmojiTestBot extends TelegramLongPollingBot {
@Override
42
Lesson 4. Emoji
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
// Set variables
String user_first_name = update.getMessage().getChat
().getFirstName();
String user_last_name = update.getMessage().getChat(
).getLastName();
long user_id = update.getMessage().getChat().getId()
;
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
String answer = EmojiParser.parseToUnicode("Here is
a smile emoji: :smile:\n\n Here is alien emoji: :alien:");
SendMessage message = new SendMessage() // Create a
message object object
.setChatId(chat_id)
.setText(answer);
log(user_first_name, user_last_name, Long.toString(u
ser_id), message_text, answer);
try {
execute(message); // Sending our message object
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 "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
);
}
}
Now you can see our beautiful messages:
Our lesson came to an end. Thank you for reading this. See you soon!
44
Lesson 5. Deploy your bot
Lesson 5. Deploy your bot
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.
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:
Connecting via SSH
You will need next software for that:
PuTTY SSH Client
FileZilla FTP Client
When you install it, open PuTTY and write server IP and port (default 22).
46
Lesson 5. Deploy your bot
And click "Open". You will see something like:
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:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install default-jre
sudo apt-get install default-jdk
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
Type java -version to check installation. You will see something like that:
47
Lesson 5. Deploy your bot
Creating and uploading JAR
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.
Uploading to the server
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:
screen
Press ENTER and then go to your folder:
cd FOLDER_NAME
48
Lesson 5. Deploy your bot
And just run your JAR:
java -jar FILE.jar
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 .
Well, that's all for now. See you soon!
49
Lesson 6. Inline keyboards and editing message's text
Lesson 6. Inline keyboards and editing
message's text
I published poll in our Telegram chat about next lesson. So, as you are reading
this, Bots API 2.0 won.
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
;
public class BotApi20 extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
if (update.getMessage().getText().equals("/start"))
{
// Set variables
String message_text = update.getMessage().getTex
t();
long chat_id = update.getMessage().getChatId();
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText(message_text);
try {
execute(message); // Sending our message obj
ect to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else {
}
}
}
@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
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new BotApi20());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
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
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
if (update.getMessage().getText().equals("/start"))
{
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText("You send /start");
try {
execute(message); // Sending our message obj
ect to user
} catch (TelegramApiException e) {
e.printStackTrace();
}
} else {
}
} else if (update.hasCallbackQuery()) {}
}
And now lets add Inline Keyboard to this message:
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
53
Lesson 6. Inline keyboards and editing message's text
if (update.getMessage().getText().equals("/start"))
{
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText("You send /start");
InlineKeyboardMarkup markupInline = new InlineKe
yboardMarkup();
List<List<InlineKeyboardButton>> rowsInline = new
ArrayList<>();
List<InlineKeyboardButton> rowInline = new Array
List<>();
rowInline.add(new InlineKeyboardButton().setText(
"Update message text").setCallbackData("update_msg_text"));
// Set the keyboard to the markup
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()) {}
}
It looks like this now:
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
;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
// Register our bot
try {
botsApi.registerBot(new BotApi20());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
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;
import static java.lang.Math.toIntExact;
public class BotApi20 extends TelegramLongPollingBot {
@Override
public void onUpdateReceived(Update update) {
// We check if the update has a message and the message
has text
if (update.hasMessage() && update.getMessage().hasText()
) {
String message_text = update.getMessage().getText();
long chat_id = update.getMessage().getChatId();
if (update.getMessage().getText().equals("/start"))
{
SendMessage message = new SendMessage() // Creat
e a message object object
.setChatId(chat_id)
.setText("You send /start");
InlineKeyboardMarkup markupInline = new InlineKe
yboardMarkup();
List<List<InlineKeyboardButton>> rowsInline = new
ArrayList<>();
List<InlineKeyboardButton> rowInline = new Array
List<>();
rowInline.add(new InlineKeyboardButton().setText(
"Update message text").setCallbackData("update_msg_text"));
// Set the keyboard to the markup
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
// Return bot username
// If bot username is @MyAmazingBot, it must return 'MyA
mazingBot'
return "BotApi20Bot";
}
@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
Lesson 7. Creating users database with
MongoDB
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 highperformance, schema-free document-oriented database. 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. Now, import MongoDB's driver for
Java. You can download it here 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:
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;
You will also need org.slf4j:slf4j-nop library to disable additional logging,
like this:
11:01:15.406 [pool-1-thread-1] DEBUG org.mongodb.driver.protocol
.query - Query completed
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.
private String check(String first_name, String last_name, int us
er_id, String username) {
MongoClientURI connectionString = new MongoClientURI("mo
ngodb://host:port");
MongoClient mongoClient = new MongoClient(connectionStri
ng);
MongoDatabase database = mongoClient.getDatabase("db_nam
e");
MongoCollection<Document> collection = database.getColle
ction("users");
long found = collection.count(Document.parse("{id : " +
Integer.toString(user_id) + "}"));
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";
}
}
Don't do kernel panic, I will explain everything now.
Here we set new connection to MongoDB's server:
61
Lesson 7. Creating users database with MongoDB
MongoClientURI connectionString = new MongoClientURI("mongodb://
host:port");
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.
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("db_name");
MongoCollection<Document> collection = database.getCollection("u
sers");
We search users like this:
long found = collection.count(Document.parse("{id : " + Integer.
toString(user_id) + "}"));
And just check if user exists or not.
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
So now our full function looks like this:
private String check(String first_name, String last_name, int us
er_id, String username) {
// Set loggers
java.util.logging.Logger.getLogger("org.mongodb.driver")
.setLevel(Level.OFF);
MongoClientURI connectionString = new MongoClientURI("mo
ngodb://host:port");
MongoClient mongoClient = new MongoClient(connectionStri
ng);
MongoDatabase database = mongoClient.getDatabase("db_nam
e");
MongoCollection<Document> collection = database.getColle
ction("users");
long found = collection.count(Document.parse("{id : " +
Integer.toString(user_id) + "}"));
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";
}
}
Just check if user exists in database by calling this function when user sends
/start :
63
Lesson 7. Creating users database with MongoDB
import static java.lang.Math.toIntExact;
// 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();
}
Well, that's all for now. Hope to see you soon!
Thanks for reading this.
MonsterDeveloper
64
Lesson 8. Integrating with Redis
search: keywords: ['lesson 8', '8', 'redis', 'database', 'fast database', 'lettuce']
Lesson 8. Integrating with Redis
Hi! Long time I haven't posted lessons. Sorry for that:) Today we are integrating
our highload bot with lighting fast database called Redis. I am using it for data that
needs quick access.
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
Download