Giter VIP home page Giter VIP logo

telegrambots's Introduction

Telegram Bot Java Library

Telegram

Build Status Jitpack Maven Central MIT License

A simple to use library to create Telegram Bots in Java

Contributions

Feel free to fork this project, work on it and then make a pull request against DEV branch. Most of the times I will accept them if they add something valuable to the code.

Please, DO NOT PUSH ANY TOKEN OR API KEY, I will never accept a pull request with that content.

Webhooks vs GetUpdates

Both ways are supported, but I recommend long polling method.

Usage

For more information, check our documentation

Example bots

Open them and send them /help command to get some information about their capabilities:

https://telegram.me/weatherbot (Use custom keyboards)

https://telegram.me/directionsbot (Basic messages)

https://telegram.me/filesbot (Send files by file_id)

https://telegram.me/TGlanguagesbot (Send files uploding them)

https://telegram.me/RaeBot (Inline support)

https://telegram.me/SnowcrashBot (Webhook support)

You can see code for those bots at TelegramBotsExample project.

Telegram Bot API

This library use Telegram bot API, you can find more information following the link.

Questions or Suggestions

Feel free to create issues here as you need or join the chat

Powered by Intellij and DigitalOcean

DigitalOcean Referral Badge

License

MIT License

Copyright (c) 2016 Ruben Bermudez

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

telegrambots's People

Contributors

addo47 avatar alexengrig avatar annimon avatar antonu17 avatar azzureman avatar bernikr avatar bvn13 avatar chase22 avatar chmilevfa avatar christianblos avatar clevero avatar costalfy avatar dapoldi avatar dschulz avatar ekiauhce avatar flicus avatar jugendhacker avatar limitium avatar loolzaaa avatar lukasprediger avatar mit0x2 avatar monkeyboiii avatar myplacedk avatar narryel avatar nea89o avatar recursiveribbons avatar rubenlagus avatar snyk-bot avatar timursergeevichname avatar unafraid 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  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

telegrambots's Issues

Cyrillic text in InlineKeyboardButton

Hi, i having a problem with the Cyrillic text in InlineKeyboardButton.
When i tried:
button.setText("ะ ัƒััะบะธะน ัะทั‹ะบ");
as the result will be button with "??????? ????" text.
I tried to change the encoding (UTF-8) - gave no results.
Someone can verify or give advice?

Recurrent typo Replay instead of Reply

I noticed using EditMessageText class, it has setReplyMarkup() method, instead SendMessage has setReplayMarkup(). A quick search in the repository showed this is a recurrent "issue".
I know correcting it could be a big problem for everyone using this library, just wanted to know if you're aware and not correcting it to avoid big troubles in users.

Question on Creating Bot

I would like to ask if it is able to create TelegramBotApi without any parameter(i.e: using no-arg constructor) and using it to register bot??

When I follow the usage, there is HTTPHostConnectException popped up.

Here is my code:

`public static void main(String[] args) {

    TelegramBotsApi telegramBotsApi = new TelegramBotsApi();

    TelegramLongPollingBot telegramLongPollingBot = new TelegramLongPollingBot() {

        @Override
        public void onUpdateReceived(Update update) {
            Message message = update.getMessage();

            if (message != null && message.hasText()) {
                HandlerMessages(message);
            }
        }

        private void HandlerMessages(Message message) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(message.getChatId().toString());

            sendMessage.setText("response");

            try {
                sendMessage(sendMessage);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String getBotUsername() {
            return "testBot";

        }

        @Override
        public String getBotToken() {
            return "{MY_TOKEN}";

        }
    };

    try {
        telegramBotsApi.registerBot(telegramLongPollingBot);
        System.out.println("registered");
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}`

Here is the console:

