ChatGPT:如何构建自己的聊天机器人?

2周前发布 yundic
399 0 0
Hi, I’m a chatbot. How can I help you today?

const chatbox = document.getElementById(‘chatbox’);
const userInput = document.getElementById(‘user-input’);

function sendUserInput() {
const userMessage = userInput.value;
if (userMessage !== ”) {
addMessage(‘user’, userMessage);
userInput.value = ”;
sendToBot(userMessage);
}
}

function sendToBot(message) {
// 修改成自己的后台服务器接口,比如 ajax 发送数据到后台,回传后响应 sendToBotResponse 函数
const url = ‘https://www.example.com/bot/response’;
fetch(url, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
input_message: message
})
})
.then(response => response.json())
.then(data => sendToBotResponse(data.bot_message))
.catch((error) => {
console.error(‘Error:’, error);
});
}

function sendToBotResponse(botMessage) {
addMessage(‘bot’, botMessage);
}

function addMessage(sender, message) {
const textClass = sender === ‘bot’ ? ‘bot-message’ : ‘user-message’;
const messageClass = sender === ‘bot’ ? ‘bot-text’ : ‘user-text’;
const text = ‘

‘ +

‘ +
message +

‘ +

‘;

chatbox.innerHTML += text;
chatbox.scrollTop = chatbox.scrollHeight;
}

source

© 版权声明

相关文章

暂无评论

暂无评论...