Telegramapirequestexception error removing old webhook

so I do long polling bot with 3.6.1 not even hello world one my bot class is public class My_Bot extends TelegramLongPollingBot { @Override public void onUpdateReceived(Update update) { } @Override...

@dygy

so I do long polling bot with 3.6.1
not even hello world one
my bot class is

public class My_Bot extends TelegramLongPollingBot {
    @Override
public void onUpdateReceived(Update update) {
}
    @Override
    public String getBotUsername() {
        return "";
    }
    @Override
    public String getBotToken() {
        return "";        
    }
}

and my main

public class Main {
    public static void main(String[] args) {
        try {
            ApiContextInitializer.init();
            TelegramBotsApi botsApi = new TelegramBotsApi();
            botsApi.registerBot((LongPollingBot) new My_Bot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

say to run and get

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
	at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
	at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
	at Main.main(Main.java:14)
Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
	at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)
	at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27)

It all means???

@dygy

not been so negative, going to try ability bot.
so main is

public class Main {
private static String botToken ="";
    private static String botName ="";
    public static void main(String[] args) {
        ApiContextInitializer.init();
        TelegramBotsApi botsApi = new TelegramBotsApi();
        DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);
        try {
            My_Bot AbilityBot = new My_Bot(botToken,botName,botOptions);
            botsApi.registerBot(AbilityBot);

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

and my bot class is

public class My_Bot extends AbilityBot {


    protected My_Bot(String botToken, String botUsername,
                        DefaultBotOptions botOptions) {
        super(botToken, botUsername, botOptions);
    }

    @Override
    public int creatorId() {
        return 12345678;
    }
    public Ability sayHelloWorld() {
        return Ability
                .builder()
                .name("hello")
                .info("says hello world!")
                .locality(ALL)
                .privacy(PUBLIC)
                .action(ctx -> silent.send("Hello world!", ctx.chatId()))
                .build();
    }
}

getting same

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
	at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
	at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
	at Main.main(Main.java:14)

what it means also???

@dygy

my gradle is

version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.telegram', name: 'telegrambots-abilities', version: '3.6.1'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.telegram', name: 'telegrambots', version: '3.6.1'
}

@rubenlagus

@dygy It is a problem executing deleteWebhook method, in a full stacktrace, there should be a new cause for this exception:

Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method

can you get it?

@dygy

@rubenlagus here is
org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27
on line
botsApi.registerBot((LongPollingBot) new My_Bot());

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
	at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
	at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
	at Main.main(Main.java:13)
Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method
	at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
	at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)
	at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27
)
	... 2 more
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)
	... 4 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)
	... 16 more
Exception in thread "main" java.lang.NullPointerException
	at Main.mash(Main.java:23)
	at Main.crunch(Main.java:20)
	at Main.main(Main.java:16)

Process finished with exit code 1

Not sure how to see «more» in IDEA or anywhere at this moment.
Will past if i will get how.

@rubenlagus

Caused by: java.net.ConnectException: Connection timed out: connect

This error means that there is a problem connecting to Telegram servers from yours. More exactly to reach [api.telegram.org/149.154.167.220], maybe you can check if there is something preventing it to reach (firewalls, slow connection, etc).

@dygy

@rubenlagus it’s blocked, as you might know. But if i will get a normal proxy, it would help to escape from webhook error?

@bvn13

@dygy yes, set up working proxy

@dygy

is it the normal way to set it up?
public class Main {

  private static String BOT_NAME = "My test bot";
   private static String BOT_TOKEN = "" /* your bot's token here */;

   private static String PROXY_HOST = "" /* proxy host */;
   private static Integer PROXY_PORT = /* proxy port */;
   private static String PROXY_USER = "" /* proxy user */;
   private static String PROXY_PASSWORD = "" /* proxy password */;

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

           ApiContextInitializer.init();

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

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

           CredentialsProvider credsProvider = new BasicCredentialsProvider();
           credsProvider.setCredentials(
                   new AuthScope(PROXY_HOST, PROXY_PORT),
                   new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

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

           botsApi.registerBot((LongPollingBot) new Bot());
       } catch (TelegramApiException e) {
           e.printStackTrace();
       }
   }
}

@dygy

