DEV Community


Posted on • Updated on

How to build a Telegram Bot with ChatGPT integration.

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.

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)

Enter fullscreen mode Exit fullscreen mode

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) Register our bot at telegram

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

Image description

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:

Image description
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

Image description

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


Enter fullscreen mode Exit fullscreen mode

Replace <your_telegram_api_token> with your actual Telegram API token provided by BotFather.

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


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.

Image description
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 users input. We will query ChatGPT with this input and redirect the answer from ChatGPT back to our user. Lets go!

2) Create the CHAT-GPT 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

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
Enter fullscreen mode Exit fullscreen mode

Now move to the openAI website and get your token.

Place the API key in the .env file, add the following line:

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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.

Image description

Thats all! Hope you enjoyed this one. Next time we are going to build a AirBnB Chatbot that can respond to guests with custom knowledge like Wifi Passwort or Checkout Times, sounds cool right ?

If you don't want to miss this article go to my site and subscribe the Newsletter, I would really appreciate this ❤️!

Top comments (3)

mannu profile image

that's rlly good but please make sure to check the syntax once more.


also u forgot to import dotenv.

hayerhans profile image

Thanks for that hint :)

mannu profile image

My pleasure