org.telegram.telegrambots.TelegramApiException: Error executing setWebook method at org.telegram.telegrambots.TelegramBotsApi.setWebhook(TelegramBotsApi.java:158) at org.telegram.telegrambots.TelegramBotsApi.setWebhook(TelegramBotsApi.java:111) at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:88) at main.Main.main(Main.java:65) Caused by: org.apache.http.conn.HttpHostConnectException: Connect to api.telegram.org:443 [api.telegram.org/149.154.167.198, api.telegram.org/149.154.167.199, api.telegram.org/149.154.167.200, api.telegram.org/149.154.167.197] failed: Connection timed out: connect at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) at org.telegram.telegrambots.TelegramBotsApi.setWebhook(TelegramBotsApi.java:147) ... 3 more Caused by: java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:337) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134) ... 13 more

workable example of get received photos

Hello,

I an looking for something that seems to be simple but I can not manage it to work, could anyone provide me a example that receives a photo to a java.io file ?

Until now I have:
` public void onUpdateReceived(Update update) {

    if(update.getMessage().getPhoto()!=null){
        GetFile getFileRequest = new GetFile();

        getFileRequest.setFileId(update.getMessage().getPhoto().get(0).getFileId());

        try {
             org.telegram.telegrambots.api.objects.File file = getFile(getFileRequest);
            // saveUrl("teste.jpg", "https://api.telegram.org/"+getBotToken()+"/"+file.getFilePath());

            File arquivo = new File("https://api.telegram.org/"+getBotToken()+"/"+file.getFilePath());
            URL url = new URL("https://api.telegram.org/"+getBotToken()+"/"+file.getFilePath());
            FileUtils.copyURLToFile(url, arquivo);

            System.out.println(arquivo.getPath());
            //System.out.println("https://api.telegram.org/"+getBotToken()+"/getFile?file_id="+photo.getFileId());
            System.out.println(Photo.classificar(arquivo));`

Log says file is null:
java.lang.NullPointerException
at br.com.prime33.telegram.bot.oficial.principal.Photo.classificar(Photo.java:35)
at br.com.prime33.telegram.bot.oficial.principal.Bela21Bot.onUpdateReceived(Bela21Bot.java:51)
at org.telegram.telegrambots.updatesreceivers.BotSession$HandlerThread.run(BotSession.java:180)

neither this output path works when I try in the browser

https://api.telegram.org/246536565:AAFS1_A6sHcwYzksZLaeoqcOd-EC9dd3IYk/photo/file_13.jpg

Thanks in advance

Deploy on Maven Central

Do you have any plan to deploy release artifacts also on Maven central?
If you want I can take care of it (probably I will just need your help to fill some legal form....)

no main manifest attribute

Hi , i create bot and it work good , in intellij , but when i create jar file and i want run , java -jar mybot.jar , it show me no main manifest attribute , i check manifest created and i chose Main class , did i missed anything ?

Exception on sending message with underline character

i catch exception when i want to sending underline '_' to bot

org.telegram.telegrambots.TelegramApiException: Error at sendmessage: 
Bad Request: Can't parse message text: Can't find end of the entity starting at byte offset 264

i find that happen when i had underline character in my message text
it's seems underline is a special character in bot API like as '' in java String that must be use '\' for that
how can i to resolve ?

Enhancement: setters to builder style

Hi!
Would it be appropriate to make setters in the builder style?
Like this:

    public SomeClass setField(String field) {
        this.field = field;
        return this;
    }

In my opinion, this will add a bit of usability.

sendMessage(new SendMessage().setChatId(chatId).setText("Text"));

If you need it, i can handle it and send you pull request.
Regards.

Error at sendMessage

When I use method with callback:

  locationCommand.locationHandlerMethod(userDocument, message.getLocation(), new ResultCallback() {
        @Override
        public void onResult(String message) {
            SendMessage messageToSend = new SendMessage();
            messageToSend.setChatId(userDocument.getString("chat_id"));
            messageToSend.setText(message);
            messageToSend.enableHtml(true);
            try {
                sendMessage(messageToSend);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }

        }
    });

Exception happens on sendMessage method:

 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
 SLF4J: Defaulting to no-operation (NOP) logger implementation
 SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
 org.telegram.telegrambots.TelegramApiException: Error at sendmessage
