Roger Hache
Roger Hache

Reputation: 415

How can aiogram bot request user's location?

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:

Thanks!

Upvotes: 1

Views: 6819

Answers (2)

Meranda Moziz
Meranda Moziz

Reputation: 1

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)

Upvotes: 0

Roger Hache
Roger Hache

Reputation: 415

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)

Upvotes: 4

Related Questions