> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ag2.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TelegramAgent

If you need an agent to send messages to your Telegram channel/group/bot and/or retrieve Telegram messages to action, [`TelegramAgent`](/docs/api-reference/autogen/agents/experimental/TelegramAgent) can help you.

<Tip>
  If you haven't had a chance to read about how AG2's Communication Platform agents and tools work, read the [overview](../overview) first.
</Tip>

## Installation

Install AG2 with the LLM model provider and Telegram platform extra.

```bash theme={null}
pip install ag2[openai,commsagent-telegram]
```

### Capabilities

[`TelegramAgent`](/docs/api-reference/autogen/agents/experimental/TelegramAgent) can:

* Construct and send a message to the configured channel/group/bot. If a message is longer than the platforms permitted message length, they will split the message into multiple messages.
* Retrieve the latest X messages from a channel/group/bot.
* Retrieve messages since a given date.
* Retrieve messages since a given message ID.
* Retrieve a message given its ID.
* Retrieve messages using a search string (and this can be done in combination with the retrieval options above).

It will also automatically append Telegram's messaging requirements to the system message:

* 4,096 character limit
* HTML
* mentions
* emojis

This is on by default, but you can turn these off by setting `has_writing_instructions` to `False` when creating the agent.

### In-built Tools

The [`TelegramAgent`](/docs/api-reference/autogen/agents/experimental/TelegramAgent) has two in-built tools that it will call upon as it needs:

* [`TelegramSendTool`](/docs/api-reference/autogen/tools/experimental/TelegramSendTool)
* [`TelegramRetrieveTool`](/docs/api-reference/autogen/tools/experimental/TelegramRetrieveTool)

Find out more about these tools and how you can add them to your own AG2 agents in the [Telegram Tools](/docs/user-guide/reference-tools/communication-platforms/telegram) documentation.

### Tokens, Bots, Groups, and Channels

The [`TelegramAgent`](/docs/api-reference/autogen/agents/experimental/TelegramAgent) requires authentication (API ID and hash) and target Bot/Group/Channel details in order to send/retrieve messages.

The [`TelegramAgent`](/docs/api-reference/autogen/agents/experimental/TelegramAgent) is different to the DiscordAgent and SlackAgent in that you can send/retrieve messages to/from a bot channel, a group channel, a channel, or even your own private channel. This is all handled by giving the respective ID to the `chat_id` parameter when creating the agent.

Here’s how to establish your API ID and Hash:

* [API ID and Hash](https://docs.telethon.dev/en/stable/basic/signing-in.html)

If you want to create a bot, which is optional but allows you to send messages to the bot channel:

* In Telegram, search for @BotFather
* Click on @BotFather (make sure it's the correct one!) and click START
* Message `/newbot`
* Give it a name then a username
* You'll then receive a token for your bot and you see the links below to get the ID for your bot

There are four types of `chat_id`s you can send to:

* Bot chat
* Group chat
* Channel chat
* Private chat (noted in Telegram as `Saved Messages`)

To find these the IDs for these, here are some references:

* [Bot, Private, Channel, Group IDs](https://gist.github.com/nafiesl/4ad622f344cd1dc3bb1ecbe468ff9f8a)
* [Group and Channel IDs](https://docs.b2core.b2broker.com/how-to-articles/manage-communication-platforms/how-to-get-telegram-chat-group-and-channel-identifiers)
* [Group ID](https://stackoverflow.com/questions/32423837/telegram-bot-how-to-get-a-group-chat-id)

It takes a bit of time to get this sorted, but once you have your token and IDs, you’re ready to go!

### Code example

Here's some code snippets showing how Telegram can send and retrieve messages.

```python theme={null}
# Tools are available in the autogen.tools namespace
from autogen import ConversableAgent, LLMConfig
from autogen.agents.experimental import TelegramAgent

# For running the code in Jupyter, use nest_asyncio to allow nested event loops
#import nest_asyncio
#nest_asyncio.apply()

llm_config = LLMConfig(model="gpt-4o-mini", api_type="openai")

# Authentication and target Chat ID (in this case a Group chat)
api_id = "123....."
api_hash = "a2e............................."
_chat_id_group = "-4712345678"

# Our tool executor agent, which will run the tools once recommended by the telegram_agent, no LLM required
executor_agent = ConversableAgent(
    name="executor_agent",
    human_input_mode="NEVER",
)

with llm_config:
    telegram_agent = TelegramAgent(
        name="telegram_agent",
        api_id=api_id,
        api_hash=api_hash,
        chat_id=_chat_id_group
    )

# We get the registered tools and register them for execution with the tool executor
for tool in telegram_agent.tools
    tool.register_for_execution(executor_agent)

# Let’s send a message to our Telegram channel, with a joke for the day.
# We’ll limit it to 2 turns, allowing the Telegram agent to receive the request,
# construct and recommend the send tool, and then the executor agent to execute the tool,
# sending the message to the Telegram group.
executor_agent.initiate_chat(
    recipient=telegram_agent,
    message="Let's send a message to Telegram giving them a joke for the day about AI agentic frameworks",
    max_turns=2,
)
```

Here's the message and joke of the day.

<img src="https://mintcdn.com/ag2ai/7LaI9NAtGf3xaVPO/docs/user-guide/reference-agents/assets/commsplatforms_telegram_sentmsg.png?fit=max&auto=format&n=7LaI9NAtGf3xaVPO&q=85&s=642679745c0c1f0d0cd0cfdc8433a202" alt="Telegram output" width="880" height="274" data-path="docs/user-guide/reference-agents/assets/commsplatforms_telegram_sentmsg.png" />

If you wanted to retrieve the last 10 messages and get their IDs:

```python theme={null}
executor_agent.initiate_chat(
    recipient=telegram_agent,
    message="Retrieve the latest 10 messages from Telegram, getting the IDs and a one sentence summary of each.",
    max_turns=2,
)
```

If you want to get all messages after a given ID, in this case ID 85. This is useful if you want to poll and retrieve new messages since the last one you retrieved.

```python theme={null}
executor_agent.initiate_chat(
    recipient=telegram_agent,
    message="Retrieve all messages since message ID 85, summarising each.",
    max_turns=2,
)
```

## Tool execution

In AG2 the tool execution is typically handled by a separate agent that will follow the agent in the conversation (unless its in a swarm whereby tools are executed automatically). So, you will need to register the tools with another agent for execution.

You will see an example of this is the example code above.

<div className="edit-url-container">
  <a className="edit-url" href="https://github.com/ag2ai/ag2/edit/main/website/docs/user-guide/reference-agents/communication-platforms/telegramagent.mdx" target="_blank"><Icon icon="pen" iconType="solid" size="13px" /> Edit this page</a>
</div>
