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.
Author - Mansur Ismagulov
The Tech AI
Get the key points in seconds - a short summary from The Tech AI.
Intelligent bots based on ChatGPT automate support and provide personalized recommendations. To launch them, you need a Telegram account, a BotFather token, an OpenAI API key, a server with Python, and the aiogram, openai, and python-dotenv libraries. The process involves creating a bot via BotFather, registering with OpenAI, installing the libraries, configuring the .env file, and running the bot.py script. The code uses the gpt-3.5-turbo model for responses and supports commands, message length limits, and conversation context preservation.
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:
- Open Telegram, find BotFather, and send the /newbot command.
- Set a name and a unique username for your bot.
- Obtain the API token — it will be needed when configuring the script.
2. Registering with OpenAI:
- Go to the OpenAI website.
- Register and obtain an API key in the API Keys section.
- 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
— 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)
The Tech on Telegram Follow The Tech on Telegram
Keep up with the latest technology and startup news.