Pythonでチャットボットを作成する

Pythonでchatbotを作成しました。
実行イメージはこんな感じです。

チャットのインターフェイス部分はChatUxを使用しました。

プログラム

import json
from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def get_request():
    value = request.args.get('text', '')
    callback = request.args.get('callback', '')

    if (value.find('おはよう') != -1):
        value = 'おはようございます。<br>ごきげんはいかがですか?'

    if (value.find('元気') != -1):
        value = '元気でよかったですね'

    if (value.find('天気') != -1):
        value = '今日の天気は晴れです。'

    dic = {'output' : [{'type' : 'text', 'value' : value }] }
    contents = callback + '(' + json.dumps(dic) + ')'
    return contents

if __name__ == "__main__":
    app.run(debug=True)

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>チャットボット</title>
</head>
<body>
<script src="https://riversun.github.io/chatux/chatux.min.js"></script>
<script>
    const chatux = new ChatUx();
    const initParam =
        {
            renderMode: 'auto',
            api: {
                endpoint: 'http://localhost:5000/',
                method: 'GET',
                dataType: 'jsonp'
            },
            bot: {
                botPhoto: 'https://www.erestage.com/wp-content/uploads/2019/07/yukata-1-150x150.jpg',
                humanPhoto: null,
                widget: {
                    sendLabel: '送信',
                    placeHolder: '質問事項を入力してください。'
                }
            },
            window: {
                title: 'お問い合わせ',
                infoUrl: 'http://www.erestage.com/'
            }
        };
    chatux.init(initParam);
    chatux.start(true);
</script>
</body>
</html>

動かし方

Pythonはそのまま実行すれば良いです。
HTMLを開くとチャット画面が表示されます。

応答内容はプログラムを見ればわかりますが3パターンです。

システム開発

Posted by @erestage