You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Aiogram获取用户真实位置并移除手动选点功能?

解决Telegram机器人限制手动发送位置的问题

一、核心解决方案:验证实时GPS位置字段

Telegram中,真实GPS实时位置会携带live_period参数,而手动在地图选点发送的位置该字段为None。通过判断这个字段,就能过滤掉手动选点的位置,只接收真实GPS数据。

修改后的处理器代码如下:

@dp.message_handler(state=UserState.location, content_types=['location'])
async def handle_location(message: types.Message, state: FSMContext):
    # 过滤手动选点的位置
    if message.location.live_period is None:
        await message.answer('请发送真实的GPS位置,不要手动选择地点')
        return
    
    user_loc1 = message.location.latitude
    user_loc2 = message.location.longitude
    data = await state.get_data()
    org_loc1 = data['id_in_qr'][0]
    org_loc2 = data['id_in_qr'][1]
    res = geolocation.ras(user_loc1, user_loc2, org_loc1, org_loc2)
    
    if res > 200 or not res:
        await message.answer('Вы еще не дошли до работы', reply_markup=types.ReplyKeyboardRemove())
        await UserState.location.set()
    else:
        await message.answer(f'Вы пришли на работу в ', reply_markup=types.ReplyKeyboardRemove())
        await state.finish()
    
    # 安全清理临时文件
    try:
        for file in glob.glob(f"data/{message.from_user.id}{message.date}.png"):
            os.remove(file)
    except Exception:
        # 可选:添加日志记录异常
        pass

二、辅助优化建议

  • 引导用户发送位置时,使用明确的请求按钮:
    async def trigger_location_request(message: types.Message, state: FSMContext):
        keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
        keyboard.add(types.KeyboardButton('发送我的实时位置', request_location=True))
        await message.answer('请点击下方按钮发送你的GPS位置', reply_markup=keyboard)
        await UserState.location.set()
    
  • 可以将提示文案替换为更贴合场景的中文/本地化内容,提升用户体验
  • 位置距离计算逻辑可增加参数合法性校验,避免因数据异常导致的报错

内容的提问来源于stack exchange,提问作者Janarbek Keneshbekov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:25:27