Skip to content

TelegramRetrieveTool

autogen.tools.experimental.TelegramRetrieveTool #

TelegramRetrieveTool(*, api_id, api_hash, chat_id)

Bases: BaseTelegramTool, Tool

Retrieves messages from a Telegram channel.

Initialize the TelegramRetrieveTool.

PARAMETER DESCRIPTION
api_id

Telegram API ID from https://my.telegram.org/apps.

TYPE: str

api_hash

Telegram API hash from https://my.telegram.org/apps.

TYPE: str

chat_id

The ID of the chat to retrieve messages from (Channel, Group, Bot Chat ID).

TYPE: str

Source code in autogen/tools/experimental/messageplatform/telegram/telegram.py
def __init__(self, *, api_id: str, api_hash: str, chat_id: str) -> None:
    """
    Initialize the TelegramRetrieveTool.

    Args:
        api_id: Telegram API ID from https://my.telegram.org/apps.
        api_hash: Telegram API hash from https://my.telegram.org/apps.
        chat_id: The ID of the chat to retrieve messages from (Channel, Group, Bot Chat ID).
    """
    BaseTelegramTool.__init__(self, api_id, api_hash, "telegram_retrieve_session")
    self._chat_id = chat_id

    async def telegram_retrieve_messages(
        chat_id: Annotated[str, Depends(on(chat_id))],
        messages_since: Annotated[
            Union[str, None],
            "Date to retrieve messages from (ISO format) OR message ID. If None, retrieves latest messages.",
        ] = None,
        maximum_messages: Annotated[
            Union[int, None], "Maximum number of messages to retrieve. If None, retrieves all messages since date."
        ] = None,
        search: Annotated[Union[str, None], "Optional string to search for in messages."] = None,
    ) -> Any:
        """
        Retrieves messages from a Telegram chat.

        Args:
            chat_id: The ID of the chat. (uses dependency injection)
            messages_since: ISO format date string OR message ID to retrieve messages from.
            maximum_messages: Maximum number of messages to retrieve.
            search: Optional string to search for in messages.
        """
        try:
            client = self._get_client()
            async with client:
                # Initialize and cache the entity
                entity = await self._initialize_entity(client, chat_id)

                # Setup retrieval parameters
                params = {
                    "entity": entity,
                    "limit": maximum_messages if maximum_messages else None,
                    "search": search if search else None,
                    "filter": InputMessagesFilterEmpty(),
                    "wait_time": None,  # No wait time between requests
                }

                # Handle messages_since parameter
                if messages_since:
                    try:
                        # Try to parse as message ID first
                        msg_id = int(messages_since)
                        params["min_id"] = msg_id
                    except ValueError:
                        # Not a message ID, try as ISO date
                        try:
                            date = datetime.fromisoformat(messages_since.replace("Z", "+00:00"))
                            params["offset_date"] = date
                            params["reverse"] = (
                                True  # Need this because the date gets messages before a certain date by default
                            )
                        except ValueError:
                            return {
                                "error": "Invalid messages_since format. Please provide either a message ID or ISO format date (e.g., '2025-01-25T00:00:00Z')"
                            }

                # Retrieve messages
                messages = []
                count = 0
                # For bot users, we need to get both sent and received messages
                if isinstance(self._get_peer_from_id(chat_id), PeerUser):
                    print(f"Retrieving messages for bot chat {chat_id}")

                async for message in client.iter_messages(**params):
                    count += 1
                    messages.append({
                        "id": str(message.id),
                        "date": message.date.isoformat(),
                        "from_id": str(message.from_id) if message.from_id else None,
                        "text": message.text,
                        "reply_to_msg_id": str(message.reply_to_msg_id) if message.reply_to_msg_id else None,
                        "forward_from": str(message.forward.from_id) if message.forward else None,
                        "edit_date": message.edit_date.isoformat() if message.edit_date else None,
                        "media": bool(message.media),
                        "entities": [
                            {"type": e.__class__.__name__, "offset": e.offset, "length": e.length}
                            for e in message.entities
                        ]
                        if message.entities
                        else None,
                    })

                    # Check if we've hit the maximum
                    if maximum_messages and len(messages) >= maximum_messages:
                        break

                return {
                    "message_count": len(messages),
                    "messages": messages,
                    "start_time": messages_since or "latest",
                }

        except Exception as e:
            return f"Message retrieval failed, exception: {str(e)}"

    Tool.__init__(
        self,
        name="telegram_retrieve",
        description="Retrieves messages from a Telegram chat based on datetime/message ID and/or number of latest messages.",
        func_or_tool=telegram_retrieve_messages,
    )

name property #

name

description property #

description

func property #

func

tool_schema property #

tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

function_schema property #

function_schema

Get the schema for the function.

This is the old way of handling function calls with OpenAI and compatible frameworks. It is provided for backward compatibility.

realtime_tool_schema property #

realtime_tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

register_for_llm #

register_for_llm(agent)

Registers the tool for use with a ConversableAgent's language model (LLM).

This method registers the tool so that it can be invoked by the agent during interactions with the language model.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_llm(self, agent: "ConversableAgent") -> None:
    """Registers the tool for use with a ConversableAgent's language model (LLM).

    This method registers the tool so that it can be invoked by the agent during
    interactions with the language model.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    agent.register_for_llm()(self)

register_for_execution #

register_for_execution(agent)

Registers the tool for direct execution by a ConversableAgent.

This method registers the tool so that it can be executed by the agent, typically outside of the context of an LLM interaction.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_execution(self, agent: "ConversableAgent") -> None:
    """Registers the tool for direct execution by a ConversableAgent.

    This method registers the tool so that it can be executed by the agent,
    typically outside of the context of an LLM interaction.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    agent.register_for_execution()(self)

register_tool #

register_tool(agent)

Register a tool to be both proposed and executed by an agent.

Equivalent to calling both register_for_llm and register_for_execution with the same agent.

Note: This will not make the agent recommend and execute the call in the one step. If the agent recommends the tool, it will need to be the next agent to speak in order to execute the tool.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_tool(self, agent: "ConversableAgent") -> None:
    """Register a tool to be both proposed and executed by an agent.

    Equivalent to calling both `register_for_llm` and `register_for_execution` with the same agent.

    Note: This will not make the agent recommend and execute the call in the one step. If the agent
    recommends the tool, it will need to be the next agent to speak in order to execute the tool.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    self.register_for_llm(agent)
    self.register_for_execution(agent)