Code Monkey home page Code Monkey logo

java-telegram-bot-api's Introduction

Java Telegram Bot API

Maven Central codecov

Java library for interacting with Telegram Bot API

Download

Gradle:

implementation 'com.github.pengrad:java-telegram-bot-api:7.7.0'

Maven:

<dependency>
  <groupId>com.github.pengrad</groupId>
  <artifactId>java-telegram-bot-api</artifactId>
  <version>7.7.0</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;
// Create Exception Handler
}, e -> {
    if (e.response() != null) {
        // got bad response from telegram
        e.response().errorCode();
        e.response().description();
    } else {
        // probably network error
        e.printStackTrace();
    }
});

// Send messages
long chatId = update.message().chat().id();
SendResponse response = bot.execute(new SendMessage(chatId, "Hello!"));

Documentation

Creating your bot

TelegramBot bot = new TelegramBot("BOT_TOKEN");

Network operations based on OkHttp library.
You can build bot with custom OkHttpClient, for specific timeouts or interceptors.

TelegramBot bot = new TelegramBot.Builder("BOT_TOKEN").okHttpClient(client).build();

Making requests

Synchronous

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 updates

You can use getUpdates request, parse incoming Webhook request, or set listener to receive updates.
Update object just copies Telegram's response.

class Update {
    Integer updateId();
    Message message();
    Message editedMessage();
    InlineQuery inlineQuery();
    ChosenInlineResult chosenInlineResult();
    CallbackQuery callbackQuery();
}

Get updates

Building 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: offset = updateId of last processed update + 1
All updates with updateId less than offset will be marked as confirmed on the server and will no longer be returned.

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) {
    
    }
});

Webhook

Building 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 Listener

You can set a listener to receive incoming updates as if using Webhook.
This will trigger executing getUpdates requests in a loop.

bot.setUpdatesListener(new UpdatesListener() {
    @Override
    public int process(List<Update> updates) {

        // process updates

        return UpdatesListener.CONFIRMED_UPDATES_ALL;
    }
// Create Exception Handler
}, new ExceptionHandler() {
    @override
    public void onException(TelegramException e)
    {
        if (e.response() != null) {
            // got bad response from telegram
            e.response().errorCode();
            e.response().description();
        } else {
            // probably network error
            e            .printStackTrace();
        }
    }
});

Listener should return id of the last processed (confirmed) update.
To confirm all updates return UpdatesListener.CONFIRMED_UPDATES_ALL, this should be enough in most cases.
To not confirm any updates return UpdatesListener.CONFIRMED_UPDATES_NONE, these updates will be redelivered.
To set a specific update as last confirmed, just return the required updateId.

To stop receiving updates

bot.removeGetUpdatesListener();

Available types

All types have the same name as original ones.
Type's fields are methods in lowerCamelCase.

Types used in responses (Update, Message, User, Document...) are in com.pengrad.telegrambot.model package.

Types used in requests (Keyboard, InlineQueryResult, ParseMode, InputMessageContent...) are in com.pengrad.telegrambot.model.request package.
When creating a request's type, required params should be passed in the constructor, optional params can be added in chains.

Keyboards

ForceReply, 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 Action

ChatAction action = ChatAction.typing;
ChatAction action = ChatAction.upload_photo;
ChatAction action = ChatAction.find_location;

Available methods

All request methods have the same names as original ones.
Required params should be passed in the constructor.
Optional params can be added in chains.

Send message

All 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 options

ParseMode parseMode = ParseMode.Markdown;
ParseMode parseMode = ParseMode.HTML;

Get file

GetFile 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 https://api.telegram.org/file/<BOT_TOKEN>/<FILE_PATH>

String fullPath = bot.getFullFilePath(file);  // com.pengrad.telegrambot.model.File

Other requests

All 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 messages

Normal 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);

Stickers

Send 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 mode

Getting 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 result

InlineQueryResult 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 query

BaseResponse 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")
);

Payments

Send 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").url("www.google.com")
        }));
SendResponse response = bot.execute(sendInvoice);

Answer shipping query