okay, last words for this. For everybody who uses long polling bot and also have problems, the situation with constructor I made like this

  protected My_Bot(DefaultBotOptions options) {
        super(options);

so creating bot is like this
botsApi.registerBot((LongPollingBot) new IiPPO_Bot(botOptions));
and it’s all working for me. Thx for help @rubenlagus and @bvn13 .

@chenhaonan-eth

Hello, do you still have the original code of this problem? I also met the same problem with you, I tried to solve it, but unfortunately I did not solve it. If you still have this code, could you please send it to me?Thank you for your email tomcat.yoyoyo@gmail.com

@drundanibel

I’m facing the same problem right now. My bot and main classes look almost the same as the ones in dygy’s first post above.

I get errors like org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error removing old webhook [...] and Caused by: org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error deleting webhook: [404] Not Found [...]

For the moment I would like to realize only a minimal setup: I’m already using my Telegram bot to automatically send (screenshot) messages to different chats with MS PowerShell and curl when our GUI tests fail. I would now like to switch this simple scenario to TelegramBots so that we can gradually equip the bot with more intelligence in the future.

But what is the specific problem with this «old webhook», which I don’t need yet, because I don’t have to listen to user actions yet?

@dygy

My problem was about connection to telegram servers. So it was because of blocks, and I solve it by these things I wrote before theme get closed. There was also a solution to put a proxy inside System Properties.

I wasn’t sure, but old webhook isn’t really about reactions for user actions. I had this error too, and it was different, and it throws only after user trying to get smth from your bot.

@dygy

About System Properties, it wasn’t really good solution, because it makes you use proxy from entire project, while you maybe don’t need a proxy for you MongoDB, for some other networks working with your bot, etc.

@kilinochi

btw, if you from Russia or another country where Telegram is blocked

You can also do this
Don’t forget open TorBrowser
image

@dygy

I just wrote it 21 Dec, that this type of solutions not really cool for enterprise. I do not use tor for a long time. In my country it’s illegal for proxy businessmens, not for users.

@kilinochi

окей, надеюсь, тут по-русски можно писать, лол
Если честно, я попытался сделать все как ты писал, но у меня почему-то не зашло
Мой метод может и выглядит коряво, но если не выпускать код дальше своего репозитория, то, в принципе, ничего страшного и не будет
Если есть какие-то особенности, или я что-то упустил, дай свои контакты, или чиркани сюда -psvm_16

@uPagge

@kilinochi тоже пытаюсь сделать как он пишет, нифига не выходит

@grigory-lobkov

@kilinochi Thanks for advice! Now it work’s!
Code for copy-past to main() method:

    System.getProperties().put("proxySet", "true");

    System.getProperties().put("socksProxyHost", "127.0.0.1");

    System.getProperties().put("socksProxyPort", "9150");

Содержание

  1. Error Removing Old Webhook #447
  2. Comments
  3. 502 Bad Gateway
  4. removing old webhook #442
  5. Comments
  6. Footer
  7. Deleting messages #555
  8. Comments
  9. Footer
  10. TelegramBot инструкция по созданию базового функционала для бота. (Часть 1)
  11. Создаем стандартный maven проект
  12. Log4j
  13. И в заключение

Error Removing Old Webhook #447

Hi, Having some problems with removing oldwebhook out of the blue. I am using TelegramLongPollingBot, my bot which has its own set of test cases passes but I am unable to register the bot to the TelegramBotsApi

This is the error message:

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)

[telegrambots-3.6.1.jar:?]
at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)

[telegrambots-meta-3.6.1.jar:?]
at main.Main.main(Main.java:34) [bin/:?]
Caused by: org.telegram.telegrambots.exceptions.TelegramApiRequestException: Unable to deserialize response
at org.telegram.telegrambots.api.methods.updates.DeleteWebhook.deserializeResponse(DeleteWebhook.java:43)

[telegrambots-meta-3.6.1.jar:?]
at org.telegram.telegrambots.api.methods.updates.DeleteWebhook.deserializeResponse(DeleteWebhook.java:19)

[telegrambots-meta-3.6.1.jar:?]
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:689)

[telegrambots-3.6.1.jar:?]
at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)

[telegrambots-meta-3.6.1.jar:?]
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27)

[telegrambots-3.6.1.jar:?]
. 2 more
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character (‘ 502 Bad Gateway

502 Bad Gateway

[jackson-core-2.8.7.jar:2.8.7] at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:558)

[jackson-core-2.8.7.jar:2.8.7] at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:456)

[jackson-core-2.8.7.jar:2.8.7] at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._handleOddValue(ReaderBasedJsonParser.java:1906)

[jackson-core-2.8.7.jar:2.8.7] at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextToken(ReaderBasedJsonParser.java:749)

[jackson-core-2.8.7.jar:2.8.7] at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3834)

[jackson-databind-2.8.7.jar:2.8.7] at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3783)

[jackson-databind-2.8.7.jar:2.8.7] at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2861)

[jackson-databind-2.8.7.jar:2.8.7] at org.telegram.telegrambots.api.methods.updates.DeleteWebhook.deserializeResponse(DeleteWebhook.java:35)

[telegrambots-meta-3.6.1.jar:?] at org.telegram.telegrambots.api.methods.updates.DeleteWebhook.deserializeResponse(DeleteWebhook.java:19)

[telegrambots-meta-3.6.1.jar:?] at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:689)

[telegrambots-3.6.1.jar:?] at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)

[telegrambots-meta-3.6.1.jar:?] at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27)

[telegrambots-3.6.1.jar:?] . 2 more

and the relevant code is as below:

public static void main(String[] args) <
logger.info(«Enable trust for SSL»);
WebController.trustAll();
logger.info(«Initializing ApiContextInitializer (required for Telegram bot API)»);
ApiContextInitializer.init();

with my extended longpollingbot:

The same code has been working up till today, please help!

The text was updated successfully, but these errors were encountered:

Источник

removing old webhook #442

so I do long polling bot with 3.6.1
not even hello world one
my bot class is

say to run and get

The text was updated successfully, but these errors were encountered:

not been so negative, going to try ability bot.
so main is

and my bot class is

public class My_Bot extends AbilityBot <

what it means also.

@dygy It is a problem executing deleteWebhook method, in a full stacktrace, there should be a new cause for this exception:

Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method

@rubenlagus here is
org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27
on line
botsApi.registerBot((LongPollingBot) new My_Bot());

Not sure how to see «more» in IDEA or anywhere at this moment.
Will past if i will get how.

Caused by: java.net.ConnectException: Connection timed out: connect

This error means that there is a problem connecting to Telegram servers from yours. More exactly to reach [api.telegram.org/149.154.167.220] , maybe you can check if there is something preventing it to reach (firewalls, slow connection, etc).

