Java spring телеграм бот

Saved searches

Use saved searches to filter your results more quickly

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. You switched accounts on another tab or window. Reload to refresh your session.

Spring Boot Java Example for the Telegram Bot API

License

PauloGaldo/telegram-bot

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.adoc

This Telegram bot can be used to get the weather forecast graphs for your desired city from www.dmi.dk.

How to use this Telegram Bot

This bot can be used by clicking on telegram.me/dmi_weather_bot or @dmi_weather_bot in your telegram app. After doing this you’ll get a description of the bot and can directly start using it and send commands.

More information concerning Telegram Bots can be found here: https://core.telegram.org/bots

Reasons for using this Telegram Bot

Personally I really like the clearly represented weather forecast graphs, which are provided by www.dmi.dk, but on a mobile device they are not easy to reach with the browser and I am not pleased by current apps for this service. So by implementing this bot I got the chance to really get the raw graphs, which saves my time, system resources on my mobile device and data volume from my mobile provider.

Creating a new Telegram Bot

In order to create a new bot you have to talk with @BotFather. There you can use several commands to create and configure your own bot.

Sending /help to the @BotFather gives an overview about the commands. To create a new bot the /newbot command can be used.

Configure the Application

To run this Spring Boot application with your own bot you usually have to adjust the application.properties file. (https://github.com/SimonScholz/telegram-bot/blob/master/telegram-bot/src/main/resources/application.properties)

bot.api-key=97307424:AAEDj2IXFDEEYfQ6SY_Ma0W_CHu1mUmQ3h8 server.port=8080

The bot.api-key property has to be changed to your own bot token and you might want to change the server.port property as well, e.g., to port 80.

By sending the /token command to the @BotFather and selecting your bot, you’ll get the token, which has to be placed in the application.properties as bot.api-key property value.

Starting the Spring Boot application

You can either import the project into the Spring Tool Suite (https://spring.io/tools/sts/all) and start it from the IDE or simply start the application by running the bootRun Gradle task.

// unix telegram-bot > ./gradlew bootRun // win telegram-bot > gradlew.bat bootRun

Once the application is running either from the IDE or with Gradle you can test it by navigating to http://localhost:8080/poll, which is used to poll your messages/commands.

Currently 4 commands are supported:

  • /now — Get the current day overview image from dmi.dk
  • /week — Get the week overview image from dmi.dk
  • /en — translates german to english
  • /de — translates english to german

When you send one of these commands to your bot and then open http://localhost:8080/poll the Spring Boot application will try to poll your commands and send appropriate answers to the chat with your bot.

Usually you’d want to use a webhook, if you’re providing a rest endpoint like this app does.

The webhook should point the /webhook endpoint, e.g., http://localhost:8080/webhook.

A nice way to set the webhook is by using curl:

curl https://api.telegram.org/bot/setWebhook -F "url=https:///webhook"

Источник

Создаем телеграм-бота с использованием Spring Boot

Java-университет

Всем привет! В какой-то момент обучения вам хочется перейти от решения задач к созданию реальных проектов, которые лягут в основу вашего портфолио. Когда я начинал учиться на стажировке (которую я всем очень рекомендую), на фрилансе поступило предложение написать телеграм- бота. Ввиду своих малых познаний написал довольно простого бота (последний коммит до миграции на Spring), который содержал в себе три нити:

  • нить приема сообщений;
  • нить отправки сообщений;
  • нить планирования событий (в ней проверялось наличие запланированных сообщений и обновление кешированных данных из JSON).

При написании этого функционала во многом я опирался на эту статью. Все вполне неплохо работало, но чем глубже я погружался в Spring, тем сильнее мне хотелось все отрефакторить с целью уменьшения связности программы и улучшения качества кода. Еще SonarLint (плагин для автоматической проверки качества кода) все время пытался меня убедить, что бесконечные циклы while иметь не очень хорошо. В какой-то момент я решился и все переписал, а теперь хочу поделиться полученными в процессе рефакторинга знаниями с вами. Начнем с основ, а конкретнее — c TelegramBots-Spring-Boot-StarterИтак, поехали! Создадим бота, который будет здороваться в ответ на любое сообщение. Для начала нам необходимо создать новый Maven проект. Добавим необходимые зависимости в pom.xml. Добавляем в properties версии Java и TelegramBots-Spring-Boot-Starter. И прописываем dependencies — здесь у нас будет уже упомянутый выше TelegramBots-Spring-Boot-Starter и Telegram API:Создаем телеграм бота с использованием Spring Boot - 1Библиотека TelegramBots-Spring-Boot-Starter включает в себя Spring Boot и Telegram API. Ее использование позволяет нам довольно простым образом объявить бота в нашем коде, а Spring сам создаст Bean и активирует бота. Если вам интересно, что происходит под капотом в этот момент, то посмотрите исходники библиотеки (в среде разработки или на гитхабе). Также добавляем параметры компиляции: Создаем телеграм бота с использованием Spring Boot - 2Не забудьте после заполнения pom обновить все зависимости! Создадим два класса — App и Bot, а также файл application.yaml в папке resources. Структура моего проекта выглядит так:Создаем телеграм бота с использованием Spring Boot - 3На данном этапе добавим в application.yaml credentials нашего бота:

 bot: name: JavaRushTelegramBot token: 22313424:AAF4gck4D8gDhq68E7k0UH8vlyQADhxQhYo 

Иерархическая запись позволяет нам избежать повторения (bot.name, bot.token) и повысить читаемость. Если у вас еще не создан бот, то завести его можно, следуя официальной инструкции. Если вы не хотите светить креденшлы к боту в application.yaml (что правильно) — используйте переменные окружения при деплое:

 package com.whiskels.telegram.bot; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.exceptions.TelegramApiException; // Аннотация @Component необходима, чтобы наш класс распознавался Spring, как полноправный Bean @Component // Наследуемся от TelegramLongPollingBot - абстрактного класса Telegram API public class Bot extends TelegramLongPollingBot < // Аннотация @Value позволяет задавать значение полю путем считывания из application.yaml @Value("$") private String botUsername; @Value("$") private String botToken; /* Перегружаем метод интерфейса LongPollingBot Теперь при получении сообщения наш бот будет отвечать сообщением Hi! */ @Override public void onUpdateReceived(Update update) < try < execute(new SendMessage().setChatId(update.getMessage().getChatId()) .setText("Hi!")); >catch (TelegramApiException e) < e.printStackTrace(); >> // Геттеры, которые необходимы для наследования от TelegramLongPollingBot public String getBotUsername() < return botUsername; >public String getBotToken() < return botToken; >> 
 package com.whiskels.telegram; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.telegram.telegrambots.ApiContextInitializer; // Аннотация, которая объединяет в себя @Configuration, @EnableAutoConfiguration, @ComponentScan @SpringBootApplication public class App < public static void main(String[] args) < // Здесь код написан по заветам // https://github.com/rubenlagus/TelegramBots/tree/master/telegrambots-spring-boot-starter ApiContextInitializer.init(); SpringApplication.run(App.class, args); >> 

Создаем телеграм бота с использованием Spring Boot - 4

Если мы все сделали правильно, то можно запустить main и поздороваться с нашим ботом.Готово! Мы успешно написали и запустили телеграм бота, который на каждое входящее сообщение здоровается. Если вам была полезна эта статья, то лучшей благодарностью будет, если вы загляните в мой репозиторий и поставите звездочку. Там же вы найдете мою версию телеграм-бота, который имеет много интересных особенностей:

  • хранение пользователей в базе Postgres;
  • авторизацию доступа к командам на основе ролей пользователя;
  • использование кастомных аннотаций @BotCommand и @RequiredRoles для создания обработчиков сообщений и проверки прав пользователя;
  • поддержка создания графика уведомлений.

Если что-то из этого функционала вас заинтересовало — пишите в комментарии, и я постараюсь либо ответить, либо написать развернутую статью о том, как его воссоздать. P. S. Это моя первая статья на JavaRush, и мне хотелось бы погрузиться в дебри Spring JPA и аннотации @Scheduled, но для начала мне показалось, что стоит написать это руководство о том, как вообще поднять бота с использованием Spring Boot. По ботам уже написано несколько статей, но поиск не выдал подобного гайда, так что я решил заполнить эту нишу 🙂 Также хотелось бы отметить Miroha — спасибо за идею UpdateHandler’ов, утащил ее себе 🙂 ЧАСТЬ 2ЧАСТЬ 3

Источник

Читайте также:  Html default display style
Оцените статью