简体   繁体   English

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

[英]How can I get Live Location in telegram bot via python?

I'm using the python-telegram-bot library.我正在使用python-telegram-bot库。 I want to track a user's Live Location, but I don't know how to do it.我想跟踪用户的实时位置,但我不知道该怎么做。 I try to use Job Queue:我尝试使用作业队列:

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

But updates are void.但是更新是无效的。 I want to track location every 1 minutes.我想每 1 分钟跟踪一次位置。

Just to ellaborate on Seans answer: It can be done quite easily using the python-telegram-bot library.只是为了详细说明肖恩斯的回答:使用 python-telegram-bot 库可以很容易地完成。 Whenever the location did update it can be found in update.edited_message .每当位置确实更新时,它都可以在update.edited_message找到。 This only works if the user is manually sharing live location with the bot of course.当然,这仅在用户手动与机器人共享实时位置时才有效。

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)

Your updates should look like this .您的更新应如下所示

It will only contain first location in .message.location , the latest location is .edit_message.location , and others will be gone, so you need to record yourself. .message.location只会包含第一个位置,最新的位置是.edit_message.location ,其他的都没有了,需要自己记录。

Use this simple function:使用这个简单的 function:

def location(update: Update, context: CallbackContext):
    current_pos = (update.message.location.latitude,update.message.location.longitude)
    print(current_pos)

dp.add_handler(MessageHandler(Filters.location, location))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM