- Published on
Creating an AI Chatbot in Telegram Using Python
- Authors
- Name
- ChatofAI Team
- @chatof_ai
Overview
In this article, we guide you to create an AI chatbot in Telegram, we use chatgpt api as the AI model to generate responses, python demo code is provided to help you learn how to create a chatbot in Telegram. openai key and telegram account is needed. if you don't have this resource or you do not have any programming knowledge, you can use ChatofAI to create a chatbot in Telegram without any coding.
Table of Contents
- Prerequisites
- Step1: Setting up a Telegram bot
- Step2: Integrating the telegram bot with Python
- Step3: Integrating ChatGPT with the Telegram bot
- Conclusion
Prerequisites
- Basic knowledge of Python
- A Telegram account
- Python installed on your machine
- A ChatGPT API key (you can get one here)
- Python libraries:
python-telegram-bot
,openai
- A text editor or an IDE like VSCode
Step1: Setting up a Telegram bot
To create a Telegram bot, you need to talk to the BotFather on Telegram. here are the steps to create a new bot:
- Open Telegram and search for
BotFather
. - Start a chat with
BotFather
, using the/newbot
command to create a new bot. - Follow the instructions to set up your bot, including choosing a name and username.
- Once your bot is created, you will receive a
token
that you will use to interact with the Telegram API.
Step2: Integrating the telegram bot with Python
Now that you have created a Telegram bot, let's integrate it with Python using the python-telegram-bot
library.
Install the library
You can install the python-telegram-bot
library using pip:
pip install python-telegram-bot
Write the Python code to interact with the bot
Here is a simple Python script that interacts with a Telegram bot. The file is named bot.py
or any name you prefer.
import logging
from telegram import ForceReply, Update
from telegram.ext import (Application, CommandHandler, ContextTypes,
MessageHandler, filters)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
BOT_TOKEN = "YOUR_BOT_TOKEN"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
await update.message.reply_html(
rf"Hi {user.mention_html()}!",
reply_markup=ForceReply(selective=True),
)
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Send a message when the command /help is issued."""
await update.message.reply_text("Help!")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
def main() -> None:
"""Start the bot."""
application = Application.builder().token(BOT_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()
Notice that you need to replace YOUR_BOT_TOKEN
with the token you received from the BotFather. now you can run the script and start chatting with your bot on Telegram.
python bot.py
Open your Telegram app and search for your bot by its username, then start chatting with it. it should respond to the /start
and /help
commands and echo any other message you send. next, we will change the echo
function to use ChatGPT to generate responses.
Step3: Integrating ChatGPT with the Telegram bot
To integrate ChatGPT with the Telegram bot, you need to make a request to the ChatGPT API with the user's message and get the response. firt you need to install the openai
and requests
libraries:
pip install openai requests
then you can modify the echo
function to use ChatGPT to generate responses:
from openai import OpenAI
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"
def get_chatgpt_response(message: str) -> str:
client = OpenAI(api_key=OPENAI_API_KEY)
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": message},
],
)
return completion.choices[0].message.content
now you can modify the echo
function to use the get_chatgpt_response
function:
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
response = get_chatgpt_response(update.message.text)
await update.message.reply_text(response)
now you can run the script and start chatting with your bot on Telegram, it should respond with ChatGPT generated responses.
Conclusion
In this tutorial, we learned how to create an AI chatbot on Telegram using Python. We started by setting up a Telegram bot and then integrated ChatGPT to enhance its intelligence. However, this is just a basic example. To build a more advanced chatbot, you should consider:
- Optimizing prompt messages for better responses.
- Incorporating private data into ChatGPT to generate more personalized responses.
- Handling more complex user inputs and responses.
Our server ChatofAI offers an advanced chatbot service that can help you create a more sophisticated chatbot with enhanced features and performance. You can build your own chatbot on our platform and seamlessly integrate it with your Telegram bot. Additionally, we support many other platforms such as Slack, Wix, and more. For more details, please refer to our documentation here.