From 5a0c822f4c40a98ce1cee0101ee0d7057f2ce9c2 Mon Sep 17 00:00:00 2001 From: SgrAlpha Date: Mon, 13 Apr 2020 00:01:59 +0800 Subject: [PATCH] Update sample application and readme files --- README.md | 57 ++++-------- README.zh-cn.md | 57 ++++-------- examples/hello/README.md | 7 ++ examples/hello/README.zh-cn.md | 7 ++ examples/spring-webhook/README.md | 7 ++ examples/spring-webhook/README.zh-cn.md | 7 ++ .../webhook}/BotApplication.java | 2 +- .../spring/webhook/UpdateController.java | 93 +++++++++++++++++++ .../webhook/spring/UpdateController.java | 63 ------------- .../src/main/resources/application.yaml | 2 +- .../webhook/spring/BotApplicationTest.java | 2 +- 11 files changed, 156 insertions(+), 148 deletions(-) create mode 100644 examples/hello/README.md create mode 100644 examples/hello/README.zh-cn.md create mode 100644 examples/spring-webhook/README.md create mode 100644 examples/spring-webhook/README.zh-cn.md rename examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/{webhook/spring => spring/webhook}/BotApplication.java (94%) create mode 100644 examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java delete mode 100644 examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/UpdateController.java diff --git a/README.md b/README.md index e97a6b8..79b5c04 100644 --- a/README.md +++ b/README.md @@ -5,50 +5,25 @@ A java library which help you build Telegram Bots in a fashion way. *Read this in other languages: [English](README.md), [简体中文](README.zh-cn.md).* -## CUT THE CRAP AND SHOW ME THE CODE!!! -[HelloTelegramBot.java](examples/hello/src/main/java/io/sgr/telegram/bot/examples/hello/HelloTelegramBot.java) -```java -public class HelloTelegramBot { - - private static final Logger LOGGER = LoggerFactory.getLogger(HelloTelegramBot.class); - - public static void main(String... args) { - final String botApiToken = System.getenv("BOT_API_TOKEN"); - final BotApi botApi = BotApi.newBuilder(botApiToken).setLogger(LOGGER).build(); - final BotEngine engine = new BotEngine(botApi).setBotUpdateProcessor((Update update) -> { - if (update.getMessage() == null) { - // Not what we want, ignored, but still send a success signal so it can deal with the next update. - return true; - } - final SendMessagePayload payload = new SendMessagePayload(update.getMessage().getChat().getId(), "Hello Telegram!"); - botApi.sendMessage(payload) // Send response message asynchronously without blocking next incoming update. - .exceptionally(e -> { - // Something wrong when sending message, you might want to at least log it. - final Throwable cause = e.getCause(); - if (cause instanceof ApiCallException) { - final String message = ((ApiCallException) cause).getErrorResponse() - .flatMap(ApiErrorResponse::getDescription) - .orElse(cause.getMessage()); - LOGGER.error(message, e); - } else { - LOGGER.error(e.getMessage(), e); - } - return null; // Return null because no message been sent. - }) - .thenAccept(message -> { - // Nullable. Do anything you want with sent message here, or ignore it directly. - }); - return true; - }); - engine.start(); - } - -} +## How to Use +Include following dependency in your `pom.xml` +```xml + + io.sgr.telegram + telegram-bot.engine + 1.1.1 + ``` +Gradle is similar, I'm pretty sure you will know what to do. + +We have several examples: +* [Example: Java Application Based Telegram Bot](examples/hello/README.md). +* [Example: Spring Boot Based Telegram Bot (Webhook)](examples/spring-webhook/README.md). +* Example: Spring Boot Based Telegram Bot (CLI) - under construction. -# License +## License - Copyright 2017-2019 SgrAlpha + Copyright 2017-2020 SgrAlpha Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.zh-cn.md b/README.zh-cn.md index 37cbdcd..800baac 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -5,50 +5,25 @@ *用其他语言阅读: [English](README.md), [简体中文](README.zh-cn.md).* -## 别废话,上 code ! -[HelloTelegramBot.java](examples/hello/src/main/java/io/sgr/telegram/bot/examples/hello/HelloTelegramBot.java) -```java -public class HelloTelegramBot { - - private static final Logger LOGGER = LoggerFactory.getLogger(HelloTelegramBot.class); - - public static void main(String... args) { - final String botApiToken = System.getenv("BOT_API_TOKEN"); - final BotApi botApi = BotApi.newBuilder(botApiToken).setLogger(LOGGER).build(); - final BotEngine engine = new BotEngine(botApi).setBotUpdateProcessor((Update update) -> { - if (update.getMessage() == null) { - // Not what we want, ignored, but still send a success signal so it can deal with the next update. - return true; - } - final SendMessagePayload payload = new SendMessagePayload(update.getMessage().getChat().getId(), "Hello Telegram!"); - botApi.sendMessage(payload) // Send response message asynchronously without blocking next incoming update. - .exceptionally(e -> { - // Something wrong when sending message, you might want to at least log it. - final Throwable cause = e.getCause(); - if (cause instanceof ApiCallException) { - final String message = ((ApiCallException) cause).getErrorResponse() - .flatMap(ApiErrorResponse::getDescription) - .orElse(cause.getMessage()); - LOGGER.error(message, e); - } else { - LOGGER.error(e.getMessage(), e); - } - return null; // Return null because no message been sent. - }) - .thenAccept(message -> { - // Nullable. Do anything you want with sent message here, or ignore it directly. - }); - return true; - }); - engine.start(); - } - -} +## How to Use +在你项目的 `pom.xml` 加入如下依赖: +```xml + + io.sgr.telegram + telegram-bot.engine + 1.1.1 + ``` +如果你使用 Gradle 来构建你的应用,引入依赖的方法是类似的,你应该知道该怎么做。 + +这里有几个例子: +* [示例:基于 Java 命令行的 Telegram 机器人](examples/hello/README.zh-cn.md)。 +* [示例:基于 Spring Boot 的 Telegram 机器人(Webhook)](examples/spring-webhook/README.zh-cn.md)。 +* 示例:基于 Spring Boot 的 Telegram 机器人(CLI) - 尚未完成。 -# 许可协议 +## 许可协议 - Copyright 2017-2019 SgrAlpha + Copyright 2017-2020 SgrAlpha Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/examples/hello/README.md b/examples/hello/README.md new file mode 100644 index 0000000..f373d70 --- /dev/null +++ b/examples/hello/README.md @@ -0,0 +1,7 @@ +# Example: Java Application Based Telegram Bot + +*Read this in other languages: [English](README.md), [简体中文](README.zh-cn.md).* + +This is a simple demonstration about how to build an echo bot which will response "Hello Telegram!" every time when message received. + +You can read the source code [here](src/main/java/io/sgr/telegram/bot/examples/hello/HelloTelegramBot.java), it's very easy to understand. diff --git a/examples/hello/README.zh-cn.md b/examples/hello/README.zh-cn.md new file mode 100644 index 0000000..dc35829 --- /dev/null +++ b/examples/hello/README.zh-cn.md @@ -0,0 +1,7 @@ +# 示例:基于 Java 命令行的 Telegram 机器人 + +*用其他语言阅读: [English](README.md), [简体中文](README.zh-cn.md).* + +这里我们展示了如何构建一个简单的机器人,它会在收到消息之后回复:"Hello Telegram!"。 + +你可以在[这里](src/main/java/io/sgr/telegram/bot/examples/hello/HelloTelegramBot.java)读到源代码,非常简单。 diff --git a/examples/spring-webhook/README.md b/examples/spring-webhook/README.md new file mode 100644 index 0000000..2071184 --- /dev/null +++ b/examples/spring-webhook/README.md @@ -0,0 +1,7 @@ +# Example: Spring Boot Based Telegram Bot (Webhook) + +*Read this in other languages: [English](README.md), [简体中文](README.zh-cn.md).* + +This is a simple demonstration about how to build an echo bot which will response "Hello Telegram!" every time when message received. + +Basically it uses a [Controller](src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java) class to listen to updates from Telegram server, it's very easy to understand. diff --git a/examples/spring-webhook/README.zh-cn.md b/examples/spring-webhook/README.zh-cn.md new file mode 100644 index 0000000..0fa6afb --- /dev/null +++ b/examples/spring-webhook/README.zh-cn.md @@ -0,0 +1,7 @@ +# 示例:基于 Spring Boot 的 Telegram 机器人(Webhook) + +*用其他语言阅读: [English](README.md), [简体中文](README.zh-cn.md).* + +这里我们展示了如何构建一个简单的机器人,它会在收到消息之后回复:"Hello Telegram!"。 + +本质上它是使用一个[Controller](src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java)类监听来自 Telegram 服务器的消息并做出相应,非常简单。 diff --git a/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/BotApplication.java b/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/BotApplication.java similarity index 94% rename from examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/BotApplication.java rename to examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/BotApplication.java index 9477b6c..988574d 100644 --- a/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/BotApplication.java +++ b/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/BotApplication.java @@ -15,7 +15,7 @@ * */ -package io.sgr.telegram.bot.examples.webhook.spring; +package io.sgr.telegram.bot.examples.spring.webhook; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java b/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java new file mode 100644 index 0000000..ac1c621 --- /dev/null +++ b/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/spring/webhook/UpdateController.java @@ -0,0 +1,93 @@ +/* + * Copyright 2017-2020 SgrAlpha + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package io.sgr.telegram.bot.examples.spring.webhook; + +import static java.util.Objects.isNull; + +import io.sgr.telegram.bot.api.BotApi; +import io.sgr.telegram.bot.api.exceptions.ApiCallException; +import io.sgr.telegram.bot.api.models.Update; +import io.sgr.telegram.bot.api.models.http.ApiErrorResponse; +import io.sgr.telegram.bot.api.models.http.SendMessagePayload; +import io.sgr.telegram.bot.engine.BotUpdateProcessor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Nonnull; + +@RestController +public class UpdateController implements BotUpdateProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(UpdateController.class); + + private final String botApiToken; + private final BotApi botApi; + + public UpdateController(@Value("${bot.apiToken}") final String botApiToken) { + this.botApiToken = botApiToken; + this.botApi = BotApi.newBuilder(botApiToken).setLogger(LOGGER).build(); + } + + @PostMapping(path = "/update/{apiToken}") + @ResponseBody + public ResponseEntity receiveUpdate(@PathVariable("apiToken") final String botAndApiToken, @RequestBody final Update update) { + if (!this.botApiToken.equalsIgnoreCase(botAndApiToken)) { + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + if (handleUpdate(update)) { + return ResponseEntity.ok().build(); + } + return ResponseEntity.badRequest().build(); + } + + @Override + public boolean handleUpdate(@Nonnull final Update update) { + LOGGER.info(update.toJson()); + if (isNull(update.getMessage())) { + return true; + } + final SendMessagePayload payload = new SendMessagePayload(update.getMessage().getChat().getId(), "Hello Telegram!"); + botApi.sendMessage(payload) // Send response message asynchronously without blocking next incoming update. + .exceptionally(e -> { + // Something wrong when sending message, you might want to at least log it. + final Throwable cause = e.getCause(); + if (cause instanceof ApiCallException) { + final String message = ((ApiCallException) cause).getErrorResponse() + .flatMap(ApiErrorResponse::getDescription) + .orElse(cause.getMessage()); + LOGGER.error(message, e); + } else { + LOGGER.error(e.getMessage(), e); + } + return null; // Return null because no message been sent. + }) + .thenAccept(message -> { + // Nullable. Do anything you want with sent message here, or ignore it directly. + }); + return true; + } +} diff --git a/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/UpdateController.java b/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/UpdateController.java deleted file mode 100644 index b09e6b4..0000000 --- a/examples/spring-webhook/src/main/java/io/sgr/telegram/bot/examples/webhook/spring/UpdateController.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2017-2020 SgrAlpha - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package io.sgr.telegram.bot.examples.webhook.spring; - -import io.sgr.telegram.bot.api.models.Update; -import io.sgr.telegram.bot.engine.BotUpdateProcessor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import javax.annotation.Nonnull; - -@RestController -public class UpdateController implements BotUpdateProcessor { - - private static final Logger LOGGER = LoggerFactory.getLogger(UpdateController.class); - - private final String botAndApiToken; - - public UpdateController(@Value("${bot.apiToken}") final String botAndApiToken) { - this.botAndApiToken = botAndApiToken; - } - - @PostMapping(path = "/update/{botAndApiToken}") - @ResponseBody - public ResponseEntity receiveUpdate(@PathVariable("botAndApiToken") final String botAndApiToken, @RequestBody final Update update) { - if (!this.botAndApiToken.equalsIgnoreCase(botAndApiToken)) { - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - if (handleUpdate(update)) { - return ResponseEntity.ok().build(); - } - return ResponseEntity.badRequest().build(); - } - - @Override public boolean handleUpdate(@Nonnull final Update update) { - LOGGER.info(update.toJson()); - return true; - } -} diff --git a/examples/spring-webhook/src/main/resources/application.yaml b/examples/spring-webhook/src/main/resources/application.yaml index 84cb9a4..dc625f7 100644 --- a/examples/spring-webhook/src/main/resources/application.yaml +++ b/examples/spring-webhook/src/main/resources/application.yaml @@ -1,5 +1,5 @@ # -# Copyright 2017-2019 SgrAlpha +# Copyright 2017-2020 SgrAlpha # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/examples/spring-webhook/src/test/java/io/sgr/telegram/examples/webhook/spring/BotApplicationTest.java b/examples/spring-webhook/src/test/java/io/sgr/telegram/examples/webhook/spring/BotApplicationTest.java index f992dcb..6894a3d 100644 --- a/examples/spring-webhook/src/test/java/io/sgr/telegram/examples/webhook/spring/BotApplicationTest.java +++ b/examples/spring-webhook/src/test/java/io/sgr/telegram/examples/webhook/spring/BotApplicationTest.java @@ -25,7 +25,7 @@ import io.sgr.telegram.bot.api.models.Message; import io.sgr.telegram.bot.api.models.Update; import io.sgr.telegram.bot.api.utils.JsonUtil; -import io.sgr.telegram.bot.examples.webhook.spring.BotApplication; +import io.sgr.telegram.bot.examples.spring.webhook.BotApplication; import org.junit.Test; import org.junit.runner.RunWith;