使用内联通过 Telegram 机器人获取地理位置

Get geolocation via Telegram bot using inline

如果您在 Telegram 中通过内联使用机器人,机器人可以请求用户的位置,前提是在机器人设置中启用了此功能。 telethon.events.inlinequery.InlineQuery class 负责获取地理定位。

这是我尝试获取地理定位以便将来使用纬度和经度的伪代码:

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),
    ])

但我无能为力。不断输出AttributeError: 'NoneType' object has no attribute 'lat'.

如果您能帮助我获取并使用这些数据,我将不胜感激。

这是 Telethon v1.23.0 中的错误。解决方案是更新到更高版本(一旦发布)。同时,您仍然可以通过原始更新获取geo:

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),
    ])