Search code examples
pythontelegramtelegram-botpython-telegram-bot

How do I send a telegram bot a location about the nearest restaurants?


I'm trying to create a bot that will show restaurants near users. I wrote a function, but it gives an error. It determines the user's location, determines places nearby, but does not output labels on the interactive map to the chat. Here is the code and the console with the error:

def restaraunt(bot,update):
    google_places = GooglePlaces(GMAPSAPI)
    a = bot.message.location
    b = a['latitude']
    c = a['longitude']
    d = {'lat': b, 'lng': c}
    query_result = google_places.nearby_search(
    lat_lng=d,
    radius=500,
    types=[types.TYPE_RESTAURANT])
    for place in query_result.places:
        print(place.geo_location['lat'])
        lat = place.geo_location['lat']
        lng = place.geo_location['lng']
        bot.send_location(bot.message.from_user.id, latitude=lat, longitude=lng)
Traceback (most recent call last):
  File "C:\Users\FuNkY\PycharmProjects\BotTG\venv\lib\site-packages\telegram\ext\dispatcher.py", line 555, in process_update
    handler.handle_update(update, self, check, context)
  File "C:\Users\FuNkY\PycharmProjects\BotTG\venv\lib\site-packages\telegram\ext\handler.py", line 198, in handle_update
    return self.callback(update, context)
  File "C:/Users/FuNkY/PycharmProjects/BotTG/123.py", line 70, in restaraunt
    bot.send_location(bot.message.from_user.id, latitude=lat, longitude=lng)
AttributeError: 'Update' object has no attribute 'send_location'


Solution

  • This is happening because you're using the old style hander callback. To fix this problem, simply change your function signature and update the references:

    def restaraunt(update, context):
        google_places = GooglePlaces(GMAPSAPI)
        a = update.message.location
        b = a.latitude
        c = a.longitude
        d = {'lat': b, 'lng': c}
        query_result = google_places.nearby_search(lat_lng=d, radius=500, types=[types.TYPE_RESTAURANT])
    
        for place in query_result.places:
            lat = float(str(place.geo_location['lat']))
            lng = float(str(place.geo_location['lng']))
            context.bot.send_location(update.effective_user.id, latitude=lat, longitude=lng)
    

    Also have a look at this transition guide if you've recently updated your python-telegram-bot

    Edit: Converted the Decimal object to float, as that was an error too.