Skip to content

Commit

Permalink
Html client (#10)
Browse files Browse the repository at this point in the history
* added a default html page to test the chatbot
* lint
  • Loading branch information
greenkey committed Apr 18, 2017
1 parent f1a140c commit 375aca9
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 9 deletions.
2 changes: 2 additions & 0 deletions pychatbot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ def command_names(self):
yield method_name

def _is_command(self, command_name):
""" Returns true if the Bot instance have a command named `command_name`
"""
command = getattr(self, command_name)
try:
return callable(command) and command.is_command
Expand Down
32 changes: 23 additions & 9 deletions pychatbot/endpoints/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from socket import error as socket_error
from http.client import HTTPConnection
import logging
import os

try: # specific imports for Python 3
from urllib.parse import parse_qs
Expand Down Expand Up @@ -38,16 +39,29 @@ def do_GET(self):
`{"out_message": "hello"}`
"""
function, params = self.path.split("?")
function, params = function[1:], parse_qs(params)
self.send_response(200)
self.end_headers()
output = {
"out_message": self.server.bot.process(
"".join(params["in_message"])
try:
function, params = self.path.split("?")
function, params = function[1:], parse_qs(params)
self.send_response(200)
self.end_headers()
output = {
"out_message": self.server.bot.process(
"".join(params["in_message"])
)
}
self.wfile.write(json.dumps(output).encode("UTF-8"))
except ValueError:
# if no command is specified, serve the default html
filename = os.path.join(
os.path.dirname(__file__),
'http',
'index.html'
)
}
self.wfile.write(json.dumps(output).encode("UTF-8"))
with open(filename, 'r') as f:
self.send_response(200)
self.end_headers()
output = f.read()
self.wfile.write(output.encode("UTF-8"))

def log_message(self, format_, *args):
""" Redefinition of the `log_message` method to use `logging` library.
Expand Down
55 changes: 55 additions & 0 deletions pychatbot/endpoints/http/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<html>
<head>
<title>Pychatbot</title>
<script>

function init(){
document.getElementById("pychatbot-message").focus();
}

function sendMessage(){
var input = document.getElementById("pychatbot-message");

addMessage("you", input.value);
var url = "/process?in_message=" + encodeURIComponent(input.value);
input.value = "";

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status == 200) {
addMessage("bot", xhr.response.out_message);
} else {
addMessage("system", "Error");
}
};
xhr.send();
}

function addMessage(user, message){
var text = "<p><b>" + user + ":</b> " + message + "</p>";
var chatScreen = document.getElementById("pychatbot-read")
chatScreen.innerHTML += text;
chatScreen.scrollTop += 100;
}

</script>
<style type="text/css">
#pychatbot-read {
height: 90%;
overflow-y: scroll;
border: 1px solid silver;
}
</style>
</head>
<body onload="javascript: init()">
<div id="pychatbot-read"></div>
<div id="pychatbot-write">
<form action="javascript: sendMessage()">
<input type="text" id="pychatbot-message" />
<input type="submit" value="Send" />
</form>
</div>
</body>
</html>
15 changes: 15 additions & 0 deletions tests/http_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,18 @@ def test_uses_a_custom_port():
assert resp.status_code == 200

bot.stop()


def test_expose_html_page(create_bot):
""" Starting the bot, an HTML page is available in the root of the webserver
showing a form to chat with the bot.
"""

endpoint = HttpEndpoint(port=randint(8000, 9000))
create_bot(Bot(), endpoint)

address = "http://%s:%d/" % (endpoint.host, endpoint.port)

response = requests.get(address)

assert 'html' in response.text.lower()

0 comments on commit 375aca9

Please sign in to comment.