I’m working with the python-telegram-bot library and need to monitor a user’s real-time location sharing. I’ve been struggling to figure out the correct approach for this.
Here’s what I attempted using a scheduled task:
def track_user_position(context):
bot_instance = context.bot
recent_messages = bot_instance.get_updates()
print([msg.message.location for msg in recent_messages])
# Schedule the tracking function
tracking_job = job_queue.run_repeating(track_user_position, 60, 5, context=user_chat_id)
chat_data['tracking_job'] = tracking_job
The problem is that I’m getting empty results when trying to fetch updates. My goal is to capture the user’s position data every minute when they share their live location. What’s the proper way to handle incoming location messages in this scenario?
You’re doing this backwards. get_updates() won’t work when you’ve got a bot running with webhooks or polling - those already consume the updates. Handle location messages through your normal message handler instead. Set up a location handler that grabs incoming location data and stores it somewhere you can access later. When someone starts sharing live location, Telegram automatically sends periodic updates - no polling needed. Use a MessageHandler with filters.LOCATION to catch these updates, then store the coordinates with timestamps in a database or memory. Live location sharing sends multiple location messages over time, so your handler gets called repeatedly while the user keeps sharing. Then you can access this stored data whenever you need it instead of trying to fetch it on a schedule.
The problem is get_updates() conflicts with your bot’s polling or webhooks - they’re already consuming the update stream, so there’s nothing left for manual calls. Don’t schedule a function to fetch updates. Let them come to you instead. Set up a location message handler that processes incoming location data as it arrives. Live location sharing sends position updates automatically every few seconds while it’s active. Store the location data in a dictionary or database - use user IDs as keys and coordinate/timestamp pairs as values. Now you can grab the latest position whenever you need it without polling. The handler keeps updating your storage as new position messages come in from users sharing live location. Way more efficient and reliable than trying to pull updates manually.
you’re mixing polling methods man. since ur bot already handles updates automatically, u can’t manually grab them with get_updates(). just set up a regular handler for location messages and save the data. telegram sends location updates automatically during live sharing, so u don’t need to schedule anything - ur handler will fire every time new coords come in.