Telegram bots are a great way to interact with users and automate tasks. In this tutorial, we'll walk through the process of creating a Telegram bot using Python and integrating it with the Gemini AI API to add advanced conversational capabilities.
Before we begin, make sure you have the following:
/newbot
.Open a terminal or command prompt.
Install the pyTelegramBotAPI library using pip:
pip install pyTelegramBotAPI
main.py
.Open main.py
in VSCode.
Add the following code to set up the Telegram bot:
import telebot bot = telebot.TeleBot("TOKEN", parse_mode=None) # Replace "TOKEN" with your actual token @bot.message_handler(func=lambda m: True) def echo_all(message): bot.reply_to(message, message.text) bot.infinity_polling()
Replace "TOKEN"
with the token obtained from BotFather.
Run python main.py
, then go to your bot in Telegram and send a message. It should echo back your message.
Install the required library:
pip install google-generativeai
Create a new file named gemini.py
and add the following code:
import google.generativeai as genai genai.configure(api_key="YOUR_API_KEY") convo = genai.ChatSession() convo.send_message("Hello! How old are you?") print(convo.last.text)
Replace "YOUR_API_KEY"
with your actual API key.
Now integrate this with main.py
. Modify the bot handler:
@bot.message_handler(func=lambda m: True) def echo_all(message): convo.send_message(message.text) response = convo.last.text bot.reply_to(message, response)
Create a .env
file in the root folder and add your API keys:
API_KEY=your_gemini_api_key TELEGRAM_BOT_TOKEN=your_telegram_bot_token
Install python-dotenv
:
pip install python-dotenv
Modify main.py
to use environment variables:
import os from dotenv import load_dotenv load_dotenv() GEMINI_API_KEY = os.getenv("API_KEY") TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
Save main.py
in VSCode.
Open a terminal or command prompt and navigate to the project folder.
Run the script:
python main.py
Check if the bot is working by sending messages on Telegram.
If you want your bot to be accessible 24x7, deploy it to a cloud service.
Follow their deployment guides to ensure your bot runs continuously.
You've successfully built a Telegram bot with Python and integrated it with the Gemini AI API.
Happy bot building! 🚀
This Markdown version will render well on GitHub, blogs, or documentation platforms. Let me know if you need any modifications! 😊
There are no datasets linked
There are no datasets linked