Building a Personalized Telegram Chatbot with Python and Gemini 2.0 Flash

🚀 Introduction
Creating a chatbot that feels like a real friend is an exciting challenge! In this guide, I’ll walk you through how I built a Telegram chatbot using Python and Google’s Gemini 2.0 Flash API. My goal was to make it respond in my personal style, switching between English and Vietnamese, and sometimes giving mentorship on programming like a senior developer.
🔹 Step 1: Setting Up the Telegram Bot
1️⃣ Create a Telegram Bot with @BotFather
Open @BotFather on Telegram.
Type:
/newbot
.Follow the instructions & give your bot a name.
Save the Bot Token (We’ll use it later in our code).
🔹 Step 2: Get the Gemini API Key
Go to Google AI Studio.
Sign in & create a new API key.
Save this API key for later use.
🔹 Step 3: Install Required Libraries
Run the following in your terminal:
pip install python-telegram-bot requests python-dotenv
🔹 Step 4: Store Configurations Securely
1️⃣ Create a .env
File
Create a file named .env
in your project directory and add:
TELEGRAM_BOT_TOKEN=your-telegram-bot-token
GEMINI_API_KEY=your-gemini-api-key
This keeps your credentials safe and prevents them from being hardcoded.
2️⃣ Create responses.json
for Predefined Replies
To make the bot more responsive, we define common replies in a JSON file. Create a new file responses.json
and add various responses based on user interactions.
🔹 Step 5: Writing the Python Bot
Develop a Python script to handle messages, fetch AI-generated replies, and respond naturally.
🔹 Step 6: Running Your Bot
Replace
YOUR_TELEGRAM_BOT_TOKEN
with your actual bot token.Replace
YOUR_GEMINI_API_KEY
with your Gemini API key.Save the file as
bot.py
.Run it with:
python bot.py
Open Telegram and chat with your bot! 🚀
🔹 Next Steps
Deploy it on a server (e.g., AWS, Heroku, or PythonAnywhere).
Improve personality by feeding more of your own replies.
Add voice & image message handling.
Train it to remember past conversations better.
This was a fun project, and the bot now feels more real, engaging, and useful! Want help with deployment? Let me know! 😊
Subscribe to my newsletter
Read articles from Larry D'Jean Art directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Larry D'Jean Art
Larry D'Jean Art
strong desire for learning new things