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@(for example: SSH [email protected])
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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3