Running Telegram bot made on python as background service on Ubuntu

147 views Asked by At

Couldn't run telegram bot as background service. When run directly from terminal - it works fine.

I've made a simple telegram bot using telebot library:

import telebot

TOKEN = 'my-token'
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(content_types=['text'])
def proc_msg(message):
    chat_id = message.chat.id
    bot.send_message(chat_id,text="I'm test bot. Sorry, can't answer anything else. Made for dummy tests.")

bot.polling(none_stop=True, interval=0)

It works when I just run the script via terminal:

python test_bot.py

I need to run the bot as background service with automatic restart after reboots, so I made test_bot.service file:

[Unit]
Description=Test Bot
After=multi-user.target

[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/python /etc/tg_bots/test4477qwe_bot/test_bot.py

[Install]
WantedBy=multi-user.target

Then put the file to /etc/systemd/system and run systemctl daemon-reload. At this stage everything is fine, my service is in list given by systemctl

But when I'm trying run the service using command systemctl start test_bot - nothing happens. It actually looks like systemctl start test_bot is hanging.

What could be wrong? (System is Ubuntu 22.04.3 LTS. Maybe it is not the best choice for running python-telegram-bots?)

2

There are 2 answers

1
turalmehrali On

You can just start script with this code and it will work in background.

nohup python test_bot.py &
0
Vladimir Naumov On

After numerous attempts I just changed operation system to CentOS 9. Now script successfully works as background service. Probably something wrong with exact Ubuntu version provided by my VPS hoster