Step 1: Set Up the Environment
1. Access your server
ssh username@your_server_ip
2. Update and Secure Your Server
a. Update your packages
sudo apt update && sudo apt upgrade -y
b. Install Firewall
sudo ufw allow OpenSSH
sudo ufw allow OpenSSH
sudo ufw enable
3. Install Python and Pip
sudo apt install python3 python3-pip -y
python3 --version
pip3 --version
Step 2: Set Up the Bot
a. Clone Your Bot Repository
git clone https://github.com/your-repo/bot.git
cd bot
b. Create a Virtual Environment
python3 -m venv venv
source venv/bin/activate
c. Install Dependencies
pip install -r requirements.txt
Step 3: Create a systemd Service
a. Create a Service File
sudo vim /etc/systemd/system/mybot.service
b. Paste and update the configuration
[Unit]
Description=Alexander Price Monitoring Bot
After=network.target
[Service]
User=awoyemivictora
WorkingDirectory=/home/awoyemivictora/alexander-price-monitoring-bot
ExecStart=/home/awoyemivictora/alexander-price-monitoring-bot/venv/bin/python /home/awoyemivictora/alexander-price-monitoring-bot/main_bot.py
Restart=always
EnvironmentFile=/home/awoyemivictora/alexander-price-monitoring-bot/.env
[Install]
WantedBy=multi-user.target
c. Save the file in vim
Press Esc and type :wq
d. Adjust Permissions
sudo chmod 644 /etc/systemd/system/alexander_bot.service
e. Ensure Your .env File is Secure
chmod 600 /home/awoyemivictora/alexander-price-monitoring-bot/.env
Step 5: Test the systemd Service
a. Reload systemd Daemon
sudo systemctl daemon-reload
b. Start the Service
sudo systemctl start alexander_bot
c. Enable the Service to Start at Boot
sudo systemctl enable alexander_bot
d. Check Status
sudo systemctl status alexander_bot
e. Verify Logs
sudo journalctl -u alexander_bot -f
Question?
okay, so if I edit the bot main file, and save it, it’ll automatically readjusted right?
Answer
No, if you edit the main_bot.py file and save it, the running instance of your bot will not automatically reload or adjust. You’ll need to restart the systemd service to apply the changes.
Step 6: Restart the Bot After Changes to the bot file
a. Restart the Service
sudo systemctl restart alexander_bot
b. Check the Service Status To ensure it restarted without errors:
sudo systemctl status alexander_bot
c. Monitor Logs (Optional) To confirm the bot is functioning as expected
sudo journalctl -u alexander_bot -f
Step 7: For Automated Restart on Code Changes
a. Install inotify-tools
sudo apt install inotify-tools
b. Run a File Watch Command Watch your bot file for changes and restart the service when detected:
while inotifywait -e modify /home/awoyemivictora/alexander-price-monitoring-bot/main_bot.py; do
sudo systemctl restart alexander_bot
done
For most use cases, manually restarting the service after editing the bot file is sufficient. If you’re frequently making changes and testing, the inotify method can streamline your workflow.