如何构建 Telegram 机器人以使用 java 向您推荐披萨?

How to build a Telegram bot to suggest you pizza using java?

我创建了一个主 java 文件并为机器人添加了一条指令:在我创建的 public 频道上说 "I love Pizza"。

public class Main {
  public static void main(String[] args) {
  //create a new Telegram bot object to start talking with Telegram
  TelegramBot bot = TelegramBotAdapter.build(“HERE YOUR API KEY”);
  bot.sendMessage(“@pizzaciaopizza”, “I love Pizza”);
  }
}

这成功了。好的开始。谢天谢地,我的机器人喜欢披萨。 我想让我的机器人能够回答像“/recommendPizza”这样的命令并回答 something.So 如何做到这一点?

有什么帮助吗?

您似乎在使用 https://github.com/pengrad/java-telegram-bot-api,对吧?

我以前用过https://github.com/rubenlagus/TelegramBots。它提供了一个简单的侦听器 API 来接收更新:

public class PizzaBot {

    private static final Logger LOG = Logger.getLogger(PizzaBot.class.getName());

    public static void main(String... args) throws Exception {
        TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
        telegramBotsApi.registerBot(new TelegramLongPollingBot() {

            @Override
            public void onUpdateReceived(Update update) {
                Message message = update.getMessage();
                Long chatId = message.getChatId();
                String input = message.getText();
                if ("/recommendPizza".equals(input)) {
                    SendMessage request = new SendMessage();
                    request.setChatId(chatId.toString());
                    request.setText("Have a calzone!");
                    try {
                        sendMessage(request);
                    } catch (TelegramApiException e) {
                        LOG.log(Level.SEVERE, "Could not send message", e);
                    }
                }
            }

            @Override
            public String getBotUsername() {
                return "YOUR_BOT_USERNAME";
            }

            @Override
            public String getBotToken() {
                return "YOUR_BOT_TOKEN";
            }
        });
    }
}