Reputation: 86
Good day, all. Can I allow my java telegram bot to wait for user's reply and continue to ask another question?
if(msg.contains("/register"))
{
SendMessage message = SendMessage
.builder()
.chatId(Long.toString(telegram_id))
.text("Please enter your name.\n" +
"/cancelReg To cancel Registration")
.build();
executeMessageMethod(message);
message = SendMessage
.builder()
.chatId(Long.toString(telegram_id))
.text("Please enter your handicap.\n" +
"/cancelReg To cancel Registration")
.build();
executeMessageMethod(message);
}
My code cannot allow my bot to ask 1 question and wait for user's reply... so how I can solve it...
Upvotes: 2
Views: 1900
Reputation: 7202
You should understand that your message receiver thread shouldn't "wait" anything. It should process every income message instantly, otherwise all your income messages will stuck waiting for the user to reply.
I would add "dialogId" field to the User object and process the incoming messages in this way:
public void process(Message message) {
User user = UserDAO.getOrCreateUserByChatId(message.fromId);
String msg = message.getMessage();
if (msg.contains("/register")) {
user.dialogId = Dialogs.REGISTER; // Dialogs - your enum or an interface/class with static final fields.
} else if (/*all other commands possible*/) {}
if (user.dialogId == null) {
return;
}
switch (user.dialogId) {
case REGISTER:
processRegister(user, msg);
break;
/*all other dialogs possible*/
}
}
private static final String PLEASE_ENTER_NAME_MESSAGE = "Please enter your name.\n/cancelReg To cancel Registration";
private static final String PLEASE_ENTER_HANDICAP_MESSAGE = "Please enter your handicap.\n/cancelReg To cancel Registration";
private static final String REGISTRATION_SUCCESSFULL_MESSAGE = "Registration successfull";
private void processRegister(User user, String msg) {
if (msg.equals("/register")) {
sendMessage(user.chatId, PLEASE_ENTER_NAME_MESSAGE);
return;
}
if (!user.hasName()) {
user.setName(msg);
sendMessage(user.chatId, PLEASE_ENTER_HANDICAP_MESSAGE);
return;
}
if (!user.hasHandicap()) {
user.setHandicap(msg);
user.dialogId = GENERAL; // for example
sendMessage(user.chatId, REGISTRATION_SUCCESSFULL_MESSAGE);
return;
}
}
private void sendMessage(long chatId, String msg) {
SendMessage message = new SendMessage
.builder()
.chatId(Long.toString(chatId))
.text(msg)
.build();
executeMessageMethod(message);
}
At least, that is the way I found and successfully used by myself, I would be grateful if someone will give an advice of how to make it elegant.
Upvotes: 3