JTelegramBot is a Java library that wraps Telegram Bot API with a simpler API using Builder design pattern.
TelegramBot library supports full functionality of Telegram Bot API 2.1 and it consists of 3 modules:
Other options will be added later.
See https://core.telegram.org/bots/api
First of all, you need to create a new Telegram Bot and get an access token as described here.
Start writing Java code by defining an instance of the interface UpdateHandler
which contains callbacks methods called upon getting new updates from Telegram server. For simplicity, you can use SimpleUpdateHandler
(which provides empty implementaions) and override the callback methods you need. UpdateHandler
provides the following callback methods:
onMessageReceived(TelegramBotApi telegramBotApi, int id, Message message)
: Invoked on receiving new incoming message of any kind — text, photo, sticker, etc, sticker, etc.onInlineQueryReceived(TelegramBotApi telegramBotApi, int id, InlineQuery inlineQuery)
: Invoked on receiving new incoming inline query.onChosenInlineResultReceived(TelegramBotApi telegramBotApi, int id, ChosenInlineResult chosenInlineResult)
: Invoked on receiving the result of an inline query that was chosen by a user and sent to their chat partner.onCallbackQueryReceived(TelegramBotApi telegramBotApi, int id, CallbackQuery callbackQuery)
: Invoked on receiving new incoming callback query.onGetUpdatesFailure(Exception e)
: Invoked in case of an exception occurs when trying to get the new update.Inside the callbck methods, wrap the low-level interface telegramBotApi
with the high-level builder ApiBuilder
. For example:
@Override
public void onMessageReceived(TelegramBotApi telegramBotApi, int id, Message message)
{
try
{
ApiBuilder.api(telegramBotApi)
.sendMessage("*This is a simple text message*")
.toChatId(message.getChat().getId())
.asReplyToMessage(message.getMessageId())
.asSilentMessage()
.parseMessageAs(ParseMode.MARKDOWN)
.execute();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(NegativeResponseException e)
{
e.printStackTrace();
}
}
There are some builder classes that facilitates the creation of complex objects:
InlineKeyboardButtonBuilder
builds InlineKeyboardButton[][]
.KeyboardButtonBuilder
builds KeyboardButton[][]
.InlineQueryResultBuilder
builds all of 19 types of InlineQueryResult
.InputMessageContentBuilder
builds all of 4 types of InputMessageContent
.ReplyMarkupBuilder
builds all of 4 types of ReplyMarkup
.After implmenting the interface UpdateHandler
, create a new instance of JTelegramBot
as follows:
JTelegramBot bot = new JTelegramBot("BotName", API_TOKEN, updateHandler);
After that, just start the bot in Polling
mode:
bot.start(); // blocking call
// or bot.startAsync(); non-blocking call
To start JTelegramBot in a Webhook
mode, instead of starting bot directly (as in step 6), wrap it with WebhookServer
:
WebhookServer webhookServer = new WebhookServer(bot, "example.com", TelegramPort.PORT_8443, "/random/path");
webhookServer.useGeneratedSelfSignedSslCertificate();
webhookServer.registerWebhook();
webhookServer.start();
Most of the APIs (methods) in this library throws 2 types of exceptions:
ApiBuilder
APIsexecute()
ends the methods chaining.ApiBuilder.api(TelegramBotApi telegramBotApi)
.asUser()
.execute();
.sendMessage(String text)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.parseMessageAs(ParseMode parseMode)
.disableLinkPreviews()
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.forwardMessage(int messageId)
.fromChatUsername(String chatUsername) or fromChatId(long chatId)
.toChatUsername(String chatUsername) or toChatId(long chatId)
.asSilentMessage()
.execute();
.sendPhoto(File photoFile) or .sendPhoto(InputStream photoInputStream, String photoName) or .resendPhoto(String photoId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.withPhotoCaption(String photoCaption)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendAudio(File audioFile) or .sendAudio(InputStream audioInputStream, String audioName) or .resendAudio(String audioId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.withAudioDuration(int duration)
.withAudioPerformer(String performer)
.withAudioTitle(String title)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendDocument(File documentFile) or .sendDocument(InputStream documentInputStream, String documentName) or .resendDocument(String documentId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.withDocumentCaption(String documentCaption)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendSticker(File stickerFile) or .sendSticker(InputStream stickerInputStream, String stickerName) or .resendSticker(String stickerId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendVideo(File videoFile) or .sendVideo(InputStream videoInputStream, String videoName) or .resendVideo(String videoId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.withVideoDuration(int duration)
.withVideoWidth(int width)
.withVideoHeight(int height)
.withVideoCaption(String videoCaption)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendVoice(File voiceFile) or .sendVoice(InputStream voiceInputStream, String voiceName) or .resendVoice(String voiceId)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.withVoiceDuration(int duration)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendLocation(int latitude, int longitude)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.asSilentMessage()
.asReplyToMessage(int messageId)
.applyReplyMarkup(ReplyMarkup replyMarkup)
.execute();
.sendChatAction(ChatAction chatAction)
.toChatUsername(String chatUsername) or .toChatId(long chatId)
.execute();
.getUserProfilePhotos(int userId) or .getUserProfilePhotos(User user)
.withOffset(int offset)
.withLimit(int limit)
.execute();
.getFileInfo(String fileId)
.execute();
.downloadFile(TelegramFile telegramFile)
.saveToOutputStream(OutputStream outputStream)
.execute();
.kickChatMember(int userId)
.fromChatUsername(String chatUsername) or .fromChatId(long chatId)
.execute();
.leaveChat()
.byChatUsername(String chatUsername) or .byChatId(long chatId)
.execute()
.unbanChatMember(int userId)
.fromChatUsername(String chatUsername) or .fromChatId(long chatId)
.execute();
.getChat()
.byChatUsername(String chatUsername) or .byChatId(long chatId)
.execute();
.getChatAdministrators()
.ofChatUsername(String chatUsername) or .ofChatId(long chatId)
.execute();
.getChatMembersCount()
.ofChatUsername(String chatUsername) or .ofChatId(long chatId)
.execute();
.getChatMember(int userId)
.ofChatUsername(String chatUsername) or .ofChatId(long chatId)
.execute();
.answerCallbackQuery()
.forQueryId(String queryId)
.withText(String text)
.showAsAlert()
.execute();
.editMessage()
.forMessageId(int messageId)
.fromChatUsername(String chatUsername) or .fromChatId(long chatId)
.withNewText(String text)
.withNewCaption(String caption)
.withNewInlineKeyboard(InlineKeyboardMarkup inlineKeyboard)
.execute();
.editInlineMessage()
.forInlineMessageId(String inlineMessageId)
.withNewText(String text)
.withNewCaption(String caption)
.withNewInlineKeyboard(InlineKeyboardMarkup inlineKeyboard)
.execute();
.answerInlineQuery()
.forQueryId(String queryId)
.withResults(InlineQueryResult... results)
.cacheResultsFor(int seconds)
.asPersonal()
.withNextOffset(String nextOffset)
.showSwitchToPM(String buttonText)
.useSwitchToPmParameter(String parameter)
.execute();
This project is licensed under The MIT License (MIT). See LICENSE for more details.