# How to Add ChatGPT to a Telegram Bot: A Complete Guide

AI bots are becoming an effective tool for automating communication, personalizing services, and improving the quality of interaction with the audience. Thanks to the integration of ChatGPT into Telegram, the bot transforms from a simple command executor into a full-fledged digital conversationalist.

Intelligent bots based on ChatGPT allow:  
— automating customer support and internal processes  
— providing quick and meaningful responses to requests  
— training, entertaining, and assisting users  
— generating personalized recommendations.

**What is required to launch**

Before starting, make sure you have:  
— a Telegram account  
— a token from BotFather to create a new bot  
— an OpenAI API key  
— a server or local computer to run the script  
— Python installed along with the aiogram, openai, and python-dotenv libraries.

**Integration stages**

1. Creating a Telegram bot:

1. Open Telegram, find BotFather, and send the /newbot command.
1. Set a name and a unique username for your bot.
1. Obtain the API token — it will be needed when configuring the script.

2. Registering with OpenAI:

1. Go to the OpenAI website.
1. Register and obtain an API key in the API Keys section.
1. Save the key for future use.

3. Configuring the code and environment.

**Install the necessary libraries:**

pip install aiogram openai python-dotenv

**Create a .env file to store sensitive data:**

TELEGRAM\_BOT\_TOKEN=your\_bot\_token

OPENAI\_API\_KEY=your\_api\_key

**Example of a basic script:**

import openai  
import os  
from aiogram import Bot, Dispatcher, types  
from aiogram.utils import executor  
from dotenv import load\_dotenv  

load\_dotenv()

TELEGRAM\_BOT\_TOKEN = os.getenv("TELEGRAM\_BOT\_TOKEN")  
OPENAI\_API\_KEY = os.getenv("OPENAI\_API\_KEY")

bot = Bot(token=TELEGRAM\_BOT\_TOKEN)  
dp = Dispatcher(bot)  
openai.api\_key = OPENAI\_API\_KEY

@dp.message\_handler()  
async def chat\_with\_gpt(message: types.Message):  
 response = openai.ChatCompletion.create(  
 model="gpt-3.5-turbo",  
 messages=\[{"role": "user", "content": message.text}\]  
 )  
 await message.reply(response\["choices"\]\[0\]\["message"\]\["content"\])

if \_\_name\_\_ == "\_\_main\_\_":  
 executor.start\_polling(dp, skip\_updates=True)

4. Launching the Telegram bot:

— save the script as [bot.py](<http://bot.py>)— run it via the terminal:

**python bot.py**

— send a message to your bot. It should respond automatically.

5. Extending functionality

**Add commands:**

@dp.message\_handler(commands=\['start', 'help'\])  
async def send\_welcome(message: types.Message):  
 await message.reply("Hi! I am a ChatGPT-based bot. Ask me questions.")

**Limit message length:**

if len(message.text) > 500:  
 await message.reply("The message is too long, please try a shorter one.")  
 return

**Add dialog context:**

user\_messages = {}

@dp.message\_handler()  
async def chat\_with\_gpt(message: types.Message):  
 chat\_id = message.chat.id  
 if chat\_id not in user\_messages:  
 user\_messages\[chat\_id\] = \[\]

user\_messages\[chat\_id\].append({"role": "user", "content": message.text})

response = openai.ChatCompletion.create(  
 model="gpt-3.5-turbo",  
 messages=user\_messages\[chat\_id\]  
 )

bot\_reply = response\["choices"\]\[0\]\["message"\]\["content"\]  
user\_messages\[chat\_id\].append({"role": "assistant", "content": bot\_reply})

await message.reply(bot\_reply)
