如何通过 python 在电报机器人中获取实时位置?

Pav*_*Zub 3 python location python-telegram-bot telegram-bot

我正在使用python-telegram-bot图书馆。我想跟踪用户的实时位置,但我不知道该怎么做。我尝试使用作业队列:

def notification(bot, job):
  updates = bot.get_updates()
  print([u.message.location for u in updates])
# Add job to queue

job = job_queue.run_repeating(notification, 10, 1, context=chat_id)
chat_data['job'] = job
Run Code Online (Sandbox Code Playgroud)

但更新无效。我想每 1 分钟跟踪一次位置。

Luk*_* E. 7

只是为了详细说明肖恩斯的回答:使用 python-telegram-bot 库可以很容易地完成。每当位置确实更新时,都可以在update.edited_message. 当然,这仅在用户手动与机器人共享实时位置时才有效。

def location(bot, update):
    message = None
    if update.edited_message:
        message = update.edited_message
    else:
        message = update.message
    current_pos = (message.location.latitude, message.location.longitude)

location_handler = MessageHandler(Filters.location, location)
dispatcher.add_handler(location_handler)
Run Code Online (Sandbox Code Playgroud)


Sea*_*ean 1

您的更新应该如下所示

只会包含 中的第一个位置.message.location,最新的位置是.edit_message.location,其他的都会消失,所以需要你自己记录。