Telegram Bot Guide
Telegram Bot Guide
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.
5. Message handlers:
Installation Instructions
Bot Features
✅ 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
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.
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
Cons: - Bot stops when your computer is off - Not suitable for production use
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
1. Enable and start the service: bash sudo systemctl enable telegram-
bot.service sudo systemctl start 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
Cons: - Limited resources on free tier - May require periodic manual restart
4. Heroku Deployment
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
Cons: - Free tier has limitations - Dynos sleep after 30 minutes of inactivity on free tier
For production use, it's important to ensure your bot stays running even if it encounters
errors or crashes.
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.
PM2 is a process manager for Node.js applications, but it can also manage Python
scripts.
Installation:
# View logs
pm2 logs telegram-bot
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
Tmux:
# Install tmux
sudo apt install tmux
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
Advanced Monitoring
The current bot implementation provides a solid foundation that you can extend with
additional features.
Adding New Commands
Inline queries allow users to interact with your bot directly from any chat by typing
@your_bot_username followed by a query.
application.add_handler(InlineQueryHandler(inline_query)) ```
1. Enable inline mode for your bot through BotFather using the /setinline
command
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")
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"
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']}"
Security Considerations
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.
4. Use HTTPS: When making API calls, always use HTTPS to ensure secure
communication.
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.
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.
1. Official Documentation:
2. python-telegram-bot Documentation
7. Community Support:
8. python-telegram-bot GitHub
9. Telegram Bot API Forum
10. Stack Overflow