@rubenlagus it’s blocked, as you might know. But if i will get a normal proxy, it would help to escape from webhook error?

@dygy yes, set up working proxy

is it the normal way to set it up?
public class Main <

okay, last words for this. For everybody who uses long polling bot and also have problems, the situation with constructor I made like this

so creating bot is like this
botsApi.registerBot((LongPollingBot) new IiPPO_Bot(botOptions));
and it’s all working for me. Thx for help @rubenlagus and @bvn13 .

Hello, do you still have the original code of this problem? I also met the same problem with you, I tried to solve it, but unfortunately I did not solve it. If you still have this code, could you please send it to me?Thank you for your email tomcat.yoyoyo@gmail.com

I’m facing the same problem right now. My bot and main classes look almost the same as the ones in dygy’s first post above.

I get errors like org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error removing old webhook [. ] and Caused by: org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error deleting webhook: [404] Not Found [. ]

For the moment I would like to realize only a minimal setup: I’m already using my Telegram bot to automatically send (screenshot) messages to different chats with MS PowerShell and curl when our GUI tests fail. I would now like to switch this simple scenario to TelegramBots so that we can gradually equip the bot with more intelligence in the future.

But what is the specific problem with this «old webhook», which I don’t need yet, because I don’t have to listen to user actions yet?

My problem was about connection to telegram servers. So it was because of blocks, and I solve it by these things I wrote before theme get closed. There was also a solution to put a proxy inside System Properties.

I wasn’t sure, but old webhook isn’t really about reactions for user actions. I had this error too, and it was different, and it throws only after user trying to get smth from your bot.

About System Properties, it wasn’t really good solution, because it makes you use proxy from entire project, while you maybe don’t need a proxy for you MongoDB, for some other networks working with your bot, etc.

btw, if you from Russia or another country where Telegram is blocked

You can also do this
Don’t forget open TorBrowser

I just wrote it 21 Dec, that this type of solutions not really cool for enterprise. I do not use tor for a long time. In my country it’s illegal for proxy businessmens, not for users.

окей, надеюсь, тут по-русски можно писать, лол
Если честно, я попытался сделать все как ты писал, но у меня почему-то не зашло
Мой метод может и выглядит коряво, но если не выпускать код дальше своего репозитория, то, в принципе, ничего страшного и не будет
Если есть какие-то особенности, или я что-то упустил, дай свои контакты, или чиркани сюда -psvm_16

@kilinochi тоже пытаюсь сделать как он пишет, нифига не выходит

@kilinochi Thanks for advice! Now it work’s!
Code for copy-past to main() method:

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Deleting messages #555

I am trying to delete a message using my bot in a direct message, and I get this error:
org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error deleting message: [400] Bad Request: message can’t be deleted
at org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage.deserializeResponse(DeleteMessage.java:95)
at org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage.deserializeResponse(DeleteMessage.java:26)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:717)
at org.telegram.telegrambots.meta.bots.AbsSender.execute(AbsSender.java:47)
at hamhub7.seversonbot.Bot.onUpdateReceived(Bot.java:170)
at java.util.ArrayList.forEach(Unknown Source)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:305)
Dec 01, 2018 12:00:06 AM org.telegram.telegrambots.meta.logging.BotLogger severe
SEVERE: BOTSESSION
java.lang.NullPointerException
at hamhub7.seversonbot.Bot.onUpdateReceived(Bot.java:23)
at java.util.ArrayList.forEach(Unknown Source)
at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:305)

It seems like the bot does not have enough permissions, but I am not sure how to add them. Can I have the bot automatically request permissions? Can I add them through @Botfather? Where do I go from here?

The text was updated successfully, but these errors were encountered:

Upon further inspection, I found that disabling the «All memebers are admin» in my group then checking my bot allows it to delete the message. I want to know now if that is possible in dms, and if that process can be automated

You can’t delete messages of ther other user in DMs
Also, for your bot to be able to delete messages in groups, your bot has to be admin in that group. I think the «all members are admin» does not allow all members to delete messages from every user.

Is this question answered? @hamhub7

I think this issue can be closed since no activity
@rubenlagus

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

TelegramBot инструкция по созданию базового функционала для бота. (Часть 1)

Не так давно я предложил вам воспользоваться моим ботом для телеграмма.

Получив много вопросов в личку, я понял, что вопрос создания ботов для Телеграм довольно популярен.

У меня спрашивали исходный код бота, просили поделиться конкретными примерами реализации тех или иных возможностей бота, просили подсказать тот или иной функционал по работе с ботом и сообщениями.

Я решил написать цикл статей, в которых хочу показать базовые вещи, которые будут нужны вам для написания своего бота.
Вас ждет Java, Maven, TelegramAPI, Lombok и Log4j.
Кому интересно — прошу под кат…

И сразу с козырей зайду 🙂

То, о чем просили в предыдущей статье.

Исходные коды по проекту вы можете найти тут .

В ветке «master» будет финальная версия бота, которого мы вместе с вами и напишем, в процессе появления новых статей.

Полный исходники по этой статье будет находится в ветке «Part1-Base».

В данной части мы создадим с вами базовый шаблон, который способен будет:

  1. регистрировать бота на серверах Телеграмм
  2. получать сообщения, написанные боту
  3. реагировать на команду /start

Создаем стандартный maven проект

(я упущу мануалы по работе со средой разработки и базовые вещи из Java программирования. Все эти вещи достаточно легко гугляться.А если не будет получаться — пишите вопросы).

Давайте посмотрим, какие зависимости нам будут нужны в этом проекте.

