-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.py
77 lines (65 loc) · 1.93 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
# Manipulate sys.path to be able to import rivescript from this local git
# repository.
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
from flask import Flask, request, Response, jsonify
import json
from rivescript import RiveScript
from redis_storage import RedisSessionStorage
# Set up the RiveScript bot. This loads the replies from `/eg/brain` of the
# git repository.
bot = RiveScript(
session_manager=RedisSessionStorage()
)
bot.load_directory(
os.path.join(os.path.dirname(__file__), "..", "brain")
)
bot.sort_replies()
app = Flask(__name__)
@app.route("/reply", methods=["POST"])
def reply():
"""Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars
"""
params = request.json
if not params:
return jsonify({
"status": "error",
"error": "Request must be of the application/json type!",
})
username = params.get("username")
message = params.get("message")
# uservars = params.get("vars", dict())
# Make sure the required params are present.
if username is None or message is None:
return jsonify({
"status": "error",
"error": "username and message are required keys",
})
# Get a reply from the bot.
reply = bot.reply(username, message)
# Send the response.
return reply
@app.route("/")
@app.route("/<path:path>")
def index(path=None):
"""On all other routes, just return an example `curl` command."""
payload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso",
}
}
return Response(r"""Usage: curl -i \
-H "Content-Type: application/json" \
-X POST -d '{}' \
http://localhost:5000/reply""".format(json.dumps(payload)),
mimetype="text/plain")
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)