5分钟内使用Flask构建聊天机器人

2025-06-07

5分钟内使用Flask构建聊天机器人

几周前我写了一篇文章《5 分钟内构建您的第一个聊天机器人》。

那个机器人很酷,而且可以通过终端聊天。今天,我们尝试用Flask构建一个同样的机器人。

因此,我们将使用ChatterBot,它是一种用于创建聊天机器人的机器学习、对话式对话引擎。

如果你还没有读过我之前的帖子,请点击此处

安装 ChatterBot

$ pip install ChatterBot

安装 Flask

$ pip install Flask

创建文件

app.py并打开它



#import files
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from chatterbot.trainers import ListTrainer


Enter fullscreen mode Exit fullscreen mode

创建一个 Flask 应用



app = Flask(__name__)


Enter fullscreen mode Exit fullscreen mode

正如我们在我之前的文章中看到的



bot = ChatBot("Candice")
bot.set_trainer(ListTrainer)
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("chatterbot.corpus.english")


Enter fullscreen mode Exit fullscreen mode

此后



@app.route("/")
def home():    
    return render_template("home.html") 
@app.route("/get")
def get_bot_response():    
    userText = request.args.get('msg')    
    return str(bot.get_response(userText)) 
if __name__ == "__main__":    
    app.run()


Enter fullscreen mode Exit fullscreen mode

因此,正如我们所看到的,我们需要创建一个 home.html 文件作为前端。

创建一个文件夹“templates”,并在其中创建一个文件 home.html。



templates/home.html


Enter fullscreen mode Exit fullscreen mode

打开 home.html



  <!DOCTYPE html>
<html>
  <title>Candice</title>
  <body>
    <center>
      <h1>
        Your Personal ChatBot
      </h1>
    </center>
      <div>
       <p>
          <center><span>Hi! I'm Candice your personal ChatBot</span></center>
          </p>
       </div>
       <div id="userInput">
          <input id="textInput" type="text" name="msg" placeholder="Message" />
       </div>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

这只是一个简单的结构,让我们添加一些 CSS 代码。我们不会创建另一个 CSS 文件,只是在 home.html 中添加样式。



<head>
    <link
      rel="shortcut icon"
      type="image/x-icon"
      href="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
    />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
      body {
        font-family: monospace;
      }
      h1 {
        background-color: yellow;
        display: inline-block;
        font-size: 3em;
        margin: 0;
        padding: 14px;
      }
      h3 {
        color: black;
        font-size: 20px;
        margin-top: 3px;
        text-align: center;
      }
      #chatbox {
        margin-left: auto;
        margin-right: auto;
        width: 40%;
        margin-top: 60px;
      }
      #userInput {
        margin-left: auto;
        margin-right: auto;
        width: 40%;
        margin-top: 60px;
      }
      #textInput {
        width: 90%;
        border: none;
        border-bottom: 3px solid black;
        font-family: monospace;
        font-size: 17px;
      }
      .userText {
        color: white;
        font-family: monospace;
        font-size: 17px;
        text-align: right;
        line-height: 30px;
      }
      .userText span {
        background-color: #808080;
        padding: 10px;
        border-radius: 2px;
      }
      .botText {
        color: white;
        font-family: monospace;
        font-size: 17px;
        text-align: left;
        line-height: 30px;
      }
      .botText span {
        background-color: #4169e1;
        padding: 10px;
        border-radius: 2px;
      }
      #tidbit {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 300px;
      }
      .boxed {
        margin-left: auto;
        margin-right: auto;
        width: 78%;
        margin-top: 60px;
        border: 1px solid green;
      }
      .box {
        border: 2px solid black;
      }
    </style>
</head>


Enter fullscreen mode Exit fullscreen mode

现在,让我们改变身体结构。



<body>
    <center>
      <h1>
        <img
          src="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
          alt="CANDICE"
          style="width:40px;height:40px;"
        />Your Personal ChatBot
      </h1>
    </center>
<div class="box"></div>
    <div class="boxed">
      <div>
        <div id="chatbox">
          <img
            src="https://user-images.githubusercontent.com/20112458/49326597-773b7280-f57a-11e8-853d-20ed61d18b0d.png"
            alt="CANDICE"
            style="width:40px;height:40px;"
          />
          <p class="botText">
            <span>Hi! I'm Candice your personal ChatBot</span>
          </p>
        </div>
        <div id="userInput">
          <input id="textInput" type="text" name="msg" placeholder="Message" />
        </div>
      </div>
    </div>
  </body>


Enter fullscreen mode Exit fullscreen mode

现在,如果我们输入一些内容,什么也不会发生。所以,让我们添加一些脚本



<script>
        function getBotResponse() {
          var rawText = $("#textInput").val();
          var userHtml = '<p class="userText"><span>' + rawText + "</span></p>";
          $("#textInput").val("");
          $("#chatbox").append(userHtml);
          document
            .getElementById("userInput")
            .scrollIntoView({ block: "start", behavior: "smooth" });
          $.get("/get", { msg: rawText }).done(function(data) {
            var botHtml = '<p class="botText"><span>' + data + "</span></p>";
            $("#chatbox").append(botHtml);
            document
              .getElementById("userInput")
              .scrollIntoView({ block: "start", behavior: "smooth" });
          });
        }
        $("#textInput").keypress(function(e) {
          if (e.which == 13) {
            getBotResponse();
          }
        });
</script>


Enter fullscreen mode Exit fullscreen mode

现在,您将看到您所写的任何内容都会显示在 ChatBox 上,但您的聊天机器人不会给出任何回复。

因此,为了做到这一点,让我们运行你的 app.py



$ python app.py


Enter fullscreen mode Exit fullscreen mode

因此,请转到链接并与您的个人聊天机器人聊天

您可以在我的Github上找到完整的源代码

文章来源:https://dev.to/sahilrajput/build-a-chatbot-using-flask-in-5-minutes-574i
PREV
5 分钟内构建您的第一个聊天机器人
NEXT
React 性能优化