В первую очередь это Lombok. Что это и зачем — можно почитать, например, тут.

И обязательно добавим логгер. Я использую log4j и чуть дальше покажу вам как полезно его можно использовать при отладке данного приложения и более глубокого осмысления работы TelegramAPI.

И, т.к. мы пишем бота для Телеграм, то и саму библиотеку от Telegram:

Структуру pom файла можно посмотреть тут
Структуру файла pom.xml можно увидеть тут.

Далее добавляем базовый класс Bot.java, который и будет реализовывать все наше взаимодействие с с сервисами Telegram. Работать мы будем с помощью LongPolling, т.к. этот метод не требует сертификатов шифрования и запускаться может с любой машины, которая имеет Java у себя на борту.

Для этого мы наследуемся от класса TelegramLongPollingBot и реализуем базовые методы:

public void onUpdateReceived(Update update)
public String getBotUsername()
public String getBotToken()

И от себя нам нужно будет добавить процедуру, которая будет подключать наш бот к TelegramAPI:

public void botConnect()

В принципе все. Данный код умеет подключаться к серверам Телеграмм и при получении адресованных ему сообщений будет фиксировать в лог файл информацию, что он получил Update.

Давайте создадим класс, который и будет запускать наше приложение.

Этим займется класс App.java. Ссылка на файл: тут

Как вы видите, для работы бота нам понадобятся только «имя бота» и «токен», которые мы и передадим в конструкторе нашего класса Bot.

Имя и токен для бота вы можете получить у отца всех ботов :), написав ему в телеграмме.
Его ник: @BotFather
Общение с ним очень простое и лаконичное.

В результате у вас должен получиться такой диалог:

Так же здесь пишут, что аккуратнее, никому не показывайте эту информацию, иначе кто-то другой сможет управлять вашим ботом 🙂

Вы скажете, что я не очень аккуратен… Возможно, но отец ботов позволяет нам менять токены и отзывать те, что попали в публичный доступ. Потому с попробовав подключиться с моими данными, вы получите такое сообщение:

Так что с моими данными вам подключиться не получится. Регистрируйте свои. Новые данные укажите в классе App.java

Теперь запустив метод main в классе App мы позволим нашему боту подключиться и ждать новых сообщений. О своих действиях и попытках он напишет нам в консоле.

Log4j

Помните, выше я говорил о полезности библиотеки log4j. И вот тут для любопытных открывается клондайк полезных данных.

В файле log4j.properties уже прописаны базовые настройки для логирования и конкретные уровни логирования для сторонних классов и для тех, которые работают в нашем боте.

Базовый уровень логирования у нас указан как Error.

Для классов Bot и App указан вывод логов на уровне Debug.

Что это за уровни и чем отличаются — вы легко найдете в гугле.

Если хотите посмотреть, как и в каком порядке отрабатывает библиотека Телеграм все ваши действия — переключите режим общего логирования на уровень ниже: info или debug.

И при запуске приложения вы в консоли увидите, сколько всего интересного происходит в процессе подключения, работы. Сколько раз опрашиваются ваши функции с именем и токеном бота.

Уровни логирования меняются вот этой строчкой:
Чтобы получить логи по уровню info, ставите вот так:

Для уровня debug, вот так:

И в заключение

Сейчас у нас бот: подключается, показывает нам красивые логи и сообщает о том, что ему приходят сообщения.

Но выше я вам обещал, что бот будет отзываться на команду старт. Давайте немного изменим процедуру, ответственную за обработку полученных сообщений.

Как видно из кода бот делает следующее:

  • Получает апдейт и фиксирует в лог его айди номер.
  • Достает из переданного сообщения ID чата и собственно текст сообщения
  • Проверяет, не является ли этот текст командой «/start»
  • И в случае успешного сравнения создает сообщение в ответ и отправляет его в чат, с полученным ранее ID

Надеюсь вам было полезно и интересно.

В дальнейшем я покажу вам, как в моих ботах реализуется:

  • использование различных команд
  • привязка этих команд к обработчикам
  • многопоточность: независимое получение и отправка сообщений
  • форматирование отправляемых сообщений
  • работа с кнопками и колбеками
  • редактирование старых сообщений

На этой базе в паблик доступе у меня сейчас работают 2 моих бота.

А второй — Дерзкий киноман. Он очень любит фильмы и очень много о них знает. А еще больше он любит делится с вами своими знаниями. Он ведет свой канал в телеграмме, в котором сам решает, какие фильмы ему нравятся и предлагает их вам. Он умеет формировать индивидуальные подборки по жанрам и создавать подписку на персональные рекомендации. Он умеет находить такие шедевры, о которых вы никогда не слышали и даже не знали как такие фильмы вообще можно найти.

Например, как вы думаете, существуют ли фильмы с такой «дикой» комбинацией жанров, как: документальный, ужасы, комедия.

А вот бот по команде

Скажет, что таких фильмов с 2010 по текущий момент сняли аж 6 штук 🙂

Как работать с подобными командами, как разбирать строки и последовательности команд мы рассмотрим с вами в следующих публикациях.

Спасибо вам за внимание. Программируйте в удовольствие 🙂

Источник

Пытаюсь создать бота для телеграмм. Класс Bot:

public class BotStart extends TelegramLongPollingBot{
    public void onUpdateReceived(Update update) {
        System.out.println(update.getMessage().getFrom().getFirstName()+": "+update.getMessage().getText());
        Message message = update.getMessage();
        if(message!= null && message.hasText()){
            if(message.getText().equals("/help")){
                sendMsg(message,"Привет");
            }
            else{
                sendMsg(message,"Я тест. робот");
            }
        }
    }

