Skip to content

Instantly share code, notes, and snippets.

@bennokr
Last active June 4, 2024 15:40
Show Gist options
  • Select an option

  • Save bennokr/738c1ef0e0e5ef2dd4906bef9cbce45d to your computer and use it in GitHub Desktop.

Select an option

Save bennokr/738c1ef0e0e5ef2dd4906bef9cbce45d to your computer and use it in GitHub Desktop.
Simple Flask chatbot interface

Simple flask chatbot interface

from flask import Flask, render_template, request
from game import guess, select
app = Flask(__name__, template_folder='.')
@app.route('/ask', methods=['POST'])
def ask():
data = request.get_json(force=True)
options = data.get('options', list(range(10)))
if data.get('answer') and data.get('candidate'):
answer = data['answer']
candidate = data['candidate']
options = select(options, candidate, answer == 3)
candidate = guess(options)
return {
'options': options,
'candidate': candidate,
}
@app.route('/')
def hello_world():
return render_template('index.html')
def guess(options):
o = sorted(options)
return options[int(len(o) / 2)]
def select(options, candidate, is_higher):
i = options.index(candidate)
if is_higher:
return options[i:]
else:
return options[:i]
if __name__ == '__main__':
options = list(range(10))
print('Think of a number from ', options)
answer = None
while True:
candidate = guess(options)
print('Is it', candidate, '?')
answer = int(input('(1 = lower, 2 = correct, 3 = higher) '))
if answer == 2:
print('yay!')
break
else:
options = select(options, candidate, answer == 3)
<!DOCTYPE html>
<html>
<head>
<title>Simple chat bot</title>
<script type="text/javascript">
function ask(answer) {
data = {
"options": document.state.options,
"candidate": document.state.candidate,
"answer": answer,
};
const params = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch("/ask", params).then((response) => {
response.json().then((data) =>{
console.log(data)
document.state = data;
const div = document.createElement('div');
div.innerHTML = '<br>Is it ' + data['candidate'] + '?<br>';
const b1 = document.createElement('button');
b1.innerText = 'lower';
b1.onclick = (() => ask(1))
div.append(b1);
const b2 = document.createElement('button');
b2.innerText = 'correct';
b2.onclick = (() => win())
div.append(b2);
const b3 = document.createElement('button');
b3.innerText = 'higher';
b3.onclick = (() => ask(3))
div.append(b3);
document.body.append(div);
});
});
}
function win() {
const div = document.createElement('div');
div.innerHTML = 'yay!';
document.body.appendChild(div);
}
function init() {
document.state = {};
ask(null)
}
</script>
</head>
<body onload="init()">
Let's play a game.
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment