Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev: Implemented http proxy authorization #435

Merged
merged 4 commits into from Apr 19, 2018
Merged

Conversation

bvn13
Copy link
Contributor

@bvn13 bvn13 commented Apr 16, 2018

Usage example:

        try {
            ApiContextInitializer.init();

            // Create the TelegramBotsApi object to register your bots
            TelegramBotsApi botsApi = new TelegramBotsApi();

            DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);
            if (NEED_AUTHORIZATION) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT),
                        new UsernamePasswordCredentials(PROXY_USER, PROXY_USER_PASS));

                HttpHost httpHost = new HttpHost(PROXY_HOST, PROXY_PORT);

                RequestConfig requestConfig = RequestConfig.custom().setProxy(httpHost).setAuthenticationEnabled(true).build();
                botOptions.setRequestConfig(requestConfig);
                botOptions.setCredentialsProvider(credsProvider);
                botOptions.setHttpProxy(httpHost);
            }

            // Register your newly created AbilityBot
            TelegramBot bot = new TelegramBot(TOKEN, BOT_NAME, botOptions);
            botsApi.registerBot(bot);

            //session.setOptions(botOptions);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }

@codecov-io
Copy link

codecov-io commented Apr 16, 2018

Codecov Report

Merging #435 into dev will decrease coverage by 0.32%.
The diff coverage is 36.36%.

Impacted file tree graph

@@             Coverage Diff              @@
##                dev     #435      +/-   ##
============================================
- Coverage     13.99%   13.66%   -0.33%     
  Complexity      355      355              
============================================
  Files           175      176       +1     
  Lines          6230     6240      +10     
  Branches        607      609       +2     
============================================
- Hits            872      853      -19     
- Misses         5251     5283      +32     
+ Partials        107      104       -3
Impacted Files Coverage Δ Complexity Δ
...gram/telegrambots/bots/TelegramLongPollingBot.java 25% <0%> (ø) 3 <0> (ø) ⬇️
...telegram/telegrambots/bots/TelegramWebhookBot.java 0% <0%> (ø) 0 <0> (ø) ⬇️
...g/telegram/telegrambots/bots/DefaultAbsSender.java 2.88% <100%> (-0.93%) 2 <0> (ø)
...legrambots/updatesreceivers/DefaultBotSession.java 57.5% <100%> (-10.19%) 11 <0> (ø)
.../telegram/telegrambots/bots/DefaultBotOptions.java 28.57% <16.66%> (-12.34%) 5 <1> (-1)
...grambots/facilities/TelegramHttpClientBuilder.java 41.66% <41.66%> (ø) 1 <1> (?)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9adb392...2930f50. Read the comment docs.

protected CloseableHttpClient createHttpClient() {
CloseableHttpClient localClient = null;

if (options.getCredentialsProvider() != null) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why such order?

if(not null) {
} else (not not null) {
}

in my opinion is more difficult to understand than

if(null){
} else (not null) {
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As for me it does not matter.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if it was

if (not null) {}
else if (null) {}

@vellrya
Copy link

vellrya commented Apr 17, 2018

@bvn13 получилось авторизоваться, но при попытке отправки сообщения получаю следующую ошибку

Буду благодарен за любую помощь)

org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute sendmessage method
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
	at org.telegram.telegrambots.bots.AbsSender.sendMessage(AbsSender.java:64)
	at Galla2.newsCheck(Galla2.kt:201)
	at Galla2$onUpdateReceived$1.doResume(Galla2.kt:56)
	at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
	at kotlinx.coroutines.experimental.DispatchTask.run(CoroutineDispatcher.kt:123)
	at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1402)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to api.telegram.org:443 [api.telegram.org/149.154.167.220] failed: Connection timed out: connect
	at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
	at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendHttpPostRequest(DefaultAbsSender.java:737)
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendMethodRequest(DefaultAbsSender.java:733)
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:688)
	... 10 more
Caused by: java.net.ConnectException: Connection timed out: connect
	at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
	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:339)
	at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
	... 22 more

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 17, 2018

@vellrya попробуйте использовать этот прокси в браузере и в десктопном клиенте телеграма. у меня есть ощущение, что прокси не работает

in english: Try to use your proxy server outside of telegram bot (i.e. browser or desktop telegram client). Seems it does not work correctly at all.

@vellrya
Copy link

vellrya commented Apr 17, 2018

@bvn13 можно ли как-то связаться с вами в телеграме, пожалуйста? Мой ник: @ryazantsev_val
Хотелось бы увидеть пример использования, потому что так, как вы указали в описании, запустить бота не получилось

@rubenlagus
Copy link
Owner

Please, keep discussion in English.

@Bogus-Coder
Copy link

What about socks5-proxy support?

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 18, 2018

@Bogus-Coder I didn't find a glue for easiest using socks5-proxy yet.

@dygy
Copy link

dygy commented Apr 18, 2018

What about some Tor?)

@carlopantaleo
Copy link

@bvn13 What if a proxy doesn't need authorisation? May one just skip setting the CredentialProvider?

