skip to Main Content

I have a simple telegram bot with a KeyboardButton that appears when a user presses on “Start”. After the user presses on KeyboardButton a window appears and in that window the user presses a button “Share phone number”. I need to get this phone number but a “Contact” object in response is empty. The module that I use – pyTelegramBotApi.

import telebot
from telebot import types

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def register(message):
    keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True)
    reg_button = types.KeyboardButton(text="Share your phone number", request_contact=True)
    keyboard.add(reg_button)
    response = bot.send_message(message.chat.id, 
                                "You should share your phone number", 
                                reply_markup=keyboard)
    print(response.contact)  # response.contact = None here

if __name__ == '__main__':
    bot.polling(none_stop=True)

Is that a right way to get a phone number from user? If no, how can i get it?

3

Answers


  1. No it’s wrong. You should define a new handler to handle the contact.

    dispatcher.add_handler(MessageHandler(Filters.contact, get_contact))
    

    then you should define your get_contact function:

    def get_contact(bot, update):
       chat_id = update.message.chat_id
       phone_number = update.message.contact.phone_number
       other stuffs...
    
    Login or Signup to reply.
  2. You should define new handler for contact

    @bot.message_handler(content_types=['contact'])
    def contact_handler(message):
        print(message.contact.phone_number)
    
    Login or Signup to reply.
  3. def get_contact(message):
        print(message.contact.phone_number)
    

    You should use handler with filter.
    It is not text it is contact.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search