LabeledPrice[] prices = new LabeledPrice[]{
        new LabeledPrice("delivery", 100),
        new LabeledPrice("tips", 50)
};
AnswerShippingQuery answerShippingQuery = new AnswerShippingQuery(shippingQueryId,
        new ShippingOption("1", "VNPT", prices),
        new ShippingOption("2", "FREE", new LabeledPrice("free delivery", 0))
);
BaseResponse response = bot.execute(answerShippingQuery);

// answer with error
AnswerShippingQuery answerShippingError = new AnswerShippingQuery(id, "Can't deliver here!");
BaseResponse response = bot.execute(answerShippingError);

Answer pre-checkout query

AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(preCheckoutQueryId);
BaseResponse response = bot.execute(answerPreCheckoutQuery);

// answer with error
AnswerPreCheckoutQuery answerCheckout = new AnswerPreCheckoutQuery(id, "Sorry, item not available");
BaseResponse response = bot.execute(answerPreCheckoutQuery);

Telegram Passport

When the user confirms your request by pressing the β€˜Authorize’ button, the Bot API sends an Update with the field passport_data to the bot that contains encrypted Telegram Passport data. Telegram Passport Manual

Receiving information

You can get encrypted Passport data from Update (via UpdatesListener or Webhook)

PassportData passportData = update.message().passportData();

PassportData contains anarray of EncryptedPassportElement and EncryptedCredentials.
You need to decrypt Credentials using private key (public key you uploaded to @BotFather)

String privateKey = "...";
EncryptedCredentials encryptedCredentials = passportData.credentials();
Credentials credentials = encryptedCredentials.decrypt(privateKey);

These Credentials can be used to decrypt encrypted data in EncryptedPassportElement.

EncryptedPassportElement[] encryptedPassportElements = passportData.data();
for (EncryptedPassportElement element : encryptedPassportElements) {
    DecryptedData decryptedData = element.decryptData(credentials);
    // DecryptedData can be cast to specific type by checking instanceOf 
    if (decryptedData instanceof PersonalDetails) {
        PersonalDetails personalDetails = (PersonalDetails) decryptedData;
    }
    // Or by checking type of passport element
    if (element.type() == EncryptedPassportElement.Type.address) {
        ResidentialAddress address = (ResidentialAddress) decryptedData;
    }
}

EncryptedPassportElement also contains an array of PassportFile (file uploaded to Telegram Passport).
You need to download them 1 by 1 and decrypt content.
This library supports downloading and decryption, returns decrypted byte[]

EncryptedPassportElement element = ...

// Combine all files 
List<PassportFile> files = new ArrayList<PassportFile>();
files.add(element.frontSide());
files.add(element.reverseSide());
files.add(element.selfie());
if (element.files() != null) {
    files.addAll(Arrays.asList(element.files()));
}
if (element.translation() != null) {
    files.addAll(Arrays.asList(element.translation()));
}

// Decrypt
for (PassportFile file : files) {
    if (file == null) continue;
    byte[] data = element.decryptFile(file, credentials, bot); // GetFile request and decrypt content
    // save to file if needed
    new FileOutputStream("files/" + element.type()).write(data);
}

Set Passport data errors

SetPassportDataErrors setPassportDataErrors = new SetPassportDataErrors(chatId,
        new PassportElementErrorDataField("personal_details", "first_name", "dataHash",
                "Please enter a valid First name"),
        new PassportElementErrorSelfie("driver_license", "fileHash",
                "Can't see your face on photo")
);
bot.execute(setPassportDataErrors);

Games

Send game

SendResponse response = bot.execute(new SendGame(chatId, "my_super_game"));

Set game score

BaseResponse response = bot.execute(new SetGameScore(userId, score, chatId, messageId));

Get game high scores

GetGameHighScoresResponse response = bot.execute(new GetGameHighScores(userId, chatId, messageId));
GameHighScore[] scores = response.result();

java-telegram-bot-api's People

Contributors

anfanik avatar brainstone avatar denisnp avatar dependabot[bot] avatar eternity-yarr avatar fabionoris avatar fernandowerneck avatar harryzalessky avatar ingvarjackal avatar intellinside avatar long76 avatar marcovaneck avatar martellienrico avatar michaelbk avatar mircoianese avatar pengrad avatar sallatik avatar vdsirotkin avatar vitalyster avatar whiskels avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