// botOptions.setCredentialsProvider(credsProvider);
botOptions.setHttpProxy(httpHost);

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@carlopantaleo yes, just skip it. Here is an example

ApiContextInitializer.init();

// Create the TelegramBotsApi object to register your bots
TelegramBotsApi botsApi = new TelegramBotsApi();

// Set up Http proxy
DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);

HttpHost httpHost = new HttpHost(PROXY_HOST, PROXY_PORT);

RequestConfig requestConfig = RequestConfig.custom().setProxy(httpHost).setAuthenticationEnabled(false).build();
botOptions.setRequestConfig(requestConfig);
botOptions.setHttpProxy(httpHost);

// Register your newly created AbilityBot
MyBot bot = new MyBot(BOT_TOKEN, BOT_NAME, botOptions);

botsApi.registerBot(bot);

@umihesh
Copy link

umihesh commented Apr 19, 2018

Maybe it's a stupid question, but I'm new to GitHub, so could you please explain, how I can add your implementation to my project?

I guess, I should somehow add the dev branch to the project, but really don't know how.

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@TGhnS if you are russian, you could read my article here https://bvn13.tk/posts/java-telegram-bot-using-http-proxy

otherwise, you may clone my repo https://github.com/bvn13/TelegramBots, build and install it with maven mvn install. And use it
for maven:

 <!--TelegramAPI-->
    <dependency>
        <groupId>org.telegram</groupId>
        <artifactId>telegrambots-abilities</artifactId>
        <version>3.6</version>
    </dependency>

or gradle:

    // telegram bot api
    compile 'org.telegram:telegrambots:3.6'

Note to change priority of repos in gradle - local must be first:

repositories {
    mavenLocal()
    mavenCentral()
    jcenter()
}

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
   }
}

@dygy
Copy link

dygy commented Apr 19, 2018

botOptions.setHttpProxy(httpHost);
can't resolve setHttpProxy . Can you help me?

@dygy
Copy link

dygy commented Apr 19, 2018

and I really like to see some examples of the full main method. It might be some of my mistakes. Thx for helping,

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@dygy You didn't use my repo. Check my explanation above.

  1. use my repo
  2. build and install TelegramBots from my repo
  3. make sure you use it in your project

@dygy
Copy link

dygy commented Apr 19, 2018

compile 'org.telegram:telegrambots:3.6'
compile group: 'org.telegram', name: 'telegrambots', version: '3.6'
is here any diffrence? And it's still same problem with both.

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@dygy it's the same for gradle. Check if gradle use it. Place mavenLocal() on top of repolist:

repositories {
    mavenLocal()
    mavenCentral()
    jcenter()
}

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
   }
}

@dygy
Copy link

dygy commented Apr 19, 2018

still
Error:(28, 23) java: cannot find symbol symbol: method setHttpProxy(org.apache.http.HttpHost) location: variable botOptions of type org.telegram.telegrambots.bots.DefaultBotOptions

@rubenlagus rubenlagus self-requested a review April 19, 2018 10:43
@rubenlagus rubenlagus added this to the v3.6.1 milestone Apr 19, 2018
@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@rubenlagus should I write a wiki page for using proxy?

@rubenlagus
Copy link
Owner

@bvn13 If you write it, it would be great. You can add the changes to this pull request and I'll merge them together with the release.

My idea is to merge everything today and get the version ready (today or tomorrow)

@umihesh
Copy link

umihesh commented Apr 19, 2018

Thank you, it works

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@rubenlagus I wrote and added wiki page, but I actually don't know if it would be linked correctly into sidebar. Could you check it?

@jakeostis
Copy link

jakeostis commented Apr 19, 2018

for those who encountered difficulties due to blocking Telegram in Russia - you can try to register your implemented bot with this proxy settings (for socks5 protocol):

System.getProperties().put( "socksProxyHost", "host" );
System.getProperties().put( "socksProxyPort", "port" );

if proxy server requires authentication add:

    Authenticator.setDefault(new Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication("username", "password".toCharArray());
        }
    });

this method is not flexible, but in some cases it can be useful (my case).

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 19, 2018

@jakeostis what if my bot works with other services placed in local network? I want my bot to use a proxy only for telegram servers, not for my local network or other services.

@dygy
Copy link

dygy commented Apr 19, 2018

last one gives me 1000000000000000000 errors but worked :D

@jakeostis
Copy link

@bvn13 i absolutely agree. i have edited my comment. Hence, this solution is not flexible for everyone and implementation proxy in code will be much better

@IgnatBeresnev
Copy link

@jakeostis @bvn13 I'm sure you don't have to set the system property to get it working. Try running your app with java ... -DsocksProxyHost=host -DsocksProxyPort=port

@bvn13
Copy link
Contributor Author

bvn13 commented Apr 23, 2018

@IgnatBeresnev I'm sure it will work, but I don't need to push all the traffic of my bot application into socks5 proxy. I need to use proxy only for bot. Not for local network for instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

10 participants