DEV Community

hayerhans
hayerhans

Posted on • Edited 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 telegram-bot.py

We are going to use this https://github.com/python-telegram-bot/python-telegram-bot 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 telegram-bot.py file:



import logging
import os

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

load_dotenv()

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)
TELEGRAM_API_TOKEN = os.getenv("TELEGRAM_API_TOKEN")

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

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, 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)
    application.add_handler(start_handler)
    application.add_handler(echo_handler)

    application.run_polling()


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 https://web.telegram.org/k/ 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 telegram-bot.py file, and add the following line to it:



TELEGRAM_API_TOKEN=<your_telegram_api_token>



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

python3 telegram-bot.py

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

“chatgpt_client.py”.

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):
    try:
        completion = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"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:



OPENAI_API_KEY="<your_openai_api_key>"


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 context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text) with the following:



response = request_chat_gpt(update.message.text)
await context.bot.send_message(chat_id=update.effective_chat.id, 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 ❤️!

https://jhayer.tech

Top comments (5)

Collapse
 
mannu profile image
Mannu

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

syntax

also u forgot to import dotenv.

Collapse
 
hayerhans profile image
hayerhans

Thanks for that hint :)

Collapse
 
mannu profile image
Mannu

My pleasure

Collapse
 
danyaleyman_19 profile image
Sad vibes forever

The nice article, but if you're not planning to make money with bot, it make no sense to create the bot. If you're regular user, just find some you like and use. For example (Not ad):
t.me/chatgpt_karfly_bot
t.me/ChatGPT_web_gobot
t.me/GPT_neirobot

Collapse
 
lmkgv profile image
K

Please tell me how to modify the code so that the bot remembers the context of the entire dialogue