skip to Main Content

Are there ways for an aiogram bot to request a user action which would send user’s location to the bot? User action could be for instance:

  • InlineKeyboardButton, or
  • ReplyKeyboardButton.

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    Here is a way to do this with a ReplyKeyboardButton.

    import logging
    from aiogram import Bot, Dispatcher, executor, types, utils
    
    API_TOKEN = 'replace_this_with_your_api_token'
    
    # Configure logging
    logging.basicConfig(level=logging.INFO)
    
    # Initialize bot and dispatcher
    bot = Bot(token=API_TOKEN, parse_mode="html")
    dp = Dispatcher(bot)
    
    def get_keyboard():
        keyboard = types.ReplyKeyboardMarkup()
        button = types.KeyboardButton("Share Position", request_location=True)
        keyboard.add(button)
        return keyboard
    
    @dp.message_handler(content_types=['location'])
    async def handle_location(message: types.Message):
        lat = message.location.latitude
        lon = message.location.longitude
        reply = "latitude:  {}nlongitude: {}".format(lat, lon)
        await message.answer(reply, reply_markup=types.ReplyKeyboardRemove())
    
    @dp.message_handler(commands=['locate_me'])
    async def cmd_locate_me(message: types.Message):
        reply = "Click on the the button below to share your location"
        await message.answer(reply, reply_markup=get_keyboard())
    
    if __name__ == '__main__':
        executor.start_polling(dp, skip_updates=True)
    

  2. To be able to send geolocation through the buttons you have to write for example like this:

    from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
    
    but1 = KeyboardButton('🕹 Share with GEO', request_location=True)
    
    button1 = ReplyKeyboardMarkup(resize_keyboard=True)
    
    button1.add(but1)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search