简体   繁体   中英

Java webhook controller for a Telegram bot

I've created a basic spring boot app (the java-getting-started from heroku), added an endpoint which I've configured as the webhook on my telegram bot.

However it seems that the endpoint reacts to a GET request, I would expect it to be a POST and therefore have a body to parse

@Controller
@SpringBootApplication
public class Main {

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

How should I be supposed to read the content sent from the telegram bot? It should be json that contains fields such as message > chat > id and message > text , the equivalent in PHP works with this:

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

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

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

So I'm a bit confused how my controller should handle the content..

Get requests support body too. You need to accept a method argument in your testendpoint() method and annotate the argument with @RequestBody so that the underlying objectmapper will attempt to parse your request into the class of the argument type. Obviously, the schema of the request body should match with the request class.

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

Also, the verb on your bot and the endpoint should match. So either you make them talk through a GET or through a POST. You should pick the on appropriate to the semantics of the interactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM