Skip to content

AI edits: add a telegram tool#63

Open
auto-swe[bot] wants to merge 1 commit intomainfrom
autoswe-edits-1763562109071
Open

AI edits: add a telegram tool#63
auto-swe[bot] wants to merge 1 commit intomainfrom
autoswe-edits-1763562109071

Conversation

@auto-swe
Copy link

@auto-swe auto-swe bot commented Nov 19, 2025

This pull request contains AI-suggested changes:

add a telegram tool

@codedaddy-reviewer
Copy link

codedaddy-reviewer bot commented Nov 19, 2025

Walkthrough

This PR introduces a powerful new TelegramSendMessage tool, enabling an LLM agent to send messages directly to a predefined Telegram chat. It also refines the handling of sensitive API keys and chat IDs for both this new Telegram tool and the existing WebSearch tool, primarily by prioritizing environment variables with interactive getpass fallbacks.

Changes

Cohort / File(s) Summary
py-server/nodes/Agents/tools/tools.py Adds telegram_send_message function and TELEGRAM_TOOL, integrating python-telegram-bot for agent-initiated messaging. Updates environment variable loading for TAVILY_API_KEY, TELEGRAM_BOT_TOKEN, and TELEGRAM_CHAT_ID to include interactive prompts as fallbacks.

🔧 Key Implementation Details

Telegram Integration & Tooling
The core addition is the telegram_send_message function and its LangChain wrapper, TELEGRAM_TOOL. This allows the agent to leverage the python-telegram-bot library to send messages, significantly expanding the agent's communication capabilities.

Environment Variable Management
API keys and chat IDs are now sourced from environment variables, with getpass.getpass() providing an interactive fallback for local development. This aims to offer flexibility but introduces considerations for automated deployment environments.


Poem

Your Daddy reviews code with care and grace,
A Telegram tool now finds its place.
With secrets handled, and functions new,
Let's refine this code, for me and you! 🐰✨


Tip

🔮 Embrace Asynchronous I/O for Agent Tools!

For tools making external network requests (like web search or sending messages), converting them to async functions with await can dramatically improve your agent's responsiveness and concurrency, especially in a server environment.


✨ Finishing Touches
  • Consider adding a pyproject.toml or requirements.txt entry for the new python-telegram-bot dependency to ensure consistent installations across environments.
  • Add comprehensive docstrings to the telegram_send_message function and update the web_search_tool docstring for clarity, including type hints and expected behavior.
  • Standardize the naming convention for environment variables (e.g., ensure consistency if other TELEGRAM_ prefixed variables are introduced).

Review Comments

📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +50 to +60

🔴 Critical: Unrestricted Telegram Message Sending via LLM Agent (Prompt Injection Vulnerability)

The new TELEGRAM_TOOL allows the LLM agent to send arbitrary messages to a predefined Telegram chat. Without proper safeguards, an attacker could exploit prompt injection to coerce the agent into sending harmful, misleading, or sensitive information. This poses a significant security risk, potentially leading to reputational damage or social engineering attacks.

Suggestion:
This requires a broader architectural fix beyond just code. Consider implementing a message approval mechanism, content filtering, or a whitelist of allowed message types/recipients when integrating LLM agents with external communication tools.

Rationale: Direct, unfiltered LLM access to external communication channels is a severe prompt injection vulnerability. An attacker can manipulate the agent to send malicious or sensitive information, causing significant harm.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +10 to +15

🟡 Medium: Sensitive Credential Handling (Telegram Bot Token)

The fallback to getpass.getpass() for TELEGRAM_BOT_TOKEN means it might be prompted interactively. While convenient for local setup, this is an anti-pattern for production or automated environments and increases the risk of token exposure.

Suggestion:

# Instead of:
# TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") or getpass.getpass("Enter your Telegram Bot Token: ")
# Use:
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
if not TELEGRAM_BOT_TOKEN:
    raise ValueError("TELEGRAM_BOT_TOKEN environment variable not set. Please set it securely.")

Rationale: Interactive prompts for sensitive credentials are unsuitable for production and automated environments. They also risk exposure via shell history. Credentials should always be loaded from secure environment variables or a dedicated secrets management system, failing explicitly if not found.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +5 to +20

