---
title: Build a ChatGPT‑Powered Bot in Python in Under an Hour
siteUrl: https://logzly.com/techtrek
author: techtrek (Tech Trek)
date: 2026-06-18T08:56:57.033325
tags: [ai, python, gadgets]
url: https://logzly.com/techtrek/build-a-chatgptpowered-bot-in-python-in-under-an-hour
---


**Disclosure: We are reader supported, and earn affiliate commissions when you buy through us.**


You’ve probably heard the [buzz about ChatGPT](/techtrek/how-ai-is-changing-everyday-apps-a-developer-s-perspective) and wondered if you can get a smart bot up and running before lunch. The good news? You can, and you don’t need a PhD in AI to do it. In this post I’ll walk you through a quick, practical setup that fits right into a busy developer’s schedule.

## What you need before you start

### Python 3.8+ installed  
If you already have a recent Python on your machine, you’re set. If not, grab the latest version from python.org – the installer does the [heavy lifting](https://www.amazon.com/s?k=heavy+lifting&tag=organizationtip101-20) for you.

### An [OpenAI API](https://www.amazon.com/s?k=OpenAI+API&tag=organizationtip101-20) key  
Sign up at openai.com, create an API key, and keep it somewhere safe. Think of it as the password that lets your code talk to ChatGPT.

### A text editor you like  
VS Code, Sublime, or even a simple Notepad will do. I usually fire up VS Code because its terminal and extensions make the workflow smoother.

### A few minutes of internet  
You’ll need to install a couple of packages, but they’re tiny and download fast on most connections.

## Step‑by‑step: Building the bot

### 1. Set up a fresh project folder  
Open a terminal, navigate to where you keep your experiments, and run:

```
mkdir chatgpt_bot
cd chatgpt_bot
python -m venv venv
```

The `venv` command creates an isolated environment so the packages you install won’t clash with other projects.

### 2. Activate the virtual environment  
On Windows:

```
venv\Scripts\activate
```

On macOS/Linux:

```
source venv/bin/activate
```

You’ll see the prompt change, indicating you’re now inside the sandbox.

### 3. Install the OpenAI client library  
Run:

```
pip install openai
```

That’s it – the library handles the HTTP calls for you, so you don’t have to write any request code yourself, unlike building a full‑fledged [ChatGPT‑powered code assistant](/techtrek/build-a-chatgptpowered-code-assistant-in-60-minutes-a-practical-guide-for-developers).

### 4. Write the bot script  
Create a file called `bot.py` and paste the following code. I’ve added comments to keep things clear.

```python
import os
import openai

# Load your API key from an environment variable.
# This keeps the key out of the source code.
openai.api_key = os.getenv("OPENAI_API_KEY")

def ask_chatgpt(prompt, model="gpt-3.5-turbo"):
    """
    Send a prompt to the ChatGPT model and return the response text.
    """
    response = openai.ChatCompletion.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        max_tokens=150,          # limit length of answer
        temperature=0.7         # creativity level
    )
    # The response structure is a bit nested; we pull out the text.
    return response["choices"][0]["message"]["content"].strip()

def main():
    print("ChatGPT Bot – type 'exit' to quit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == "exit":
            print("Goodbye!")
            break
        reply = ask_chatgpt(user_input)
        print("Bot:", reply)

if __name__ == "__main__":
    main()
```

A quick note on the parameters:

* **model** – `gpt-3.5-turbo` is the most cost‑effective for most tasks. If you need higher quality, swap in `gpt-4` (but watch the price).
* **max_tokens** – Controls how long the answer can be. 150 tokens is roughly a short paragraph.
* **temperature** – A value between 0 and 1. Higher numbers make the bot more creative; lower numbers make it more focused.

### 5. Secure your API key  
In the same folder, create a file named `.env` (make sure your editor shows hidden files). Add:

```
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

Replace the placeholder with the key you got from OpenAI. Then install `python-dotenv` to load the variable automatically:

```
pip install python-dotenv
```

Update the top of `bot.py` to load the file:

```python
from dotenv import load_dotenv
load_dotenv()
```

Now you can run the script without ever typing the key in plain text.

### 6. Run the bot  
In the terminal, execute:

```
python bot.py
```

You should see the greeting, and you can start chatting. Try something simple like “What’s the capital of Japan?” or “Give me a one‑line joke about programmers.” The bot will answer, and you can type `exit` when you’re done.

## Testing and tweaking

Once the basic loop works, you might want to add a few niceties:

* **Error handling** – Wrap the [API call](https://www.amazon.com/s?k=API+call&tag=organizationtip101-20) in a `try/except` block to catch network hiccups, following our [debugging tips for remote teams](/techtrek/debugging-tips-for-remote-teams-keeping-code-clean-across-time-zones).
* **Conversation memory** – Keep a list of past messages and send them each time so the bot remembers context. Just be careful not to exceed the token limit.
* **Rate limiting** – If you plan to let others use the bot, add a short pause (`time.sleep(1)`) between calls to stay within OpenAI’s free‑tier limits.

Here’s a tiny snippet for error handling:

```python
import time

def ask_chatgpt(prompt, model="gpt-3.5-turbo"):
    try:
        response = openai.ChatCompletion.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            max_tokens=150,
            temperature=0.7
        )
        return response["choices"][0]["message"]["content"].strip()
    except openai.error.OpenAIError as e:
        print("API error:", e)
        time.sleep(2)  # wait before retrying
        return "Sorry, I ran into a problem. Try again?"
```

## Tips to keep it fast and cheap

1. **Pick the right model** – For most everyday queries, `gpt-3.5-turbo` is more than enough. Reserve `gpt-4` for tasks that truly need higher reasoning.
2. **Limit tokens** – Lower `max_tokens` reduces cost and speeds up responses. If you only need a short answer, 100 tokens is plenty.
3. **Cache frequent answers** – If your bot often gets the same question (e.g., “What time is it in UTC?”), store the result locally for a few minutes and return the cached value instead of calling the API each time.
4. **Batch requests** – If you ever need to process many prompts at once, send them in a single API call using the `messages` array. This reduces overhead.

## Wrap-up

There you have it – a [fully functional ChatGPT‑powered bot](/techtrek/building-a-personal-chatbot-with-openai-s-api-stepbystep-guide) built in under an hour. The whole process is just a few commands, a short script, and a dash of curiosity. Once you’ve got the basics down, you can expand the bot into a Slack helper, a Discord companion, or even a tiny [web service](https://www.amazon.com/s?k=web+service&tag=organizationtip101-20). The sky’s the limit, and the setup is simple enough that you can squeeze it into a coffee break.

Happy coding, and may your bots be ever witty!
