Connecting to External Services: Telegram Bot
Imagine you want to collect your thoughts and tasks throughout the day without switching apps. A Telegram bot can be your personal assistant, capturing ideas and to-dos. By the end of this lesson, you'll be able to connect Claude Code to a Telegram bot and retrieve data using APIs.
Core idea
To connect Claude Code to external services like Telegram, you'll use APIs (Application Programming Interfaces). An API is a way for different software systems to communicate and exchange data. Think of it as a digital waiter: you place an order (request data), and the waiter (API) brings you the food (data) from the kitchen (Telegram server).
To access the Telegram API, you'll need a token. A token is like a password that authorizes your Claude Code to access your bot's data. You get this token from BotFather within Telegram when you create a new bot. It's crucial to keep your token secret, like a password. Store it in a .env file in your project directory. This file is excluded from being uploaded to GitHub to protect your secrets.
Example
Let's walk through connecting to the Telegram API to retrieve messages.
Task: Retrieve messages from your Telegram bot.
Get your API token: Create a bot using BotFather in Telegram and obtain the API token.
Store the token: Create a
.envfile in your project and store the token like this:TELEGRAM_BOT_TOKEN=YOUR_TELEGRAM_BOT_TOKENConstruct the API URL: Use Claude Code to construct the Telegram Bot API URL for retrieving updates. The basic format is:
https://api.telegram.org/bot<YOUR_TELEGRAM_BOT_TOKEN>/getUpdates. Claude can read the token from your.envfile.Retrieve data: Ask Claude Code to fetch the data from the API URL. You can do this by prompting Claude to make an HTTP request to the URL.
Display the data: Claude Code will receive a JSON response containing your messages. You can then ask Claude to parse and format this data for further processing.
Common mistakes
- Exposing your token: Never commit your API token directly to your GitHub repository. Always store it in a
.envfile and ensure that.envis in your.gitignorefile. - Incorrect API URL: Double-check the API URL for typos or incorrect formatting. A wrong URL will result in errors.
- Not sending messages: If you're not seeing any data, make sure you've sent some messages to your bot after creating it. The API only returns recent messages.
Key takeaways
- APIs allow Claude Code to interact with external services like Telegram.
- A token is required to authenticate with the Telegram API.
- Store your token securely in a
.envfile. - Claude Code can construct API URLs and retrieve data from them.
- The data is returned in JSON format, which Claude Code can parse.
The student marks this lesson as read to continue. (Knowledge checks coming later.)