Search code examples
pythonpython-3.xtelegramtelethontelegram-api

Get geolocation via Telegram bot using inline


If you use the bot via Inline in the Telegram, the bot can request the user's location, if this is enabled in the bot settings. The telethon.events.inlinequery.InlineQuery class is responsible for getting geolocation.

Here is the pseudo-code through which I tried to get geolocation in order to use latitude and longitude in the future:

from telethon import TelegramClient, events

@client.on(events.InlineQuery)
async def handler(event):
    location = event.geo
    builder = event.builder

    await event.answer([
        builder.article("Coordinates: ", text="Long: " + location.long + "\nLat: " + location.lat),
    ])

But I can't do anything. Constantly outputs AttributeError: 'NoneType' object has no attribute 'lat'.

I would be grateful if you could help me in obtaining and using this data.


Solution

  • This was a bug in Telethon v1.23.0. The solution will be to update to a greater version (once that's out). In the meantime, you can still obtain the geo through the raw update:

    from telethon import TelegramClient, events
    
    @client.on(events.InlineQuery)
    async def handler(event):
        location = event.query.geo
        #                ^^^^^ raw update query
        builder = event.builder
    
        if location is None:
            # you still should check if the location is None because user may deny it or not have the GPS on
            return await event.answer([builder.article('Geo must be enabled!', text='Please enable GPS to use this bot'])
    
        await event.answer([
            builder.article("Coordinates: ", text="Long: " + location.long + "\nLat: " + location.lat),
        ])