at org.telegram.telegrambots.bots.AbsSender.sendApiMethod(AbsSender.java:435)
at org.telegram.telegrambots.bots.AbsSender.sendMessage(AbsSender.java:51)

Why this exception happens? Is there any option to disable this StaticLoggerBinder @rubenlagus ?
I also use async version of MongoDB Java driver.

UPDATE

I have added SLF4J and configured. However, I still get error at sendMessage:

  org.telegram.telegrambots.TelegramApiException: Error at sendmessage
at org.telegram.telegrambots.bots.AbsSender.sendApiMethod(AbsSender.java:435)
at org.telegram.telegrambots.bots.AbsSender.sendMessage(AbsSender.java:51)
at my.MyBotHandler$3.onResult(MyBotHandler.java:173)
at my.structure.commands.location.NearestATMSLocationCommand$1.sendResult(NearestATMSLocationCommand.java:69)
at org.asynchttpclient.AsyncCompletionHandler.onCompleted(AsyncCompletionHandler.java:64)
at org.asynchttpclient.netty.NettyResponseFuture.getContent(NettyResponseFuture.java:173)
at org.asynchttpclient.netty.NettyResponseFuture.done(NettyResponseFuture.java:210)
at org.asynchttpclient.netty.handler.HttpProtocol.finishUpdate(HttpProtocol.java:198)
at org.asynchttpclient.netty.handler.HttpProtocol.exitAfterHandlingBody(HttpProtocol.java:399)
at org.asynchttpclient.netty.handler.HttpProtocol.handleHttpResponse(HttpProtocol.java:434)
at org.asynchttpclient.netty.handler.HttpProtocol.handle(HttpProtocol.java:473)
at org.asynchttpclient.netty.handler.Processor.messageReceived(Processor.java:85)
at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
at org.jboss.netty.handler.stream.ChunkedWriteHandler.handleUpstream(ChunkedWriteHandler.java:142)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
at org.jboss.netty.handler.codec.http.HttpContentDecoder.messageReceived(HttpContentDecoder.java:108)
at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:296)
at org.jboss.netty.handler.codec.frame.FrameDecoder.unfoldAndFireMessageReceived(FrameDecoder.java:459)
at org.jboss.netty.handler.codec.replay.ReplayingDecoder.callDecode(ReplayingDecoder.java:536)
at org.jboss.netty.handler.codec.replay.ReplayingDecoder.messageReceived(ReplayingDecoder.java:485)
at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70)
at org.jboss.netty.handler.codec.http.HttpClientCodec.handleUpstream(HttpClientCodec.java:92)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:296)
at org.jboss.netty.handler.codec.frame.FrameDecoder.unfoldAndFireMessageReceived(FrameDecoder.java:462)
at org.jboss.netty.handler.codec.frame.FrameDecoder.callDecode(FrameDecoder.java:443)
at org.jboss.netty.handler.codec.frame.FrameDecoder.messageReceived(FrameDecoder.java:310)
at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:70)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564)
at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268)
at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255)
at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:88)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:108)
at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337)
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89)
at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178)
at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
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)

There is no proper description of what is happening.

UPDATE: I have found why this error is happening

Telegram has message length limit, which is 4096 symbols. My messages where more than 6000 symbols.

Your Bot API does not handle this error explicitly it just says ERROR HAPPENED and thats all. I spend 4 hours thinking that error is happening because of other libs.

Please add proper error message to this condition!

Imposible to use API behind proxy

Hi, there is no chance to use your library if the server is behind the proxy. Could you please add the ability to read the default system proxy settings by HttpClient and RequestConfig.

InlineKeyboardMarkup and InlineKeyboardButton

Greetings. Today I was starting to play around with InlineKeyboardMarkup type, so I supposed it should have been working like ReplyKeyboardMarkup (according to Telegram APIs)
Although the add method takes a List<List<String>> as parameter instead of a List<List<InlineKeyboadButton>> or a consistent List<InlineKeyboardRows>.

I'm I missing something? Thank you.

Problem with Inline Query

