Build your own telegram bot with Chat-GPT integration
- 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: https://github.com/XamHans/telegram-chatgpt-bot
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()
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 https://web.telegram.org/k/ and log in with your smartphone. Use the search bar to search for “BotFather”.
Head over to https://web.telegram.org/k/ 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 telegram-bot.py
file, and add the following line to it:
TELEGRAM_API_TOKEN=<your_telegram_api_token>
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 [telegram-bot.py](http://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.
(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
“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
from dotenv import load_dotenv
load_dotenv()
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
Now move to the openAI website and get your token.
Go to the .env
file, add the following line:
OPENAI_API_KEY="<your_openai_api_key>"
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)
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 ⇢