    private void sendMsg(Message message, String s) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.enableMarkdown(true);
        sendMessage.setChatId(message.getChatId().toString());
        sendMessage.setReplyToMessageId(message.getMessageId());
        sendMessage.setText(s);
        try {
            sendMessage(sendMessage);
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    public String getBotUsername() {
        return "TeenSpiritBot";
    }

    public String getBotToken() {
        return "TOKEN"; //На самом деле он введен здесь, но я не рискую выкладывать его здесь
    }
}

И так же вот код класса MainClass:

public class MainClass {
    public static void main(String[] args) {
        ApiContextInitializer.init();
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
        BotStart bot = new BotStart();
        try {
            telegramBotsApi.registerBot(bot);
        } catch (TelegramApiRequestException e) {
            e.printStackTrace();
        }
    }
}

Почему при выполнении кода из MainClass я получаю

TelegramApiRequestException: Error removing old webhook

Что я делаю неправильно и как это исправить?

Ниже все логи:

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
at MainClass.main(MainClass.java:11)
Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27)
… 2 more
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)
… 4 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)
… 16 more

I’m writing a telegram of the bot.

org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error removing old webhook

The rest of the logic:

at org.telegram.telegrambots.util.WebhookUtils.clearWebhook(WebhookUtils.java:79)
at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:25)
at org.telegram.telegrambots.meta.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
at Bot.main(Bot.java:28)
Caused by: org.telegram.telegrambots.meta.exceptions.TelegramApiException: Unable to execute deleteWebhook method
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:719)
at org.telegram.telegrambots.meta.bots.AbsSender.execute(AbsSender.java:47)
at org.telegram.telegrambots.util.WebhookUtils.clearWebhook(WebhookUtils.java:74)
... 3 more
Caused by: org.apache.http.conn.ConnectTimeoutException: Connect to api.telegram.org:443 [api.telegram.org/77.241.16.24] failed: Connect timed out
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151)
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.telegram.telegrambots.bots.DefaultAbsSender.sendHttpPostRequest(DefaultAbsSender.java:765)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendMethodRequest(DefaultAbsSender.java:761)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:716)
... 5 more
Caused by: java.net.SocketTimeoutException: Connect timed out
at java.base/java.net.SocksSocketImpl.readSocksReply(Unknown Source)
at java.base/java.net.SocksSocketImpl.connect(Unknown Source)
at java.base/java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:339)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
... 16 more

I use proxy, but it doesn’t.

System.getProperties().put( "proxySet", "true" );
System.getProperties().put( "socksProxyHost", "ip" );
System.getProperties().put( "socksProxyPort", "port" );

so I do long polling bot with 3.6.1
not even hello world one
my bot class is

public class My_Bot extends TelegramLongPollingBot {
    @Override
public void onUpdateReceived(Update update) {
}
    @Override
    public String getBotUsername() {
        return "";
    }
    @Override
    public String getBotToken() {
        return "";        
    }
}

and my main

public class Main {
    public static void main(String[] args) {
        try {
            ApiContextInitializer.init();
            TelegramBotsApi botsApi = new TelegramBotsApi();
            botsApi.registerBot((LongPollingBot) new My_Bot());
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }
}

say to run and get

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
    at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
    at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
    at Main.main(Main.java:14)
Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method
    at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
    at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)
    at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27)

It all means???

All 18 comments

not been so negative, going to try ability bot.
so main is

public class Main {
private static String botToken ="";
    private static String botName ="";
    public static void main(String[] args) {
        ApiContextInitializer.init();
        TelegramBotsApi botsApi = new TelegramBotsApi();
        DefaultBotOptions botOptions = ApiContext.getInstance(DefaultBotOptions.class);
        try {
            My_Bot AbilityBot = new My_Bot(botToken,botName,botOptions);
            botsApi.registerBot(AbilityBot);

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

and my bot class is

public class My_Bot extends AbilityBot {

    protected My_Bot(String botToken, String botUsername,
                        DefaultBotOptions botOptions) {
        super(botToken, botUsername, botOptions);
    }

    @Override
    public int creatorId() {
        return 12345678;
    }
    public Ability sayHelloWorld() {
        return Ability
                .builder()
                .name("hello")
                .info("says hello world!")
                .locality(ALL)
                .privacy(PUBLIC)
                .action(ctx -> silent.send("Hello world!", ctx.chatId()))
                .build();
    }
}

getting same

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
    at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
    at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
    at Main.main(Main.java:14)

what it means also???

my gradle is

version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.telegram', name: 'telegrambots-abilities', version: '3.6.1'
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.telegram', name: 'telegrambots', version: '3.6.1'
}

@dygy It is a problem executing deleteWebhook method, in a full stacktrace, there should be a new cause for this exception:

Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method

can you get it?

@rubenlagus here is
org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27
on line
botsApi.registerBot((LongPollingBot) new My_Bot());

org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error removing old webhook
    at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:32)
    at org.telegram.telegrambots.TelegramBotsApi.registerBot(TelegramBotsApi.java:120)
    at Main.main(Main.java:13)
Caused by: org.telegram.telegrambots.exceptions.TelegramApiException: Unable to execute deleteWebhook method
    at org.telegram.telegrambots.bots.DefaultAbsSender.sendApiMethod(DefaultAbsSender.java:691)
    at org.telegram.telegrambots.bots.AbsSender.execute(AbsSender.java:53)
    at org.telegram.telegrambots.bots.TelegramLongPollingBot.clearWebhook(TelegramLongPollingBot.java:27
)
    ... 2 more
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)
    ... 4 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)
    ... 16 more
