Telegram Coding Assistant Bot Python Implementation
Telegram Coding Assistant Bot Python Implementation
Implementation
This document provides a complete, optimized Python code snippet for a Telegram bot that
uses the python-telegram-bot library to interact with the Google Gemini API. The bot is
designed to receive a message from a user, send that text to the Google Gemini API, and
then reply to the user with the generated content.
Key Features
• Asynchronous Operations: Leverages asyncio for efficient handling of multiple user
requests.
• Environment Variable Configuration: Securely manages API tokens using
environment variables.
• Clear Command Handling: Implements /start and /help commands for user guidance.
• Gemini API Integration: Sends user messages to the Google Gemini API ( gemini-pro
model) and retrieves responses.
• Error Handling: Includes basic error handling for API communication.
• Logging: Provides informative logging for debugging and monitoring.
Prerequisites
Before running the bot, ensure you have the following installed:
• Python 3.8+
• python-telegram-bot library (version 20.x or higher)
• google-generativeai library
You can install these using pip:
Bash
pip install python-telegram-bot==20.7 --pre google-generativeai
Configuration
Set the following environment variables:
• TELEGRAM_BOT_TOKEN : Your Telegram bot token, obtained from BotFather.
• GOOGLE_GEMINI_API_KEY : Your Google Gemini API key.
Note on Pabbly Connect: While this code directly integrates with the Google Gemini API,
your context mentions using Pabbly Connect. Pabbly Connect would typically act as an
intermediary webhook. In that scenario, the handle_message function would send the user's
message to a Pabbly Connect webhook URL, and Pabbly Connect would then forward it to
the Gemini API and return the response. For direct integration, as requested, the code
below bypasses Pabbly Connect for the Gemini API call.
Python Code Snippet
Python
import os
import logging
from telegram import Update
from [Link] import Application, CommandHandler, MessageHandler, filters, C
import [Link] as genai
# Configure logging
[Link](
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging
)
logger = [Link](__name__)
user_message = [Link]
[Link](f"Received message from {update.effective_user.full_name}: {use
try:
# Send message to Gemini API
response = gemini_model.generate_content(user_message)
gemini_response = [Link]
[Link](f"Gemini API response: {gemini_response}")
# Register handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler([Link] & ~[Link], hand
if __name__ == "__main__":
main()
Code Explanation
1. Imports: Necessary libraries like os for environment variables, logging for output,
telegram and [Link] for the bot, and [Link] for Gemini API interaction
are imported.
2. Configuration:
• TELEGRAM_BOT_TOKEN and GOOGLE_GEMINI_API_KEY are retrieved from environment
variables. This is a best practice for security to avoid hardcoding sensitive
information directly in the code.
• Basic logging is set up to provide feedback on bot operations.
3. Google Gemini API Setup:
• The [Link] function is called with your GOOGLE_GEMINI_API_KEY .
• [Link]("gemini-pro") initializes the Gemini model. You can switch to
other models like gemini-pro-vision if your bot needs to handle multimodal inputs.
• An error is logged if the API key is missing.
4. Telegram Bot Handlers:
• start(update, context) : An asynchronous function that sends a welcome message
when a user sends the /start command.
• help_command(update, context) : An asynchronous function that provides a help
message for the /help command.
• handle_message(update, context) : This is the core logic for processing user messages.
• It first checks if the gemini_model is configured.
• It extracts the user_message text.
• It then calls gemini_model.generate_content(user_message) to send the user's query
to the Gemini API.
• The [Link] is extracted and sent back to the user using
[Link].reply_text() .
• A try-except block is used to catch potential errors during API communication
and inform the user.
5. Main Bot Function ( main ):
• Checks for the TELEGRAM_BOT_TOKEN environment variable.
• [Link]().token(TELEGRAM_BOT_TOKEN).build() creates the bot application
instance.
• application.add_handler() registers the command handlers ( /start , /help ) and a
MessageHandler for all text messages that are not commands. The [Link] &
~[Link] ensures that only plain text messages are processed by
handle_message .
• application.run_polling() starts the bot, continuously checking for new messages.
allowed_updates=Update.ALL_TYPES ensures all types of updates are processed.
How to Run
1. Save the code as telegram_gemini_bot.py .
2. Set your TELEGRAM_BOT_TOKEN and GOOGLE_GEMINI_API_KEY environment variables.
• On Linux/macOS:
Bash
export TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
export GOOGLE_GEMINI_API_KEY="YOUR_GOOGLE_GEMINI_API_KEY"
python telegram_gemini_bot.py