получить телефон пользователя

Python Telebot – get user phone number

Hello to all! Actually, the essence of the problem is indicated in the title of the entry: how to get the user’s phone using Python and the Telebot library. Let’s figure it out;)

Below is an example of a working year that I hope will help you 🙂 Suddenly what – feel free to ask questions on mail or in Telegram.

  1. import telebot #Connect the Telebot library - for working with Telegram
  2. from telebot import types #add-ons connected
  3. import config #We connected the Config library, with which we can store the token not in the program code;) but in the config.py file. Important: this file must be in the same directory as the code!
  4.  
  5. bot = telebot.TeleBot (config.token) # Connect a token
  6.  
  7. @bot.message_handler (commands = ['number']) # Announced a branch to work on the <strong> number </strong> command
  8. def phone (message):
  9.     keyboard = types.ReplyKeyboardMarkup (row_width = 1, resize_keyboard = True) # Connect the keyboard
  10.     button_phone = types.KeyboardButton (text = "Send phone", request_contact = True) # Specify the name of the button that the user will see
  11.     keyboard.add (button_phone) #Add this button
  12.     bot.send_message (message.chat.id, 'Phone number', reply_markup = keyboard) # Duplicate with a message that the user will now send his phone number to the bot (just in case, but this is not necessary)
  13.  
  14. @bot.message_handler (content_types = ['contact']) # Announced a branch in which we prescribe logic in case the user decides to send a phone number :)
  15. def contact (message):
  16.     if message.contact is not None: # If the sent object <strong> contact </strong> is not zero
  17.         print (message.contact) # We display the contact information in our panel. But in general, you can save them, or do something else, for example.

As you can see – everything is very, very simple 🙂
Thanks for attention!