Exception in thread "main" java.lang.NullPointerException
    at Main.mash(Main.java:23)
    at Main.crunch(Main.java:20)
    at Main.main(Main.java:16)

Process finished with exit code 1

Not sure how to see «more» in IDEA or anywhere at this moment.
Will past if i will get how.

Caused by: java.net.ConnectException: Connection timed out: connect

This error means that there is a problem connecting to Telegram servers from yours. More exactly to reach [api.telegram.org/149.154.167.220], maybe you can check if there is something preventing it to reach (firewalls, slow connection, etc).

@rubenlagus it’s blocked, as you might know. But if i will get a normal proxy, it would help to escape from webhook error?

@dygy yes, set up working proxy

is it the normal way to set it up?
public class Main {

«`
private static String BOT_NAME = «My test bot»;
private static String BOT_TOKEN = «» /* your bot’s token here */;

private static String PROXY_HOST = "" /* proxy host */;
private static Integer PROXY_PORT = /* proxy port */;
private static String PROXY_USER = "" /* proxy user */;
private static String PROXY_PASSWORD = "" /* proxy password */;

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

        ApiContextInitializer.init();

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

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

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

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

        botsApi.registerBot((LongPollingBot) new Bot());
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

}
«`

okay, last words for this. For everybody who uses long polling bot and also have problems, the situation with constructor I made like this

  protected My_Bot(DefaultBotOptions options) {
        super(options);

so creating bot is like this
botsApi.registerBot((LongPollingBot) new IiPPO_Bot(botOptions));
and it’s all working for me. Thx for help @rubenlagus and @bvn13 .

Hello, do you still have the original code of this problem? I also met the same problem with you, I tried to solve it, but unfortunately I did not solve it. If you still have this code, could you please send it to me?Thank you for your email tomcat.[email protected]

I’m facing the same problem right now. My bot and main classes look almost the same as the ones in dygy’s first post above.

I get errors like org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error removing old webhook [...] and Caused by: org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException: Error deleting webhook: [404] Not Found [...]

For the moment I would like to realize only a minimal setup: I’m already using my Telegram bot to automatically send (screenshot) messages to different chats with MS PowerShell and curl when our GUI tests fail. I would now like to switch this simple scenario to TelegramBots so that we can gradually equip the bot with more intelligence in the future.

But what is the specific problem with this «old webhook», which I don’t need yet, because I don’t have to listen to user actions yet?

My problem was about connection to telegram servers. So it was because of blocks, and I solve it by these things I wrote before theme get closed. There was also a solution to put a proxy inside System Properties.

I wasn’t sure, but old webhook isn’t really about reactions for user actions. I had this error too, and it was different, and it throws only after user trying to get smth from your bot.

About System Properties, it wasn’t really good solution, because it makes you use proxy from entire project, while you maybe don’t need a proxy for you MongoDB, for some other networks working with your bot, etc.

btw, if you from Russia or another country where Telegram is blocked

You can also do this
Don’t forget open TorBrowser
image

I just wrote it 21 Dec, that this type of solutions not really cool for enterprise. I do not use tor for a long time. In my country it’s illegal for proxy businessmens, not for users.

окей, надеюсь, тут по-русски можно писать, лол
Если честно, я попытался сделать все как ты писал, но у меня почему-то не зашло
Мой метод может и выглядит коряво, но если не выпускать код дальше своего репозитория, то, в принципе, ничего страшного и не будет
Если есть какие-то особенности, или я что-то упустил, дай свои контакты, или чиркани сюда -psvm_16

@kilinochi тоже пытаюсь сделать как он пишет, нифига не выходит

@kilinochi Thanks for advice! Now it work’s!
Code for copy-past to main() method:

    System.getProperties().put("proxySet", "true");

    System.getProperties().put("socksProxyHost", "127.0.0.1");

    System.getProperties().put("socksProxyPort", "9150");

Was this page helpful?

0 / 5 — 0 ratings

Java, API


Рекомендация: подборка платных и бесплатных курсов 3D max — https://katalog-kursov.ru/

Не так давно я предложил вам воспользоваться моим ботом для телеграмма.

Telegram Bot — помощник в планировании мероприятий

Получив много вопросов в личку, я понял, что вопрос создания ботов для Телеграм довольно популярен.

У меня спрашивали исходный код бота, просили поделиться конкретными примерами реализации тех или иных возможностей бота, просили подсказать тот или иной функционал по работе с ботом и сообщениями.

Я решил написать цикл статей, в которых хочу показать базовые вещи, которые будут нужны вам для написания своего бота. Кому интересно — прошу под кат…

И сразу с козырей зайду :)

То, о чем просили в предыдущей статье.

Исходные коды по проекту вы можете найти тут .

В ветке «master» будет финальная версия бота, которого мы вместе с вами и напишем, в процессе появления новых статей.

Полный исходники по этой статье будет находится в ветке «Part1-Base».

В данной части мы создадим с вами базовый шаблон, который способен будет:

