Home > Article > Backend Development > Host Telegram Bot on Raspberry Pi 5
In my previous article, I demonstrated how to create and run a Telegram Bot using Python. You can find it here
In this guide, I’ll walk you through hosting your Telegram bot on your own Raspberry Pi server.
Follow this guide to create an image with Raspberry Pi Imager.
I recommend choosing Raspberry Pi OS Lite OS because it is the best option in terms of lightweight simplicity.
In the imager settings check the box next to Enable SSH and select use password authentification. This will allow you to connect to your Raspberry Pi via SSH.
After creating the image on a USB flash drive, insert the flash card into your Raspberry Pi and power it on.
ping raspberrypi.local
You’ll receive ping statistics along with the IP address of your Raspberry Pi.
SSH pi@<your_raspberry_pi_ip> (for example: SSH pi@192.168.0.10)
sudo apt update sudo apt upgrade
python3 --version
If Python is not installed, you can install it using:
sudo apt install python3 python3-pip
sudo apt install python3-venv python3 -m venv telegram-bot-env source telegram-bot-env/bin/activate
pip install python-telegram-bot --upgrade
nano bot.py
python3 bot.py
Your bot is now running, and you can test it on Telegram.
However, this method will terminate the bot when you close the terminal.
To keep it running in the background we can use tmux
sudo apt update sudo apt install tmux
nano start_bot.sh
#!/bin/bash source telegram-bots-env/bin/activate python3 bot.py
chmod +x start_bot.sh
tmux new -s my_bot_session
./start_bot.sh
tmux attach -t my_bot_session
If you want your bot to start automatically on boot, you can use a systemd service. Here’s how:
sudo nano /etc/systemd/system/my_bot.service
[Unit] Description=My Bot Service [Service] ExecStart=/usr/bin/tmux new-session -d -s my_bot_session '/path/to/start_bot.sh' WorkingDirectory=/path/to/my_bot User=pi [Install] WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable my_bot.service
sudo systemctl start my_bot.service
The above is the detailed content of Host Telegram Bot on Raspberry Pi 5. For more information, please follow other related articles on the PHP Chinese website!