Изучи информацию и сделай мне чат-бота. У меня нет API ключа и никогда не будет. Пусть бот подсасывает информацию из интернета, и напиши, что для этого нужно
Create Working Chatbot in HTML CSS & JavaScript
Last Updated : 08 Mar, 2024
A working chatbot is an application that can be developed to answer every sort of question. Chatbot is a web interface that can answer every question in the most human possible way. It is based on the technology of artificial intelligence. In this article, we will be learning how to create a working chatbot using HTML, CSS & Javascript by using OpenAI's API Key.
Screenshot-(370)
Chatbot Preview
Prerequisites:
HTML
CSS
JavaScript
Approach:
Create a directory with 3 files & one cross icon : index.html, style.css & script.js. Add basic boiler plate code and create a container of a chatbot with a cross icon to remove the chatbot after use, two paragraphs, one for incoming messages, and the other one for outgoing messages. Also create a send button to send a message.
Create styling for the containers & also add a class of error where the incoming message's container turns light red in color to show there is an error in API Key.
Create a free OpenAI Key using the official website. Create an account, or login onto your existing account and go to API Documentation. Select the option to view secret API Keys, and create a new API Key. Store it for future usage.
Copy the API Key in the script file and generate a response using fetch method. Add the required headers and add the answer or response to the message if the API key works successfully. If not generate an error message stating that an error occurred. Finally, whatsoever message is created, scroll the chatbot container downwards.
The send button handles the sending of messages.
On clicking the cross button, the chatbot container disappears and a final thanks message is received.
Project Structure:
Screenshot-(369)
Project Structure
Example: This example demonstrate the working of Chatbot by giving response of the user queries and it shows an error when there is an error in the API key.
ntroduction
Chatbots have revolutionized the way people interact with technology. A chatbot is an artificial intelligence (AI) software that can simulate a conversation (or a chat) with a user in natural language through messaging applications, websites, mobile apps or through the telephone. In this article, I will explain a menu-based chatbot designed and implemented using HTML, CSS, Bootstrap, JavaScript, and jQuery. It is deployed as a prototype to OpenGenus IQ's homepage.
Codebase: github.com/OpenGenus/chatbot-web
Features
This chatbot is menu-based, which means that the user is presented with several options to choose from, and the bot responds accordingly. The chatbot is designed to be user-friendly and easy to use. Some of the features of the chatbot include:
Menu-based: The chatbot offers the user a choice of options to choose from. The user clicks on the option he wants, and the bot then presents another set of options for him to choose from.
Assistant
User
ничего нет на экране
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Rule-based: This chatbot is rule-based, which means that it responds based on pre-defined rules. The bot has a set of responses for each option that the user can choose from.
Night mode: The chatbot has a night mode functionality, which allows the user to switch between a light and dark mode for better visibility.
Contact option: The chatbot has an option to contact, which allows the user to connect with the support team.
Menu-driven interface: Menu-based chatbots use pre-defined menus to guide users through the conversation flow.
Structured conversation flow: Chatbots with menus are typically designed with a structured conversation flow that is easy to follow.
Limited user input: Users are limited to selecting options from a menu, so there is less
opportunity for misunderstandings or errors in communication.
Clear navigation: Menus are designed to be easy to navigate, with clear labels and logically grouped options.
Repetitive tasks: Menu-based chatbots are ideal for handling repetitive tasks, such as placing orders or answering frequently asked questions.
Faster response times: Because menus are pre-defined, chatbots can respond quickly to user requests without needing to process natural language input.
Lower development costs: Menu-based chatbots can be easier and less expensive to develop than more complex natural language processing (NLP) chatbots.
Consistency: Menu-based chatbots can ensure consistent responses and experiences for all users, regardless of their communication skills.
Limited customization: Chatbots with menus are limited in their ability to provide personalized responses since they are designed to follow a fixed conversation flow.
Limited functionality: While menu-based chatbots can handle basic tasks effectively, they may not be able to provide the same level of functionality as more advanced chatbots that use NLP and other Al technologies.
Approach/Design
Implementation Details with Code Snippet:
The chatbot is implemented using HTML, CSS, Bootstrap, JavaScript, and jQuery. The HTML code for the chatbot is as follows:
Rule-based and click-based are two common approaches for building chatbots:
Rule-based chatbots:
These chatbots are built using a set of predefined rules that determine how the chatbot will respond to user inputs. These rules are typically based on keyword matching or regular expressions, and they can be programmed to provide specific responses based on the user's input. Rule-based chatbots are relatively simple to build and are useful for handling specific tasks, such as answering frequently asked questions or providing basic customer support.
Design Implementation
Approach and Design:
The chatbot is designed to be simple and user-friendly. The user interface is clean and easy to navigate. The chatbot offers the user a choice of options to choose from, and the bot responds accordingly. The chatbot uses a rule-based approach, which means that it responds based on pre-defined rules.
Designing a menu-based chatbot involved designing a conversational interface that allowed users to interact with the chatbot by selecting options from a menu.
The purpose and scope of the chatbot were defined to identify the features that needed to be included. The user flow was identified by creating a sequence of questions and responses that the chatbot used to interact with the user. Menu options were designed to be easy for the user to understand and navigate, with each option clearly labeled and providing a brief description of what it did.
The chatbot interface was designed to be intuitive and responsive to the user's input. The chatbot backend was developed using a programming language and framework suitable for the project, handling user input and providing appropriate responses based on the menu options selected by the user.
The chatbot was then thoroughly tested to ensure it functioned as intended. Finally, the chatbot was deployed to the desired platform.
It contains the following file and its content.
FOLDER and CONTENT
demo-data data.json [database file to intereact with user]
flow.css Include code for Chat Container
flowchart.css Include code for Chat Window
flowchat.js Include javascript code for Chat Window
flowchatui.js Include javascript code for Chat UI
index.html Include html code for help page
styles.scss Include css code for UI
main.js Include js code for MENU
styles.css Include css code for UI
demo-data
demo-data is data.json database file to intereact with user. This file contain JSON object that represents a message in a chatbot or messaging application.
"id": - This is a unique identifier for the message.
"text": "Welcome To OpenGenus" - This is the text content of the message.
"messageType": "Text" - This specifies the type of message, which in this case is a text message.
"imageUrl": "" - This is the URL of an image that can be displayed with the message. Since it's empty in this case, no image is displayed.
"nextMessageId": 3 - This is the ID of the next message that should be displayed after this one.
"option1" through "option6" - These are options that can be presented to the user, such as buttons or links.
"option1_nextMessageId" through "option6_nextMessageId" - These are the IDs of the messages that should be displayed when the corresponding option is selected by the user.
Overall, this JSON object provides information about a message that can be displayed to a user in a chatbot or messaging application, along with options that the user can select to continue the conversation.
code snippet
{
"id": 2,
"text": "Welcome To OpenGenus",
"messageType": "Text",
"imageUrl": "",
"nextMessageId": 3,
"option1": "",
"option1_nextMessageId": "",
"option2": "",
"option2_nextMessageId": "",
"option3": "",
"option3_nextMessageId": "",
"option4": "",
"option4_nextMessageId": "",
"option5": "",
"option5_nextMessageId": "",
"option6": "",
"option6_nextMessageId": ""
}
Flowchart.js
This is a jQuery plugin named "flowchat" that creates a chatbot interface. The plugin takes an options object as an argument which can be used to customize the chatbot behavior. The options include delay between bot replies, ID of the button that starts the chat, ID of the first message to be displayed, and a JSON object that contains the chatbot messages.
The plugin has several helper functions like "selectOption() which is called when the user
selects a chatbot option, findMessageIn]sonById() which finds the message in the JSON
object by its ID, 'addoptions() which adds the chatbot options to the chat window,
toggleLoader()" which shows and hides a typing indicator during bot reply, andgenerateMessageHTML() which generates and adds the chat messages to the chat window
recursively.
The plugin attaches an event listener to the start button that calls startChat() function when clicked. This function clears the chat window, gets the first message from the JSON object, and calls "generateMessageHTML() to display it in the chat window.
The generateMessageHTML() function generates and adds the chat messages to the chat window recursively. It checks if the message has options and adds them if it is a question. It also checks if the message has a next message ID and recursively calls itself to display the next message.
The plugin uses 'jquery' library and wraps itself in an immediately invoked function expression (IIFE) to create a private namespace and avoid polluting the global namespace. The use strict directive is used to enable strict mode and catch common JavaScript mistakes.
"use strict";
(function() {
.fn.flowchat = function(options) {
// override options with user preferences
var settings = $.extend({
delay: 1500,
startButtonId: '#btn-submit',
autoStart: true,
startMessageId: 1,
dataJSON: null
}, options);
var container = $(this);
// on click of Start button
$(document).on('click', settings.startButtonId, function() {
startChat(container, settings.dataJSON, settings.startMessageId, settings.delay)
});
}
function selectOption(this, container, data, delay) {
this.parent().hide();
var userReply=('' + this.html()+′</div></li>′);container.chiluserReply);
// get the message
var nextMessageId = $this.attr('data-nextId');
var nextMessage = findMessageInJsonById(data, nextMessageId);
// add next message
generateMessageHTML(container, data, nextMessage, delay);
// get the first message
var message = findMessageInJsonById(data, startId);
// add message
generateMessageHTML(container, data, message, delay);
}
function findMessageInJsonById(data, id) {
var messages = data;
for (var i = 0; messages.length > i; i++)
if (messages[i].id == id)
return messages[i];
}
function addOptions(container, data, delay, m) {
var optionsContainer=('');
var optionsList=('');
var optionText = null;
var optionMessageId = null;
for (var i = 1; i < 12; i++) {
optionText = m["option" + i]
optionMessageId = m["option" + i + "_nextMessageId"]
if (optionText != "" && optionText != undefined && optionText != null) { // add option only if text exists
var optionElem=("" + optionText + "");
optionElem.click(function() {
selectOption((this), container, data, delay)
});
optionsList.append(optionElem);
}
}
optionsContainer.append(optionsList);
return $optionsContainer;
}
function toggleLoader(status, container) {
if (status == "show")
container.children('.chat-window').append("");
else
container.find('.typing-indicator').remove();
}
function generateMessageHTML(container, messages, m, delay) {
// create template if text is not null
if (m.imageUrl != '')
var template=('<li class')
JavaScriptCopy
Flowchatui.js
This code creates a chat icon on the bottom right of a webpage. When clicked, it shows a chat popup box where users can enter their names and start chatting. Here are some implementation details:
A div element is created using JavaScript and given the class "chaticon". An image tag is added to the div, which shows an icon. The div is appended to the body of the webpage.
Another div element is created with the id "flowchart" and the class "flow". This element contains a form with an input field for the user's name and a submit button.
The "flowchart" div is appended to the "chat_icon" div using jQuery.
A click event listener is added to the icon image. When the icon is clicked, the "chat- popup" element is shown or hidden using jQuery's fadeIn() and animate() functions.
The "chat-popup" element is hidden by default and only shown when the icon is clicked.
Overall, this code creates a simple chat interface that can be easily added to any webpage.
// Create chat icon
let d = document.createElement('div');
(d).addClass(′chaticon′).html(("body")) //main div
// Add chat popup form to chat icon
(".chat_icon").append(function() {
return (("")
.attr("id", "flowchat")
.addClass("flow")
.html('OpenGenusStart'))
});
// Toggle chat popup form visibility when chat icon is clicked
(document).ready(function() {
('#icon').on('click', function() {
if (('.flow').is(':visible')) {
('.flow').fadeIn(400, function() {
('.flow').animate({
'width': 'hide'
}, 1000);
});
} else {
('.flow').animate({
'width': 'show'
}, 1000, function() {
('.flow').fadeIn(400);
});
};
if (('.chat-popup').is(':visible')) {
('.chat-popup').fadeIn(400, function() {
('.chat-popup').animate({
'width': 'hide'
}, 1000);
});
} else {
('.chat-popup').animate({
'width': 'show'
}, 1000, function() {
('.chat-popup').fadeIn(400);
});
};
});
});
JavaScriptCopy
Flowchart.css
The given code is a CSS stylesheet that defines the style for a chat window interface. It includes various styles for the chat messages, options, and a typing indicator animation. The chat messages are displayed in a list format with the user and bot messages differentiated by their alignment and background color. The options for the user are displayed as a list of clickable items with a border and background color. The typing indicator animation is displayed as a series of circles that blink in a sequence, with a bulging effect applied to them.
JavaScriptCopy
Flow.css
This is the CSS code for a chat container with a chat icon. The container has a fixed position on the right bottom of the screen, and it has a specific height and width. It also has an overflow property set to hide to prevent the content from overflowing.
There is a media query for screens that are smaller than 600px in width, which adjusts the width of the container and changes its position. It also hides some elements like the footer and adjusts the submit button's width.
The chat icon has a fixed position on the bottom right of the screen, and it is colored blue. The chat window has a list of chat messages, which are either from the user or the bot. The messages have different styles and colors, and there is also an indicator for when the bot is typing a message.
Overall, the CSS code is for a chat interface that is responsive and has a modern look.
Создание чат-бота без использования API-ключа, который будет «подсасывать» информацию из интернета, можно реализовать, но это вызывает определенные ограничения и технические трудности. Чтобы понять, как это сделать, вам придется использовать веб-технологии, такие как HTML, CSS и JavaScript, но также надо будет учитывать законность и этичность сбора данных (scraping) с веб-страниц.
Вот шаги, которые можно предпринять для создания простого чат-бота, который будет получать информацию из открытых источников в интернете:
Шаги для создания чат-бота:
Создание HTML-шаблона:
Создайте базовую структуру HTML для вашего чат-бота. Это будет похоже на предоставленный вами пример, но без API-вызовов.
Создание логики чат-бота с помощью JavaScript:
Здесь вы создадите отправку сообщений и сделаете вызов для получения данных.
document.getElementById('sendBTN').addEventListener('click', function() {
const userInput = document.getElementById('userInput').value;
document.getElementById('chatbox').innerHTML += `<li class="chat-outgoing chat">
<p>${userInput}</p>
</li>`;
// Здесь будет функция получения ответа
getBotResponse(userInput);
document.getElementById('userInput').value = ''; // Очистка поля
});
function getBotResponse(input) {
// Подключение к внешнему API или парсинг данных с веб-страниц
// Это пример для иллюстрации
fetch(`https://api.example.com/search?q=${encodeURIComponent(input)}`)
.then(response => response.json())
.then(data => {
const botResponse = data.response || "Извините, я не знаю, как ответить на это.";
document.getElementById('chatbox').innerHTML += `<li class="chat-incoming chat">
<p>${botResponse}</p>
</li>`;
})
.catch(error => {
console.error('Ошибка:', error);
document.getElementById('chatbox').innerHTML += `<li class="chat-incoming chat">
<p>Произошла ошибка при получении ответа.</p>
</li>`;
});
}
// Функция для показа чат-бота
function cancel() {
document.querySelector('.chatBot').style.display = 'none';
}
Важные замечания:
Этика и легальность: Делать веб-скрапинг можно, но обязательно ознакомьтесь с правилами использования сайтов и соблюдайте их. Некоторые сайты запрещают автоматизированный доступ к их содержанием.
Технические навыки: Вам могут понадобиться базовые знания JavaScript, а также возможно, серверные технологии, если вы планируете делать более сложную логику и взаимодействие с API.
Библиотеки и фреймворки: Использование фреймворков, таких как Node.js для серверной части или библиотеки, такие как Axios для HTTP-запросов в JavaScript, может облегчить процесс.
Таким образом, вы сможете создать своей чат-бот с минимальными затратами, но имейте в виду ограничения и юридические аспекты.
Если ничего не отображается на экране, давайте проверим несколько шагов и убедимся, что все правильно настроено. Я предложу полный код для вашей веб-страницы, включая HTML, CSS и JavaScript. Пожалуйста, следуйте инструкциям ниже.
Полный код для простой чат-бота:
Создайте файл index.html и вставьте в него следующий код:
Создайте файл script.js и вставьте в него следующий код:
document.getElementById('sendBTN').addEventListener('click', function() {
const userInput = document.getElementById('userInput').value;
if (userInput.trim() === "") return; // Отмена отправки пустого сообщения
// Отправка сообщения пользователя
document.getElementById('chatbox').innerHTML += `<li class="chat-outgoing chat">
<p>${userInput}</p>
</li>`;
// Получение ответа от бота
getBotResponse(userInput);
document.getElementById('userInput').value = ''; // Очистка поля ввода
});
function getBotResponse(input) {
// Имитация ответа бота (можно заменить на вызов API)
const botResponse = `Вы сказали: "${input}"` || "Извините, я не знаю, как ответить на это.";
document.getElementById('chatbox').innerHTML += `<li class="chat-incoming chat">
<p>${botResponse}</p>
</li>`;
}
function cancel() {
document.getElementById('chatBot').style.display = 'none';
}
Проверьте следующие моменты:
Структура файлов: Убедитесь, что файлы index.html, style.css и script.js находятся в одной папке и имеют правильные имена.
Запуск файла: Откройте файл index.html в вашем браузере. Для этого вы можете просто дважды кликнуть на файл или открыть его через браузер с помощью функции «Открыть файл».
Проверка консоли: Если ничего не отображается, откройте инструменты разработчика (F12 в большинстве браузеров) и перейдите на вкладку «Консоль», чтобы проверить наличие ошибок.
Теперь, после выполнения всех шагов, вы должны увидеть интерфейс вашего чат-бота. Попробуйте ввести текст в текстовое поле и нажать кнопку "Отправить", и вы должны увидеть ответ от бота. Если у вас возникнут дополнительные вопросы или проблемы, пожалуйста, дайте знать!