Once I return an article and it appears on the client if the user click on the article it starts a never ending loop on my Java App that doesn't allow any more request from the user.

Article Code:

InlineQueryResultArticle inlineQueryResultArticle1 = new InlineQueryResultArticle();
        inlineQueryResultArticle1.setTitle("bla bla bla");
        inlineQueryResultArticle1.setDescription(Emoji.BLACK_RIGHT_POINTING_DOUBLE_TRIANGLE.toString());
        inlineQueryResultArticle1.setDisableWebPagePreview(false);
        inlineQueryResultArticle1.enableMarkdown(true);
        inlineQueryResultArticle1.setId("1");
        inlineQueryResultArticle1.setThumbUrl("http://someUrl");
        inlineQueryResultArticle1.setUrl("http://someOtherUrl");            inlineQueryResultArticle1.setMessageText("http://someUrlAgain");
        InlineQueryResult inlineQueryResult1 = inlineQueryResultArticle1;
List<InlineQueryResult> inlineQueryResults = new ArrayList<>();
        inlineQueryResults.add(inlineQueryResult1);

        AnswerInlineQuery answerInlineQuery = new AnswerInlineQuery();
        answerInlineQuery.setCacheTime(CACHETIME);
        answerInlineQuery.setInlineQueryId(inlineQuery.getId());
        answerInlineQuery.setResults(inlineQueryResults);
        try {
            sendAnswerInlineQuery(answerInlineQuery);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }

The above code print out a single article on the client and once the user select it I see the following loop in the log (I've cut off some boilerplate):

016-03-20 16:48:18,308 DEBUG [Thread-0] conn.Wire (Wire.java:86) - http-outgoing-37 << ""chosen_inline_result":{"from":{"id":215222037,"first_name":"Alexio","last_name":"Cassani"},"query":"123","result_id":"1"}}]}"

During this loop if user send other messages they are received by my bot but they are collected and not elaborated. Maybe I need in some way tell to my bot to pop the inline_message or doing something with the offset of the update query?

sendAudio support

Is there any way to send audio files? Not voice message.

I saw that there is no method for that in AbsSender.java yet to do this. Could you please add support?

Or am I on the wrong way of thinking to send audio?

Apache HTTP Components could shaded

Currently it is a pain to include other libs (for example jenkins-client) in an project that also depends on telegrambots, because HttpComponents conflict easily.

Please shade/repackage the Apache Http client (see mvn shade plugin)

Java Compiler.1.7 or 1.8

when i set java Compiler to 1.7
this error shows

Cannot refer to the non-final local variable callback defined in an enclosing scope AbsSender.java /telegrambots/src/main/java/org/telegram/telegrambots/bots line 802

but i must set java build path to 1.7

Command API

Hello,

I'd like do suggest a command API to handle the commands issued in the platform in a decoupled way. It would work like this:

  1. You register the commands your robot treat
  2. For each command you create a class which handles that command accordingly
  3. All the code will stay contained.

I have done this in my local copy, if you guys would like to see it, I could submit.

Regards.

Unregister/stop a bot session.

Hi. I'm the developer of the open source instant messenger project known as PlanetaMessenger.org and I'm developing a network plugin compatible with Telegram, based on TelegramBots api.

I already have connected with the Telegram host successfully using your bot api, but now I need some way to disconnect from the telegram bot account (stop listening events maybe).

I think that there's no a disconnect or unregister a bot handler, like TelegramBotsApi.unregisterBot(). Am I right ?

If no, please tell me how can I disconnect from telegram account/server.

If disconnecting from Telegram server is not possible today, please tell me if you're planning add tome feature like this on your bot library ?

Thanks in advance.

Slip at the InlineQueryResultVoice.java.

@Override
    public JSONObject toJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(TYPE_FIELD, type);
        jsonObject.put(ID_FIELD, this.id);
        _//        jsonObject.put(**VOICE_DURATION_FIELD**, voiceUrl);_
        jsonObject.put(VOICEURL_FIELD, voiceUrl);
        if (title != null) {
            jsonObject.put(TITLE_FIELD, this.title);
        }
        if (voiceDuration != null) {
            jsonObject.put(VOICE_DURATION_FIELD, voiceDuration);
        }
        if (replyMarkup != null) {
            jsonObject.put(REPLY_MARKUP_FIELD, replyMarkup.toJson());
        }
        if (inputMessageContent != null) {
            jsonObject.put(INPUTMESSAGECONTENT_FIELD, inputMessageContent.toJson());
        }
        return jsonObject;
    }

