rubenlagus / TelegramBots

Java library to create bots using Telegram Bots API
https://telegram.me/JavaBotsApi
MIT License
4.77k stars 1.22k forks source link

How to associate user replies with messages #1222

Open guoxiaopang opened 1 year ago

guoxiaopang commented 1 year ago

For example: Bot: Please enter your recharge amount? user: 20 But I got this 20. It's just an ordinary piece of news. It's not related to what the robot said

guoxiaopang commented 1 year ago

i used
implementation 'org.telegram:telegrambots:6.5.0' not Ability

centralhardware commented 1 year ago

you need implement FSM. some thing like this

Map<Long, UserState> fsm = new HashMap<>();
---
Send message Please enter your recharge amount?
fsm.put(chatId, WAITING_RECHARGE)
--- and waiting for user answer
if (fsm.get(chatId) == WAITING_RECHARGE){

}
kenkoro commented 1 year ago

@centralhardware or @rubenlagus, suppose I have an ability to add a new book (or something in String format), here's an example:

public class AbilityAddBook implements AbilityExtension {
    private final BookBot extension;

    public AbilityAddBook(BookBot extension) {
        this.extension = extension;
    }

    public Ability addBook() {
        return Ability.builder()
                .name("addbook")
                .info("add a new book")
                .locality(ALL)
                .privacy(PUBLIC)
                .action(ctx -> extension.responseHandler().replyToAddBook(ctx.chatId()))
                .build();
    }
}

Also in ResponseHandler.class:

public void replyToAddBook(final long chatId) {
    try {
        sender.execute(buildAddBookMessage(chatId));
        chatStates.put(chatId, AWAITING_ANSWER);
        // What's next?
    } catch (TelegramApiException te) {
        LOG.error(ERROR_ON_REPLY + te.getMessage());
    }
}

private SendMessage buildAddBookMessage(long chatId) {
    final var message = new SendMessage();
    message.setText(ADD_BOOK_MSG);
    message.enableMarkdown(true);
    message.setChatId(chatId);
    message.setReplyMarkup(KeyboardFactory.withBackButton());

    return message;
}

So, I want to actually store (you can also say capture) user's reply (which book he/she wants to add) in a variable (for now, not in DB). How should I do that? Would you be kind enough to write detailed example of it? Because, when I actually try to use Reply.class, eg. add the .reply() to AbilityAddBook.class, it comes to overlapping the other commands like /start or /help. If you don't mind, can you explain this as well?

P.S.: repo