在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:pengrad/java-telegram-bot-api开源软件地址:https://github.com/pengrad/java-telegram-bot-api开源编程语言:Java 100.0%开源软件介绍:Java Telegram Bot APIJava library for interacting with Telegram Bot API
DownloadGradle: implementation 'com.github.pengrad:java-telegram-bot-api:6.0.1' Maven: <dependency>
<groupId>com.github.pengrad</groupId>
<artifactId>java-telegram-bot-api</artifactId>
<version>6.0.1</version>
</dependency> JAR with all dependencies on release page Usage// Create your bot passing the token received from @BotFather
TelegramBot bot = new TelegramBot("BOT_TOKEN");
// Register for updates
bot.setUpdatesListener(updates -> {
// ... process updates
// return id of last processed update or confirm them all
return UpdatesListener.CONFIRMED_UPDATES_ALL;
});
// Send messages
long chatId = update.message().chat().id();
SendResponse response = bot.execute(new SendMessage(chatId, "Hello!")); Documentation
Creating your botTelegramBot bot = new TelegramBot("BOT_TOKEN"); Network operations based on OkHttp library. TelegramBot bot = new TelegramBot.Builder("BOT_TOKEN").okHttpClient(client).build(); Making requestsSynchronous BaseResponse response = bot.execute(request); Asynchronous bot.execute(request, new Callback() {
@Override
public void onResponse(BaseRequest request, BaseResponse response) {
}
@Override
public void onFailure(BaseRequest request, IOException e) {
}
}); Request in response to update String response = request.toWebhookResponse(); Getting updatesYou can use getUpdates request, parse incoming Webhook request, or set listener to receive updates. class Update {
Integer updateId();
Message message();
Message editedMessage();
InlineQuery inlineQuery();
ChosenInlineResult chosenInlineResult();
CallbackQuery callbackQuery();
} Get updatesBuilding request GetUpdates getUpdates = new GetUpdates().limit(100).offset(0).timeout(0); The getUpdates method returns the earliest 100 unconfirmed updates. To confirm an update, use the offset parameter when calling getUpdates like this:
Executing // sync
GetUpdatesResponse updatesResponse = bot.execute(getUpdates);
List<Update> updates = updatesResponse.updates();
...
Message message = update.message()
// async
bot.execute(getUpdates, new Callback<GetUpdates, GetUpdatesResponse>() {
@Override
public void onResponse(GetUpdates request, GetUpdatesResponse response) {
List<Update> updates = response.updates();
}
@Override
public void onFailure(GetUpdates request, IOException e) {
}
}); WebhookBuilding request SetWebhook request = new SetWebhook()
.url("url")
.certificate(new byte[]{}) // byte[]
.certificate(new File("path")); // or file Executing // sync
BaseResponse response = bot.execute(request);
boolean ok = response.isOk();
// async
bot.execute(request, new Callback<SetWebhook, BaseResponse>() {
@Override
public void onResponse(SetWebhook request, BaseResponse response) {
}
@Override
public void onFailure(SetWebhook request, IOException e) {
}
}); Using Webhook you can parse request to Update Update update = BotUtils.parseUpdate(stringRequest); // from String
Update update = BotUtils.parseUpdate(reader); // or from java.io.Reader
Message message = update.message(); Updates ListenerYou can set a listener to receive incoming updates as if using Webhook. bot.setUpdatesListener(new UpdatesListener() {
@Override
public int process(List<Update> updates) {
// process updates
return UpdatesListener.CONFIRMED_UPDATES_ALL;
}
}); Listener should return id of the last processed (confirmed) update. To stop receiving updates bot.removeGetUpdatesListener(); Available typesAll types have the same name as original ones. Types used in responses (Update, Message, User, Document...) are in Types used in requests (Keyboard, InlineQueryResult, ParseMode, InputMessageContent...) are in KeyboardsForceReply, ReplyKeyboardRemove Keyboard forceReply = new ForceReply(isSelective); // or just new ForceReply();
Keyboard replyKeyboardRemove = new ReplyKeyboardRemove(); // new ReplyKeyboardRemove(isSelective) ReplyKeyboardMarkup Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup(
new String[]{"first row button1", "first row button2"},
new String[]{"second row button1", "second row button2"})
.oneTimeKeyboard(true) // optional
.resizeKeyboard(true) // optional
.selective(true); // optional KeyboardButton Keyboard keyboard = new ReplyKeyboardMarkup(
new KeyboardButton[]{
new KeyboardButton("text"),
new KeyboardButton("contact").requestContact(true),
new KeyboardButton("location").requestLocation(true)
}
); InlineKeyboardMarkup InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(
new InlineKeyboardButton[]{
new InlineKeyboardButton("url").url("www.google.com"),
new InlineKeyboardButton("callback_data").callbackData("callback_data"),
new InlineKeyboardButton("Switch!").switchInlineQuery("switch_inline_query")
}); Chat ActionChatAction action = ChatAction.typing;
ChatAction action = ChatAction.upload_photo;
ChatAction action = ChatAction.find_location; Available methodsAll request methods have the same names as original ones. Send messageAll send requests (SendMessage, SendPhoto, SendLocation...) return SendResponse object that contains Message. SendMessage request = new SendMessage(chatId, "text")
.parseMode(ParseMode.HTML)
.disableWebPagePreview(true)
.disableNotification(true)
.replyToMessageId(1)
.replyMarkup(new ForceReply());
// sync
SendResponse sendResponse = bot.execute(request);
boolean ok = sendResponse.isOk();
Message message = sendResponse.message();
// async
bot.execute(request, new Callback<SendMessage, SendResponse>() {
@Override
public void onResponse(SendMessage request, SendResponse response) {
}
@Override
public void onFailure(SendMessage request, IOException e) {
}
}); Formatting optionsParseMode parseMode = ParseMode.Markdown;
ParseMode parseMode = ParseMode.HTML; Get fileGetFile request = new GetFile("fileId")
GetFileResponse getFileResponse = bot.execute(request);
File file = getFileResponse.file(); // com.pengrad.telegrambot.model.File
file.fileId();
file.filePath(); // relative path
file.fileSize(); To get downloading link as String fullPath = bot.getFullFilePath(file); // com.pengrad.telegrambot.model.File Other requestsAll requests return BaseResponse if not mention here class BaseResponse {
boolean isOk();
int errorCode();
String description();
} GetMe request returns GetMeResponse class GetMeResponse {
User user();
} GetChatAdministrators class GetChatAdministratorsResponse {
List<ChatMember> administrators()
} GetChatMembersCount class GetChatMembersCountResponse {
int count()
} GetChatMember class GetChatMemberResponse {
ChatMember chatMember()
} GetChat class GetChatResponse {
Chat chat()
} GetUserProfilePhotos class GetUserProfilePhotosResponse {
UserProfilePhotos photos()
} StopPoll class PollResponse {
Poll poll()
} Updating messagesNormal message EditMessageText editMessageText = new EditMessageText(chatId, messageId, "new test")
.parseMode(ParseMode.HTML)
.disableWebPagePreview(true)
.replyMarkup(new ReplyKeyboardRemove());
BaseResponse response = bot.execute(editMessageText); Inline message EditMessageText editInlineMessageText = new EditMessageText(inlineMessageId, "new text");
BaseResponse response = bot.execute(editInlineMessageText); Delete message DeleteMessage deleteMessage = new DeleteMessage(chatId, messageId);
BaseResponse response = bot.execute(deleteMessage); StickersSend sticker // File or byte[] or string fileId of existing sticker or string URL
SendSticker sendSticker = new SendSticker(chatId, imageFile);
SendResponse response = bot.execute(sendSticker); Get sticker set GetStickerSet getStickerSet = new GetStickerSet(stickerSet);
GetStickerSetResponse response = bot.execute(getStickerSet);
StickerSet stickerSet = response.stickerSet(); Upload sticker file // File or byte[] or string URL
UploadStickerFile uploadStickerFile = new UploadStickerFile(chatId, stickerFile);
GetFileResponse response = bot.execute(uploadStickerFile); Inline modeGetting updates GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates());
List<Update> updates = updatesResponse.updates();
...
InlineQuery inlineQuery = update.inlineQuery();
ChosenInlineResult chosenInlineResult = update.chosenInlineResult();
CallbackQuery callbackQuery = update.callbackQuery(); If using webhook, you can parse request to InlineQuery Update update = BotUtils.parseUpdate(stringRequest); // from String
Update update = BotUtils.parseUpdate(reader); // from java.io.Reader
InlineQuery inlineQuery = update.inlineQuery(); Inline query resultInlineQueryResult r1 = new InlineQueryResultPhoto("id", "photoUrl", "thumbUrl");
InlineQueryResult r2 = new InlineQueryResultArticle("id", "title", "message text").thumbUrl("url");
InlineQueryResult r3 = new InlineQueryResultGif("id", "gifUrl", "thumbUrl");
InlineQueryResult r4 = new InlineQueryResultMpeg4Gif("id", "mpeg4Url", "thumbUrl");
InlineQueryResult r5 = new InlineQueryResultVideo(
"id", "videoUrl", InlineQueryResultVideo.MIME_VIDEO_MP4, "message", "thumbUrl", "video title")
.inputMessageContent(new InputLocationMessageContent(21.03f, 105.83f)); Answer inline queryBaseResponse response = bot.execute(new AnswerInlineQuery(inlineQuery.id(), r1, r2, r3, r4, r5));
// or full
bot.execute(
new AnswerInlineQuery(inlineQuery.id(), new InlineQueryResult[]{r1, r2, r3, r4, r5})
.cacheTime(cacheTime)
.isPersonal(isPersonal)
.nextOffset("offset")
.switchPmParameter("pmParam")
.switchPmText("pmText")
); PaymentsSend invoice SendInvoice sendInvoice = new SendInvoice(chatId, "title", "desc", "my_payload",
"providerToken", "my_start_param", "USD", new LabeledPrice("label", 200))
.needPhoneNumber(true)
.needShippingAddress(true)
.isFlexible(true)
.replyMarkup(new InlineKeyboardMarkup(new InlineKeyboardButton[]{
new InlineKeyboardButton("just pay").pay(),
new InlineKeyboardButton("google it"< |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论