  1. регистрировать бота на серверах Телеграмм
  2. получать сообщения, написанные боту
  3. реагировать на команду /start

Создаем стандартный maven проект

(я упущу мануалы по работе со средой разработки и базовые вещи из Java программирования. Все эти вещи достаточно легко гугляться.А если не будет получаться — пишите вопросы).

Давайте посмотрим, какие зависимости нам будут нужны в этом проекте.

В первую очередь это Lombok. Что это и зачем — можно почитать, например, тут.

И обязательно добавим логгер. Я использую log4j и чуть дальше покажу вам как полезно его можно использовать при отладке данного приложения и более глубокого осмысления работы TelegramAPI.

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

И, т.к. мы пишем бота для Телеграм, то и саму библиотеку от Telegram:

<dependency>
            <groupId>org.telegram</groupId>
            <artifactId>telegrambots</artifactId>
            <version>3.5</version>
</dependency>

Структуру pom файла можно посмотреть тут
Структуру файла pom.xml можно увидеть тут.

Далее добавляем базовый класс Bot.java, который и будет реализовывать все наше взаимодействие с с сервисами Telegram. Работать мы будем с помощью LongPolling, т.к. этот метод не требует сертификатов шифрования и запускаться может с любой машины, которая имеет Java у себя на борту.

Для этого мы наследуемся от класса TelegramLongPollingBot и реализуем базовые методы:

public void onUpdateReceived(Update update)
public String getBotUsername()
public String getBotToken()

И от себя нам нужно будет добавить процедуру, которая будет подключать наш бот к TelegramAPI:

public void botConnect()

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.log4j.Logger;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;

@AllArgsConstructor
@NoArgsConstructor
public class Bot extends TelegramLongPollingBot {
    private static final Logger log = Logger.getLogger(Bot.class);

    final int RECONNECT_PAUSE =10000;

    @Setter
    @Getter
    String userName;
    @Setter
    @Getter
    String token;

    @Override
    public void onUpdateReceived(Update update) {
        // TODO: 11/18/2019 добавить обработку полученных сообщений
        log.debug("new Update recieve");
    }

    @Override
    public String getBotUsername() {
        return userName;
    }

    @Override
    public String getBotToken() {
        return token;
    }

    public void botConnect() {
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
        try {
            telegramBotsApi.registerBot(this);
            log.info("TelegramAPI started. Look for messages");
        } catch (TelegramApiRequestException e) {
            log.error("Cant Connect. Pause " + RECONNECT_PAUSE / 1000 + "sec and try again. Error: " + e.getMessage());
            try {
                Thread.sleep(RECONNECT_PAUSE);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                return;
            }
            botConnect();
        }
    }
}

В принципе все. Данный код умеет подключаться к серверам Телеграмм и при получении адресованных ему сообщений будет фиксировать в лог файл информацию, что он получил Update.

Давайте создадим класс, который и будет запускать наше приложение.

Этим займется класс App.java. Ссылка на файл: тут

package com.example.telegrambot;

import com.example.telegrambot.bot.Bot;
import org.apache.log4j.Logger;
import org.telegram.telegrambots.ApiContextInitializer;

public class App {
    private static final Logger log = Logger.getLogger(App.class);

    public static void main(String[] args) {
        ApiContextInitializer.init();
        Bot test_habr_bot = new Bot("test_habr_bot", "1012522162:AAHLvPVqKF48LdqnsvS3l5YrJfvFey6dBa0");
        test_habr_bot.botConnect();
    }
}

Как вы видите, для работы бота нам понадобятся только «имя бота» и «токен», которые мы и передадим в конструкторе нашего класса Bot.

Имя и токен для бота вы можете получить у отца всех ботов :), написав ему в телеграмме.
Его ник: @BotFather
Общение с ним очень простое и лаконичное.

По команде

/newbot

В результате у вас должен получиться такой диалог:

Так же здесь пишут, что аккуратнее, никому не показывайте эту информацию, иначе кто-то другой сможет управлять вашим ботом :)

Вы скажете, что я не очень аккуратен… Возможно, но отец ботов позволяет нам менять токены и отзывать те, что попали в публичный доступ. Потому с попробовав подключиться с моими данными, вы получите такое сообщение:

2019-12-04 13:44:25,252[DEBUG][main            ][ com.example.telegrambot.bot.Bot] - Bot token: 1012522162:AAF5D49N4NreEJfCk0aOsC-UnmIu_GLkoyc
2019-12-04 13:44:26,613[ERROR][main            ][ com.example.telegrambot.bot.Bot] - Cant Connect. Pause 10sec and try again. Error: Error removing old webhook

Так что с моими данными вам подключиться не получится. Регистрируйте свои. Новые данные укажите в классе App.java

Теперь запустив метод main в классе App мы позволим нашему боту подключиться и ждать новых сообщений. О своих действиях и попытках он напишет нам в консоле.

Log4j

Помните, выше я говорил о полезности библиотеки log4j. И вот тут для любопытных открывается клондайк полезных данных.

В файле log4j.properties уже прописаны базовые настройки для логирования и конкретные уровни логирования для сторонних классов и для тех, которые работают в нашем боте.

log4j.rootLogger= error, file
log4j.logger.com.example.telegrambot.App = debug, stdout
log4j.logger.com.example.telegrambot.bot.Bot = debug, stdout

Базовый уровень логирования у нас указан как Error.

Для классов Bot и App указан вывод логов на уровне Debug.

Что это за уровни и чем отличаются — вы легко найдете в гугле.

Если хотите посмотреть, как и в каком порядке отрабатывает библиотека Телеграм все ваши действия — переключите режим общего логирования на уровень ниже: info или debug.

И при запуске приложения вы в консоли увидите, сколько всего интересного происходит в процессе подключения, работы. Сколько раз опрашиваются ваши функции с именем и токеном бота.

