Integrate Telegram Bot using Java
Hi Guys,
A short and really useful blog on Telegram Bot.
Before writing ahead i want to say a big thank you to Telegram for providing such a rich API and flexibility to create our own bot.
Use Case
Official telegram site shows many use cases where bot is really useful.
Here i used telegram bot to test my services which is deployed in raspberry pi board and bot will work as adhoc between a raspberry pi and Mobile Device using which i am sending a different commands to device.
Code
The sample java code which is used to register a bot with telegram server and echo to mobile device whatever you have sent to bot.
pom.xml
Use below snippet to download required dependency.
1 2 3 4 5 |
<dependency> <groupId>org.telegram</groupId> <artifactId>telegrambots</artifactId> <version>2.4.4</version> </dependency> |
App.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import org.telegram.telegrambots.ApiContextInitializer; import org.telegram.telegrambots.TelegramBotsApi; 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 App extends TelegramLongPollingBot { @Override public String getBotToken() { return "REPLACE_YOUR_KEY"; } public String getBotUsername() { return "Kode12Bot"; } public void onUpdateReceived(Update update) { if (update.hasMessage() && update.getMessage().hasText()) { // Create a SendMessage object with mandatory fields SendMessage message = new SendMessage().setChatId(update.getMessage().getChatId()) .setText("You Said: " + update.getMessage().getText()); try { sendMessage(message); // Call method to send the message } catch (TelegramApiException e) { e.printStackTrace(); } } } public static void main(String[] args) { ApiContextInitializer.init(); TelegramBotsApi botsApi = new TelegramBotsApi(); try { botsApi.registerBot(new App()); } catch (TelegramApiException e) { e.printStackTrace(); } } } |
You just need to execute main method, that it and Your bot will start reacting.
You need to create your bot and need to get token by talking with BotFather, you can talk to BotFather via TeleGram App by searching @BotFather
. Refer https://core.telegram.org/api for more.
Thanks Guys for reading.
Happy Learning.
Share current post by copy: https://goo.gl/wlb8Bw
Thanks,
Yogesh P