java-telegram-bot-api's Issues

Duplicated messages

Hello, i'm trying to create an automatic answer bot, but when it answer to the messages it sends the previous messages that it sent.

use with Android?

I get the following message from build process
"major version 52 is newer than 51, the highest major version supported by this compiler. [javac] It is recommended that the compiler be upgraded."

which suggests that library requires Java 8
is there no way to use it with Android?

Failure to execute "TelegramBot bot = TelegramBotAdapter.build(token);"

Failed to execute "TelegramBot bot = TelegramBotAdapter.build(token);"

Am I missing a dependency from a third-party source not mentioned in the readme?

Stack Trace:
Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/Interceptor at SampleBot.main(SampleBot.java:13) Caused by: java.lang.ClassNotFoundException: okhttp3.Interceptor at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 1 more

Photo message

How can I download image via this java-telegram-bot-api?
I got a response that contains Message model. now I want to get to the Image file, how can I do this?

Bot example

Where I can find example of telegram bot using your library?

No way to check message type.

Hi there,

Usually to check if a message is a reply, forwarded etc we simply have an if statement like this:

if(msg.replyToMessage())
        {
            //stuffs 
        }
        else if(msg.forwardFrom())
        {
            //stufs 
        }

However this does not work in java, is there another way to check if a message is of these types that I am missing?

Regards
BladeZero

crash cause of retrofit.RetrofitError

unable to start activity ComponentInfo{com.example.hadist.sharetext/com.example.hadist.sharetext.MainActivity}: retrofit.RetrofitError

it crash and show this error

setWebhook

Hi, i notice TelegramBot.setWebhook is deprecated. And there's seems no documentation about the replacement method.

Can you give example how to create TelegramBot with webhook with non deprecated API?

Thanks

java.io.EOFException: \n not found: size=0 content=…

Hi,
When I try getting updates or when trying to send text messages or images, at intermittent intervals, the following exception generated (The application communicates with the bot over an authenticated proxy):
Caused by: java.io.IOException: unexpected end of stream on null
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:199)
at okhttp3.internal.io.RealConnection.createTunnel(RealConnection.java:251)
at okhttp3.internal.io.RealConnection.connectTls(RealConnection.java:175)
at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:148)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:188)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241)
at okhttp3.RealCall.getResponse(RealCall.java:240)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.pengrad.telegrambot.impl.TelegramBotClient.send(TelegramBotClient.java:50)
... 4 more
Caused by: java.io.EOFException: \n not found: size=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:215)
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:184)
... 18 more

   Any pointers on how to resolve the issue?

Help With Example

Thanks a lot for publishing code and good explanation. Can you post some examples, complete code as well to understand more.

Get chat id from chat

I would like to get the chat id from the chat which used my Telegram bot. Since my bot is used by multiple chats. I would like to get chat id from that individual chat.

Incompatible chat id types

Chat.id() is of type Long, but all TelegramBot.send*() methods have Integer as the first argument. Not only do you have to cast the id, which is already annoying enough, but because both types are boxed, you have to do a double cast:

bot.sendWhatever((int) (long) Chat.id(), ...)

The specification says that the id field of the Chat type is an integer, so maybe Chat.id should be changed?

How to send formated text & picture as response to inline bot

Hi @pengrad ,

I see that there are several type of content that we can send to the picker

example picker with text & photos:
new InlineQueryResultArticle("id", "title", "response send to user if selecting").thumbUrl("url");

However, how do I format the message send to the user after the user made a selection in the picker? As example, suppose the user select the content above, how can I send back a message with a picture with text, where some part of the text is in bold and some words are links?

I have tried using markdown and html, but none are interpreted. I guess there must be an option to enable HTML usage.