Уровни логирования меняются вот этой строчкой:
Чтобы получить логи по уровню info, ставите вот так:

log4j.rootLogger= info, file

Для уровня debug, вот так:

log4j.rootLogger= debug, file

И в заключение

Сейчас у нас бот: подключается, показывает нам красивые логи и сообщает о том, что ему приходят сообщения.

Но выше я вам обещал, что бот будет отзываться на команду старт. Давайте немного изменим процедуру, ответственную за обработку полученных сообщений.

@Override
    public void onUpdateReceived(Update update) {
        log.debug("Receive new Update. updateID: " + update.getUpdateId());

        Long chatId = update.getMessage().getChatId();
        String inputText = update.getMessage().getText();

        if (inputText.startsWith("/start")) {
            SendMessage message = new SendMessage();
            message.setChatId(chatId);
            message.setText("Hello. This is start message");
            try {
                execute(message);
            } catch (TelegramApiException e) {
                e.printStackTrace();
            }
        }
    }

Как видно из кода бот делает следующее:

  • Получает апдейт и фиксирует в лог его айди номер.
  • Достает из переданного сообщения ID чата и собственно текст сообщения
  • Проверяет, не является ли этот текст командой «/start»
  • И в случае успешного сравнения создает сообщение в ответ и отправляет его в чат, с полученным ранее ID

Надеюсь вам было полезно и интересно.

В дальнейшем я покажу вам, как в моих ботах реализуется:

  • использование различных команд
  • привязка этих команд к обработчикам
  • многопоточность: независимое получение и отправка сообщений
  • форматирование отправляемых сообщений
  • работа с кнопками и колбеками
  • редактирование старых сообщений

На этой базе в паблик доступе у меня сейчас работают 2 моих бота.

Одного вы знаете — это помощник в планировании мероприятий.

А второй — Дерзкий киноман. Он очень любит фильмы и очень много о них знает. А еще больше он любит делится с вами своими знаниями. Он ведет свой канал в телеграмме, в котором сам решает, какие фильмы ему нравятся и предлагает их вам. Он умеет формировать индивидуальные подборки по жанрам и создавать подписку на персональные рекомендации. Он умеет находить такие шедевры, о которых вы никогда не слышали и даже не знали как такие фильмы вообще можно найти.

Например, как вы думаете, существуют ли фильмы с такой «дикой» комбинацией жанров, как: документальный, ужасы, комедия.

А вот бот по команде

фильм комедия документальный ужасы топ 2010-

Скажет, что таких фильмов с 2010 по текущий момент сняли аж 6 штук :)

Как работать с подобными командами, как разбирать строки и последовательности команд мы рассмотрим с вами в следующих публикациях.

Спасибо вам за внимание. Программируйте в удовольствие :)

Best Java code snippets using org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException (Showing top 20 results out of 315)

private <T> Runnable getDownloadFileAsyncJob(T fileIdentifier, DownloadFileCallback<T> callback, String url, String tempFileName) {
  
  return new Runnable() {
    @Override
    public void run() {
      try {
        callback.onResult(fileIdentifier, downloadToTemporaryFile(url, tempFileName));
      } catch (MalformedURLException e) {
        callback.onException(fileIdentifier, new TelegramApiException("Wrong url for file: " + url));
      } catch (IOException e) {
        callback.onException(fileIdentifier, new TelegramApiRequestException("Error downloading the file", e));
      }
    }
  };
}
  private static void validateServerKeystoreFile(String keyStore) throws TelegramApiRequestException {
    File file = new File(keyStore);
    if (!file.exists() || !file.canRead()) {
      throw new TelegramApiRequestException("Can't find or access server keystore file.");
    }
  }
}
 public static void clearWebhook(DefaultAbsSender bot) throws TelegramApiRequestException {
  try {
   boolean result = bot.execute(new DeleteWebhook());
   if (!result) {
    throw new TelegramApiRequestException("Error removing old webhook");
   }
  } catch (TelegramApiException e) {
   throw new TelegramApiRequestException("Error removing old webhook", e);
  }
 }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error deleting chat sticker set", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public File deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<File> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<File>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error uploading sticker set", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error restricting chat member", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error creating new sticker set", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error unpinning chat message", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error answering pre-checkout query", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public ChatMember deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<ChatMember> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<ChatMember>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error getting chat member", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error setting chat photo", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Message>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error sending video", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public ArrayList<GameHighScore> deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<ArrayList<GameHighScore>> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<ArrayList<GameHighScore>>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error getting game high scores", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Message>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error sending venue", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public File deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<File> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<File>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error getting file", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error setting chat sticker set", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Boolean deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Boolean> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Boolean>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error unbanning chat member", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Message>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error sending sticker", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public Message deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<Message> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<Message>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error sending video note", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}
@Override
public StickerSet deserializeResponse(String answer) throws TelegramApiRequestException {
  try {
    ApiResponse<StickerSet> result = OBJECT_MAPPER.readValue(answer,
        new TypeReference<ApiResponse<StickerSet>>(){});
    if (result.getOk()) {
      return result.getResult();
    } else {
      throw new TelegramApiRequestException("Error getting sticker set", result);
    }
  } catch (IOException e) {
    throw new TelegramApiRequestException("Unable to deserialize response", e);
  }
}

Понравилась статья? Поделить с друзьями:
  • Telegram как изменить пароль
  • Telegram как изменить номер телефона
  • Telegram аналитика ошибок
  • Telegram update error
  • Telegram network error