【问题标题】:Java webhook controller for a Telegram botTelegram bot 的 Java webhook 控制器
【发布时间】:2020-06-26 07:35:24
【问题描述】:

我创建了一个基本的 spring boot 应用程序(从 heroku 开始的 java-getting-started),添加了一个端点,我已将其配置为我的电报机器人上的 webhook。

但是看起来端点对 GET 请求做出反应,我希望它是一个 POST,因此有一个要解析的主体

@Controller
@SpringBootApplication
public class Main {

  @RequestMapping(value = "/testendpoint", method = RequestMethod.GET)
  public String testendpoint() {
    // send a response to the bot, this part works fine
  }

我应该如何阅读电报机器人发送的内容?它应该是包含 message > chat > idmessage > text 等字段的 json,PHP 中的等效项适用于此:

$update = json_decode(file_get_contents("php://input"), TRUE)

$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

来自https://nordicapis.com/how-to-build-your-first-telegram-bot-using-php-in-under-30-minutes/

所以我有点困惑我的控制器应该如何处理内容..

【问题讨论】:

  • 您是否尝试过更改第一个代码中的RequestMethod.GET
  • 是的,我也有它的双端点和 POST,但答案是 GET

标签: java php spring spring-boot telegram


【解决方案1】:

获取请求也支持正文。您需要在 testendpoint() 方法中接受方法参数并使用 @RequestBody 注释参数,以便底层对象映射器将尝试将您的请求解析为参数类型的类。显然,请求体的 schema 应该与请求类匹配。

  @RequestMapping(value = "/testendpoint", method = RequestMethod.GET)
  public String testendpoint(@RequestBody MyRequestClass request) {
    // send a response to the bot, this part works fine
  }

此外,您的机器人和端点上的动词应该匹配。因此,要么让他们通过 GET 或通过 POST 交谈。您应该选择适合交互语义的选项。

【讨论】:

  • 很高兴知道,谢谢!我已经输入了@RequestBody Object object,直到我确切地知道模型应该是怎样的。但是,当我检查日志时,我会收到 HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.Main.testendpoint(java.lang.Object),我会尝试找出原因(如果您有任何想法,我们非常欢迎)
  • 看起来客户端没有发送带有请求的正文。你如何测试这个端点?尝试使用 Postman 等休息工具直接调用您的端点并将字符串作为正文传递
猜你喜欢
  • 2017-08-03
  • 2018-03-12
  • 2016-08-27
  • 2017-01-11
  • 2017-07-22
  • 2016-07-15
  • 1970-01-01
  • 2015-09-24
  • 2016-04-10
相关资源
最近更新 更多