Step 1: Update and Configure the Server
-
Connect to the server via SSH:
shssh user@your_server_ip
-
Update system packages:
shsudo apt update && sudo apt upgrade -y
-
Install necessary utilities:
shsudo apt install -y curl wget git
Step 2: Install Python and PIP
-
Install Python and PIP:
shsudo apt install -y python3 python3-pip
-
Check Python and PIP installation:
shpython3 --version && pip3 --version
Step 3: Create a Virtual Environment
-
Install virtualenv:
shsudo pip3 install virtualenv
-
Create and activate a virtual environment:
shmkdir ~/mytelegrambot && cd ~/mytelegrambot virtualenv venv source venv/bin/activate
Step 4: Install the Telegram API Library
- Install the Python Telegram Bot library:
sh
pip install python-telegram-bot
Step 5: Create a Telegram Bot
-
Create a bot in Telegram:
- Open Telegram and find @BotFather.
- Send the command
/newbot
and follow the instructions to create a new bot. - Save the access token you receive.
-
Create a file for your bot:
- In your virtual environment directory, create a file, e.g.,
bot.py
, and write your bot code in it.
- In your virtual environment directory, create a file, e.g.,
Step 6: Run the Bot
-
Run your bot:
shpython bot.py
-
Check the bot's operation in Telegram:
- Open Telegram and find your bot.
- Send the command
/start
and ensure that the bot responds.
Step 7: Configure the Bot as a Service
To ensure the bot starts automatically on server boot, configure it as a service:
-
Create a systemd unit file:
shsudo nano /etc/systemd/system/telegrambot.service
-
Add the following lines to the file:
makefile[Unit] Description=Telegram Bot After=network.target [Service] User=your_username WorkingDirectory=/home/your_username/mytelegrambot ExecStart=/home/your_username/mytelegrambot/venv/bin/python /home/your_username/mytelegrambot/bot.py Restart=always [Install] WantedBy=multi-user.target
- Replace
your_username
with your actual username.
- Replace
-
Reload systemd and enable the service:
shsudo systemctl daemon-reload sudo systemctl enable telegrambot.service sudo systemctl start telegrambot.service
-
Check the status of the service:
shsudo systemctl status telegrambot.service
Conclusion
By following these steps, you will set up a Debian server for running a Telegram bot, create and run the bot, and configure it as a service to start automatically. This ensures continuous operation of your bot and improves server management.
If you have any questions or encounter issues during setup, the QCKL support team is always ready to assist. We aim to provide you with the best tools and solutions for successfully utilizing Telegram bots.