电报漫游器未返回API请求

时间:2020-03-24 06:16:18

标签: python telegram python-telegram-bot

我是创建聊天机器人的新手。

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')

我一直在尝试获取api以返回数据。但是,无论何时我尝试发送请求,该机器人都不会提醒我任何事情。任何帮助表示赞赏。

谢谢!

1 个答案:

答案 0 :(得分:1)

问题是两个功能的过滤器相同,因此第一个功能将始终具有优先级并回答您的消息。您的选择是:融合两个功能,删除第一个功能,从消息更改为命令其中一个功能,或者您可以尝试使用register_next_step_handler(),因此您总是必须在询问信息之前向bot致敬(听起来像是过分杀了我)

好吧,让我们开始融合吧

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()

就是这样。好吧,我作弊,我使用的是丹麦,而不是美国,因为与美国相比,丹麦的信息很少。但这不是问题吗?好吧,解决此问题的最佳方法是发送所需的最少信息,因为否则,您将遇到两个限制:邮件中的最大字符数,如果拆分邮件,则请求过多。

PS:也许当您显示从API检索信息时遇到的错误代码并不完美,我无法对其进行测试。