Skip to main content

 

🔥 Full Beginner Tutorial: Create Your Own Chatbot Using ChatGPT API Key

🟩 Introduction

In this tutorial, you will learn how to create your own AI chatbot using the ChatGPT API.
This is perfect for:

✔ Websites
✔ Blogger blogs
✔ Personal projects
✔ Portfolio projects

We will create a chatbot that:

  • Sends user messages to the ChatGPT API

  • Gets responses

  • Displays chat bubbles

  • Works on any device

  • Uses your OpenAI API key


🟦 How the Chatbot Works (Explained in Simple Words)

1. HTML Structure

This creates:

  • A chat screen

  • A message input box

  • A send button

2. CSS Styling

This gives the chatbot:

  • Clean look

  • Chat bubbles

  • Responsive UI

3. JavaScript

This is the real brain:

  • Detect user’s message

  • Send it to ChatGPT API

  • Wait for reply

  • Show reply on screen

We use fetch() to call:

https://api.openai.com/v1/chat/completions

with your API key.


🟥 Very Important

Replace:

YOUR_API_KEY_HERE

with your real ChatGPT API key.

You can get one from:

https://platform.openai.com



ChatGPT Chatbot (Secure)

Copy This Code



<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>ChatGPT Chatbot</title>

  <style>
    body { font-family: system-ui, Arial; margin:0; padding:0; background:#f4f6f8; }
    .app { max-width:700px; margin:24px auto; background:#fff; border-radius:12px; box-shadow:0 6px 24px rgba(0,0,0,0.06); overflow:hidden; }
    .chat { height:60vh; overflow:auto; padding:18px; }
    .bubble { display:inline-block; padding:12px 14px; border-radius:12px; margin:8px 0; max-width:80%; }
    .user { background:#007bff; color:#fff; margin-left:auto; }
    .bot { background:#eee; color:#000; margin-right:auto; }
    .controls { display:flex; gap:8px; padding:12px; border-top:1px solid #f0f0f0; }
    input[type="text"] { flex:1; padding:10px 12px; border-radius:8px; border:1px solid #ddd; }
    button { padding:10px 14px; border-radius:8px; border:none; background:#007bff; color:#fff; cursor:pointer; }
    @media(max-width:600px){ .chat{height:50vh} }
  </style>
</head>
<body>

<div class="app">
  <div class="chat" id="chat"></div>

  <div class="controls">
    <input id="prompt" type="text" placeholder="Type a message..." />
    <button id="send">Send</button>
  </div>
</div>

<script>
(() => {
  const API_KEY = "sk-REPLACE_WITH_YOUR_KEY";

  const chatEl = document.getElementById("chat");
  const promptEl = document.getElementById("prompt");
  const sendBtn = document.getElementById("send");

  function appendBubble(text, who = "bot") {
    const d = document.createElement("div");
    d.className = "bubble " + (who === "user" ? "user" : "bot");
    d.innerText = text;
    chatEl.appendChild(d);
    chatEl.scrollTop = chatEl.scrollHeight;
  }

  async function sendMessage() {
    const text = promptEl.value.trim();
    if (!text) return;

    appendBubble(text, "user");
    promptEl.value = "";
    appendBubble("...", "bot");

    try {
      const res = await fetch("https://api.openai.com/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": "Bearer " + API_KEY
        },
        body: JSON.stringify({
          model: "gpt-4.1-mini",
          messages: [{ role: "user", content: text }]
        })
      });

      const data = await res.json();

      const last = chatEl.querySelectorAll(".bot");
      if (last.length) last[last.length - 1].remove();

      appendBubble(data.choices?.[0]?.message?.content || "(no reply)", "bot");

    } catch (err) {
      const last = chatEl.querySelectorAll(".bot");
      if (last.length) last[last.length - 1].remove();
      appendBubble("Error: " + err.message, "bot");
    }
  }

  sendBtn.addEventListener("click", sendMessage);
  promptEl.addEventListener("keydown", e => {
    if (e.key === "Enter") sendMessage();
  });
})();
</script>

</body>
</html>

Comments

Popular posts from this blog

HTML Forms Tutorial HTML Forms Tutorial HTML Forms allow users to enter and submit data. They are used everywhere—login forms, signup forms, search boxes, feedback forms, etc. In this complete tutorial, you will learn all form elements with examples and demos. 1. What is an HTML Form? A form collects user input using different form elements like text fields, checkboxes, radio buttons, buttons, and more. <form> Form elements go here... </form> 2. Basic Form Structure <form action="#" method="post"> <input type="text" placeholder="Enter name"> <button>Submit</button> </form> Submit Attributes: action → URL where form data is sent method="POST" → Secure data sending method="GET" → Data shows in URL 3. Text Input Field <i...
📸 HTML Image Gallery Tutorial for Beginners Image galleries make your website more beautiful and professional. In this tutorial, you will learn how to create different types of image galleries using HTML and CSS. 📌 1. Simple HTML Image Gallery This is the most basic gallery layout. <div> <img src="image1.jpg" width="200"> <img src="image2.jpg" width="200"> <img src="image3.jpg" width="200"> </div> ✔ Explanation All images are inside a <div> Each image has the same width They appear in a row 📌 2. Responsive Image Gallery (CSS Grid) This gallery automatically adjusts on mobile and PC. <style> .gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; } .gallery img { width: 100%; border-radius: 10px; } </style> <div class="galle...
📝 HTML Notes App Tutorial for Beginners (Full Project) In this tutorial, you will learn how to build a fully functional Notes App using HTML, CSS, and JavaScript. This app works on all devices and saves notes even after refreshing the page! ✨ Features of This Notes App Add new notes Edit notes Delete notes Dark Mode Search notes Auto-save using LocalStorage No backend needed 📌 Step 1 — HTML Structure Copy Code Run Demo <div class="container"> <h1>Notes App</h1> <button id="toggleDark">🌙 Dark Mode</button> <input type="text" id="searchBox" placeholder="Search notes..."> <textarea id="noteInput" placeholder="Write your note here..."></textarea> <button id="addNote">Add Note</button> <div id="notesList"></div> ...
HTML Tags Tutorial – A Complete Beginner-Friendly Guide HTML tags are the basic building blocks of every webpage. Whether you want to create a simple webpage or a full website, understanding HTML tags is the first and most important step. In this post, we’ll explore what HTML tags are, how they work, why they matter, and the most commonly used tags with examples. Table of Contents What Are HTML Tags? How HTML Tags Work Types of HTML Tags Most Common HTML Tags Self-Closing Tags Nesting Tags Practical Examples Best Practices What Are HTML Tags? HTML tags are keywords enclosed in angle brackets < > that tell the browser how to display content. Tags create elements such as headings, paragraphs, images, links, lists, buttons, forms, and much more. Example of a simple tag: <p>This is a paragraph.</p> How HTML Tags Work Most HTML tags come in pairs: <opening-tag>...
HTML Images Tutorial HTML Images Tutorial The <img> tag is used to display images on a webpage. In this tutorial, you'll learn how to add images, resize them, add borders, captions, and more. 1. Basic Image Tag The simplest way to add an image is by using the src and alt attributes. <img src="image.jpg" alt="My Image"> Attributes: src → Image URL alt → Text shown if image fails to load 2. Image Size (width & height) You can resize an image using width or height . <img src="photo.jpg" width="300" height="200"> 3. Responsive Images Responsive images automatically adjust to device size. <img src="photo.jpg" style="width:100%;max-width:400px;"> 4. Add Border to Images <img src="file.jpg" style="border:3px solid #333;...