Как бот телеграмма может от пользователя получить номер телефона и местоположение?

Хочется сделать отправку контакта и местоположения, например, через кнопки на ReplyKeyboardMarkup.

Минимальный пример:

# pip install python-telegram-bot
from telegram import Update, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext

import config

...

def on_request(update: Update, context: CallbackContext):
    message = update.message

    message.reply_text(
        'Echo: ' + message.text
    )


def main():
    updater = Updater(
        config.TOKEN,
        use_context=True
    )

    dp = updater.dispatcher

    dp.add_handler(CommandHandler('start', on_start))
    dp.add_handler(MessageHandler(Filters.text, on_request))
    
    updater.start_polling()
    
    updater.idle()


if __name__ == '__main__':
    main()

Ответы (1 шт):

Автор решения: gil9red

Нужно:

  • Создать ReplyKeyboardMarkup добавив кнопки с специальными атрибутами:
    • request_location=True и request_contact=True
  • Добавить обработчики для:
    • Filters.contact и Filters.location
  • В обработчиках контракт или геопозицию можно получить из полей:
    • update.message.contact и update.message.location

Тогда, при клике на одну из кнопок, клиент запросит разрешение на отправку и бот получит данные.

Пример:

# pip install python-telegram-bot
from telegram import Update, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext

import config


contact_keyboard = KeyboardButton('Send contact', request_contact=True)
location_keyboard = KeyboardButton('Send location', request_location=True)
custom_keyboard = [[contact_keyboard, location_keyboard]]
REPLY_KEYBOARD_MARKUP = ReplyKeyboardMarkup(custom_keyboard)

...

def on_request(update: Update, context: CallbackContext):
    message = update.message

    message.reply_text(
        'Echo: ' + message.text,
        reply_markup=REPLY_KEYBOARD_MARKUP
    )


def on_contact_or_location(update: Update, context: CallbackContext):
    message = update.message

    text = ''
    if message.contact:
        text += str(message.contact)

    if message.location:
        text += str(message.location)

    message.reply_text(
        text,
        reply_markup=REPLY_KEYBOARD_MARKUP
    )


def main():
    updater = Updater(
        config.TOKEN,
        use_context=True
    )

    dp = updater.dispatcher

    dp.add_handler(CommandHandler('start', on_start))
    dp.add_handler(MessageHandler(Filters.text, on_request))
    dp.add_handler(MessageHandler(Filters.contact | Filters.location, on_contact_or_location))

    updater.start_polling()

    updater.idle()


if __name__ == '__main__':
    main()
→ Ссылка