🟡 Medium: Interactive API Key Prompts (Anti-pattern for production/automation)

The code uses getpass.getpass to interactively prompt for TAVILY_API_KEY, TELEGRAM_BOT_TOKEN, and TELEGRAM_CHAT_ID if they are not found in environment variables. This makes the module non-deterministic and unsuitable for automated environments (e.g., CI/CD, production servers) where interactive prompts are not possible or desired.

Suggestion:

# For all API keys/IDs (e.g., TAVILY_API_KEY, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID):
# Replace `os.environ.get("VAR_NAME") or getpass.getpass("Prompt:")`
# with:
VAR_NAME = os.environ.get("VAR_NAME")
if not VAR_NAME:
    raise ValueError(f"Environment variable {VAR_NAME_STRING} is not set. Please set it for automated environments.")

Rationale: Interactive prompts (getpass.getpass) block execution, making the module unsuitable for CI/CD, production servers, or containerized deployments. Environment variables should be the primary and often sole source for such configurations in automated systems.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +35

🟢 Low: Hardcoded print() statement in web_search_tool

The web_search_tool function directly prints the search result to standard output (print(result)).

Suggestion:
Please remove the direct console print.

Rationale: Tool functions should ideally return their output without side effects like printing, allowing the calling agent or system to decide how to handle the result (e.g., log it, display it, process it). This mixes concerns and makes the tool less flexible.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +55 to +60

🟡 Medium: Lack of Error Handling in telegram_send_message

The telegram_send_message function does not include any error handling for potential failures during the Telegram API call (e.g., invalid token, incorrect chat ID, network issues). If an error occurs, it will raise an unhandled exception, which can crash the application.

Suggestion:

import logging
from telegram import error

logger = logging.getLogger(__name__)

def telegram_send_message(message: str) -> str:
    token = TELEGRAM_BOT_TOKEN
    chat_id = TELEGRAM_CHAT_ID
    bot = telegram.Bot(token=token)
    try:
        bot.send_message(chat_id=chat_id, text=message)
        return f"Message sent to chat {chat_id}."
    except error.Unauthorized:
        logger.error("Telegram bot token is invalid. Please check TELEGRAM_BOT_TOKEN.")
        return "Failed to send message: Invalid bot token."
    except error.BadRequest as e:
        logger.error(f"Telegram API Bad Request: {e}")
        return f"Failed to send message: {e}"
    except Exception as e:
        logger.error(f"An unexpected error occurred while sending Telegram message: {e}")
        return f"Failed to send message: An unexpected error occurred."

Rationale: Unhandled exceptions during external API calls can crash the application. Robust error handling ensures graceful degradation and provides informative feedback to the user or logs for debugging.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +54

🟡 Medium: Repeated telegram.Bot Instantiation

The telegram.Bot object is instantiated inside the telegram_send_message function on every call. For a frequently called function, it would be more efficient to instantiate the Bot object once and reuse it.

Suggestion:

# Define bot globally or pass as dependency.
# If TELEGRAM_BOT_TOKEN is static:
# _telegram_bot = telegram.Bot(token=TELEGRAM_BOT_TOKEN) # Instantiate once at module load
# Then in function:
# _telegram_bot.send_message(...)

# If tokens are dynamic, consider a memoized function or dependency injection.

Rationale: Instantiating telegram.Bot on every call is inefficient, introducing unnecessary overhead (object creation, potential connection setup). Reusing a single Bot instance improves performance and resource utilization.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +30 to +60

🟡 Medium: Performance: Blocking I/O Operations (Significant Impact)

Both web_search_tool (via TavilySearch.run()) and telegram_send_message (via telegram.Bot.send_message()) perform external network requests synchronously. These calls will block the execution thread until the external API responds.

Suggestion:
Convert web_search_tool and telegram_send_message to async functions and utilize asynchronous client methods (e.g., TavilySearch.arun() and telegram.Bot.send_message() with await).

