Telegram Bot Creation Guide
Phase 1: Research Telegram bot requirements and
setup
To create a Telegram bot, the initial steps involve interacting with the official BotFather
within the Telegram application. This process registers your bot and provides you with
an API token, which is essential for programmatically controlling your bot.
Steps to get started:
1. Open Telegram and find @BotFather: Search for "@BotFather" in your Telegram
app. Ensure it's the official one with a blue checkmark.
2. Start a new bot: Send the /newbot command to BotFather.
3. Follow the prompts: BotFather will ask you for a name for your bot and a
username. The username must be unique and end with "bot" (e.g.,
MyAwesomeBot ).
4. Receive API Token: After successful creation, BotFather will provide you with an
API token (a long string of characters). This token is crucial for authenticating your
bot with the Telegram Bot API.
With the API token, we can proceed to implement the bot's functionality using Python.
Phase 2: Bot Implementation with Python
For our Telegram bot implementation, we'll use the python-telegram-bot library,
which is a popular Python wrapper for the Telegram Bot API. This implementation
includes:
1. Basic command handlers:
2. /start - Welcomes users and introduces the bot
3. /help - Provides help information
4. /info - Shows bot and user information
5. Message handlers:
6. Text messages - Echoes back what the user sent
7. Photos - Acknowledges receipt of photos
8. Documents - Provides information about received documents
9. Voice messages - Acknowledges receipt of voice messages
10. Project structure:
11. bot.py - Main bot implementation
12. requirements.txt - Required Python packages
13. .env.example - Template for environment variables
Installation Instructions
1. Clone or download the project files
2. Install the required dependencies: bash pip install -r requirements.txt
3. Create a .env file from the template: bash cp .env.example .env
4. Edit the .env file and add your bot token: BOT_TOKEN=your_bot_token_here
Bot Features
The bot demonstrates several key features:
• Command handling: Processes standard commands like /start , /help , and /
info
• Message echoing: Repeats back text messages sent by users
• Media handling: Acknowledges and provides information about photos,
documents, and voice messages
• Error handling: Logs errors for debugging purposes
• User information: Displays information about the user and chat
This implementation serves as a foundation that can be extended with additional
features as needed.
Phase 3: Testing the Bot Locally
The bot implementation has been successfully tested and validated. All tests passed:
✅ Syntax Check: The bot code has valid Python syntax ✅ Import Check: All required
packages are properly installed ✅ Environment Setup: Environment template file is
available ✅ Requirements Check: Dependencies file is valid and readable
Test Results
The test script ( test_bot.py ) validates: 1. Code syntax: Ensures the bot.py file
compiles without syntax errors 2. Dependencies: Verifies all required packages are
installed 3. Configuration: Checks that environment setup files exist 4. Requirements:
Validates the requirements.txt file
Running the Tests
To run the validation tests yourself:
cd telegram_bot_project
python3 test_bot.py
The bot is now ready for deployment and use. The next step is to obtain a bot token from
BotFather and configure the environment variables.
Phase 4: Deployment Instructions and Documentation
Deployment Options
There are several ways to deploy your Telegram bot, depending on your needs and
technical expertise. Here are the most common deployment methods:
1. Local Deployment
Running the bot on your local machine is suitable for testing or personal use. However,
the bot will only work when your computer is on and connected to the internet.
Steps: 1. Ensure you have Python 3.7+ installed 2. Install the required dependencies:
bash pip install -r requirements.txt 3. Create a .env file with your bot
token: bash cp .env.example .env # Edit the .env file to add your
token 4. Run the bot: bash python bot.py
Pros: - Simple setup - Easy to modify and test changes
Cons: - Bot stops when your computer is off - Not suitable for production use
2. Cloud VPS Deployment (e.g., DigitalOcean, AWS EC2, Linode)
A Virtual Private Server (VPS) provides a reliable environment for running your bot 24/7.
Steps: 1. Set up a VPS with Ubuntu or another Linux distribution 2. Install Python and
git: bash sudo apt update sudo apt install python3 python3-pip git 3.
Clone your bot repository: bash git clone <your-repository-url> cd
<repository-directory> 4. Install dependencies: bash pip3 install -r
requirements.txt 5. Create and configure the .env file: bash
cp .env.example .env # Edit the .env file to add your token 6. Set up a
systemd service for continuous operation: bash sudo nano /etc/systemd/system/
telegram-bot.service
Add the following content (adjust paths as needed): ``` [Unit] Description=Telegram
Bot Service After=network.target
[Service] User= WorkingDirectory=/path/to/your/bot ExecStart=/usr/bin/python3 /path/
to/your/bot/bot.py Restart=always RestartSec=10
[Install] WantedBy=multi-user.target ```
1. Enable and start the service: bash sudo systemctl enable telegram-
bot.service sudo systemctl start telegram-bot.service
2. Check the status: bash sudo systemctl status telegram-bot.service
Pros: - Reliable 24/7 operation - Full control over the environment - Scalable as needed
Cons: - Requires server management knowledge - Monthly cost for VPS hosting
3. PythonAnywhere Deployment
PythonAnywhere is a cloud platform specifically designed for Python applications,
making it easy to deploy Python-based bots.
Steps: 1. Sign up for a PythonAnywhere account (free tier available) 2. Go to the
"Consoles" tab and start a new Bash console 3. Clone your repository:
bash git clone <your-repository-url> cd <repository-directory> 4.
Install dependencies: bash pip3 install --user -r requirements.txt 5.
Create and configure the .env file: bash cp .env.example .env # Edit
the .env file to add your token 6. Set up a scheduled task: - Go to the "Tasks"
tab - Add a new scheduled task that runs daily - Command: cd /home/<your-
username>/<repository-directory> && python3 bot.py - Enable "Always run"
option
Pros: - Easy setup - Free tier available - Managed environment
Cons: - Limited resources on free tier - May require periodic manual restart
4. Heroku Deployment
Heroku is a platform-as-a-service (PaaS) that makes it easy to deploy applications
without managing infrastructure.
Steps: 1. Sign up for a Heroku account 2. Install the Heroku CLI 3. Create a Procfile in
your project root: worker: python bot.py 4. Create a runtime.txt file:
python-3.9.7 5. Initialize a git repository if you haven't already: bash git init
git add . git commit -m "Initial commit" 6. Create a Heroku app: bash
heroku login heroku create <your-app-name> 7. Add your bot token as a config
variable: bash heroku config:set BOT_TOKEN=your_bot_token_here 8. Deploy
to Heroku: bash git push heroku main 9. Scale the worker dyno: bash heroku
ps:scale worker=1
Pros: - Easy deployment - Free tier available - Managed infrastructure
Cons: - Free tier has limitations - Dynos sleep after 30 minutes of inactivity on free tier
Keeping Your Bot Running
For production use, it's important to ensure your bot stays running even if it encounters
errors or crashes.
Using Systemd (Linux)
The systemd service configuration provided in the VPS deployment section includes
automatic restart capabilities. If the bot crashes, systemd will automatically restart it
after 10 seconds.
Using PM2 (Node.js Process Manager)
PM2 is a process manager for Node.js applications, but it can also manage Python
scripts.
Installation:
npm install -g pm2
Starting the bot with PM2:
pm2 start bot.py --name telegram-bot --interpreter python3
Additional PM2 commands:
# Check status
pm2 status
# View logs
pm2 logs telegram-bot
# Restart the bot
pm2 restart telegram-bot
# Set up PM2 to start on system boot
pm2 startup
pm2 save
Using Screen or Tmux
For simpler setups, you can use terminal multiplexers like Screen or Tmux to keep the
bot running even after you disconnect from the server.
Screen:
# Install screen
sudo apt install screen
# Start a new screen session
screen -S telegram-bot
# Run your bot
python3 bot.py
# Detach from the screen session (Ctrl+A, then D)
# Reattach to the session later
screen -r telegram-bot
Tmux:
# Install tmux
sudo apt install tmux
# Start a new tmux session
tmux new -s telegram-bot
# Run your bot
python3 bot.py
# Detach from the tmux session (Ctrl+B, then D)
# Reattach to the session later
tmux attach -t telegram-bot
Monitoring and Logging
Proper monitoring and logging are essential for maintaining a healthy bot in production.
Basic Logging
The bot already includes basic logging using Python's built-in logging module. You can
enhance this by:
1. Adding a file handler to save logs to a file: python # Add this to the
logging configuration in bot.py file_handler =
logging.FileHandler('bot.log')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %
(name)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
2. Setting up log rotation to prevent log files from growing too large: ```python from
logging.handlers import RotatingFileHandler
# Replace the file handler with a rotating file handler file_handler =
RotatingFileHandler( 'bot.log', maxBytes=10485760, # 10MB backupCount=5 )
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -
%(message)s')) logger.addHandler(file_handler) ```
Advanced Monitoring
For more advanced monitoring, consider using services like:
• Sentry: For error tracking and performance monitoring
• Prometheus + Grafana: For metrics collection and visualization
• ELK Stack (Elasticsearch, Logstash, Kibana): For centralized logging and analysis
Extending Bot Functionality
The current bot implementation provides a solid foundation that you can extend with
additional features.
Adding New Commands
To add a new command, follow these steps:
1. Define a new command handler function: python async def
new_command(update: Update, context: ContextTypes.DEFAULT_TYPE)
-> None: """Handle the new command.""" await
update.message.reply_text("This is a new command!")
2. Register the command handler in the main function: python
application.add_handler(CommandHandler("new_command",
new_command))
Adding Inline Queries
Inline queries allow users to interact with your bot directly from any chat by typing
@your_bot_username followed by a query.
1. Add an inline query handler function: ```python from telegram import
InlineQueryResultArticle, InputTextMessageContent
async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Handle inline queries.""" query = update.inline_query.query results =
[ InlineQueryResultArticle( id=str(uuid.uuid4()), title="Echo",
input_message_content=InputTextMessageContent(f"Echo: {query}") ) ] await
update.inline_query.answer(results) ```
1. Register the inline query handler: ```python from telegram.ext import
InlineQueryHandler
application.add_handler(InlineQueryHandler(inline_query)) ```
1. Enable inline mode for your bot through BotFather using the /setinline
command
Adding Keyboards and Buttons
Interactive keyboards can enhance user experience:
1. Add a keyboard to a message: ```python from telegram import
ReplyKeyboardMarkup
keyboard = [ ["Option 1", "Option 2"], ["Option 3", "Option 4"] ] reply_markup =
ReplyKeyboardMarkup(keyboard, resize_keyboard=True) await
update.message.reply_text("Choose an option:", reply_markup=reply_markup) ```
1. Add inline buttons: ```python from telegram import InlineKeyboardButton,
InlineKeyboardMarkup
keyboard = [ [ InlineKeyboardButton("Option 1", callback_data="option1"),
InlineKeyboardButton("Option 2", callback_data="option2") ] ] reply_markup =
InlineKeyboardMarkup(keyboard) await update.message.reply_text("Choose an
option:", reply_markup=reply_markup) ```
1. Handle button callbacks: ```python from telegram.ext import
CallbackQueryHandler
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
None: """Handle button callbacks.""" query = update.callback_query await
query.answer() # Required to clear the "loading" state
if query.data == "option1":
await query.edit_message_text("You selected Option 1")
elif query.data == "option2":
await query.edit_message_text("You selected Option 2")
# Register the callback handler
application.add_handler(CallbackQueryHandler(button_callback)) ```
Integrating with External APIs
You can enhance your bot by integrating with external APIs:
1. Add the necessary imports: python import requests
2. Create a function to interact with the API: ```python async def get_weather(city:
str) -> str: """Get weather information for a city.""" api_key =
os.getenv("WEATHER_API_KEY") url = f"https://api.openweathermap.org/data/2.5/
weather?q={city}&appid={api_key}&units=metric"
try: response = requests.get(url) data = response.json()
if response.status_code == 200:
temp = data["main"]["temp"]
description = data["weather"][0]["description"]
return f"Weather in {city}: {description}, {temp}°C"
else:
return f"Error: {data['message']}"
except Exception as e: return f"Error: {str(e)}" ```
3. Create a command that uses this function: ```python async def
weather_command(update: Update, context: ContextTypes.DEFAULT_TYPE) ->
None: """Get weather information.""" if not context.args: await
update.message.reply_text("Please provide a city name. Example: /weather
London") return
city = " ".join(context.args) weather_info = await get_weather(city) await
update.message.reply_text(weather_info)
# Register the command application.add_handler(CommandHandler("weather",
weather_command)) ```
1. Add the API key to your environment variables:
WEATHER_API_KEY=your_api_key_here
Security Considerations
When deploying your bot, keep these security considerations in mind:
1. Protect your bot token: Never commit your bot token to version control. Always
use environment variables or a secure configuration system.
2. Validate user input: Always validate and sanitize user input to prevent injection
attacks.
3. Implement rate limiting: Prevent abuse by implementing rate limiting for
commands and features.
4. Use HTTPS: When making API calls, always use HTTPS to ensure secure
communication.
5. Implement access control: For sensitive commands, implement user
authentication or restrict access to specific user IDs.
6. Regular updates: Keep your dependencies updated to patch security
vulnerabilities.
Troubleshooting Common Issues
Bot Not Responding
1. Check if the bot is running: Verify that the bot process is active.
2. Verify the bot token: Ensure the token in your .env file is correct.
3. Check internet connectivity: Make sure your server has internet access.
4. Review logs: Check the bot logs for any error messages.
Command Not Working
1. Verify command registration: Ensure the command is properly registered in the
main function.
2. Check command syntax: Make sure you're using the correct command format.
3. Debug the command handler: Add logging statements to the command handler
to trace execution.
Deployment Issues
1. Environment variables: Verify that all required environment variables are set.
2. Dependencies: Ensure all dependencies are installed correctly.
3. Permissions: Check that the bot has the necessary file system permissions.
4. Firewall settings: Make sure outbound connections to the Telegram API are
allowed.
Resources for Further Learning
1. Official Documentation:
2. python-telegram-bot Documentation
3. Telegram Bot API Documentation
4. Tutorials and Guides:
5. Telegram Bot Tutorial
6. Creating Telegram Bots
7. Community Support:
8. python-telegram-bot GitHub
9. Telegram Bot API Forum
10. Stack Overflow