By obrizan on May 9, 2025 · Read this post in other languages: Ukrainian Russian
In this lesson, you will learn how to create a Telegram bot that answers your questions using artificial intelligence — the ChatGPT model from OpenAI. Step by step, we will:
Contents:
For your bot to access ChatGPT, you need an API key from OpenAI. To do this:
sk-proj-abc1234567890...
Be sure to save this key in a safe place. It will not be shown again.
Learn more about working with the OpenAI API in the lesson: "How to work with ChatGPT using OpenAI API and Python"
/newbot
command and provide the following information:bot
(for example, my_gpt_bot
).
1234567890:AdfgqAAWEGaASDqwefeasefadfaweAEFAA
.⚠️ Note:
Let's move to programming practice.
main.py
and add the basic Telegram bot code:import asyncio
import logging
import sys
from aiogram import Bot, Dispatcher, html
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
# You can get the bot token at https://t.me/BotFather
# IMPORTANT: specify your token
TOKEN = "1234567890:AdfgqAAWEGaASDqwefeasefadfaweAEFAA"
dp = Dispatcher()
@dp.message(CommandStart())
async def command_start_handler(message: Message) -> None:
await message.answer(f"Hello, {html.bold(message.from_user.full_name)}!")
@dp.message()
async def echo_handler(message: Message) -> None:
try:
# Send a copy of the received message
await message.send_copy(chat_id=message.chat.id)
except TypeError:
# But not all types support copying, so handle this
await message.answer("Nice try!")
async def main() -> None:
# Initialize the bot instance with default properties that will be passed to all API calls
bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
# Start event processing
await dp.start_polling(bot)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
asyncio.run(main())
IMPORTANT: in the line TOKEN = "1234567890:AdfgqAAWEGaASDqwefeasefadfaweAEFAA"
specify your Telegram bot token obtained in the previous step.
This code uses the aiogram library — a modern fully asynchronous framework for Telegram Bot API, written in Python using asyncio and aiohttp. You need to install this library in your project environment. Open the Terminal in PyCharm and run the command:
pip install aiogram
After running this command, you should see the message Successfully installed aiogram-3.20.0
, as shown in the image.
Run the main.py
file using the Debug button (green bug), or via the terminal command: python main.py
.
In the PyCharm terminal, you will see the message Run polling for bot @obrizan_ai_assistant_bot id=7893124402 - "Obrizan's AI Assistant"
, as shown below. This means the Telegram bot is ready to receive messages. (The bot name and ID will be different for you).
Open your bot in Telegram, execute the /start
command. Send any message. Your bot should reply with the same message:
🚀 Congratulations! If you see the bot's replies, the integration is set up correctly.
In this step, we will connect ChatGPT via the OpenAI API so that artificial intelligence responds to your messages. Important: for this step, you need to have an OpenAI API key and have installed the OpenAI library (pip install openai
) as described in the tutorial "How to work with ChatGPT using OpenAI API and Python"
Modify the main.py
file as follows:
# IMPORTANT: specify your API key
client = AsyncOpenAI(
api_key="sk-proj-ieqbTxAWEF0GDSgfv4K0m2..._3sROehQhz4afQWAWEASDFt9"
)
def echo_handler(message: Message)
;def openai_handler(message: Message)
, where we receive the user's query, forward it to ChatGPT via the OpenAI API (method client.responses.create(...)
), and after receiving ChatGPT's response, send it back to the user in Telegram (method message.answer(...)
):@dp.message()
async def openai_handler(message: Message) -> None:
# Forward the user's query to ChatGPT
response = await client.responses.create(
model="gpt-4o-mini",
instructions="Answer in a plain text without formatting.",
input=message.text
)
try:
# Send ChatGPT's response to the user
await message.answer(response.output_text)
except TypeError:
await message.answer("Can't process this request!")
The final version of the main.py
file should look like this:
import asyncio
import logging
import sys
from os import getenv
from aiogram import Bot, Dispatcher, html
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from openai import AsyncOpenAI
# You can get the bot token at https://t.me/BotFather
# IMPORTANT: specify your token
TOKEN = "1234567890:AdfgqAAWEGaASDqwefeasefadfaweAEFAA"
dp = Dispatcher()
# IMPORTANT: specify your API key
client = AsyncOpenAI(
api_key="sk-proj-ieqbTxAWEF0GDSgfv4K0m2..._3sROehQhz4afQWAWEASDFt9"
)
@dp.message(CommandStart())
async def command_start_handler(message: Message) -> None:
await message.answer(f"Hello, {html.bold(message.from_user.full_name)}!")
@dp.message()
async def openai_handler(message: Message) -> None:
# Forward the user's query to ChatGPT
response = await client.responses.create(
model="gpt-4o-mini",
instructions="Answer in a plain text without formatting.",
input=message.text
)
try:
# Send ChatGPT's response to the user
await message.answer(response.output_text)
except TypeError:
await message.answer("Can't process this request!")
async def main() -> None:
bot = Bot(token=TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
await dp.start_polling(bot)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
asyncio.run(main())
Run the main.py
file using the Debug button (green bug), or via the terminal command: python main.py
. Let's check communication with ChatGPT through the Telegram bot:
👏 Congratulations! You have created your own chatbot with artificial intelligence features!