Skip to content

Commit

Permalink
Update sample application and readme files
Browse files Browse the repository at this point in the history
  • Loading branch information
SgrAlpha committed Apr 12, 2020
1 parent e545b26 commit 5a0c822
Show file tree
Hide file tree
Showing 11 changed files with 156 additions and 148 deletions.
57 changes: 16 additions & 41 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<dependency>
<groupId>io.sgr.telegram</groupId>
<artifactId>telegram-bot.engine</artifactId>
<version>1.1.1</version>
</dependency>
```
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.
Expand Down
57 changes: 16 additions & 41 deletions README.zh-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<dependency>
<groupId>io.sgr.telegram</groupId>
<artifactId>telegram-bot.engine</artifactId>
<version>1.1.1</version>
</dependency>
```
如果你使用 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.
Expand Down
7 changes: 7 additions & 0 deletions examples/hello/README.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions examples/hello/README.zh-cn.md
Original file line number Diff line number Diff line change
@@ -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)读到源代码,非常简单。
7 changes: 7 additions & 0 deletions examples/spring-webhook/README.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions examples/spring-webhook/README.zh-cn.md
Original file line number Diff line number Diff line change
@@ -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 服务器的消息并做出相应,非常简单。
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5a0c822

Please sign in to comment.