0% found this document useful (0 votes)
2 views5 pages

Telegram Coding Assistant Bot Python Implementation

This document outlines the implementation of a Telegram bot using Python that integrates with the Google Gemini API for generating responses to user messages. Key features include asynchronous operations, environment variable configuration for API tokens, and basic error handling. The document also provides a Python code snippet, configuration instructions, and steps to run the bot successfully.

Uploaded by

myatkotai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Telegram Coding Assistant Bot Python Implementation

This document outlines the implementation of a Telegram bot using Python that integrates with the Google Gemini API for generating responses to user messages. Key features include asynchronous operations, environment variable configuration for API tokens, and basic error handling. The document also provides a Python code snippet, configuration instructions, and steps to run the bot successfully.

Uploaded by

myatkotai
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Telegram Coding Assistant Bot: Python

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

# --- Configuration --- #


# Get API tokens from environment variables for security
TELEGRAM_BOT_TOKEN = [Link]("TELEGRAM_BOT_TOKEN")
GOOGLE_GEMINI_API_KEY = [Link]("GOOGLE_GEMINI_API_KEY")

# Configure logging
[Link](
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging
)
logger = [Link](__name__)

# --- Google Gemini API Setup --- #


if GOOGLE_GEMINI_API_KEY:
[Link](api_key=GOOGLE_GEMINI_API_KEY)
# Initialize the Gemini model
# You can choose different models, e.g., 'gemini-pro-vision' for multimodal
gemini_model = [Link]("gemini-pro")
else:
[Link]("GOOGLE_GEMINI_API_KEY not found. Please set the environment va
gemini_model = None

# --- Telegram Bot Handlers --- #


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Sends a welcome message when the command /start is issued."""
user = update.effective_user
await [Link].reply_html(
f"Hi {user.mention_html()}! I am your AI Coding Assistant. Send me a pro
)

async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No


"""Sends a help message when the command /help is issued."""
await [Link].reply_text(
"Send me any programming-related question or request, and I will do my b
)

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) ->


"""Processes user messages and sends them to the Gemini API."""
if not gemini_model:
await [Link].reply_text("Gemini API is not configured. Please ch
return

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}")

# Reply to the user


await [Link].reply_text(gemini_response)
except Exception as e:
[Link](f"Error communicating with Gemini API: {e}")
await [Link].reply_text(
"Sorry, I encountered an error while processing your request. Please
)

# --- Main Bot Function --- #


def main() -> None:
"""Starts the bot."""
if not TELEGRAM_BOT_TOKEN:
[Link]("TELEGRAM_BOT_TOKEN not found. Please set the environment v
return

# Create the Application and pass it your bot's token.


application = [Link]().token(TELEGRAM_BOT_TOKEN).build()

# Register handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(MessageHandler([Link] & ~[Link], hand

# Run the bot until the user presses Ctrl-C


[Link]("Bot started. Press Ctrl-C to stop.")
application.run_polling(allowed_updates=Update.ALL_TYPES)

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

• On Windows (Command Prompt):


Plain Text
set TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
set GOOGLE_GEMINI_API_KEY="YOUR_GOOGLE_GEMINI_API_KEY"
python telegram_gemini_bot.py

3. Run the script: python telegram_gemini_bot.py .


Your bot should now be running and ready to respond to messages in Telegram.
References
• [1] python-telegram-bot. (n.d.). python-telegram-bot. Retrieved from [Link]
[Link]/
• [2] Google AI for Developers. (n.d. ). Gemini API libraries. Retrieved from
[Link]

You might also like