[英]Python-telegram-bot detect start and end of live location
如果用戶分享他們的實時位置,我能夠檢測到用戶的當前位置。 在調試模式下,我檢查了生成的消息,確實有 GPS 坐標。 但是,消息中沒有信息告訴我實時位置是開始還是結束。
當我啟動實時位置時,它只會更新位置。 更奇怪的是,當我結束實時位置時,程序將此視為任何其他位置更新。 因此,結束直播位置無法與開始直播位置或發送單個當前(非直播)位置區分開來。
我的問題是:如何檢測實時位置的開始和結束?
到目前為止,這是我的代碼:
def location(update: Update, context: CallbackContext):
user = update.effective_user
message = None
global prev_message
if update.edited_message:
message = update.edited_message
else:
message = update.message
current_pos = (message.location.latitude, message.location.longitude)
def main() -> None:
updater = Updater(API_KEY)
dispatcher = updater.dispatcher
location_handler = MessageHandler(Filters.location, location)
dispatcher.add_handler(location_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
編輯:我發現每種處理的位置相關回調的消息屬性略有不同:
有“edit_date” | 有“live_period” | |
---|---|---|
單個(非實時)位置更新 | —— | —— |
直播位置的開始 | —— | 伏 |
直播位置結束 | 伏 | —— |
實時位置更新 | 伏 | 伏 |
使用此信息,我可以准確確定我正在處理的位置回調類型:
def location(update: Update, context: CallbackContext):
user = update.effective_user
msg_type = 0
if update.edited_message:
message = update.edited_message
else:
message = update.message
if message["edit_date"] is not None:
msg_type += 1
if message["location"]["live_period"] is not None:
msg_type += 1 << 1
if msg_type == 0:
context.bot.send_message(user.id, "Single (non-live) location update.")
elif msg_type == 1:
context.bot.send_message(user.id, "End of live period.")
elif msg_type == 2:
context.bot.send_message(user.id, "Start of live period")
elif msg_type == 3:
context.bot.send_message(user.id, "Live location update.")
這種方法的問題在於它只適用於回調。 當您手動結束直播期時,它會起作用。 但是,當直播期自行結束時,沒有回調。 這意味着此方法不會檢測自動活動期結束。
我通過創建一個定時事件來解決它。 當實時位置開始時,我計划在message["location"]["live_period"]
秒后運行一個事件:
threading.Timer(interval=message["location"]["live_period"], function=end_live_period,
args=(this_user, context))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.