Basically something similar as what the popcornbot (https://telegram.me/imdb) does.

Thanks in advance.
PA

mark updates as already "read" (or processed)

Hi there, congrats for this api, looks pretty easy to use.
this is not an issue but a question.
Is there any way to mark as already processed the Updates?
Or that logic should be in the bot itself by getting the last "n" events and comparing if they were already processed or not. GetUpdate has a method limit(int) and offset(int), any way to get the updates in reverse order?

best regards

Listener

HI!

how to make listener for bot? i like to get messages from bot and response to messages

SendDocument didn't change file name and use always file.txt

Steps to reproduce:

  1. Try to use code:
public void sendDocument(chanId, byte[] fileBytes){
        File temp = File.createTempFile("My own file name", ".pdf");
        FileUtils.writeByteArrayToFile(temp, fileBytes);

        SendDocument sendDocument = new SendDocument(chatId, temp);
        sendDocument.caption("My own file name caption.pdf");
        bot.execute(sendDocument);

        temp.delete();

}
  1. Run code
  2. Get file with name "file.txt"

Expected result:
File with name "My own file name.pdf" or "My own file name caption.pdf"

Actual result:
File with name "file.txt"

ChosenInlineResult always null

Hello,

could it be that ChosenInlineResult is buggy and always returns null?
I've set it up inside my update loop like this:

if(update.chosenInlineResult() != null) { System.out.println(update.chosenInlineResult().query()); chatIdResultMapping.remove(update.chosenInlineResult().from().id()); }

But it never actually has a value.
Getting normal updates or sending InlineQueryResults is no problem, just getting the ChosenResult always seems to fail.

Bot game simple example.

Hi all,

I am having problems in setting up an HTML5 app for my bot.

I've got these pieces of code on my updatesCallback loop:

...
        } else if (update.inlineQuery()!=null) {
            sendInlineGameResponse(update);
        } else if (text.startsWith("mb")) {
            sendGame(update);
        }
...
    private void sendGame(Update u) {
        getTelegramBot().execute(new SendGame(u.message().chat().id(), "mygamealias"));

    }

    private void sendInlineGameResponse(Update u) {
        InlineQuery inlineQuery = u.inlineQuery();
        InlineQueryResult r1 = new InlineQueryResultGame("mygamealias", "mygamealias");
        r1.inputMessageContent(new InputTextMessageContent("./mygameapp.html"));
        getTelegramBot().execute(new AnswerInlineQuery(inlineQuery.id(), r1));
    }

The main problem is i don't fully undestand how this is supposed to work. Can you please provide a working example of a simple bot game?

exception when proguard is on

Please help.

Exception thrown whenever I try to SendMessage or SendDocument with proGuard on (true)

E: Exception java.lang.Enum$1.create(Enum.java:43)
E: Exception java.lang.Enum$1.create(Enum.java:35)
E: Exception libcore.util.BasicLruCache.get(BasicLruCache.java:54)
E: Exception java.lang.Enum.getSharedConstants(Enum.java:209)
E: Exception java.lang.Enum.valueOf(Enum.java:189)
E: Exception a.l.b(Unknown Source)
E: Exception a.l.a(Unknown Source)
E: Exception a.z.a(Unknown Source)
E: Exception a.a.c.a.a(Unknown Source)
E: Exception a.a.c.a.a(Unknown Source)
E: Exception a.a.b.z.a(Unknown Source)
E: Exception a.a.b.z.b(Unknown Source)
E: Exception a.a.b.z.a(Unknown Source)
E: Exception a.a.b.n.a(Unknown Source)
E: Exception a.ap.a(Unknown Source)
E: Exception a.aq.a(Unknown Source)
E: Exception a.ap.a(Unknown Source)
E: Exception a.ap.a(Unknown Source)
E: Exception com.pengrad.telegrambot.impl.TelegramBotClient.send(Unknown Source)
E: Exception com.pengrad.telegrambot.TelegramBot.execute(Unknown Source)

Proguard:

-keep class com.github.pengrad.* { ; }
-keep class com.github.pengrad.telegrambot.request.
* { ; }
-keep class github.pengrad.
* { ; }
-keep class github.pengrad.telegrambot.request.
* { ; }
-keep class github.pengrad.telegrambot.
* { ; }
-keep class java.lang.
* { ; }
-keep class java.io.File
-keep class java.io.

-keep class java.io.
* { ; }
-keep class java.lang.reflect.Type
-keep class java.util.HashMap
-keep class java.util.Map
-keepclassmembers,allowoptimization enum * {
public static *
[] values();
public static * valueOf(java.lang.String);
}
-keep class com.google.
* { ; }
-keep class com.pengrad.telegrambot.
* { ; }
-keep class com.pengrad.
* { *; }

Thank you

key

Hi

i use bot.sendMessage(102504428, "Message",null,null,null,new ReplyKeyboardMarkup(new String[]{"ok", "cancel"}).oneTimeKeyboard(true));

but message not send to bot

why?

sending photo

I have problem with sending photo using your API.(I think the problem is by me or generating files)
please see this issue Issue
I didn't found another way to communicate with you.

Java EE

Hi. I am curious is this api working fine with Java EE? I am asking it because another java bot API listed in official telegram page have some troubles with concurrency in java EE.

Thanks.

Download files by file path from getFile

  1. Is it write to have method which downloads file.
  2. To current realization of TelegramBot interface, there is no way to add method for download files directly (cause of different base urls). Maybe it can be done somehow in retrofit?
  3. Maybe define new interface, like TelegramDownload.

Long pooling socket time out exception

Hi, I'm using long pooling to get the updates instead of webhook. When there's no message for the bot, it throws SocketTimeOutException and it's clutering server log, since i run the updates every minute. doing catch (Exception e) {} seems to be a bad practice, is there any better way to handle this?

Thanks.

Edit Message

How long after sending messages can we edit them?

Send message to a channel error

Hi,
first of all thanks for the wonderful API.
Second, I'm getting a retrofit.RetrofitError: 400 Bad Request when trying to send a message to a channel using bot.sendMessage("@mychannel", "short message sending");.

Please add some useful documentation

Is not quite easy and fast use this library without any kind of documentation. I hope you can provide some documentation out there. Anyway, thank you so much for this library.

Getting inline updates. Yeah, a new issue.

Probably that's bad luck, probably that's my bad programmation skill, but I don't get the inline updates.

GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates().offset(offset)); List<Update> updates = updatesResponse.updates(); for(Update update : updates) { CallbackQuery callbackQuery = update.callbackQuery(); Message message = update.message(); System.out.println(message.chat().id()+">"+message.text()); System.out.println(callbackQuery.data()); }

Where is my problem? D:

Connection via authenticated proxy

Hi,
I'm trying to connect to a bot via an authenticated proxy. Could you consider this feature enhancement.
For now, I have updated the TelegramBotAdapter class to get the authentication working that suits my purpose:

private static OkHttpClient client(Interceptor interceptor, final String proxyHost, final int proxyPort, final String userName, final String password) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (interceptor != null) builder.addInterceptor(interceptor);

        final Authenticator proxyAuthenticator = new Authenticator() {
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic(userName, password);
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)    
                        .build();
            }
        };

        builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
        .proxyAuthenticator(proxyAuthenticator)
        .retryOnConnectionFailure(true);

        return builder.build();
    }

InlineKeyboardMarkup is not getting displayed.. and getting the response as null

The following piece of code is not displaying the inlinekeyboard or the message

InlineKeyboardMarkup inlineKeyboard = new InlineKeyboardMarkup(
new InlineKeyboardButton[]{
new InlineKeyboardButton("url").url("url"),
new InlineKeyboardButton("callback_data").callbackData("callback_data"),
new InlineKeyboardButton("switch_inline_query").switchInlineQuery("switch_inline_query")
});
bot.execute(new SendMessage(192591982, "typing...").replyMarkup(inlineKeyboard))

Getting updates.

Can you send me an exaple for getting updates without webhook?

Keyboards

Hi!

this code not work i dont know why

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

bot keyboard not change

this is my full code

 private class Bot extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
          //  for (int i = 0; i < 20; i++) {
Keyboard replyKeyboardMarkup = new ReplyKeyboardMarkup(
                    new String[]{"a", "b"},
                    new String[]{"c", "d"})
        .oneTimeKeyboard(true)   // optional
        .resizeKeyboard(true)    // optional
        .selective(true);        // optional


            try {



                   bot.sendMessage(102504428, "Hello _italic_ *bold*!");


           //         Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                 //   ByteArrayOutputStream bos = new ByteArrayOutputStream();
                 //   bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                //    byte[] data = bos.toByteArray();

                  //  bot.sendPhoto(102504428, InputFileBytes.photo(data), "caption", null,null);


              //      byte[] bytes = convert("/sdcard/k.mp3");


                  //  bot.sendVoice(102504428, InputFileBytes.voice(bytes), 3, null, null);


                  //  bot.sendChatAction("@testbootapi", ChatAction.upload_audio);

                } catch (Exception e) {

              //  }
           }





            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }

