Hey there, fellow developer! Ready to dive into the world of Telegram bots? You're in for a treat. Telegram's API is a powerhouse for creating interactive and engaging bots, and with the java-telegram-bot-api package, we'll make it a breeze. Let's get started!
Before we jump in, make sure you've got:
First things first, let's get our project ready:
build.gradle
or pom.xml
:implementation 'com.github.pengrad:java-telegram-bot-api:5.7.0'
Now, let's create our bot class:
import com.pengrad.telegrambot.TelegramBot; import com.pengrad.telegrambot.UpdatesListener; import com.pengrad.telegrambot.model.Update; public class MyAwesomeBot { private final TelegramBot bot; public MyAwesomeBot(String botToken) { this.bot = new TelegramBot(botToken); } public void start() { bot.setUpdatesListener(updates -> { // We'll handle updates here return UpdatesListener.CONFIRMED_UPDATES_ALL; }); } }
Time to make our bot respond to commands:
private void handleUpdate(Update update) { if (update.message() != null && update.message().text() != null) { String messageText = update.message().text(); long chatId = update.message().chat().id(); if (messageText.startsWith("/start")) { bot.execute(new SendMessage(chatId, "Hello! I'm your awesome bot.")); } else if (messageText.startsWith("/help")) { bot.execute(new SendMessage(chatId, "Here's how to use me...")); } } }
Don't forget to register your commands with BotFather!
Sending messages is a piece of cake:
// Text message bot.execute(new SendMessage(chatId, "Hello, World!")); // Photo bot.execute(new SendPhoto(chatId, new File("path/to/image.jpg"))); // Document bot.execute(new SendDocument(chatId, new File("path/to/document.pdf")));
Let's implement long polling to receive updates:
public void start() { bot.setUpdatesListener(updates -> { for (Update update : updates) { handleUpdate(update); } return UpdatesListener.CONFIRMED_UPDATES_ALL; }); }
Spice things up with inline keyboards:
InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup( new InlineKeyboardButton[]{ new InlineKeyboardButton("Option 1").callbackData("option1"), new InlineKeyboardButton("Option 2").callbackData("option2") } ); bot.execute(new SendMessage(chatId, "Choose an option:").replyMarkup(inlineKeyboard));
Handle callback queries in your handleUpdate
method:
if (update.callbackQuery() != null) { String callbackData = update.callbackQuery().data(); // Handle the callback data }
Always be prepared for the unexpected:
try { // Your bot logic here } catch (Exception e) { logger.error("An error occurred: ", e); }
Set up logging with your preferred library, like SLF4J or java.util.logging.
Time to see your creation in action! Run your bot locally and start chatting with it on Telegram. Don't be shy, give it a workout!
When you're ready to share your bot with the world:
And there you have it! You've just created a Telegram bot using Java. Pretty cool, right? Remember, this is just the beginning. There's a whole world of features waiting for you to explore.
Keep coding, keep learning, and most importantly, have fun with it! If you want to dive deeper, check out the Telegram Bot API documentation for more advanced features.
Now go forth and bot on!