用js写一个聊天机器人
时间: 2023-03-23 20:02:25 浏览: 105
好的,我可以用 JavaScript 编写一个简单的聊天机器人。
首先,我们需要创建一个 HTML 文件来容纳我们的聊天窗口。在这个文件中,我们将创建一个输入框和一个用于显示聊天历史记录的区域。这个区域可以是一个 `<ul>` 元素,其中每条消息都是一个 `<li>` 元素。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>聊天机器人</title>
</head>
<body>
<ul id="chat-history"></ul>
<input type="text" id="user-input" placeholder="请输入您的消息">
<button id="send-button">发送</button>
<script src="chatbot.js"></script>
</body>
</html>
```
接下来,我们将使用 JavaScript 编写聊天机器人的逻辑。我们将使用一个数组来存储聊天历史记录,并使用一个函数来更新聊天历史记录的显示。
```javascript
// 获取元素
const chatHistory = document.getElementById('chat-history');
const userInput = document.getElementById('user-input');
const sendButton = document.getElementById('send-button');
// 存储聊天历史记录
const history = [];
// 更新聊天历史记录的显示
function updateHistory() {
chatHistory.innerHTML = '';
for (const message of history) {
const li = document.createElement('li');
li.textContent = message;
chatHistory.appendChild(li);
}
}
// 处理用户输入并生成回复
function handleInput() {
const userInputValue = userInput.value.trim();
if (!userInputValue) {
return;
}
// TODO: 编写回复逻辑
history.push(`我:${userInputValue}`);
updateHistory();
userInput.value = '';
userInput.focus();
}
// 监听发送按钮的点击事件
sendButton.addEventListener('click', handleInput);
// 监听用户输入框的回车事件
userInput.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
handleInput();
}
});
```
现在我们可以在 `handleInput` 函数中编写回复逻辑。这个逻辑可以非常简单,只需要根据用户输入生成一些静态的回复即可。
```javascript
function handleInput() {
const userInputValue = userInput.value.trim();
if (!userInputValue) {
return;
}
let reply;
if (userInputValue === '你好') {
reply = '你好啊!';
} else if (userInputValue === '你是谁') {
reply = '我是聊天机器人!';
} else {
reply = '抱歉,我不理解你的意思。';
}
history.push(`我:${userInputValue}`);
history.push(`机器人:${reply}`);
updateHistory();
userInput.value = '';
userInput.focus();
}
```
这样,我们就完成了一个简单的聊天机器人!当用户输入“你好”或“你是谁”时,机器人会回复相应的消息,否则机器人会回复一条默认消息。