我用Python和Flask制作了这个简单的聊天机器人。当我在本地服务器上运行它时,它工作得非常好,但我将它上传到Heroku(我第一次上传),有些选项有时才起作用
在上图中,输入3会提示应用程序向用户询问城市名称,但大多数情况下不会
#imports
import requests
from flask import Flask, render_template, request
app = Flask(__name__)
import random
newsApiKey = 'c0f976e7caac4b608d84c4546e0b892c'
isGreeted = False
isThree = False
def getRequest(location):
global newsApiKey
url = "http://newsapi.org/v2/everything?q={} AND +corona AND english&qInTitle=+corona&language=en&from=2020-03-25&sortBy=relevancy&apiKey={}".format(location,newsApiKey)
r = requests.get(url)
return r
def getGreeting():
greets = ['Hello there General Kenobi!', 'Hi there!', 'Hi, how are you?']
return random.choice(greets)
#define app routes
@app.route("/")
def index():
return render_template("index.html")
@app.route("/get")
#function for the bot response
def get_bot_response():
global isGreeted
global isThree
userText = request.args.get('msg')
# return str(englishBot.get_response(userText))
responseMessage = ""
if userText in ['Hi!', 'Hello!', 'Hi'] and isGreeted == False:
responseMessage = getGreeting() + "\n\nChoose an option from below menu:\n\n1 - What is Covid-19?\n\n2 - What are the symptoms of Covid-19?\n\n3 - Local news about Covid-19\n\n4 - What should I do?"
isGreeted = True
elif userText in ['1','2','3','4'] and isGreeted:
if userText == '1':
responseMessage = "Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus."
elif userText == '2':
responseMessage = "Common symptoms include fever, tiredness, dry cough. Other symptoms include shortness of breath, aches and pains, sore throat, diarrhoea, runny nose. People with mild symptoms should try self isolating and others should seek medical attention."
elif userText == '3' and isThree == False:
responseMessage = 'Enter your city name'
isThree = True
elif userText == '4':
responseMessage = 'Stay at home. If you plan to go outside, avoid using public transportation. Seek medical attention if you have trouble breathing, pain in chest, bluish lips. Cover your face with an N95 mask. Clean your hands often.'
elif isThree:
r = getRequest(userText).json()
# print(r)
isThree = False
counter = 0
for article in r['articles']:
if counter != 3:
responseMessage += article['title'] + '\n' + article['description'] + '\n\n'
counter = counter + 1
else:
break
return responseMessage
if __name__ == "__main__":
app.run()
这和我处理回应的方式有关吗?或者我使用全局变量的事实?如果是,那么更好的方法是什么?先谢谢你
我建议使用flask socketio进行实时通信,尤其是聊天。它是套接字io的包装器 https://flask-socketio.readthedocs.io/en/latest/
用python
客户
还要检查heroku服务器上发生了什么,请使用此
相关问题 更多 >
编程相关推荐