This handbook outlines the process of creating Telegram bots using BotFather. It emphasizes accuracy, provides detailed explanations, and includes optional/required tagging for clarity.
1. Initiating the Bot Creation Process
- Tool: Telegram application
- Actor: You (the bot developer)
- Prerequisite: A Telegram account.
Open Telegram and Search for BotFather: In the Telegram search bar, type
@BotFather
. Verify that the account has a blue checkmark, indicating it's the official BotFather.Start a Chat with BotFather: Click on the BotFather account and initiate a chat by pressing the "Start" button.
-
Issue the
/newbot
Command: Type/newbot
in the chat and send it. BotFather will respond with:
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
2. Naming Your Bot
- Requirement: Choose a name and a username for your bot.
- Considerations:
- Name: This is the display name of your bot (e.g., "My Awesome Bot").
- Username: This is the unique identifier for your bot (e.g., "MyAwesomeBot"). It must end in
bot
orBot
.
-
Provide the Bot Name: Type the desired name for your bot and send it. For example:
My Awesome Bot
BotFather will then ask for the username:
Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.
-
Provide the Bot Username: Type the desired username for your bot, ensuring it ends with
bot
orBot
. For example:
MyAwesomeBot
If the username is available, BotFather will respond with a success message, including your bot's API token:
Done! Congratulations on your new bot. You will find it at t.me/MyAwesomeBot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. Use this token to access the HTTP API: YOUR_API_TOKEN Keep your token secure and store it safely, it can be used by anyone to control your bot. For a description of the Bot API, see this page: https://core.telegram.org/bots/api
3. Securing and Storing the API Token
- Critical: The API token is your bot's password. Keep it secret!
- Best Practices:
- Never commit the token to public repositories.
- Use environment variables to store the token.
- Restrict access to the token in your development environment.
-
Store the API Token: Immediately copy the API token and store it securely. A common practice is to set it as an environment variable in your development environment:
export TELEGRAM_BOT_TOKEN="YOUR_API_TOKEN"
In a
.env
file (if using a library likedotenv
):
TELEGRAM_BOT_TOKEN=YOUR_API_TOKEN
4. Configuring Bot Settings (Optional)
BotFather provides several commands to configure your bot's settings. Here are some common ones:
-
/setname
: Changes the bot's name. -
/setdescription
: Sets a description for the bot (visible on the bot's profile page). -
/setabouttext
: Sets the bot's "About" information (visible on the bot's profile page). -
/setuserpic
: Sets the bot's profile picture. -
/setcommands
: Defines a list of commands that users can access via the bot's menu.
-
Setting a Description: To set a description, use the
/setdescription
command:
/setdescription
BotFather will prompt you to enter the description:
OK. What's the new description for your bot?
Enter the description:
This bot provides awesome services.
-
Setting Commands: To set commands, use the
/setcommands
command. This is crucial for usability. The format is:
/setcommands
BotFather will prompt you to enter the list of commands. Each command should be on a new line, with the command and its description separated by a hyphen:
start - Start the bot help - Get help and usage instructions subscribe - Subscribe to updates unsubscribe - Unsubscribe from updates
After sending this, users will see these commands in the bot's menu.
5. Developing Your Bot
- Technology Stack: Choose your preferred programming language and Telegram Bot API library. TypeScript is highly recommended.
- Libraries (TypeScript):
-
node-telegram-bot-api
: A popular and actively maintained library.
-
-
Install
node-telegram-bot-api
:
npm install node-telegram-bot-api --save npm install --save-dev @types/node-telegram-bot-api npm install --save-dev @types/node
Basic Bot Implementation (TypeScript):
import TelegramBot from "node-telegram-bot-api";
import * as dotenv from "dotenv";
dotenv.config();
const token = process.env.TELEGRAM_BOT_TOKEN;
if (!token) {
throw new Error("TELEGRAM_BOT_TOKEN is not defined in the environment.");
}
const bot = new TelegramBot(token, { polling: true });
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(
chatId,
"Welcome! Use /help to see available commands."
);
});
bot.onText(/\/help/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(
chatId,
"Available commands:\n/start - Start the bot\n/help - Show this help message"
);
});
console.log("Bot is running...");
- Explanation:
- Import Statements: Imports the necessary modules.
- Token Retrieval: Retrieves the API token from the environment variables.
- Bot Instantiation: Creates a new
TelegramBot
instance with the token and enables polling to receive updates. - Command Handlers: Registers handlers for the
/start
and/help
commands. When a user sends these commands, the corresponding function is executed, sending a message back to the user. - Error Handling: Checks if the token exists, throws an error if it doesn't.
-
Running the Bot:
npx ts-node your-bot-file.ts
6. Advanced Features and Considerations
- Inline Keyboards: Create interactive buttons within messages.
- Webhooks: Use webhooks for more efficient update delivery (recommended for production).
- Database Integration: Store user data and bot state.
- Error Handling: Implement robust error handling to catch and log exceptions.
- Rate Limiting: Be mindful of Telegram's API rate limits.
- Security: Sanitize user input to prevent injection attacks.
7. Deploying Your Bot
- Platforms: Consider platforms like Heroku, AWS, Google Cloud, or a VPS.
- Process Managers: Use a process manager like
pm2
to keep your bot running.
8. Updating Your Bot
- Continuous Integration/Continuous Deployment (CI/CD): Automate the deployment process.
- Version Control: Use Git for version control.
References
- Telegram Bot API Documentation: https://core.telegram.org/bots/api
- node-telegram-bot-api: https://github.com/yagop/node-telegram-bot-api
- BotFather: Within Telegram, search for
@BotFather
.
This handbook provides a solid foundation for creating Telegram bots. Remember to consult the official Telegram Bot API documentation for the most up-to-date information and advanced features. Good luck!
Top comments (0)