java.lang.UnsupportedClassVersionError when launching bot

I have added *.jar file to my NetBeans project as library. I have created java file which extends TelegramLongPollingBot. When I launch my main class it throws me this exception:

   java.lang.UnsupportedClassVersionError: org/telegram/telegrambots/TelegramApiException : Unsupported major.minor version 52.0
     at java.lang.ClassLoader.defineClass1(Native Method)
     at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
     at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
     at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
     at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
     at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
     at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
     at java.security.AccessController.doPrivileged(Native Method)
     at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
     at java.lang.Class.getDeclaredMethods0(Native Method)
     at java.lang.Class.privateGetDeclaredMethods(Class.java:2451)
     at java.lang.Class.getMethod0(Class.java:2694)
     at java.lang.Class.getMethod(Class.java:1622)
     at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
     at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Exception in thread "main" Java Result: 1

I'm using JDK 1.7

Java EE

Hi, I'm trying to use telegram api inside an entreprise application.
It is working but there are a lot of problem due to thread generations UpdatesThread.java, because threads conflict with the container.
Is there a way to use your library in java EE or do you know any working implementation?
Thank you

Copy message from other channel

Hi
Sorry,I have a question about your project(telegram).
Can I get the message channels that I'm not their admin?
I want write a script that read message from other chanel and write to
my chanel.
I can do it?
best regards
thanks

InlineKeyboardMarkup usage error.

There is little snippet

                       final List<InlineKeyboardButton> buttons = Arrays.asList(
                new InlineKeyboardButton().setText("DELETE")
                    .setCallbackData("delete"),
                new InlineKeyboardButton().setText("CANCEL")
                    .setCallbackData("cancel"));
            final List<List<InlineKeyboardButton>> keyboard = Arrays
                .asList(buttons);

            return new InlineQueryResultCachedPhoto()
                .setPhotoFileId(picture.getFileId())
                .setId(String.valueOf(System.nanoTime()))
                .setReplyMarkup(
                    new InlineKeyboardMarkup().setKeyboard(keyboard)
                );

Later it's sent like List<InlineQueryResult>.
Without adding of .setReplyMarkup( new InlineKeyboardMarkup().setKeyboard(keyboard) ) it works fine.
With InlineKeyboardMarkup i receives TelegramResponse: Bad request: Field "reply_markup" must be of type Object

Complete answer as Json
{"inline_query_id":"SOME_ID","results":[{"photo_file_id":"SOME_ID","id":"SOME_ID","type":"photo","reply_markup":"InlineKeyboardMarkup{inline_keyboard=[[InlineKeyboardButton{text=DELETE, url=null, callbackData=delete, switchInlineQuery=null}, InlineKeyboardButton{text=CANCEL, url=null, callbackData=cancel, switchInlineQuery=null}]]}"}]}

any simpe exampe to work with GetChatAdministrators

Hello i looking for simple example to work with GetChatAdministrators , when i use this class like this
GetChatAdministrators getAmins = new GetChatAdministrators();

                getAmins.deserializeResponse();

it want a jsonObject , which jsonObjec ??

Write Error in KickChatMember.class

at the class
src/main/java/org/telegram/telegrambots/api/methods/groupadministration/KickChatMember.java

