├── system.properties ├── settings.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ └── config │ │ └── application.yml │ └── java │ └── com │ └── github │ └── unafraid │ └── spring │ ├── Application.java │ ├── bot │ ├── AccessLevelValidator.java │ ├── handlers │ │ └── impl │ │ │ ├── CancelHandler.java │ │ │ ├── StartHandler.java │ │ │ ├── ResolveHandler.java │ │ │ ├── WhoAmI.java │ │ │ ├── HelpHandler.java │ │ │ └── ExampleInlineMenuHandler.java │ └── TelegramWebHookBot.java │ ├── controllers │ └── MainController.java │ ├── config │ └── TelegramBotConfig.java │ └── services │ └── TelegramBotService.java ├── Procfile ├── .gitignore ├── .gitattributes ├── .github └── workflows │ └── test.yml ├── app.json ├── gradle.bat ├── README.md ├── gradlew.bat └── gradlew /system.properties: -------------------------------------------------------------------------------- 1 | java.runtime.version=11 2 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "SpringTelegramBot" 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UnAfraid/SpringTelegramBot/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/config/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: telegram-bot 4 | 5 | server: 6 | port: ${PORT:9090} 7 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: java -Xmx256m -Dlog4j2.formatMsgNoLookups=true -Dserver.port=$PORT --add-opens java.base/java.lang=ALL-UNNAMED $JAVA_OPTS -jar build/install/SpringTelegramBot/lib/SpringTelegramBot.jar 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Eclipse 2 | .classpath 3 | .project 4 | .settings 5 | .metadata 6 | bin/ 7 | out/ 8 | build/ 9 | /.recommenders/ 10 | 11 | # Idea 12 | *.iml 13 | .idea/ 14 | 15 | # Gradle 16 | /.gradle/ 17 | */build/ 18 | gradle.properties 19 | 20 | .DS_Store 21 | .directory 22 | *.log 23 | .env 24 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly declare text files you want to always be normalized and converted 5 | # to native line endings on checkout. 6 | *.java text 7 | *.xml text 8 | *.properties text 9 | 10 | # SH files must always use LF. 11 | *.sh eol=lf 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: [ push ] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v1 8 | - name: Set up JDK 17 9 | uses: actions/setup-java@v4 10 | with: 11 | distribution: 'temurin' 12 | java-version: 17 13 | - name: Test with Gradle 14 | run: ./gradlew test 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/Application.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 6 | 7 | 8 | /** 9 | * @author UnAfraid 10 | */ 11 | @SpringBootApplication 12 | public class Application extends SpringBootServletInitializer { 13 | public static void main(String[] args) { 14 | SpringApplication.run(Application.class); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/AccessLevelValidator.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot; 2 | 3 | import com.github.unafraid.telegrambot.handlers.IAccessLevelValidator; 4 | import com.github.unafraid.telegrambot.handlers.ITelegramHandler; 5 | import org.springframework.stereotype.Service; 6 | import org.telegram.telegrambots.meta.api.objects.User; 7 | 8 | /** 9 | * @author UnAfraid 10 | */ 11 | @Service 12 | public class AccessLevelValidator implements IAccessLevelValidator { 13 | public AccessLevelValidator() { 14 | } 15 | 16 | @Override 17 | public boolean validate(ITelegramHandler handler, User user) { 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/controllers/MainController.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.controllers; 2 | 3 | import com.github.unafraid.spring.services.TelegramBotService; 4 | import org.springframework.web.bind.annotation.RequestBody; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestMethod; 7 | import org.springframework.web.bind.annotation.ResponseBody; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import org.telegram.telegrambots.meta.api.objects.Update; 10 | 11 | /** 12 | * @author UnAfraid 13 | */ 14 | @RestController 15 | public class MainController { 16 | private final TelegramBotService telegramBotService; 17 | 18 | public MainController(TelegramBotService telegramBotService) { 19 | this.telegramBotService = telegramBotService; 20 | } 21 | 22 | @RequestMapping(value = "/callback/${TELEGRAM_TOKEN}", method = RequestMethod.POST) 23 | @ResponseBody 24 | public void onUpdateReceived(@RequestBody Update update) { 25 | telegramBotService.onWebhookUpdateReceived(update); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/config/TelegramBotConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.config; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.validation.annotation.Validated; 7 | 8 | /** 9 | * @author UnAfraid 10 | */ 11 | @Configuration 12 | @Validated 13 | public class TelegramBotConfig { 14 | @Value("${TELEGRAM_TOKEN}") 15 | @NotNull 16 | private String token; 17 | 18 | @Value("${TELEGRAM_URL}") 19 | @NotNull 20 | private String url; 21 | 22 | @Value("${TELEGRAM_MAX_CONNECTIONS:40}") 23 | @NotNull 24 | private Integer maxConnections; 25 | 26 | @Value("${TELEGRAM_LANGUAGE_CODE:en}") 27 | @NotNull 28 | private String languageCode; 29 | 30 | public String getToken() { 31 | return token; 32 | } 33 | 34 | public String getUrl() { 35 | return url; 36 | } 37 | 38 | public int getMaxConnections() { 39 | return maxConnections; 40 | } 41 | 42 | public String getLanguageCode() { 43 | return languageCode; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Telegram Bot Spring Example", 3 | "description": "A barebones Telegram bot using java and Spring framework", 4 | "repository": "https://github.com/UnAfraid/SpringTelegramBot", 5 | "logo": "https://upload.wikimedia.org/wikipedia/commons/8/82/Telegram_logo.svg", 6 | "keywords": [ 7 | "java", 8 | "telegram-bot", 9 | "example", 10 | "spring" 11 | ], 12 | "formation": { 13 | "web": { 14 | "quantity": 1, 15 | "size": "free" 16 | } 17 | }, 18 | "env": { 19 | "TELEGRAM_TOKEN": { 20 | "description": "The bot name from BotFather", 21 | "value": "" 22 | }, 23 | "TELEGRAM_URL": { 24 | "description": "The base url on which your bot would listen example: https://mybot.example.com", 25 | "value": "" 26 | }, 27 | "TELEGRAM_MAX_CONNECTIONS": { 28 | "description": "The Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput", 29 | "value": "40" 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/CancelHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import com.github.unafraid.telegrambot.bots.AbstractTelegramBot; 4 | import com.github.unafraid.telegrambot.handlers.ICancelHandler; 5 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 6 | import org.springframework.stereotype.Service; 7 | import org.telegram.telegrambots.meta.api.objects.Update; 8 | import org.telegram.telegrambots.meta.api.objects.message.Message; 9 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @author UnAfraid 15 | */ 16 | @Service 17 | public class CancelHandler implements ICommandHandler { 18 | @Override 19 | public String getCommand() { 20 | return "/cancel"; 21 | } 22 | 23 | @Override 24 | public String getUsage() { 25 | return "/cancel"; 26 | } 27 | 28 | @Override 29 | public String getDescription() { 30 | return "Cancels current action"; 31 | } 32 | 33 | @Override 34 | public void onCommandMessage(AbstractTelegramBot bot, Update update, Message message, List args) throws TelegramApiException { 35 | for (ICancelHandler handler : bot.getAvailableHandlersForUser(ICancelHandler.class, message.getFrom())) { 36 | handler.onCancel(bot, update, message); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/TelegramWebHookBot.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.github.unafraid.telegrambot.bots.DefaultTelegramBot; 7 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 8 | import org.jetbrains.annotations.NotNull; 9 | import org.springframework.beans.factory.ObjectProvider; 10 | import org.springframework.context.ApplicationContext; 11 | import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient; 12 | import org.telegram.telegrambots.meta.api.objects.Update; 13 | import org.telegram.telegrambots.meta.generics.TelegramClient; 14 | 15 | /** 16 | * @author UnAfraid 17 | */ 18 | public abstract class TelegramWebHookBot extends DefaultTelegramBot { 19 | public TelegramWebHookBot(@NotNull String token, 20 | @NotNull ApplicationContext appContext, 21 | @NotNull ObjectProvider telegramClientProvider, 22 | AccessLevelValidator accessLevelValidator) { 23 | super(telegramClientProvider.getIfAvailable(() -> new OkHttpTelegramClient(token))); 24 | 25 | setAccessLevelValidator(accessLevelValidator); 26 | 27 | final Map handlers = appContext.getBeansOfType(ICommandHandler.class); 28 | handlers.values().forEach(this::addHandler); 29 | } 30 | 31 | public final void onWebhookUpdateReceived(Update update) { 32 | if (update != null) { 33 | consume(List.of(update)); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/StartHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import java.util.List; 4 | 5 | import com.github.unafraid.telegrambot.bots.AbstractTelegramBot; 6 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 7 | import com.github.unafraid.telegrambot.util.BotUtil; 8 | import org.springframework.stereotype.Service; 9 | import org.telegram.telegrambots.meta.api.methods.GetMe; 10 | import org.telegram.telegrambots.meta.api.objects.Update; 11 | import org.telegram.telegrambots.meta.api.objects.User; 12 | import org.telegram.telegrambots.meta.api.objects.message.Message; 13 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 14 | 15 | /** 16 | * @author UnAfraid 17 | */ 18 | @Service 19 | public final class StartHandler implements ICommandHandler { 20 | public StartHandler() { 21 | } 22 | 23 | @Override 24 | public String getCommand() { 25 | return "/start"; 26 | } 27 | 28 | @Override 29 | public String getUsage() { 30 | return "/start"; 31 | } 32 | 33 | @Override 34 | public String getDescription() { 35 | return "Shows greetings message"; 36 | } 37 | 38 | @Override 39 | public void onCommandMessage(AbstractTelegramBot bot, Update update, Message message, List args) throws TelegramApiException { 40 | final User me = bot.execute(GetMe.builder().build()); 41 | BotUtil.sendMessage(bot, message, "Hello, i am " + me.getUserName() + ", if you want to know what i can do type /start", true, false, null); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/ResolveHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import java.net.InetAddress; 4 | import java.util.List; 5 | 6 | import com.github.unafraid.telegrambot.bots.AbstractTelegramBot; 7 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 8 | import com.github.unafraid.telegrambot.util.BotUtil; 9 | import org.springframework.stereotype.Service; 10 | import org.telegram.telegrambots.meta.api.objects.Update; 11 | import org.telegram.telegrambots.meta.api.objects.message.Message; 12 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 13 | 14 | 15 | /** 16 | * @author UnAfraid 17 | */ 18 | @Service 19 | public final class ResolveHandler implements ICommandHandler { 20 | @Override 21 | public String getCommand() { 22 | return "/resolve"; 23 | } 24 | 25 | @Override 26 | public String getUsage() { 27 | return "/resolve "; 28 | } 29 | 30 | @Override 31 | public String getDescription() { 32 | return "Resolved hostname to ip address"; 33 | } 34 | 35 | @Override 36 | public String getCategory() { 37 | return "Utilities"; 38 | } 39 | 40 | @Override 41 | public int getRequiredAccessLevel() { 42 | return 1; 43 | } 44 | 45 | @Override 46 | public void onCommandMessage(AbstractTelegramBot bot, Update update, Message message, List args) throws TelegramApiException { 47 | if (args.isEmpty()) { 48 | BotUtil.sendUsage(bot, message, this); 49 | return; 50 | } 51 | final String hostName = args.get(0); 52 | try { 53 | final InetAddress address = InetAddress.getByName(hostName); 54 | BotUtil.sendMessage(bot, message, "*" + hostName + "* = " + address.getHostAddress(), true, true, null); 55 | } catch (Exception e) { 56 | BotUtil.sendMessage(bot, message, "Failed to resolve: " + hostName + " " + e.getMessage(), true, false, null); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/WhoAmI.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import java.util.List; 4 | 5 | import com.github.unafraid.telegrambot.bots.AbstractTelegramBot; 6 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 7 | import com.github.unafraid.telegrambot.util.BotUtil; 8 | import org.springframework.stereotype.Service; 9 | import org.telegram.telegrambots.meta.api.objects.Update; 10 | import org.telegram.telegrambots.meta.api.objects.message.Message; 11 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 12 | 13 | /** 14 | * @author UnAfraid 15 | */ 16 | @Service 17 | public final class WhoAmI implements ICommandHandler { 18 | @Override 19 | public String getCommand() { 20 | return "/whoami"; 21 | } 22 | 23 | @Override 24 | public String getUsage() { 25 | return "/whoami"; 26 | } 27 | 28 | @Override 29 | public String getDescription() { 30 | return "Shows information for the user who types the command"; 31 | } 32 | 33 | @Override 34 | public void onCommandMessage(AbstractTelegramBot bot, Update update, Message message, List args) throws TelegramApiException { 35 | final StringBuilder sb = new StringBuilder(); 36 | sb.append("Your id: ").append(message.getFrom().getId()).append(System.lineSeparator()); 37 | sb.append("Name: ").append(message.getFrom().getFirstName()).append(System.lineSeparator()); 38 | if (message.getFrom().getUserName() != null) { 39 | sb.append("Username: @").append(message.getFrom().getUserName()).append(System.lineSeparator()); 40 | } 41 | sb.append("Chat Type: ").append(message.getChat().isGroupChat() ? "Group Chat" : message.getChat().isSuperGroupChat() ? "Super Group Chat" : message.getChat().isChannelChat() ? "Channel Chat" : message.getChat().isUserChat() ? "Private Chat" : "No way!?").append(System.lineSeparator()); 42 | if (message.getChat().getId() < 0) { 43 | sb.append("Group Id: ").append(message.getChat().getId()).append(System.lineSeparator()); 44 | sb.append("Group Name: ").append(message.getChat().getTitle()).append(System.lineSeparator()); 45 | } 46 | BotUtil.sendMessage(bot, message, sb.toString(), true, false, null); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /gradle.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME%.. 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\lib\gradle-launcher-3.5.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.launcher.GradleMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/HelpHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedHashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import com.github.unafraid.telegrambot.bots.AbstractTelegramBot; 9 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 10 | import com.github.unafraid.telegrambot.util.BotUtil; 11 | import org.springframework.stereotype.Service; 12 | import org.telegram.telegrambots.meta.api.objects.Update; 13 | import org.telegram.telegrambots.meta.api.objects.message.Message; 14 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 15 | 16 | /** 17 | * @author UnAfraid 18 | */ 19 | @Service 20 | public final class HelpHandler implements ICommandHandler { 21 | @Override 22 | public String getCommand() { 23 | return "/help"; 24 | } 25 | 26 | @Override 27 | public String getUsage() { 28 | return "/help [command]"; 29 | } 30 | 31 | @Override 32 | public String getDescription() { 33 | return "Shows help for all or specific command"; 34 | } 35 | 36 | @Override 37 | public void onCommandMessage(AbstractTelegramBot bot, Update update, Message message, List args) throws TelegramApiException { 38 | if (args.isEmpty()) { 39 | final StringBuilder sb = new StringBuilder(); 40 | final Map> help = new LinkedHashMap<>(); 41 | bot.getHandlers() 42 | .stream() 43 | .filter(handler -> bot.validateAccessLevel(handler, message.getFrom())) 44 | .filter(handler -> handler instanceof ICommandHandler) 45 | .map(handler -> (ICommandHandler) handler) 46 | .forEach(handler -> help.computeIfAbsent(handler.getCategory(), key -> new ArrayList<>()).add(handler.getCommand() + " - " + handler.getDescription())); 47 | 48 | help.forEach((key, value) -> { 49 | sb.append(key).append(":").append(System.lineSeparator()); 50 | for (String line : value) { 51 | sb.append(line).append(System.lineSeparator()); 52 | } 53 | sb.append(System.lineSeparator()); 54 | }); 55 | 56 | BotUtil.sendMessage(bot, message, sb.toString(), true, false, null); 57 | return; 58 | } 59 | 60 | String command = args.get(0); 61 | if (command.charAt(0) != '/') { 62 | command = '/' + command; 63 | } 64 | final ICommandHandler handler = bot.getHandler(command); 65 | if (handler == null) { 66 | BotUtil.sendMessage(bot, message, "Unknown command.", false, false, null); 67 | return; 68 | } 69 | 70 | BotUtil.sendMessage(bot, message, "Usage:" + System.lineSeparator() + handler.getUsage(), true, false, null); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringTelegramBot ![Test](https://github.com/UnAfraid/SpringTelegramBot/workflows/Test/badge.svg) [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/UnAfraid/SpringTelegramBot) 2 | 3 | This repository contains an example of telegram bot written in Java (17 and above) using Spring Framework. 4 | 5 | This project uses https://github.com/rubenlagus/TelegramBots, check it out for more telegram bot implementation details, 6 | also https://core.telegram.org/bots/api for telegram bots API details 7 | 8 | Current version supports the following commands: 9 | 10 | * /help - Displays help about all or specified command 11 | * /whoami - Displays information about the person who wrote the command: User Id, Name and chat type 12 | * /start - The default bot command, shows greeting message 13 | 14 | ### Configuration 15 | 16 | Configuration is supplied through Environment Variables: 17 | 18 | | Environment variable | Required | Default value | Description | 19 | |------------------------------|:------------:|-------------------|-------------------------------------------------------------------------------- | 20 | | TELEGRAM_TOKEN | Yes | | The token from [@BotFather](https://t.me/BotFather) | 21 | | TELEGRAM_URL | Yes | | The base url on which your bot would listen example: `https://mybot.example.com` | 22 | | TELEGRAM_MAX_CONNECTIONS | No | 40 | The Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput | 23 | | TELEGRAM_LANGUAGE_CODE | No | en | A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands | 24 | | PORT | No | 9090 | The port on which web server will listen for incoming requests | 25 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/bot/handlers/impl/ExampleInlineMenuHandler.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.bot.handlers.impl; 2 | 3 | import com.github.unafraid.telegrambot.handlers.inline.*; 4 | import com.github.unafraid.telegrambot.handlers.inline.events.InlineCallbackEvent; 5 | import org.springframework.stereotype.Service; 6 | import org.telegram.telegrambots.meta.api.methods.AnswerCallbackQuery; 7 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 8 | 9 | /** 10 | * Very basic inline menu handler, accepts command starting with /menu 11 | */ 12 | @Service 13 | public class ExampleInlineMenuHandler extends AbstractInlineHandler { 14 | @Override 15 | public String getUsage() { 16 | return "/menu"; 17 | } 18 | 19 | @Override 20 | public String getDescription() { 21 | return "Renders static menu"; 22 | } 23 | 24 | @Override 25 | public String getCommand() { 26 | return "/menu"; 27 | } 28 | 29 | @Override 30 | public int getRequiredAccessLevel() { 31 | return 1; 32 | } 33 | 34 | @Override 35 | public void registerMenu(InlineContext ctx, InlineMenuBuilder builder) { 36 | builder 37 | .name("Main Menu") 38 | .button(new InlineButtonBuilder(ctx) 39 | .name("Button 1") 40 | .onQueryCallback(this::handleButtonClick) 41 | .row(0) 42 | .build()) 43 | .button(new InlineButtonBuilder(ctx) 44 | .name("Button 2") 45 | .onQueryCallback(this::handleButtonClick) 46 | .row(0) 47 | .build()) 48 | .button(new InlineButtonBuilder(ctx) 49 | .name("Button 3") 50 | .onQueryCallback(this::handleButtonClick) 51 | .row(0) 52 | .build()) 53 | .button(new InlineButtonBuilder(ctx) 54 | .name("Sub menu") 55 | .row(0) 56 | .menu(new InlineMenuBuilder(ctx) 57 | .name("Sub menu") 58 | .button(new InlineButtonBuilder(ctx) 59 | .name("Sub Button 1") 60 | .onQueryCallback(this::handleButtonClick) 61 | .build()) 62 | .button(new InlineButtonBuilder(ctx) 63 | .name("Sub Button 2") 64 | .onQueryCallback(this::handleButtonClick) 65 | .build()) 66 | .button(new InlineButtonBuilder(ctx) 67 | .name("Sub Button 3") 68 | .onQueryCallback(this::handleButtonClick) 69 | .build()) 70 | .button(defaultBack(ctx)) 71 | .build()) 72 | .build()) 73 | .button(defaultClose(ctx)); 74 | } 75 | 76 | private boolean handleButtonClick(InlineCallbackEvent event) throws TelegramApiException { 77 | final InlineUserData userData = event.getContext().getUserData(event.getQuery().getFrom().getId()); 78 | event.getTelegramClient().execute(AnswerCallbackQuery.builder(). 79 | callbackQueryId(event.getQuery().getId()). 80 | showAlert(true). 81 | text("You've clicked at " + userData.getActiveButton().getName()). 82 | build()); 83 | return true; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/github/unafraid/spring/services/TelegramBotService.java: -------------------------------------------------------------------------------- 1 | package com.github.unafraid.spring.services; 2 | 3 | import com.github.unafraid.spring.bot.AccessLevelValidator; 4 | import com.github.unafraid.spring.bot.TelegramWebHookBot; 5 | import com.github.unafraid.spring.config.TelegramBotConfig; 6 | import com.github.unafraid.telegrambot.handlers.ICommandHandler; 7 | import com.github.unafraid.telegrambot.handlers.ITelegramHandler; 8 | import org.jetbrains.annotations.NotNull; 9 | import org.springframework.beans.factory.ObjectProvider; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.http.HttpEntity; 12 | import org.springframework.http.HttpHeaders; 13 | import org.springframework.http.HttpMethod; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.web.client.RestTemplate; 16 | import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands; 17 | import org.telegram.telegrambots.meta.api.methods.updates.GetWebhookInfo; 18 | import org.telegram.telegrambots.meta.api.methods.updates.SetWebhook; 19 | import org.telegram.telegrambots.meta.api.objects.ApiResponse; 20 | import org.telegram.telegrambots.meta.api.objects.WebhookInfo; 21 | import org.telegram.telegrambots.meta.api.objects.commands.BotCommand; 22 | import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault; 23 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 24 | import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException; 25 | import org.telegram.telegrambots.meta.generics.TelegramClient; 26 | 27 | import java.util.ArrayList; 28 | import java.util.List; 29 | 30 | /** 31 | * @author UnAfraid 32 | */ 33 | @Service 34 | public class TelegramBotService extends TelegramWebHookBot { 35 | private final TelegramBotConfig config; 36 | 37 | public TelegramBotService(TelegramBotConfig config, 38 | ApplicationContext appContext, 39 | AccessLevelValidator accessLevelValidator, 40 | @NotNull ObjectProvider telegramClientProvider 41 | ) throws Exception { 42 | super(config.getToken(), appContext, telegramClientProvider, accessLevelValidator); 43 | this.config = config; 44 | init(); 45 | } 46 | 47 | private void init() throws Exception { 48 | final WebhookInfo info = execute(new GetWebhookInfo()); 49 | final String url = info.getUrl(); 50 | final String webHookUrl = computeCallbackEndpoint(); 51 | 52 | if (url == null || url.isEmpty() || !url.equals(webHookUrl) || info.getMaxConnections() != config.getMaxConnections()) { 53 | setWebhook(SetWebhook.builder(). 54 | url(webHookUrl). 55 | maxConnections(config.getMaxConnections()). 56 | build()); 57 | } 58 | 59 | registerMyCommands(); 60 | } 61 | 62 | private String computeCallbackEndpoint() { 63 | final StringBuilder sb = new StringBuilder(config.getUrl()); 64 | if (sb.charAt(sb.length() - 1) != '/') { 65 | sb.append('/'); 66 | } 67 | sb.append("callback/"); 68 | sb.append(config.getToken()); 69 | return sb.toString(); 70 | } 71 | 72 | private void registerMyCommands() throws TelegramApiException { 73 | final List botCommandList = new ArrayList<>(); 74 | for (ITelegramHandler handler : getHandlers()) { 75 | if (handler instanceof ICommandHandler commandHandler) { 76 | botCommandList.add(new BotCommand(commandHandler.getCommand(), commandHandler.getDescription())); 77 | } 78 | } 79 | 80 | if (!botCommandList.isEmpty()) { 81 | execute(new SetMyCommands(botCommandList, new BotCommandScopeDefault(), config.getLanguageCode())); 82 | } 83 | } 84 | 85 | private void setWebhook(SetWebhook setWebhook) throws TelegramApiException { 86 | try { 87 | final RestTemplate rest = new RestTemplate(); 88 | final HttpHeaders headers = new HttpHeaders(); 89 | headers.add("Content-Type", "application/json"); 90 | headers.add("Accept", "application/json"); 91 | 92 | final String setWebhookUrl = String.format("https://api.telegram.org/bot%s/%s", config.getToken(), SetWebhook.PATH); 93 | rest.exchange(setWebhookUrl, HttpMethod.POST, new HttpEntity<>(setWebhook, headers), ApiResponse.class); 94 | } catch (Exception e) { 95 | throw new TelegramApiRequestException("Error executing setWebHook method", e); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | # Collect all arguments for the java command; 201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 202 | # shell script including quotes and variable substitutions, so put them in 203 | # double quotes to make sure that they get re-expanded; and 204 | # * put everything else in single quotes, so that it's not re-expanded. 205 | 206 | set -- \ 207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 208 | -classpath "$CLASSPATH" \ 209 | org.gradle.wrapper.GradleWrapperMain \ 210 | "$@" 211 | 212 | # Stop when "xargs" is not available. 213 | if ! command -v xargs >/dev/null 2>&1 214 | then 215 | die "xargs is not available" 216 | fi 217 | 218 | # Use "xargs" to parse quoted args. 219 | # 220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 221 | # 222 | # In Bash we could simply go: 223 | # 224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 225 | # set -- "${ARGS[@]}" "$@" 226 | # 227 | # but POSIX shell has neither arrays nor command substitution, so instead we 228 | # post-process each arg (as a line of input to sed) to backslash-escape any 229 | # character that might be a shell metacharacter, then use eval to reverse 230 | # that process (while maintaining the separation between arguments), and wrap 231 | # the whole thing up as a single "set" statement. 232 | # 233 | # This will of course break if any of these variables contains a newline or 234 | # an unmatched quote. 235 | # 236 | 237 | eval "set -- $( 238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 239 | xargs -n1 | 240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 241 | tr '\n' ' ' 242 | )" '"$@"' 243 | 244 | exec "$JAVACMD" "$@" 245 | --------------------------------------------------------------------------------