Build your own telegram bot with Chat-GPT integration

By Johannes Hayer
Picture of the author
Published on

This tutorial explains step-by-step how to build a custom Telegram chatbot that can interact with OpenAI ChatGPT. The tutorial is written in Python and uses the python-telegram-bot and openai packages. You can find the code on github here:

1) Create Telegram Chatbot

Open your IDE and create a file named

We are going to use this package that will help us to create the telegram bot. Make sure to install it with

pip3 install python-telegram-bot python-dotenv

After installing, paste in this code to your file:

import logging
import os

from dotenv import load_dotenv
from telegram import Update
from telegram.ext import (ApplicationBuilder, CommandHandler, ContextTypes,
                          MessageHandler, filters)


    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await, text="I'm a bot, please talk to me!")

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await, text=update.message.text)

if __name__ == '__main__':
    application = ApplicationBuilder().token(TELEGRAM_API_TOKEN).build()

    start_handler = CommandHandler('start', start)
    echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)


We are defining two handlers, one command helper (so if you type /start in telegram) and one message handler.

The message handler (funcion echo) for testing purposes only gives back what the user typed. So let's try out our bot. But before we can do this we need to register our bot at telegram in order to get the API_KEY.

1.1) Create Bot & API Key

Head over to and log in with your smartphone. Use the search bar to search for “BotFather”.

Head over to and log in with your smartphone. Use the search bar to search for “BotFather”. ![(Start your bot registration with BotFather)]

Start the registration with the /start command.

It lists all possible commands, we go further with /newbot to register a new bot.

Now try to find a good name for your bot, I had some struggles:

(Find a good name for your bot)

After successful registration you will get a message from BotFather that your bot is registered, where you can find it and the token to access it. Copy this token

(Copy the token - thanks BotFather, a offer we can't refuse)

Create a .env file in the same directory as the file, and add the following line to it:


Replace <your_telegram_api_token> with your actual Telegram API token, which can be obtained by registering a bot on the Telegram website.

We can now test your telegram bot ! In your IDE open a terminal and in the path where you script is start the bot with

python3 [](

Open the link where you can find your bot or use the search bar on telegram to find it. Click the start button and lets write something.

(Our bot is working!)

Sweet! We have successfully achieved part 1. What we now need to do is to connect our bot with chatgpt. The idea is simple, the bot is taking the userinput. We will query chatgpt with this input and redirect the answer from chatgpt back to our user. Lets go!

2) Create ChatGPT Client

Let’s create a new python file that will handle all the ChatGPT Stuff, I will call it


We are going to use the official openai python package to query chatgpt api. lets install the openai python package with

pip3 install openai

Copy this code to the new created file:

import os
import openai
from dotenv import load_dotenv


openai.api_key = os.getenv("OPENAI_API_KEY")

def request_chat_gpt(user_message):
        completion = openai.ChatCompletion.create(
                {"role": "user", "content": user_message}
        return completion.choices[0].message['content']
    except Exception as e:
        print(f"An error occurred: {e}")
        return ""  # Return an empty string or handle the error appropriately

Now move to the openAI website and get your token.

Go to the .env file, add the following line:


Replace <your_openai_api_key> with your actual OpenAI API key.

To use the openai integration in the echo handler, we can replace the line

await, text=update.message.text)

with the following:

response = request_chat_gpt(update.message.text)
await, text=response)

Of course don’t forget to import the function

from chatgpt_client import request_chat_gpt

This will send the user's input to the request_chat_gpt function, which will use the OpenAI API to generate a response. The response will then be sent back to the user via the echo handler.

(Our bot is smart now!)

Thats all! Hope you enjoyed this one. Would you be interested to extend this tutorial where we build a AirBnB Chatbot based on custom data? Sounds cool right? Subscribe to my newsletter and I will let you know!

If you found this content helpful ⇢

Stay Tuned

Subscribe for development and indie hacking tips!