@OverRide
public String toString() {
return "SendMessage{" +
"chatId='" + chatId + ''' +
", userId='" + userId +
'}';
}

here is a write error i think?

is should be?
" '}";

Some exceptions are only logged into a file, but not into the logger

see lines

public static void severe(String tag, Throwable throwable) {
logToFile(Level.SEVERE, tag, throwable);
}
public static void warning(String tag, Throwable throwable) {
logToFile(Level.WARNING, tag, throwable);
}
public static void info(String tag, Throwable throwable) {
logToFile(Level.INFO, tag, throwable);
}
public static void config(String tag, Throwable throwable) {
logToFile(Level.CONFIG, tag, throwable);
}
public static void fine(String tag, Throwable throwable) {
logToFile(Level.FINE, tag, throwable);
}
public static void finer(String tag, Throwable throwable) {
logToFile(Level.FINER, tag, throwable);
}
public static void finest(String tag, Throwable throwable) {
logToFile(Level.FINEST, tag, throwable);
}

is this on purpose or just a copy/paste error?

Logger

May be it would be better to use a more abstract entity for logging? I just use my logger and current static instance writes not that it is necessary...

Can't send photo

I try send new photo.
But receive error from server: {"ok":false,"error_code":400,"description":"[Error]: Photo has unsupported extension. Use one of .jpg, .jpeg, .gif, .png, .tif or .bmp"}
I use jpg image.

sendPhoto fails to return resulting json

Greetings,
the following code snippet from the bottom of AbsSender::sendPhoto method fails to create new Message object.

JSONObject jsonObject1 = new JSONObject(responseContent);
        if(!jsonObject1.getBoolean("ok")) {
            throw new TelegramApiException("Error at sendPhoto", jsonObject1.getString("description"));
        } else {
            return new Message(jsonObject1);
        }
public Message(JSONObject jsonObject) {
        this.messageId = Integer.valueOf(jsonObject.getInt("message_id"));
        if(jsonObject.has("from")) {
            this.from = new User(jsonObject.getJSONObject("from"));
        }

the Message constructor is reading json wrong (there are 2 top level fields: ok and result), have to jsonObject.getJSONObject("result") first

No proper documentation about custom keyboards

In Node.js library that works with TelegramBot, in order to create Keyboard I needed to create JSON like object:

  {
    reply_markup: JSON.stringify({
        keyboard: [["Button 1", "Button2"], ["Button 3", "Button4"]],
        one_time_keyboard: true,
        resize_keyboard: true,
        force_reply: true
    }),
    parse_mode: 'HTML'
  }

This will be passed as options parameters to sendMessage method.

In this Java library there are multiple classes about keyboard and it is hard to understand how to use each of them.

Heroku Port issue

After deployment my bot with TelegramBots java sdk on heroku, app work fine, but after 90 second it's crashed with log:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. How i can switch listener like this (js telegram sdk):
.listen(process.env.PORT || 5000)
I can get port from env in java like System.getenv("PORT") but can't find where to put it in TelegramBots sdk.

Strange Exception including the jar in a Spring MVC Project

Hi,
I'm developing a Spring MVC Application and I have included your library in my POM with Maven:

<dependency>
  <groupId>com.github.rubenlagus</groupId>
  <artifactId>TelegramBots</artifactId>
  <version>v1.0</version>
  <type>jar</type>
</dependency>

It works fine (I tested sendMessage and LongPolling), but I have a very strange behavior when glassfish hot redeploy my application after a manual save to apply a code modification in my java classes. This is the stacktrace of the exception:

Warning:   Error invoking requestInitialized method on ServletRequestListener org.jboss.weld.servlet.WeldListener
org.jboss.weld.exceptions.IllegalStateException: WELD-000227: Bean identifier index inconsistency detected - the distributed container probably does not work with identical applications
Expected hash: 422265265
Current index: BeanIdentifierIndex [hash=-141639221, indexed=20]:
   0: WELD%AbstractBuiltInBean%WEB-INF/lib/hk2-api-2.4.0-b31%HttpSession
   1: WELD%AbstractBuiltInBean%WEB-INF/lib/hk2-locator-2.4.0-b31%HttpSession
   2: WELD%AbstractBuiltInBean%WEB-INF/lib/jersey-common-2.22.1%HttpSession
   3: WELD%AbstractBuiltInBean%WEB-INF/lib/jersey-entity-filtering-2.22.1%HttpSession
   4: WELD%AbstractBuiltInBean%WEB-INF/lib/jersey-media-jaxb-2.22.1%HttpSession
   5: WELD%AbstractBuiltInBean%WEB-INF/lib/jersey-media-json-jackson-2.22.1%HttpSession
   6: WELD%AbstractBuiltInBean%WEB-INF/lib/jersey-server-2.22.1%HttpSession
   7: WELD%AbstractBuiltInBean%acceleratori%HttpSession
   8: WELD%AbstractBuiltInBean%com.ibm.jbatch.container.cdi.BatchCDIInjectionExtension%HttpSession
   9: WELD%AbstractBuiltInBean%com.sun.faces.flow.FlowDiscoveryCDIExtension%HttpSession
  10: WELD%AbstractBuiltInBean%com.sun.jersey.server.impl.cdi.CDIExtension%HttpSession
  11: WELD%AbstractBuiltInBean%org.glassfish.cdi.transaction.TransactionalExtension%HttpSession
  12: WELD%AbstractBuiltInBean%org.glassfish.jersey.ext.cdi1x.internal.CdiComponentProvider%HttpSession
  13: WELD%AbstractBuiltInBean%org.glassfish.jersey.ext.cdi1x.servlet.internal.CdiExternalRequestScopeExtension%HttpSession
  14: WELD%AbstractBuiltInBean%org.glassfish.jersey.ext.cdi1x.transaction.internal.TransactionalExceptionInterceptorProvider%HttpSession
  15: WELD%AbstractBuiltInBean%org.glassfish.jms.injection.JMSCDIExtension%HttpSession
  16: WELD%AbstractBuiltInBean%org.glassfish.osgicdi.impl.OSGiServiceExtension%HttpSession
  17: WELD%AbstractBuiltInBean%org.glassfish.sse.impl.ServerSentEventCdiExtension%HttpSession
  18: WELD%AbstractBuiltInBean%org.hibernate.validator.internal.cdi.ValidationExtension%HttpSession
  19: WELD%AbstractBuiltInBean%root_acceleratori%HttpSession
    at org.jboss.weld.context.http.HttpSessionContextImpl.checkBeanIdentifierIndexConsistency(HttpSessionContextImpl.java:88)
    at org.jboss.weld.context.http.HttpSessionContextImpl.associate(HttpSessionContextImpl.java:42)
    at org.jboss.weld.context.http.HttpSessionContextImpl.associate(HttpSessionContextImpl.java:19)
    at org.jboss.weld.servlet.HttpContextLifecycle.requestInitialized(HttpContextLifecycle.java:217)
    at org.jboss.weld.servlet.WeldInitialListener.requestInitialized(WeldInitialListener.java:167)
    at org.apache.catalina.core.StandardContext.fireRequestInitializedEvent(StandardContext.java:5257)
    at org.apache.catalina.core.StandardHostValve.preInvoke(StandardHostValve.java:655)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:166)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

After this error my application stops working and I have to restart my server. It happens also if I include only the jar in my pom, without write any code that use the library. It works properly at the first time that my server starts and it crashes after the second HOT REDEPLOY.

Can you help me please? Thank you a lot.

Question on retrieving files.

I want to be able to save received photos to the disk where my Bot is running, but I honestly don't where to start on getting the file path to download from the server.

editMessageText command returned Empty Message

Hello everybody! Thank you for the excellent library :)

editMessageText command returned Message object:

Message{messageId=null, from=null, date=null, chat=null, forwardFrom=null, forwardFromChat=null, forwardDate=null, text='null', audio=null, document=null, photo=null, sticker=null, video=null, contact=null, location=null, venue=null, newChatMember=null, leftChatMember=null, newChatTitle='null', newChatPhoto=null, deleteChatPhoto=null, groupchatCreated=null, replyToMessage=null, voice=null, caption=null, superGroupCreated=null, channelChatCreated=null, migrateToChatId=null, migrateFromChatId=null, editDate=null}

Why is this so?
Thanks.

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.