Search code examples
pythontelegrampython-telegram-bot

Telegram bot not returning API requests


I'm v new to creating chatbots.

import telebot

bot = telebot.TeleBot('123345677789')

def sendMessage(message, text):
   bot.send_message(message.chat.id, text)

@bot.message_handler(func=lambda msg: msg.text is not None)
def reply_to_message(message):
    if 'hello' in message.text.lower():
        sendMessage(message, 'Hello! How are you doing today?')
    else:
        bot.reply_to(message,'try hi or hello')

@bot.message_handler(func=lambda msg: msg.text is not None)
def getresponse(user_input):
    if 'virus' in user_input.text.lower():
        url = "https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats"
        querystring = {"country":"USA"}
        headers = {
            'x-rapidapi-host': "covid-19-coronavirus-statistics.p.rapidapi.com",
            'x-rapidapi-key': "ea33a4fd9cmshd4ead0c7290"}
        response = requests.request("GET", url, headers=headers, params=querystring)
        bot.reply_to(user_input,response.text)
    else:
        bot.reply_to(user_input,'type virus')

I've been trying to get the api to return the data. But whenever i try to send the requests, the bot doesnt remind me anything. Any help is appreciated.

Thanks!


Solution

  • The problem is that you have the same filter for both functions, so the first function will always take the priority and answer your messages. Your options would be: fuse both functions, delete the first function, changing from message to command one of your functions or you can try using register_next_step_handler() so you always have to salute the bot before asking for information (sounds like overkill to me).

    Ok, lets go with fusing:

    import telebot
    import requests
    
    bot = telebot.TeleBot(tgtoken)
    
    def sendMessage(message, text):
        bot.send_message(message.chat.id, text)
    
    @bot.message_handler(func=lambda msg: msg.text is not None)
    def getresponse(user_input):
        if user_input.text.lower() in ["hello", "hi"]:
            sendMessage(user_input, 'Hello! How are you doing today?')
        elif 'virus' in user_input.text.lower():
            url = "https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats"
            querystring = {"country":"Denmark"}
            headers = {
                'x-rapidapi-host': "covid-19-coronavirus-statistics.p.rapidapi.com",
                'x-rapidapi-key': rapidapitoken}
            response = requests.request("GET", url, headers=headers, params=querystring)
            if not response.json()["error"]:
                bot.reply_to(user_input,str(response.json()["data"]))
            else:
                bot.reply_to(user_input,"Error: {!s} , StatusCode: {!s}, Message: {!s}".format(response.json()["error"], response.json()["statusCode"], response.json()["message"]))
        else:
            bot.reply_to(user_input,'type hi, hello, or virus')
    
    bot.polling()
    

    And that's it. Ok, I cheated, I used Denmark and not USA because Denmark information is small compared to USA. But that wasn't the question, riiiiight? Well, the best way to solve it is to send the minimum information required because otherwise you will hit two limits: max characters in a message and too many requests if you split the message.

    PS: Maybe the code when you show the error you get at retrieving the information from the API isn't perfect, I couldn't test it.