Java Telegram Bot: Handling User Contact Information

Need help with Telegram bot contact handling in Java

I’m working on a Telegram bot using Java. I want the bot to ask for the user’s contact info and then confirm if the phone number is correct. I’m stuck on how to implement this feature.

Here’s what I’ve tried so far:

// When user presses a button to send contact
if (message.getText().equals("ShareContact")) {
    // How to handle contact here?
}

// Attempt to check if message has contact
if (message.hasContactInfo()) {
    // How to resend contact to user?
}

// Another attempt
String phone = message.getContactInfo().getPhone();
sendMessage(phone);

How can I properly receive the contact info and then send it back to the user for confirmation? Any help would be greatly appreciated!

I’ve dealt with this exact issue in my Telegram bot projects. Here’s a solution that worked well for me:

Use the TelegramLongPollingBot class and override the onUpdateReceived method. Inside this method, check for contact info like this:

if (update.hasMessage() && update.getMessage().hasContact()) {
Contact contact = update.getMessage().getContact();
String phoneNumber = contact.getPhoneNumber();

SendMessage confirmMsg = new SendMessage();
confirmMsg.setChatId(update.getMessage().getChatId());
confirmMsg.setText("Is this your correct number: " + phoneNumber + "?");

// Add confirmation buttons here

execute(confirmMsg);

}

This approach handles the contact reception smoothly and sends back a confirmation message. You’ll need to implement the button logic separately. Hope this helps with your bot development!

hey, i had similar issues when working on this. try checking if update.getMessage().hasContact() and then get the contact phone.

send a confirmation to the user and see if it works. hope that helps!

I’ve worked with Telegram bots in Java before, and handling contact information can be tricky. Here’s what worked for me:

First, you need to use the ‘Contact’ class from the Telegram API. When a user shares their contact, you’ll receive a Message object containing a Contact object.

To handle this, modify your code like this:

if (update.hasMessage() && update.getMessage().hasContact()) {
Contact contact = update.getMessage().getContact();
String phoneNumber = contact.getPhoneNumber();

// Send confirmation message
SendMessage confirmMessage = new SendMessage();
confirmMessage.setChatId(update.getMessage().getChatId().toString());
confirmMessage.setText("Is this your correct number: " + phoneNumber + "?");

// Add yes/no inline keyboard here for user confirmation

execute(confirmMessage);

}

This should get you started. Remember to handle the user’s confirmation response appropriately.