Rationale: Synchronous I/O operations severely degrade the responsiveness and concurrency of the application, especially if these tools are used in a web server or any multi-threaded/multi-process environment. Asynchronous I/O allows the application to perform other tasks while waiting for network responses, significantly improving concurrency.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +32 and +54

🟡 Medium: Performance: Repeated Object Instantiation (TavilySearch and telegram.Bot)

TavilySearch is instantiated every time web_search_tool is invoked, and telegram.Bot is instantiated every time telegram_send_message is called. This introduces unnecessary overhead for object creation.

Suggestion:
Instantiate TavilySearch and telegram.Bot objects once (e.g., at the module level or by passing them as dependencies) and reuse them across function calls.

Rationale: Repeatedly creating these objects incurs unnecessary overhead in terms of CPU and memory. Reusing instances is more efficient, especially for frequently called functions.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +5 to +20

🟡 Medium: Performance: Blocking Startup for API Keys via getpass (Startup Performance & Deployment Issue)

The getpass.getpass() calls at the module level for TAVILY_API_KEY, TELEGRAM_BOT_TOKEN, and TELEGRAM_CHAT_ID will block the program's execution during startup if these environment variables are not set.

Suggestion:
Remove getpass.getpass() from module-level code. Instead, ensure environment variables are properly set before the application starts (e.g., via .env files, Docker environment variables, or CI/CD secrets). If a variable is missing, raise an informative error and exit cleanly, rather than blocking.

Rationale: Interactive prompts at startup prevent automated deployment and impact "time to readiness" for the service. Configuration should be declarative and non-blocking for production systems.


📁 py-server/nodes/Agents/tools/tools.py

Comment on lines +EOF

🟢 Low: Missing Newline at End of File

The file py-server/nodes/Agents/tools/tools.py does not end with a newline character.

Suggestion:
Add a newline character at the end of the file.

Rationale: This is a minor but common issue that can cause problems with some tools and version control systems. It's generally considered good practice for all text files to end with a newline.


Summary by CodeDaddy

  • New Features

    • Introduction of TelegramSendMessage tool for LLM agent communication.
    • Enhanced environment variable loading for API keys (TAVILY_API_KEY, TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID).
  • Improvements

    • Centralized API key management (though with room for security enhancements).
  • Tests

    • Comprehensive unit, edge case, and integration tests are highly recommended to ensure robustness and security of the new tools and credential handling.
  • Security Findings

    • 🔴 Critical: Unrestricted Telegram Message Sending via LLM Agent (Prompt Injection Vulnerability)
    • 🟡 Medium: Sensitive Credential Handling (Telegram Bot Token)
    • 🟢 Low: New Dependency Introduction (Supply Chain Risk)
  • Code Quality Findings

    • 🟡 Medium: Interactive API Key Prompts (Anti-pattern for production/automation)
    • 🟢 Low: Hardcoded print() statement in web_search_tool
    • 🟡 Medium: Lack of Error Handling in telegram_send_message
    • 🟡 Medium: Repeated telegram.Bot Instantiation
    • 🟢 Low: Missing Newline at End of File
  • Performance Findings

    • 🟡 Medium: Blocking I/O Operations (Significant Impact)
    • 🟡 Medium: Repeated Object Instantiation (TavilySearch and telegram.Bot)
    • 🟡 Medium: Blocking Startup for API Keys via getpass (Startup Performance & Deployment Issue)

Thanks for using code-Daddy! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Hey there! CodeDaddy here. I've put a lot of love into this review to help you ship awesome code. If you found it helpful, why not give us a shout-out on social media or star our repo? Every bit of support helps CodeDaddy grow and keep providing free reviews for open-source projects! Thanks, you're the best! 🧔🏻‍♂️✨

📚 Tips
  • Prioritize Security Fixes First: Address critical and major security findings before diving into other improvements. Security is paramount!
  • Automate Environment Setup: For local development, consider using a .env file and a library like python-dotenv to load environment variables, avoiding interactive prompts.
  • Continuous Integration for Quality: Integrate static analysis tools (linters, formatters) and automated tests into your CI/CD pipeline to catch issues early and maintain code quality.

Actionable comments posted: 10

@coderabbitai
Copy link

coderabbitai bot commented Nov 19, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants