Simple Telegram bot on Java from scratch

in #programming7 years ago

 Today we will write a simple bot Telegram, which will respond to commands.
Why I chose exactly Java?
Java in terms of bots, servers, plug-ins and indeed programs will be more convenient for me.  
1. A virtual machine, although it's a long one, but if you handle events in several threads, it will work quickly. (Generally, for many servers / multiplayer games in one thread, it's not always possible to handle events, in Java it's much easier)   
2. The availability of good documentation and Javadocs, which can be done for all libraries (not only for system libraries)  

And what is a "bot"?

A bot is a profile in the social network / messenger (in this case Telegram) which responds to commands. (In any case, all actions will occur after the command is executed)
Type of chat with a bot is a 1 to 1 correspondence.   

1.With what to begin?

Here, download the Telegram library (mandatory with-dependiciens)   IDE can be chosen any, I would recommend eclipse.   
We impose the library of Telegram and proceed.

2.Inheritance of the bot
In order to respond to commands, the class must inherit TelegramLongPillingBot  

Create a class:




And write to it:


package ru.thematdev.bot;

import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.bots.TelegramLongPollingBot;

public class Example extends TelegramLongPollingBot{         public static void main(String[] args) { ApiContextInitializer.init(); // Initialize api TelegramBotsApi botapi = new TelegramBotsApi();
try {
 botapi.registerBot(new Bot());
} catch (TelegramApiException e) { e.printStackTrace();
}
}
@Override
public String getBotUsername() {
return "USER";                 //return user
}
@Override
public void onUpdateReceived(Update e) {
//what happens when you receive a message
}
@Override
public String getBotToken() {
return "YOUR_BOT_TOKEN";
// Bots token
}
}

You can get a token and username by typing @BotFather and writing to it / newbot

3.How do we add something to it?

In  telegram there is no "welcome message", but when we press the "Start" button to start communication with the bot, the "/ start" command is assigned to the machine, so we'll add it first. In telegram api there is no method to send a message like send (string), but we'll create it, after all the voices we write:

@SuppressWarnings("deprecation")
// Means that in new versions the method will be removed or replaced
private void sendMsg(Message msg, String text) {
SendMessage s = new SendMessage();
s.setChatId(msg.getChatId());
// Bot can write to more than one person, and therefore to send a message,  you need to know where to send it
s.setText(text);
try {  
// So that the program does not crash when Exception is thrown
sendMessage(s);
} catch (TelegramApiException e){
e.printStackTrace();
}
}

And in UpdateReceived we add this:

Message msg = e.getMessage();  
String txt = msg.getText();
if (txt.equals("/start")) {
endMsg(msg, "Hello, world! This is simple bot!");  
}

4.Yes it turned out, how to start?

It is possible in the Runnable JAR File since we have the main method, but it's better to run directly from the IDE:

When we started the bot, registered and got the token from BotFather, then we can write to him / start and see that everything works. But the bot will only work when it is started.
Also with the help of the Telegram API you can send pictures, create inline-bots with buttons and much more, but this is already in the continuation ...

Sort:  

This post has received a 2.27 % upvote from @boomerang thanks to: @zirar

You got a 2.78% upvote from @ipromote courtesy of @zirar!
If you believe this post is spam or abuse, please report it to our Discord #abuse channel.

If you want to support our Curation Digest or our Spam & Abuse prevention efforts, please vote @themarkymark as witness.

You got a 1.09% upvote from @buildawhale courtesy of @zirar!
If you believe this post is spam or abuse, please report it to our Discord #abuse channel.

If you want to support our Curation Digest or our Spam & Abuse prevention efforts, please vote @themarkymark as witness.