Documentation

I want to get started with this API, but there is no documentation.

I'm trying to make it so that when I get 'x' message, something happens.

How do I use the Updates class to do that?

Getting an IllegalStateException were only IOExceptions are caught

Getting an IllegalStateException but only IOException will result in a failed async response

Exception in thread "BotHttp Dispatcher" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
    at com.google.gson.Gson.fromJson(Gson.java:879)
    at com.google.gson.Gson.fromJson(Gson.java:844)
    at com.google.gson.Gson.fromJson(Gson.java:793)
    at com.pengrad.telegrambot.impl.TelegramBotClient$1.onResponse(TelegramBotClient.java:34)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:388)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:209)
    ... 9 more

Consuming callback query

Hi, how to consume a callback query from an inline keyboard markup?

With update, using lastId() +1, will consume the update. With callbackquery, the object still remain.

Thanks.

Problems with downloading this api

Hello,

how can i download this api? I saw that i need to use gradle or maven, but how?
Can i use it directly in Eclipse? Can anyone help me or send me a link.

I really dont know how i do this.

Channel Bot Example

Hi!
Can u post a bot code example that sends messages to a channel? I don't know how to start coding using your api, I'm so confused.
Thanks!

One Message incoming twice

Hey everyone,

I test a bit with that api in combination with Spring and I may found a bug or something?
I have a Scheduled Bean with a fixedRate by 500ms - so every 500ms spring is calling that method.
The rest of that method is like your example but if i write to the bot a bit faster then I get 2 messages with the same messageId... (see picture)

`
GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates().limit(0).offset(0).timeout(0));
List updates = updatesResponse.updates();

    // Collections.reverse(updates); // is that needed? 
    for (Update update : updates) {

        Message message = update.message();
        Chat chat = message.chat();
        User user = message.from();

        if (message.text() != null) {
            System.out.println("New message: " + message.text() + " id: " + message.messageId() + " from " + chat);
            SendResponse sendResponse = bot.execute(new SendMessage(chat.id(), "Selber: " + message.text()));

        }
    }

`
Picture
Terminaloutput and picture are not the same - it can reproduce...

Terminaloutput:

  • New message: 1 id: 1005 from Chat{id=5..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 1 id: 1005 from Chat{id=5..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 2 id: 1008 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 3 id: 1010 from Chat{id=..,, type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 3 id: 1010 from Chat{id=...,, type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 4 id: 1013 from Chat{id=...,, type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 5 id: 1015 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 5 id: 1015 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 6 id: 1018 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 7 id: 1020 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 8 id: 1022 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}
  • New message: 9 id: 1024 from Chat{id=..., type=Private, first_name='Domme', last_name='null', username='Turael', title='null'}

Problems in Google App Engine

Hi,
I tried to use this lib on Google App Engine, but I continue to get this problem with several classes:

Unable to invoke no-args constructor for class com.pengrad.telegrambot.model.Update. Register an InstanceCreator with Gson for this type may fix this problem.

Caused by:

java.lang.RuntimeException: Unable to invoke no-args constructor for class com.pengrad.telegrambot.model.Update. Register an InstanceCreator with Gson for this type may fix this problem.

I tried to register an InstanceCreator but I continue to get this problem, so I added some empty constructors in the model classes. But then I had to remove "final" from class attributes.
Have you got any other suggestion to fix it? Otherwise I am going to send you a pull request.

Thanks

Type KeyboardButton

Hello!
I need to send field "request_location" in object "KeyboardButton". How i can do that? Thank you.

Encoding problem

Hello! When I am trying to send cyrillic text (in russian), Telegram client incorrectly represents it.
Also, when client send to server cyrillic text, that text is incorrectly decoded.
All data looks like: ??????? ?????? ?????

Sample text: ΠŸΡ€ΠΈΠ²Π΅Ρ‚ (Hello)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.